diff --git a/.gitattributes b/.gitattributes index 0261edb4fc96dc3d60313720d129158ebc3e8d6e..059ecdeda4fbd1f7b7116f39be50565d5dda08a5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -736,3 +736,23 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/torchvision.libs/libpng16.fdd68bd0.so.16 filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/torchvision.libs/libwebp.14e109ad.so.7 filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/torchvision.libs/libz.1140de3a.so.1 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/augment.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/exporter.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/predict.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/tasks.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/block.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/head.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/metrics.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_058c7585.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_336a71a1.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_59180a0d.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_65c6beb5.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_8c2ae14d.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_97904ece.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_a5880eeb.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_b6d33cf4.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_c57c295b.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_e18ac6a7.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_fb5fd79b.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_fdc99132.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/yaml/_yaml.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/METADATA b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..0ab47b047680ae0434cf9e70e0b9b9e49035cdb4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/METADATA @@ -0,0 +1,1600 @@ +Metadata-Version: 2.4 +Name: tqdm +Version: 4.70.1 +Summary: Fast, Extensible Progress Meter +Maintainer-email: tqdm developers +License: MPL-2.0 AND MIT +Project-URL: homepage, https://tqdm.github.io +Project-URL: repository, https://github.com/tqdm/tqdm +Project-URL: changelog, https://tqdm.github.io/releases +Project-URL: wiki, https://github.com/tqdm/tqdm/wiki +Keywords: progressbar,progressmeter,progress,bar,meter,rate,eta,console,terminal,time +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Environment :: MacOS X +Classifier: Environment :: Other Environment +Classifier: Environment :: Win32 (MS Windows) +Classifier: Environment :: X11 Applications +Classifier: Framework :: IPython +Classifier: Framework :: Jupyter +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: End Users/Desktop +Classifier: Intended Audience :: Other Audience +Classifier: Intended Audience :: System Administrators +Classifier: Operating System :: MacOS +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft +Classifier: Operating System :: Microsoft :: MS-DOS +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX +Classifier: Operating System :: POSIX :: BSD +Classifier: Operating System :: POSIX :: BSD :: FreeBSD +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: POSIX :: SunOS/Solaris +Classifier: Operating System :: Unix +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation +Classifier: Programming Language :: Python :: Implementation :: IronPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Programming Language :: Unix Shell +Classifier: Topic :: Desktop Environment +Classifier: Topic :: Education :: Computer Aided Instruction (CAI) +Classifier: Topic :: Education :: Testing +Classifier: Topic :: Office/Business +Classifier: Topic :: Other/Nonlisted Topic +Classifier: Topic :: Software Development :: Build Tools +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Software Development :: Pre-processors +Classifier: Topic :: Software Development :: User Interfaces +Classifier: Topic :: System :: Installation/Setup +Classifier: Topic :: System :: Logging +Classifier: Topic :: System :: Monitoring +Classifier: Topic :: System :: Shells +Classifier: Topic :: Terminals +Classifier: Topic :: Utilities +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENCE +Requires-Dist: colorama; platform_system == "Windows" +Provides-Extra: discord +Requires-Dist: requests; extra == "discord" +Requires-Dist: envwrap; extra == "discord" +Provides-Extra: slack +Requires-Dist: slack-sdk; extra == "slack" +Requires-Dist: envwrap; extra == "slack" +Provides-Extra: telegram +Requires-Dist: requests; extra == "telegram" +Requires-Dist: envwrap; extra == "telegram" +Provides-Extra: notebook +Requires-Dist: ipywidgets>=6; extra == "notebook" +Dynamic: license-file + +|Logo| + +tqdm +==== + +|Py-Versions| |Versions| |Conda-Forge-Status| |Docker| |Snapcraft| + +|Build-Status| |Coverage-Status| |Branch-Coverage-Status| |Codacy-Grade| |Libraries-Rank| |PyPI-Downloads| + +|LICENCE| |OpenHub-Status| |colab-demo| |binder-demo| |awesome-python| + +``tqdm`` derives from the Arabic word *taqaddum* (تقدّم) which can mean "progress," +and is an abbreviation for "I love you so much" in Spanish (*te quiero demasiado*). + +Instantly make your loops show a smart progress meter - just wrap any +iterable with ``tqdm(iterable)``, and you're done! + +.. code:: python + + from tqdm import tqdm + for i in tqdm(range(10000)): + ... + +``76%|████████████████████████        | 7568/10000 [00:33<00:10, 229.00it/s]`` + +``trange(N)`` can also be used as a convenient shortcut for +``tqdm(range(N))``. + +|Screenshot| + |Video| |Slides| |Merch| + +It can also be executed as a module with pipes: + +.. code:: sh + + $ seq 9999999 | tqdm --bytes | wc -l + 75.2MB [00:00, 217MB/s] + 9999999 + + $ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \ + > backup.tgz + 32%|██████████▍ | 8.89G/27.9G [00:42<01:31, 223MB/s] + +Overhead is low -- about 60ns per iteration (80ns with ``tqdm.gui``), and is +unit tested against performance regression. +By comparison, the well-established +`ProgressBar `__ has +an 800ns/iter overhead. + +In addition to its low overhead, ``tqdm`` uses smart algorithms to predict +the remaining time and to skip unnecessary iteration displays, which allows +for a negligible overhead in most cases. + +``tqdm`` works on any platform +(Linux, Windows, Mac, FreeBSD, NetBSD, Solaris/SunOS), +in any console or in a GUI, and is also friendly with IPython/Jupyter notebooks. + +``tqdm`` does not require any dependencies (not even ``curses``!), just +Python and an environment supporting ``carriage return \r`` and +``line feed \n`` control characters. + +**Featured Sponsors** + +======== ================================================ +|OpenAI| Your Logo Here +======== ================================================ +OpenAI `Sponsors `__ +======== ================================================ + +.. |OpenAI| image:: https://avatars.githubusercontent.com/u/14957082?s=96 + :target: https://openai.com + +------------------------------------------ + +.. contents:: Table of contents + :backlinks: top + :local: + + +Installation +------------ + +Latest PyPI stable release +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +|Versions| |PyPI-Downloads| |Libraries-Dependents| + +.. code:: sh + + pip install tqdm + +Latest development release on GitHub +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +|GitHub-Status| |GitHub-Stars| |GitHub-Commits| |GitHub-Forks| |GitHub-Updated| + +Pull and install pre-release ``devel`` branch: + +.. code:: sh + + pip install "git+https://github.com/tqdm/tqdm.git@devel#egg=tqdm" + +Latest Conda release +~~~~~~~~~~~~~~~~~~~~ + +|Conda-Forge-Status| + +.. code:: sh + + conda install -c conda-forge tqdm + +Latest Snapcraft release +~~~~~~~~~~~~~~~~~~~~~~~~ + +|Snapcraft| + +There are 3 channels to choose from: + +.. code:: sh + + snap install tqdm # implies --stable, i.e. latest tagged release + snap install tqdm --candidate # master branch + snap install tqdm --edge # devel branch + +Note that ``snap`` binaries are purely for CLI use (not ``import``-able), and +automatically set up ``bash`` tab-completion. + +Latest Docker release +~~~~~~~~~~~~~~~~~~~~~ + +|Docker| + +.. code:: sh + + docker pull tqdm/tqdm + docker run -i --rm tqdm/tqdm --help + +Other +~~~~~ + +There are other (unofficial) places where ``tqdm`` may be downloaded, particularly for CLI use: + +|Repology| + +.. |Repology| image:: https://repology.org/badge/tiny-repos/python:tqdm.svg + :target: https://repology.org/project/python:tqdm/versions + +Changelog +--------- + +The list of all changes is available either on GitHub's Releases: +|GitHub-Status|, on the +`wiki `__, or on the +`website `__. + + +Usage +----- + +``tqdm`` is very versatile and can be used in a number of ways. +The three main ones are given below. + +Iterable-based +~~~~~~~~~~~~~~ + +Wrap ``tqdm()`` around any iterable: + +.. code:: python + + from tqdm import tqdm + from time import sleep + + text = "" + for char in tqdm(["a", "b", "c", "d"]): + sleep(0.25) + text = text + char + +``trange(i)`` is a special optimised instance of ``tqdm(range(i))``: + +.. code:: python + + from tqdm import trange + + for i in trange(100): + sleep(0.01) + +Instantiation outside of the loop allows for manual control over ``tqdm()``: + +.. code:: python + + pbar = tqdm(["a", "b", "c", "d"]) + for char in pbar: + sleep(0.25) + pbar.set_description("Processing %s" % char) + +Manual +~~~~~~ + +Manual control of ``tqdm()`` updates using a ``with`` statement: + +.. code:: python + + with tqdm(total=100) as pbar: + for i in range(10): + sleep(0.1) + pbar.update(10) + +If the optional variable ``total`` (or an iterable with ``len()``) is +provided, predictive stats are displayed. + +``with`` is also optional (you can just assign ``tqdm()`` to a variable, +but in this case don't forget to ``del`` or ``close()`` at the end: + +.. code:: python + + pbar = tqdm(total=100) + for i in range(10): + sleep(0.1) + pbar.update(10) + pbar.close() + +Module +~~~~~~ + +Perhaps the most wonderful use of ``tqdm`` is in a script or on the command +line. Simply inserting ``tqdm`` (or ``python -m tqdm``) between pipes will pass +through all ``stdin`` to ``stdout`` while printing progress to ``stderr``. + +The example below demonstrate counting the number of lines in all Python files +in the current directory, with timing information included. + +.. code:: sh + + $ time find . -name '*.py' -type f -exec cat \{} \; | wc -l + 857365 + + real 0m3.458s + user 0m0.274s + sys 0m3.325s + + $ time find . -name '*.py' -type f -exec cat \{} \; | tqdm | wc -l + 857366it [00:03, 246471.31it/s] + 857365 + + real 0m3.585s + user 0m0.862s + sys 0m3.358s + +Note that the usual arguments for ``tqdm`` can also be specified. + +.. code:: sh + + $ find . -name '*.py' -type f -exec cat \{} \; | + tqdm --unit loc --unit_scale --total 857366 >> /dev/null + 100%|█████████████████████████████████| 857K/857K [00:04<00:00, 246Kloc/s] + +Backing up a large directory? + +.. code:: sh + + $ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \ + > backup.tgz + 44%|██████████████▊ | 153M/352M [00:14<00:18, 11.0MB/s] + +This can be beautified further: + +.. code:: sh + + $ BYTES=$(du -sb docs/ | cut -f1) + $ tar -cf - docs/ \ + | tqdm --bytes --total "$BYTES" --desc Processing | gzip \ + | tqdm --bytes --total "$BYTES" --desc Compressed --position 1 \ + > ~/backup.tgz + Processing: 100%|██████████████████████| 352M/352M [00:14<00:00, 30.2MB/s] + Compressed: 42%|█████████▎ | 148M/352M [00:14<00:19, 10.9MB/s] + +Or done on a file level using 7-zip: + +.. code:: sh + + $ 7z a -bd -r backup.7z docs/ | grep Compressing \ + | tqdm --total $(find docs/ -type f | wc -l) --unit files \ + | grep -v Compressing + 100%|██████████████████████████▉| 15327/15327 [01:00<00:00, 712.96files/s] + +Pre-existing CLI programs already outputting basic progress information will +benefit from ``tqdm``'s ``--update`` and ``--update_to`` flags: + +.. code:: sh + + $ seq 3 0.1 5 | tqdm --total 5 --update_to --null + 100%|████████████████████████████████████| 5.0/5 [00:00<00:00, 9673.21it/s] + $ seq 10 | tqdm --update --null # 1 + 2 + ... + 10 = 55 iterations + 55it [00:00, 90006.52it/s] + +FAQ and Known Issues +-------------------- + +|GitHub-Issues| + +The most common issues relate to excessive output on multiple lines, instead +of a neat one-line progress bar. + +- Consoles in general: require support for carriage return (``CR``, ``\r``). + + * Some cloud logging consoles which don't support ``\r`` properly + (`cloudwatch `__, + `K8s `__) may benefit from + ``export TQDM_POSITION=-1``. + +- Nested progress bars: + + * Consoles in general: require support for moving cursors up to the + previous line. For example, + `IDLE `__, + `ConEmu `__ and + `PyCharm `__ (also + `here `__, + `here `__, and + `here `__) + lack full support. + * Windows: additionally may require the Python module ``colorama`` + to ensure nested bars stay within their respective lines. + +- Unicode: + + * Environments which report that they support unicode will have solid smooth + progress bars. The fallback is an ``ascii``-only bar. + * Windows consoles often only partially support unicode and thus + `often require explicit ascii=True `__ + (also `here `__). This is due to + either normal-width unicode characters being incorrectly displayed as + "wide", or some unicode characters not rendering. + +- Wrapping generators: + + * Generator wrapper functions tend to hide the length of iterables. + ``tqdm`` does not. + * Replace ``tqdm(enumerate(...))`` with ``enumerate(tqdm(...))`` or + ``tqdm(enumerate(x), total=len(x), ...)``. + The same applies to ``numpy.ndenumerate``. + * Replace ``tqdm(zip(a, b))`` with ``zip(tqdm(a), b)`` or even + ``zip(tqdm(a), tqdm(b))``. + * The same applies to ``itertools``. + * Some useful convenience functions can be found under ``tqdm.contrib``. + +- `No intermediate output in docker-compose `__: + use ``docker-compose run`` instead of ``docker-compose up`` and ``tty: true``. + +- Overriding defaults via environment variables: + e.g. in CI/cloud jobs, ``export TQDM_MININTERVAL=5`` to avoid log spam. + This override logic is handled by the ``tqdm.utils.envwrap`` decorator + (useful independent of ``tqdm``). + +If you come across any other difficulties, browse and file |GitHub-Issues|. + +Documentation +------------- + +|Py-Versions| |README-Hits| (Since 19 May 2016) + +.. code:: python + + class tqdm(): + """ + Decorate an iterable object, returning an iterator which acts exactly + like the original iterable, but prints a dynamically updating + progress bar every time a value is requested. + """ + + @envwrap("tqdm") # override defaults via env vars + def __init__(self, iterable=None, desc=None, total=None, leave=True, + file=None, ncols=None, mininterval=0.1, + maxinterval=10.0, miniters=None, ascii=None, disable=False, + unit='it', unit_scale=False, dynamic_ncols=False, + smoothing=0.3, bar_format=None, initial=0, position=None, + postfix=None, unit_divisor=1000, write_bytes=False, + lock_args=None, nrows=None, colour=None, delay=0): + +Parameters +~~~~~~~~~~ + +* iterable : iterable, optional + Iterable to decorate with a progress bar. + Leave blank to manually manage the updates. +* desc : str, optional + Prefix for the progress bar. +* total : int or float, optional + The number of expected iterations. If unspecified, + len(iterable) is used if possible. If float("inf") or as a last + resort, only basic progress statistics are displayed + (no ETA, no progress bar). + If ``gui`` is True and this parameter needs subsequent updating, + specify an initial arbitrary large positive number, + e.g. 9e9. +* leave : bool, optional + If [default: True], keeps all traces of the progress bar + upon termination of iteration. + If ``None``, will leave only if ``position`` is ``0``. +* file : ``io.TextIOWrapper`` or ``io.StringIO``, optional + Specifies where to output the progress messages + (default: sys.stderr). Uses ``file.write(str)`` and ``file.flush()`` + methods. For encoding, see ``write_bytes``. +* ncols : int, optional + The width of the entire output message. If specified, + dynamically resizes the progress bar to stay within this bound. + If unspecified, attempts to use environment width. The + fallback is a meter width of 10 and no limit for the counter and + statistics. If 0, will not print any meter (only stats). +* mininterval : float, optional + Minimum progress display update interval [default: 0.1] seconds. +* maxinterval : float, optional + Maximum progress display update interval [default: 10] seconds. + Automatically adjusts ``miniters`` to correspond to ``mininterval`` + after long display update lag. Only works if ``dynamic_miniters`` + or monitor thread is enabled. +* miniters : int or float, optional + Minimum progress display update interval, in iterations. + If 0 and ``dynamic_miniters``, will automatically adjust to equal + ``mininterval`` (more CPU efficient, good for tight loops). + If > 0, will skip display of specified number of iterations. + Tweak this and ``mininterval`` to get very efficient loops. + If your progress is erratic with both fast and slow iterations + (network, skipping items, etc) you should set miniters=1. +* ascii : bool or str, optional + If unspecified or False, use unicode (smooth blocks) to fill + the meter. The fallback is to use ASCII characters " 123456789#". +* disable : bool, optional + Whether to disable the entire progress bar wrapper + [default: False]. If set to None, disable on non-TTY. +* unit : str, optional + String that will be used to define the unit of each iteration + [default: it]. +* unit_scale : bool or int or float, optional + If 1 or True, the number of iterations will be reduced/scaled + automatically and a metric prefix following the + International System of Units standard will be added + (kilo, mega, etc.) [default: False]. If any other non-zero + number, will scale ``total`` and ``n``. +* dynamic_ncols : bool, optional + If set, constantly alters ``ncols`` and ``nrows`` to the + environment (allowing for window resizes) [default: False]. +* smoothing : float, optional + Exponential moving average smoothing factor for speed estimates + (ignored in GUI mode). Ranges from 0 (average speed) to 1 + (current/instantaneous speed) [default: 0.3]. +* bar_format : str, optional + Specify a custom bar string formatting. May impact performance. + [default: '{l_bar}{bar}{r_bar}'], where + l_bar='{desc}: {percentage:3.0f}%|' and + r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ' + '{rate_fmt}{postfix}]' + Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, + percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, + rate, rate_fmt, rate_noinv, rate_noinv_fmt, + rate_inv, rate_inv_fmt, postfix, unit_divisor, + remaining, remaining_s, eta. + Note that a trailing ": " is automatically removed after {desc} + if the latter is empty. +* initial : int or float, optional + The initial counter value. Useful when restarting a progress + bar [default: 0]. If using float, consider specifying ``{n:.3f}`` + or similar in ``bar_format``, or specifying ``unit_scale``. +* position : int, optional + Specify the line offset to print this bar (starting from 0) + Automatic if unspecified. + Useful to manage multiple bars at once (eg, from threads). +* postfix : dict or ``*``, optional + Specify additional stats to display at the end of the bar. + Calls ``set_postfix(**postfix)`` if possible (dict). +* unit_divisor : float, optional + [default: 1000], ignored unless ``unit_scale`` is True. +* write_bytes : bool, optional + Whether to write bytes. If (default: False) will write unicode. +* lock_args : tuple, optional + Passed to ``refresh`` for intermediate output + (initialisation, iterating, and updating). +* nrows : int, optional + The screen height. If specified, hides nested bars outside this + bound. If unspecified, attempts to use environment height. + The fallback is 20. +* colour : str, optional + Bar colour (e.g. 'green', '#00ff00'). +* delay : float, optional + Don't display until [default: 0] seconds have elapsed. + +Extra CLI Options +~~~~~~~~~~~~~~~~~ + +* delim : chr, optional + Delimiting character [default: '\n']. Use '\0' for null. + N.B.: on Windows systems, Python converts '\n' to '\r\n'. +* buf_size : int, optional + String buffer size in bytes [default: 256] + used when ``delim`` is specified. +* bytes : bool, optional + If true, will count bytes, ignore ``delim``, and default + ``unit_scale`` to True, ``unit_divisor`` to 1024, and ``unit`` to 'B'. +* tee : bool, optional + If true, passes ``stdin`` to both ``stderr`` and ``stdout``. +* update : bool, optional + If true, will treat input as newly elapsed iterations, + i.e. numbers to pass to ``update()``. Note that this is slow + (~2e5 it/s) since every input must be decoded as a number. +* update_to : bool, optional + If true, will treat input as total elapsed iterations, + i.e. numbers to assign to ``self.n``. Note that this is slow + (~2e5 it/s) since every input must be decoded as a number. +* null : bool, optional + If true, will discard input (no stdout). +* manpath : str, optional + Directory in which to install tqdm man pages. +* comppath : str, optional + Directory in which to place tqdm completion. +* log : str, optional + CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET. + +Returns +~~~~~~~ + +* out : decorated iterator. + +.. code:: python + + class tqdm(): + def update(self, n=1): + """ + Manually update the progress bar, useful for streams + such as reading files. + E.g.: + >>> t = tqdm(total=filesize) # Initialise + >>> for current_buffer in stream: + ... ... + ... t.update(len(current_buffer)) + >>> t.close() + The last line is highly recommended, but possibly not necessary if + `t.update()` will be called in such a way that `filesize` will be + exactly reached and printed. + + Parameters + ---------- + n : int or float, optional + Increment to add to the internal counter of iterations + [default: 1]. If using float, consider specifying `{n:.3f}` + or similar in `bar_format`, or specifying `unit_scale`. + + Returns + ------- + out : bool or None + True if a `display()` was triggered. + """ + + def close(self): + """Cleanup and (if leave=False) close the progress bar.""" + + def clear(self, nomove=False): + """Clear current bar display.""" + + def refresh(self): + """ + Force refresh the display of this bar. + + Parameters + ---------- + nolock : bool, optional + If `True`, does not lock. + If [default: `False`]: calls `acquire()` on internal lock. + lock_args : tuple, optional + Passed to internal lock's `acquire()`. + If specified, will only `display()` if `acquire()` returns `True`. + """ + + def unpause(self): + """Restart tqdm timer from last print time.""" + + def reset(self, total=None): + """ + Resets to 0 iterations for repeated use. + + Consider combining with `leave=True`. + + Parameters + ---------- + total : int or float, optional. Total to use for the new bar. + """ + + def set_description(self, desc=None, refresh=True): + """ + Set/modify description of the progress bar. + + Parameters + ---------- + desc : str, optional + refresh : bool, optional + Forces refresh [default: True]. + """ + + def set_postfix(self, ordered_dict=None, refresh=True, **tqdm_kwargs): + """ + Set/modify postfix (additional stats) + with automatic formatting based on datatype. + + Parameters + ---------- + ordered_dict : dict or OrderedDict, optional + refresh : bool, optional + Forces refresh [default: True]. + kwargs : dict, optional + """ + + @classmethod + def write(cls, s, file=sys.stdout, end="\n"): + """Print a message via tqdm (without overlap with bars).""" + + @property + def format_dict(self): + """Public API for read-only member access.""" + + def display(self, msg=None, pos=None): + """ + Use `self.sp` to display `msg` in the specified `pos`. + + Consider overloading this function when inheriting to use e.g.: + `self.some_frontend(**self.format_dict)` instead of `self.sp`. + + Parameters + ---------- + msg : str, optional. What to display (default: `repr(self)`). + pos : int, optional. Position to `moveto` + (default: `abs(self.pos)`). + """ + + @classmethod + @contextmanager + def wrapattr(cls, stream, method, total=None, bytes=True, **tqdm_kwargs): + """ + stream : file-like object. + method : str, "read" or "write". The result of `read()` and + the first argument of `write()` should have a `len()`. + + >>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj: + ... while True: + ... chunk = fobj.read(chunk_size) + ... if not chunk: + ... break + """ + + @classmethod + def pandas(cls, *targs, **tqdm_kwargs): + """Registers the current `tqdm` class with `pandas`.""" + + def trange(*args, **tqdm_kwargs): + """Shortcut for `tqdm(range(*args), **tqdm_kwargs)`.""" + +Convenience Functions +~~~~~~~~~~~~~~~~~~~~~ + +.. code:: python + + def tqdm.contrib.tenumerate(iterable, start=0, total=None, + tqdm_class=tqdm.auto.tqdm, **tqdm_kwargs): + """Equivalent of `numpy.ndenumerate` or builtin `enumerate`.""" + + def tqdm.contrib.tzip(iter1, *iter2plus, **tqdm_kwargs): + """Equivalent of builtin `zip`.""" + + def tqdm.contrib.tmap(function, *sequences, **tqdm_kwargs): + """Equivalent of builtin `map`.""" + +Submodules +~~~~~~~~~~ + +.. code:: python + + class tqdm.notebook.tqdm(tqdm.tqdm): + """IPython/Jupyter Notebook widget.""" + + class tqdm.auto.tqdm(tqdm.tqdm): + """Automatically chooses between `tqdm.notebook` and `tqdm.tqdm`.""" + + class tqdm.asyncio.tqdm(tqdm.tqdm): + """Asynchronous version.""" + @classmethod + def as_completed(cls, fs, *, loop=None, timeout=None, total=None, + **tqdm_kwargs): + """Wrapper for `asyncio.as_completed`.""" + + class tqdm.gui.tqdm(tqdm.tqdm): + """Matplotlib GUI version.""" + + class tqdm.tk.tqdm(tqdm.tqdm): + """Tkinter GUI version.""" + + class tqdm.rich.tqdm(tqdm.tqdm): + """`rich.progress` version.""" + + class tqdm.keras.TqdmCallback(keras.callbacks.Callback): + """Keras callback for epoch and batch progress.""" + + class tqdm.dask.TqdmCallback(dask.callbacks.Callback): + """Dask callback for task progress.""" + + +``contrib`` ++++++++++++ + +The ``tqdm.contrib`` package also contains experimental modules: + +- `tqdm.contrib.itertools `_: Thin wrappers around ``itertools`` +- `tqdm.contrib.concurrent `_: Thin wrappers around ``concurrent.futures`` +- `tqdm.contrib.slack `_: Posts to `Slack `__ bots +- `tqdm.contrib.discord `_: Posts to `Discord `__ bots +- `tqdm.contrib.telegram `_: Posts to `Telegram `__ bots +- `tqdm.contrib.bells `_: Automagically enables all optional features + + * ``auto``, ``pandas``, ``slack``, ``discord``, ``telegram`` + +.. image:: https://tqdm.github.io/img/screenshot-discord.png + :alt: Screenshot of `tqdm.contrib.discord` in action + +Examples and Advanced Usage +--------------------------- + +- See the `examples `__ + folder; +- import the module and run ``help()``; +- consult the `wiki `__; + + * this has an + `excellent article `__ + on how to make a **great** progress bar; + +- check out the `slides from PyData London `__, or +- run the |binder-demo|. + +Description and additional stats +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Custom information can be displayed and updated dynamically on ``tqdm`` bars +with the ``desc`` and ``postfix`` arguments: + +.. code:: python + + from tqdm import tqdm, trange + from random import random, randint + from time import sleep + + with trange(10) as t: + for i in t: + # Description will be displayed on the left + t.set_description('GEN %i' % i) + # Postfix will be displayed on the right, + # formatted automatically based on argument's datatype + t.set_postfix(loss=random(), gen=randint(1,999), str='h', + lst=[1, 2]) + sleep(0.1) + + with tqdm(total=10, bar_format="{postfix[0]} {postfix[1][value]:>8.2g}", + postfix=["Batch", {"value": 0}]) as t: + for i in range(10): + sleep(0.1) + t.postfix[1]["value"] = i / 2 + t.update() + +Points to remember when using ``{postfix[...]}`` in the ``bar_format`` string: + +- ``postfix`` also needs to be passed as an initial argument in a compatible + format, and +- ``postfix`` will be auto-converted to a string if it is a ``dict``-like + object. To prevent this behaviour, insert an extra item into the dictionary + where the key is not a string. + +Additional ``bar_format`` parameters may also be defined by overriding +``format_dict``, and the bar itself may be modified using ``ascii``: + +.. code:: python + + from tqdm import tqdm + class TqdmExtraFormat(tqdm): + """Provides a `total_time` format parameter""" + @property + def format_dict(self): + d = super().format_dict + total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1) + d.update(total_time=self.format_interval(total_time) + " in total") + return d + + for i in TqdmExtraFormat( + range(9), ascii=" .oO0", + bar_format="{total_time}: {percentage:.0f}%|{bar}{r_bar}"): + if i == 4: + break + +.. code:: + + 00:00 in total: 44%|0000. | 4/9 [00:00<00:00, 962.93it/s] + +Note that ``{bar}`` also supports a format specifier ``[width][type]``. + +- ``width`` + + * unspecified (default): automatic to fill ``ncols`` + * ``int >= 0``: fixed width overriding ``ncols`` logic + * ``int < 0``: subtract from the automatic default + +- ``type`` + + * ``a``: ascii (``ascii=True`` override) + * ``u``: unicode (``ascii=False`` override) + * ``b``: blank (``ascii=" "`` override) + +This means a fixed bar with right-justified text may be created by using: +``bar_format="{l_bar}{bar:10}|{bar:-10b}right-justified"`` + +Nested progress bars +~~~~~~~~~~~~~~~~~~~~ + +``tqdm`` supports nested progress bars. Here's an example: + +.. code:: python + + from tqdm.auto import trange + from time import sleep + + for i in trange(4, desc='1st loop'): + for j in trange(5, desc='2nd loop'): + for k in trange(50, desc='3rd loop', leave=False): + sleep(0.01) + +For manual control over positioning (e.g. for multi-processing use), +you may specify ``position=n`` where ``n=0`` for the outermost bar, +``n=1`` for the next, and so on. +However, it's best to check if ``tqdm`` can work without manual ``position`` +first. + +.. code:: python + + from time import sleep + from tqdm import trange, tqdm + from multiprocessing import Pool, RLock, freeze_support + + L = list(range(9)) + + def progresser(n): + interval = 0.001 / (n + 2) + total = 5000 + text = f"#{n}, est. {interval * total:<04.2}s" + for _ in trange(total, desc=text, position=n): + sleep(interval) + + if __name__ == '__main__': + freeze_support() # for Windows support + tqdm.set_lock(RLock()) # for managing output contention + p = Pool(initializer=tqdm.set_lock, initargs=(tqdm.get_lock(),)) + p.map(progresser, L) + +Note that in Python 3, ``tqdm.write`` is thread-safe: + +.. code:: python + + from time import sleep + from tqdm import tqdm, trange + from concurrent.futures import ThreadPoolExecutor + + L = list(range(9)) + + def progresser(n): + interval = 0.001 / (n + 2) + total = 5000 + text = f"#{n}, est. {interval * total:<04.2}s" + for _ in trange(total, desc=text): + sleep(interval) + if n == 6: + tqdm.write("n == 6 completed.") + tqdm.write("`tqdm.write()` is thread-safe in py3!") + + if __name__ == '__main__': + with ThreadPoolExecutor() as p: + p.map(progresser, L) + +Hooks and callbacks +~~~~~~~~~~~~~~~~~~~ + +``tqdm`` can easily support callbacks/hooks and manual updates. +Here's an example with ``urllib``: + +**``urllib.urlretrieve`` documentation** + + | [...] + | If present, the hook function will be called once + | on establishment of the network connection and once after each block read + | thereafter. The hook will be passed three arguments; a count of blocks + | transferred so far, a block size in bytes, and the total size of the file. + | [...] + +.. code:: python + + import urllib, os + from tqdm import tqdm + urllib = getattr(urllib, 'request', urllib) + + class TqdmUpTo(tqdm): + """Provides `update_to(n)` which uses `tqdm.update(delta_n)`.""" + def update_to(self, b=1, bsize=1, tsize=None): + """ + b : int, optional + Number of blocks transferred so far [default: 1]. + bsize : int, optional + Size of each block (in tqdm units) [default: 1]. + tsize : int, optional + Total size (in tqdm units). If [default: None] remains unchanged. + """ + if tsize is not None: + self.total = tsize + return self.update(b * bsize - self.n) # also sets self.n = b * bsize + + eg_link = "https://cgi.cdcl.ml/matryoshka.zip" + with TqdmUpTo(unit='B', unit_scale=True, unit_divisor=1024, miniters=1, + desc=eg_link.split('/')[-1]) as t: # all optional kwargs + urllib.urlretrieve(eg_link, filename=os.devnull, + reporthook=t.update_to, data=None) + t.total = t.n + +Inspired by `twine#242 `__. +Functional alternative in +`examples/tqdm_wget.py `__. + +It is recommend to use ``miniters=1`` whenever there is potentially +large differences in iteration speed (e.g. downloading a file over +a patchy connection). + +**Wrapping read/write methods** + +To measure throughput through a file-like object's ``read`` or ``write`` +methods, use ``CallbackIOWrapper``: + +.. code:: python + + from tqdm.auto import tqdm + from tqdm.utils import CallbackIOWrapper + + with tqdm(total=file_obj.size, + unit='B', unit_scale=True, unit_divisor=1024) as t: + fobj = CallbackIOWrapper(t.update, file_obj, "read") + while True: + chunk = fobj.read(chunk_size) + if not chunk: + break + t.reset() + # ... continue to use `t` for something else + +Alternatively, use the even simpler ``wrapattr`` convenience function, +which would condense both the ``urllib`` and ``CallbackIOWrapper`` examples +down to: + +.. code:: python + + import urllib, os + from tqdm import tqdm + + eg_link = "https://cgi.cdcl.ml/matryoshka.zip" + response = getattr(urllib, 'request', urllib).urlopen(eg_link) + with tqdm.wrapattr(open(os.devnull, "wb"), "write", + miniters=1, desc=eg_link.split('/')[-1], + total=getattr(response, 'length', None)) as fout: + for chunk in response: + fout.write(chunk) + +The ``requests`` equivalent is nearly identical: + +.. code:: python + + import requests, os + from tqdm import tqdm + + eg_link = "https://cgi.cdcl.ml/matryoshka.zip" + response = requests.get(eg_link, stream=True) + with tqdm.wrapattr(open(os.devnull, "wb"), "write", + miniters=1, desc=eg_link.split('/')[-1], + total=int(response.headers.get('content-length', 0))) as fout: + for chunk in response.iter_content(chunk_size=4096): + fout.write(chunk) + +**Custom callback** + +``tqdm`` is known for intelligently skipping unnecessary displays. To make a +custom callback take advantage of this, simply use the return value of +``update()``. This is set to ``True`` if a ``display()`` was triggered. + +.. code:: python + + from tqdm.auto import tqdm as std_tqdm + + def external_callback(*args, **kwargs): + ... + + class TqdmExt(std_tqdm): + def update(self, n=1): + displayed = super().update(n) + if displayed: + external_callback(**self.format_dict) + return displayed + +``asyncio`` +~~~~~~~~~~~ + +Note that ``break`` isn't currently caught by asynchronous iterators. +This means that ``tqdm`` cannot clean up after itself in this case: + +.. code:: python + + from tqdm.asyncio import tqdm + + async for i in tqdm(range(9)): + if i == 2: + break + +Instead, either call ``pbar.close()`` manually or use the context manager syntax: + +.. code:: python + + from tqdm.asyncio import tqdm + + with tqdm(range(9)) as pbar: + async for i in pbar: + if i == 2: + break + +Pandas Integration +~~~~~~~~~~~~~~~~~~ + +Due to popular demand we've added support for ``pandas`` -- here's an example +for ``DataFrame.progress_apply`` and ``DataFrameGroupBy.progress_apply``: + +.. code:: python + + import pandas as pd + import numpy as np + from tqdm import tqdm + + df = pd.DataFrame(np.random.randint(0, 100, (100000, 6))) + + # Register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm` + # (can use `tqdm.gui.tqdm`, `tqdm.notebook.tqdm`, optional kwargs, etc.) + tqdm.pandas(desc="my bar!") + + # Now you can use `progress_apply` instead of `apply` + # and `progress_map` instead of `map` + df.progress_apply(lambda x: x**2) + # can also groupby: + # df.groupby(0).progress_apply(lambda x: x**2) + +In case you're interested in how this works (and how to modify it for your +own callbacks), see the +`examples `__ +folder or import the module and run ``help()``. + +Keras Integration +~~~~~~~~~~~~~~~~~ + +A ``keras`` callback is also available: + +.. code:: python + + from tqdm.keras import TqdmCallback + + ... + + model.fit(..., verbose=0, callbacks=[TqdmCallback()]) + +Dask Integration +~~~~~~~~~~~~~~~~ + +A ``dask`` callback is also available: + +.. code:: python + + from tqdm.dask import TqdmCallback + + with TqdmCallback(desc="compute"): + ... + arr.compute() + + # or use callback globally + cb = TqdmCallback(desc="global") + cb.register() + arr.compute() + +IPython/Jupyter Integration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +IPython/Jupyter is supported via the ``tqdm.notebook`` submodule: + +.. code:: python + + from tqdm.notebook import trange, tqdm + from time import sleep + + for i in trange(3, desc='1st loop'): + for j in tqdm(range(100), desc='2nd loop'): + sleep(0.01) + +In addition to ``tqdm`` features, the submodule provides a native Jupyter +widget (compatible with IPython v1-v4 and Jupyter), fully working nested bars +and colour hints (blue: normal, green: completed, red: error/interrupt, +light blue: no ETA); as demonstrated below. + +|Screenshot-Jupyter1| +|Screenshot-Jupyter2| +|Screenshot-Jupyter3| + +The ``notebook`` version supports percentage or pixels for overall width +(e.g.: ``ncols='100%'`` or ``ncols='480px'``). + +It is also possible to let ``tqdm`` automatically choose between +console or notebook versions by using the ``autonotebook`` submodule: + +.. code:: python + + from tqdm.autonotebook import tqdm + tqdm.pandas() + +Note that this will issue a ``TqdmExperimentalWarning`` if run in a notebook +since it is not meant to be possible to distinguish between ``jupyter notebook`` +and ``jupyter console``. Use ``auto`` instead of ``autonotebook`` to suppress +this warning. + +Note that notebooks will display the bar in the cell where it was created. +This may be a different cell from the one where it is used. +If this is not desired, either + +- delay the creation of the bar to the cell where it must be displayed, or +- create the bar with ``display=False``, and in a later cell call + ``display(bar.container)``: + +.. code:: python + + from tqdm.notebook import tqdm + pbar = tqdm(..., display=False) + +.. code:: python + + # different cell + display(pbar.container) + +The ``keras`` callback has a ``display()`` method which can be used likewise: + +.. code:: python + + from tqdm.keras import TqdmCallback + cbk = TqdmCallback(display=False) + +.. code:: python + + # different cell + cbk.display() + model.fit(..., verbose=0, callbacks=[cbk]) + +Another possibility is to have a single bar (near the top of the notebook) +which is constantly re-used (using ``reset()`` rather than ``close()``). +For this reason, the notebook version (unlike the CLI version) does not +automatically call ``close()`` upon ``Exception``. + +.. code:: python + + from tqdm.notebook import tqdm + pbar = tqdm() + +.. code:: python + + # different cell + iterable = range(100) + pbar.reset(total=len(iterable)) # initialise with new `total` + for i in iterable: + pbar.update() + pbar.refresh() # force print final status but don't `close()` + +Custom Integration +~~~~~~~~~~~~~~~~~~ + +To change the default arguments (such as making ``dynamic_ncols=True``), +simply use built-in Python magic: + +.. code:: python + + from functools import partial + from tqdm import tqdm as std_tqdm + tqdm = partial(std_tqdm, dynamic_ncols=True) + +For further customisation, +``tqdm`` may be inherited from to create custom callbacks (as with the +``TqdmUpTo`` example `above <#hooks-and-callbacks>`__) or for custom frontends +(e.g. GUIs such as notebook or plotting packages). In the latter case: + +1. ``def __init__()`` to call ``super().__init__(..., gui=True)`` to disable + terminal ``status_printer`` creation. +2. Redefine: ``close()``, ``clear()``, ``display()``. + +Consider overloading ``display()`` to use e.g. +``self.frontend(**self.format_dict)`` instead of ``self.sp(repr(self))``. + +Some submodule examples of inheritance: + +- `tqdm/notebook.py `__ +- `tqdm/gui.py `__ +- `tqdm/tk.py `__ +- `tqdm/contrib/slack.py `__ +- `tqdm/contrib/discord.py `__ +- `tqdm/contrib/telegram.py `__ + +Dynamic Monitor/Meter +~~~~~~~~~~~~~~~~~~~~~ + +You can use a ``tqdm`` as a meter which is not monotonically increasing. +This could be because ``n`` decreases (e.g. a CPU usage monitor) or ``total`` +changes. + +One example would be recursively searching for files. The ``total`` is the +number of objects found so far, while ``n`` is the number of those objects which +are files (rather than folders): + +.. code:: python + + from tqdm import tqdm + import os.path + + def find_files_recursively(path, show_progress=True): + files = [] + # total=1 assumes `path` is a file + t = tqdm(total=1, unit="file", disable=not show_progress) + if not os.path.exists(path): + raise IOError("Cannot find:" + path) + + def append_found_file(f): + files.append(f) + t.update() + + def list_found_dir(path): + """returns os.listdir(path) assuming os.path.isdir(path)""" + listing = os.listdir(path) + # subtract 1 since a "file" we found was actually this directory + t.total += len(listing) - 1 + # fancy way to give info without forcing a refresh + t.set_postfix(dir=path[-10:], refresh=False) + t.update(0) # may trigger a refresh + return listing + + def recursively_search(path): + if os.path.isdir(path): + for f in list_found_dir(path): + recursively_search(os.path.join(path, f)) + else: + append_found_file(path) + + recursively_search(path) + t.set_postfix(dir=path) + t.close() + return files + +Using ``update(0)`` is a handy way to let ``tqdm`` decide when to trigger a +display refresh to avoid console spamming. + +Writing messages +~~~~~~~~~~~~~~~~ + +This is a work in progress (see +`#737 `__). + +Since ``tqdm`` uses a simple printing mechanism to display progress bars, +you should not write any message in the terminal using ``print()`` while +a progress bar is open. + +To write messages in the terminal without any collision with ``tqdm`` bar +display, a ``.write()`` method is provided: + +.. code:: python + + from tqdm.auto import tqdm, trange + from time import sleep + + bar = trange(10) + for i in bar: + # Print using tqdm class method .write() + sleep(0.1) + if not (i % 3): + tqdm.write("Done task %i" % i) + # Can also use bar.write() + +By default, this will print to standard output ``sys.stdout``. but you can +specify any file-like object using the ``file`` argument. For example, this +can be used to redirect the messages writing to a log file or class. + +Redirecting writing +~~~~~~~~~~~~~~~~~~~ + +If using a library that can print messages to the console, editing the library +by replacing ``print()`` with ``tqdm.write()`` may not be desirable. +In that case, redirecting ``sys.stdout`` to ``tqdm.write()`` is an option. + +To redirect ``sys.stdout``, create a file-like class that will write +any input string to ``tqdm.write()``, and supply the arguments +``file=sys.stdout, dynamic_ncols=True``. + +A reusable canonical example is given below: + +.. code:: python + + from time import sleep + import contextlib + import sys + from tqdm import tqdm + from tqdm.contrib import DummyTqdmFile + + + @contextlib.contextmanager + def std_out_err_redirect_tqdm(): + orig_out_err = sys.stdout, sys.stderr + try: + sys.stdout, sys.stderr = map(DummyTqdmFile, orig_out_err) + yield orig_out_err[0] + # Relay exceptions + except Exception as exc: + raise exc + # Always restore sys.stdout/err if necessary + finally: + sys.stdout, sys.stderr = orig_out_err + + def some_fun(i): + print("Fee, fi, fo,".split()[i]) + + # Redirect stdout to tqdm.write() (don't forget the `as save_stdout`) + with std_out_err_redirect_tqdm() as orig_stdout: + # tqdm needs the original stdout + # and dynamic_ncols=True to autodetect console width + for i in tqdm(range(3), file=orig_stdout, dynamic_ncols=True): + sleep(.5) + some_fun(i) + + # After the `with`, printing is restored + print("Done!") + +Redirecting ``logging`` +~~~~~~~~~~~~~~~~~~~~~~~ + +Similar to ``sys.stdout``/``sys.stderr`` as detailed above, console ``logging`` +may also be redirected to ``tqdm.write()``. + +Warning: if also redirecting ``sys.stdout``/``sys.stderr``, make sure to +redirect ``logging`` first if needed. + +Helper methods are available in ``tqdm.contrib.logging``. For example: + +.. code:: python + + import logging + from tqdm import trange + from tqdm.contrib.logging import logging_redirect_tqdm + + LOG = logging.getLogger(__name__) + + if __name__ == '__main__': + logging.basicConfig(level=logging.INFO) + with logging_redirect_tqdm(): + for i in trange(9): + if i == 4: + LOG.info("console logging redirected to `tqdm.write()`") + # logging restored + +Monitoring thread, intervals and miniters +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``tqdm`` implements a few tricks to increase efficiency and reduce overhead. + +- Avoid unnecessary frequent bar refreshing: ``mininterval`` defines how long + to wait between each refresh. ``tqdm`` always gets updated in the background, + but it will display only every ``mininterval``. +- Reduce number of calls to check system clock/time. +- ``mininterval`` is more intuitive to configure than ``miniters``. + A clever adjustment system ``dynamic_miniters`` will automatically adjust + ``miniters`` to the amount of iterations that fit into time ``mininterval``. + Essentially, ``tqdm`` will check if it's time to print without actually + checking time. This behaviour can be still be bypassed by manually setting + ``miniters``. + +However, consider a case with a combination of fast and slow iterations. +After a few fast iterations, ``dynamic_miniters`` will set ``miniters`` to a +large number. When iteration rate subsequently slows, ``miniters`` will +remain large and thus reduce display update frequency. To address this: + +- ``maxinterval`` defines the maximum time between display refreshes. + A concurrent monitoring thread checks for overdue updates and forces one + where necessary. + +The monitoring thread should not have a noticeable overhead, and guarantees +updates at least every 10 seconds by default. +This value can be directly changed by setting the ``monitor_interval`` of +any ``tqdm`` instance (i.e. ``t = tqdm.tqdm(...); t.monitor_interval = 2``). +The monitor thread may be disabled application-wide by setting +``tqdm.tqdm.monitor_interval = 0`` before instantiation of any ``tqdm`` bar. + + +Merch +----- + +You can buy `tqdm branded merch `__ now! + +Contributions +------------- + +|GitHub-Commits| |GitHub-Issues| |GitHub-PRs| |OpenHub-Status| |GitHub-Contributions| |CII Best Practices| + +All source code is hosted on `GitHub `__. +Contributions are welcome. + +See the +`CONTRIBUTING `__ +file for more information. + +Developers who have contributed more that 5 *loc* (surviving lines of code): + +|git-fame| + +Honourable mentions: + +- Casper da Costa-Luis `casperdcl `__ primary maintainer |Gift-Casper| +- Stephen Larroque `lrq3000 `__ maintainer +- Hadrien Mary `hadim `__ maintainer +- Mikhail Korobov `kmike `__ maintainer +- Noam Yorav-Raphael `noamraph `__ original author + +Ports to Other Languages +~~~~~~~~~~~~~~~~~~~~~~~~ + +A list is available on +`this wiki page `__. + + +LICENCE +------- + +Open Source (OSI approved): |LICENCE| + +Citation information: |DOI| + +|README-Hits| (Since 19 May 2016) + +.. |Logo| image:: https://tqdm.github.io/img/logo.gif +.. |Screenshot| image:: https://tqdm.github.io/img/tqdm.gif +.. |Video| image:: https://tqdm.github.io/img/video.jpg + :target: https://tqdm.github.io/video +.. |Slides| image:: https://tqdm.github.io/img/slides.jpg + :target: https://tqdm.github.io/PyData2019/slides.html +.. |Merch| image:: https://tqdm.github.io/img/merch.jpg + :target: https://tqdm.github.io/merch +.. |Build-Status| image:: https://img.shields.io/github/actions/workflow/status/tqdm/tqdm/test.yml?branch=master&label=tqdm&logo=GitHub + :target: https://github.com/tqdm/tqdm/actions/workflows/test.yml +.. |Coverage-Status| image:: https://img.shields.io/coveralls/github/tqdm/tqdm/master?logo=coveralls + :target: https://coveralls.io/github/tqdm/tqdm +.. |Branch-Coverage-Status| image:: https://codecov.io/gh/tqdm/tqdm/branch/master/graph/badge.svg + :target: https://codecov.io/gh/tqdm/tqdm +.. |Codacy-Grade| image:: https://app.codacy.com/project/badge/Grade/3f965571598f44549c7818f29cdcf177 + :target: https://app.codacy.com/gh/tqdm/tqdm/dashboard +.. |CII Best Practices| image:: https://bestpractices.coreinfrastructure.org/projects/3264/badge + :target: https://bestpractices.coreinfrastructure.org/projects/3264 +.. |GitHub-Status| image:: https://img.shields.io/github/tag/tqdm/tqdm.svg?maxAge=86400&logo=github&logoColor=white + :target: https://github.com/tqdm/tqdm/releases +.. |GitHub-Forks| image:: https://img.shields.io/github/forks/tqdm/tqdm.svg?logo=github&logoColor=white + :target: https://github.com/tqdm/tqdm/network +.. |GitHub-Stars| image:: https://img.shields.io/github/stars/tqdm/tqdm.svg?logo=github&logoColor=white + :target: https://github.com/tqdm/tqdm/stargazers +.. |GitHub-Commits| image:: https://img.shields.io/github/commit-activity/y/tqdm/tqdm.svg?logo=git&logoColor=white + :target: https://github.com/tqdm/tqdm/graphs/commit-activity +.. |GitHub-Issues| image:: https://img.shields.io/github/issues-closed/tqdm/tqdm.svg?logo=github&logoColor=white + :target: https://github.com/tqdm/tqdm/issues?q= +.. |GitHub-PRs| image:: https://img.shields.io/github/issues-pr-closed/tqdm/tqdm.svg?logo=github&logoColor=white + :target: https://github.com/tqdm/tqdm/pulls +.. |GitHub-Contributions| image:: https://img.shields.io/github/contributors/tqdm/tqdm.svg?logo=github&logoColor=white + :target: https://github.com/tqdm/tqdm/graphs/contributors +.. |GitHub-Updated| image:: https://img.shields.io/github/last-commit/tqdm/tqdm/master.svg?logo=github&logoColor=white&label=pushed + :target: https://github.com/tqdm/tqdm/pulse +.. |git-fame| image:: https://git-fame.cdcl.ml/gh/tqdm/tqdm?min=5&w=1&M=1&C=1&excl=(png|gif|jpg)$&enum=1&auth=share + :alt: git-fame.cdcl.ml/gh/tqdm/tqdm + :target: https://git-fame.cdcl.ml/gh/tqdm/tqdm?w=1&M=1&C=1&excl=(png|gif|jpg)$&enum=1&auth=share +.. |Gift-Casper| image:: https://img.shields.io/badge/sponsor-casper-ff69b4.svg + :target: https://cdcl.ml/sponsor +.. |Versions| image:: https://img.shields.io/pypi/v/tqdm.svg + :target: https://tqdm.github.io/releases +.. |PyPI-Downloads| image:: https://static.pepy.tech/personalized-badge/tqdm?left_text=downloads%2Fmonth + :target: https://pepy.tech/project/tqdm +.. |Py-Versions| image:: https://img.shields.io/pypi/pyversions/tqdm.svg?logo=python&logoColor=white + :target: https://pypi.org/project/tqdm +.. |Conda-Forge-Status| image:: https://img.shields.io/conda/v/conda-forge/tqdm.svg?label=conda-forge&logo=conda-forge + :target: https://anaconda.org/conda-forge/tqdm +.. |Snapcraft| image:: https://img.shields.io/badge/snap-install-82BEA0.svg?logo=snapcraft + :target: https://snapcraft.io/tqdm +.. |Docker| image:: https://img.shields.io/badge/docker-pull-blue.svg?logo=docker&logoColor=white + :target: https://hub.docker.com/r/tqdm/tqdm +.. |Libraries-Rank| image:: https://img.shields.io/librariesio/sourcerank/pypi/tqdm.svg?logo=koding&logoColor=white + :target: https://libraries.io/pypi/tqdm +.. |Libraries-Dependents| image:: https://img.shields.io/librariesio/dependent-repos/pypi/tqdm.svg?logo=koding&logoColor=white + :target: https://github.com/tqdm/tqdm/network/dependents +.. |OpenHub-Status| image:: https://www.openhub.net/p/tqdm/widgets/project_thin_badge?format=gif + :target: https://www.openhub.net/p/tqdm?ref=Thin+badge +.. |awesome-python| image:: https://awesome.re/mentioned-badge.svg + :target: https://github.com/vinta/awesome-python +.. |LICENCE| image:: https://img.shields.io/pypi/l/tqdm.svg + :target: https://raw.githubusercontent.com/tqdm/tqdm/master/LICENCE +.. |DOI| image:: https://img.shields.io/badge/DOI-10.5281/zenodo.595120-blue.svg + :target: https://doi.org/10.5281/zenodo.595120 +.. |colab-demo| image:: https://colab.research.google.com/assets/colab-badge.svg + :target: https://colab.research.google.com/github/tqdm/tqdm/blob/master/DEMO.ipynb +.. |binder-demo| image:: https://mybinder.org/badge_logo.svg + :target: https://mybinder.org/v2/gh/tqdm/tqdm/master?filepath=DEMO.ipynb +.. |Screenshot-Jupyter1| image:: https://tqdm.github.io/img/jupyter-1.gif +.. |Screenshot-Jupyter2| image:: https://tqdm.github.io/img/jupyter-2.gif +.. |Screenshot-Jupyter3| image:: https://tqdm.github.io/img/jupyter-3.gif +.. |README-Hits| image:: https://cgi.cdcl.ml/hits?q=tqdm&style=social&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif + :target: https://cgi.cdcl.ml/hits?q=tqdm&a=plot&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif&style=social diff --git a/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/RECORD b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..4ca70d8585109b1032925b636b153b4193109c24 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/RECORD @@ -0,0 +1,73 @@ +../../../bin/tqdm,sha256=rucCCUVlHdONB1hjTa3oLODsVh0RL7FXaqThv5xyjHU,239 +tqdm-4.70.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tqdm-4.70.1.dist-info/METADATA,sha256=pdpwuWav6jp1lxYEG61xh_Ls4CwiNIz558ClErvxX1c,57366 +tqdm-4.70.1.dist-info/RECORD,, +tqdm-4.70.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tqdm-4.70.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91 +tqdm-4.70.1.dist-info/entry_points.txt,sha256=ReJCH7Ui3Zyh6M16E4OhsZ1oU7WtMXCfbtoyBhGO29Y,39 +tqdm-4.70.1.dist-info/licenses/LICENCE,sha256=_P-Hw6R86AKKhRKqGC1PzwrRyQVE7nXPmzQ2hMrBlN4,1985 +tqdm-4.70.1.dist-info/top_level.txt,sha256=NLiUJNfmc9At15s7JURiwvqMEjUi9G5PMGRrmMYzNSM,5 +tqdm/__init__.py,sha256=9mQNYSSqP99JasubEC1POJLMmhkkBH6cJZxPIR5G2pQ,1572 +tqdm/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30 +tqdm/__pycache__/__init__.cpython-312.pyc,, +tqdm/__pycache__/__main__.cpython-312.pyc,, +tqdm/__pycache__/_main.cpython-312.pyc,, +tqdm/__pycache__/_monitor.cpython-312.pyc,, +tqdm/__pycache__/_tqdm.cpython-312.pyc,, +tqdm/__pycache__/_tqdm_gui.cpython-312.pyc,, +tqdm/__pycache__/_tqdm_notebook.cpython-312.pyc,, +tqdm/__pycache__/_tqdm_pandas.cpython-312.pyc,, +tqdm/__pycache__/_utils.cpython-312.pyc,, +tqdm/__pycache__/asyncio.cpython-312.pyc,, +tqdm/__pycache__/auto.cpython-312.pyc,, +tqdm/__pycache__/autonotebook.cpython-312.pyc,, +tqdm/__pycache__/cli.cpython-312.pyc,, +tqdm/__pycache__/dask.cpython-312.pyc,, +tqdm/__pycache__/gui.cpython-312.pyc,, +tqdm/__pycache__/keras.cpython-312.pyc,, +tqdm/__pycache__/notebook.cpython-312.pyc,, +tqdm/__pycache__/rich.cpython-312.pyc,, +tqdm/__pycache__/std.cpython-312.pyc,, +tqdm/__pycache__/tk.cpython-312.pyc,, +tqdm/__pycache__/utils.cpython-312.pyc,, +tqdm/__pycache__/version.cpython-312.pyc,, +tqdm/_main.py,sha256=9ySvgmi_2Sw4CAo5UDW0Q2dxfTryboEWGHohfCJz0sA,283 +tqdm/_monitor.py,sha256=1VcavuotYSN6K-1jbpNuy6HYtr3mwo5Nh_jZMQ-jg3A,4013 +tqdm/_tqdm.py,sha256=LfLCuJ6bpsVo9xilmtBXyEm1vGnUCFrliW85j3J-nD4,283 +tqdm/_tqdm_gui.py,sha256=03Hc8KayxJveieI5-0-2NGiDpLvw9jZekofJUV7CCwk,287 +tqdm/_tqdm_notebook.py,sha256=BuHiLuxu6uEfZFaPJW3RPpPaxaVctEQA3kdSJSDL1hw,307 +tqdm/_tqdm_pandas.py,sha256=c9jptUgigN6axRDhRd4Rif98Tmxeopc1nFNFhIpbFUE,888 +tqdm/_utils.py,sha256=CfLztxFY-QRiNfxQCqAb2N8E13uauIM95RSQiFlaEuE,559 +tqdm/asyncio.py,sha256=IpcGo6ZFwc6KKHYj5s7h4kaRiogcabJ6PcqHj6jdy0I,3196 +tqdm/auto.py,sha256=nDZflj6p2zKkjBCNBourrhS81zYfZy1_dQvbckrdW8o,871 +tqdm/autonotebook.py,sha256=2pNgGCJDsesNNyYnmSve8BNQLiGSgo97SsPoMXCrNRQ,1440 +tqdm/cli.py,sha256=t1j_PqI0SuMyhJGoBxMPCXY-UTbfjciaAQYxAU_f_V0,11011 +tqdm/completion.sh,sha256=j79KbSmpIj_E11jfTfBXrGnUTzKXVpQ1vGVQvsyDRl4,946 +tqdm/contrib/__init__.py,sha256=1GMYYE866WCvlHg5MdmzOvPsQj4ZuMlXzz8xcRcJD60,2479 +tqdm/contrib/__pycache__/__init__.cpython-312.pyc,, +tqdm/contrib/__pycache__/bells.cpython-312.pyc,, +tqdm/contrib/__pycache__/concurrent.cpython-312.pyc,, +tqdm/contrib/__pycache__/discord.cpython-312.pyc,, +tqdm/contrib/__pycache__/itertools.cpython-312.pyc,, +tqdm/contrib/__pycache__/logging.cpython-312.pyc,, +tqdm/contrib/__pycache__/slack.cpython-312.pyc,, +tqdm/contrib/__pycache__/telegram.cpython-312.pyc,, +tqdm/contrib/__pycache__/utils_worker.cpython-312.pyc,, +tqdm/contrib/bells.py,sha256=IaxC2YW57xHDinxdUDQHvSego0HSTdDTExQQENvSB_k,921 +tqdm/contrib/concurrent.py,sha256=CpxrwcKaQRH7nwTPG3mVYuleGs_u0MNhW4hTuabpYYs,9873 +tqdm/contrib/discord.py,sha256=LPjxDbmfiYtw3OAm_WhtwbX9BVYDlPc8lJ96aY3YZDE,5337 +tqdm/contrib/itertools.py,sha256=MA9-Jvb3ToseppInvev2iF4bokN7GQy4Q4LgjUyYdA4,2949 +tqdm/contrib/logging.py,sha256=0nFn2C7qUUiKPB19qTGuS9Lfja8aiFW0u9kybRdG0hU,3902 +tqdm/contrib/slack.py,sha256=sC182v7xBkfGftnDeUmQALMOfwQzU3ZiNf1Q_XA1DjI,4049 +tqdm/contrib/telegram.py,sha256=ybTraGjUQx5m443TsX6pJ7Uxrpsh1m4a43BTWVl_4e4,5081 +tqdm/contrib/utils_worker.py,sha256=vaxyJyagYwOCQXLUMd86bCbI4sPqZysuMGbDSGmvEWo,1199 +tqdm/dask.py,sha256=9Ei58eVqTossRLhAfWyUFCduXYKjmLmwkaXIy-CHYfs,1319 +tqdm/gui.py,sha256=maQ7jgB5leWHwxMlbBv08hpe5lytvmH0hEARu22GRdU,5481 +tqdm/keras.py,sha256=ugd80-xCxMqnrbx_DEOpmj6c2Sh1xoVtQ8V9-bw29eo,4396 +tqdm/notebook.py,sha256=6xkUTcYRsFxN4_BSUYYZ51kAgI7ycnT0HLpP9HukEqg,10888 +tqdm/rich.py,sha256=J04yq6y2Ur9012zC7PkczA1t7cDjet88hmBkrAv-s2s,5255 +tqdm/std.py,sha256=3XbZZd5SxZCBnew3ZkQiDLNdxIMeQO-0wwlEiE_FfYY,58047 +tqdm/tk.py,sha256=3VsB1MDAkCItaWu7CmMb2CoTLMiqmDiEgNi3yiqQ5GY,6702 +tqdm/tqdm.1,sha256=MLg9qjeHThZpPEQbWVrf5P5gOXMKHE_X606FSOBI9eU,7538 +tqdm/utils.py,sha256=o_f0V32H_wrn0XmRno3j9pJ9xlp5xL0fHT3gtqL-k58,9746 +tqdm/version.py,sha256=0uH4TLe8I8H71x29dlmtEZBObLT3b5IW-nytF3V0IVw,233 diff --git a/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..13013d7b49be5a84c3ee5931b06285b9553cf5d0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (84.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..540e60f4e073bc53a5f0a521a3639e0d80780af4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +tqdm = tqdm.cli:main diff --git a/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/licenses/LICENCE b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/licenses/LICENCE new file mode 100644 index 0000000000000000000000000000000000000000..194caf554f8f10ba4cac8a81b631a61d0d81f60d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/licenses/LICENCE @@ -0,0 +1,49 @@ +`tqdm` is a product of collaborative work. +Unless otherwise stated, all authors (see commit logs) retain copyright +for their respective work, and release the work under the MIT licence +(text below). + +Exceptions or notable authors are listed below +in reverse chronological order: + +* files: * + MPL-2.0 2015-2026 (c) Casper da Costa-Luis + [casperdcl](https://github.com/casperdcl). +* files: tqdm/_tqdm.py + MIT 2016 (c) [PR #96] on behalf of Google Inc. +* files: tqdm/_tqdm.py README.rst .gitignore + MIT 2013 (c) Noam Yorav-Raphael, original author. + +[PR #96]: https://github.com/tqdm/tqdm/pull/96 + + +Mozilla Public Licence (MPL) v. 2.0 - Exhibit A +----------------------------------------------- + +This Source Code Form is subject to the terms of the +Mozilla Public License, v. 2.0. +If a copy of the MPL was not distributed with this project, +You can obtain one at https://mozilla.org/MPL/2.0/. + + +MIT License (MIT) +----------------- + +Copyright (c) 2013 noamraph + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..78620c472c9d799a14ccb02a0233f4669b3bcdcb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm-4.70.1.dist-info/top_level.txt @@ -0,0 +1 @@ +tqdm diff --git a/.venv/lib/python3.12/site-packages/tqdm/auto.py b/.venv/lib/python3.12/site-packages/tqdm/auto.py new file mode 100644 index 0000000000000000000000000000000000000000..206c4409d5269594bdbab3a092ef6e09e7c01947 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/auto.py @@ -0,0 +1,40 @@ +""" +Enables multiple commonly used features. + +Method resolution order: + +- `tqdm.autonotebook` without import warnings +- `tqdm.asyncio` +- `tqdm.std` base class + +Usage: +>>> from tqdm.auto import trange, tqdm +>>> for i in trange(10): +... ... +""" +import warnings + +from .std import TqdmExperimentalWarning + +with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=TqdmExperimentalWarning) + from .autonotebook import tqdm as notebook_tqdm + +from .asyncio import tqdm as asyncio_tqdm +from .std import tqdm as std_tqdm + +if notebook_tqdm != std_tqdm: + class tqdm(notebook_tqdm, asyncio_tqdm): # pylint: disable=inconsistent-mro + pass +else: + tqdm = asyncio_tqdm + + +def trange(*args, **kwargs): + """ + A shortcut for `tqdm.auto.tqdm(range(*args), **kwargs)`. + """ + return tqdm(range(*args), **kwargs) + + +__all__ = ["tqdm", "trange"] diff --git a/.venv/lib/python3.12/site-packages/tqdm/autonotebook.py b/.venv/lib/python3.12/site-packages/tqdm/autonotebook.py new file mode 100644 index 0000000000000000000000000000000000000000..df1d21b2b0f933b460c0f1021ae22a1f058b0871 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/autonotebook.py @@ -0,0 +1,38 @@ +""" +Automatically choose between `tqdm.notebook` and `tqdm.std`. + +Usage: +>>> from tqdm.autonotebook import trange, tqdm +>>> for i in trange(10): +... ... +""" +import os +import sys +from warnings import warn + +try: + if 'ipykernel.zmqshell' in sys.modules: + if any(i == 'QT_API' or i.startswith('SPYDER') for i in os.environ): + raise ImportError("console") # jupyter-qtconsole/spyder + ipy = sys.modules['IPython'].get_ipython().__class__.__name__.lower() + if 'qt' in ipy or 'spyder' in ipy: + raise ImportError("console") # older jupyter-qtconsole/spyder + # jupyter-notebook/jupyterlab/vscode/binder/colab + elif 'IPython.utils._process_emscripten' in sys.modules: + pass # jupyterlite (pyodide)/jupyterlite-xeus + else: + raise ImportError("console") # ipython/jupyter-console + from .notebook import WARN_NOIPYW, IProgress + if IProgress is None: + from .std import TqdmWarning + warn(WARN_NOIPYW, TqdmWarning, stacklevel=2) + raise ImportError('ipywidgets') +except Exception: + from .std import tqdm, trange +else: # pragma: no cover + from .notebook import tqdm, trange + from .std import TqdmExperimentalWarning + warn("Using `tqdm.autonotebook.tqdm` in notebook mode." + " Use `tqdm.tqdm` instead to force console mode" + " (e.g. in jupyter console)", TqdmExperimentalWarning, stacklevel=2) +__all__ = ["tqdm", "trange"] diff --git a/.venv/lib/python3.12/site-packages/tqdm/cli.py b/.venv/lib/python3.12/site-packages/tqdm/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..e5599efdc7c1c2aaad1cd95dd02eacdffc71c658 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/cli.py @@ -0,0 +1,324 @@ +""" +Module version for monitoring CLI pipes (`... | python -m tqdm | ...`). +""" +import logging +import re +import sys +from ast import literal_eval +from textwrap import indent + +from .std import TqdmKeyError, TqdmTypeError, tqdm +from .version import __version__ + +__all__ = ["main"] +log = logging.getLogger(__name__) + + +def cast(val, typ): + log.debug((val, typ)) + if " or " in typ: + for t in typ.split(" or "): + try: + return cast(val, t) + except TqdmTypeError: + pass + raise TqdmTypeError(f"{val} : {typ}") + + # sys.stderr.write('\ndebug | `val:type`: `' + val + ':' + typ + '`.\n') + if typ == 'bool': + if (val == 'True') or (val == ''): + return True + if val == 'False': + return False + raise TqdmTypeError(val + ' : ' + typ) + if typ == 'chr': + if len(val) == 1: + return val.encode() + if re.match(r"^\\\w+$", val): + return literal_eval(f'"{val}"').encode() + raise TqdmTypeError(f"{val} : {typ}") + if typ == 'str': + return val + if typ == 'int': + try: + return int(val) + except ValueError as exc: + raise TqdmTypeError(f"{val} : {typ}") from exc + if typ == 'float': + try: + return float(val) + except ValueError as exc: + raise TqdmTypeError(f"{val} : {typ}") from exc + raise TqdmTypeError(f"{val} : {typ}") + + +def posix_pipe(fin, fout, delim=b'\\n', buf_size=256, + callback=lambda float: None, callback_len=True): + """ + Params + ------ + fin : binary file with `read(buf_size : int)` method + fout : binary file with `write` (and optionally `flush`) methods. + callback : function(float), e.g.: `tqdm.update` + callback_len : If (default: True) do `callback(len(buffer))`. + Otherwise, do `callback(data) for data in buffer.split(delim)`. + """ + fp_write = fout.write + + if not delim: + while True: + tmp = fin.read(buf_size) + + # flush at EOF + if not tmp: + getattr(fout, 'flush', lambda: None)() + return + + fp_write(tmp) + callback(len(tmp)) + # return + + buf = b'' + len_delim = len(delim) + # n = 0 + while True: + tmp = fin.read(buf_size) + + # flush at EOF + if not tmp: + if buf: + fp_write(buf) + if callback_len: + # n += 1 + buf.count(delim) + callback(1 + buf.count(delim)) + else: + for i in buf.split(delim): + callback(i) + getattr(fout, 'flush', lambda: None)() + return # n + + while True: + i = tmp.find(delim) + if i < 0: + buf += tmp + break + fp_write(buf + tmp[:i + len(delim)]) + # n += 1 + callback(1 if callback_len else (buf + tmp[:i])) + buf = b'' + tmp = tmp[i + len_delim:] + + +# ((opt, type), ... ) +RE_OPTS = re.compile(r'\n {4}(\S+)\s{2,}:\s*([^,]+)') +# better split method assuming no positional args +RE_SHLEX = re.compile(r'\s*(? : \2', d) + split = RE_OPTS.split(d) + opt_types_desc = zip(split[1::3], split[2::3], split[3::3]) + d = ''.join(('\n --{0} : {2}{3}' if otd[1] == 'bool' else + '\n --{0}=<{1}> : {2}{3}').format( + otd[0].replace('_', '-'), otd[0], *otd[1:]) + for otd in opt_types_desc if otd[0] not in UNSUPPORTED_OPTS) + + help_short = "Usage:\n tqdm [--help | options]\n" + d = help_short + """ +Options: + -h, --help Print this help and exit. + -v, --version Print version and exit. +""" + d.strip('\n') + '\n' + + # opts = docopt(d, version=__version__) + if any(v in argv for v in ('-v', '--version')): + sys.stdout.write(__version__ + '\n') + sys.exit(0) + elif any(v in argv for v in ('-h', '--help')): + sys.stdout.write(d + '\n') + sys.exit(0) + elif argv and argv[0][:2] != '--': + sys.stderr.write(f"Error:Unknown argument:{argv[0]}\n{help_short}") + + argv = RE_SHLEX.split(' '.join(["tqdm"] + argv)) + opts = dict(zip(argv[1::3], argv[3::3])) + + log.debug(opts) + opts.pop('log', True) + + tqdm_args = {'file': fp} + try: + for (o, v) in opts.items(): + o = o.replace('-', '_') + try: + tqdm_args[o] = cast(v, opt_types[o]) + except KeyError as e: + raise TqdmKeyError(str(e)) + log.debug('args:' + str(tqdm_args)) + + delim_per_char = tqdm_args.pop('bytes', False) + update = tqdm_args.pop('update', False) + update_to = tqdm_args.pop('update_to', False) + if sum((delim_per_char, update, update_to)) > 1: + raise TqdmKeyError("Can only have one of --bytes --update --update_to") + except Exception: + fp.write("\nError:\n" + help_short) + stdin, stdout_write = sys.stdin, sys.stdout.write + for i in stdin: + stdout_write(i) + raise + else: + buf_size = tqdm_args.pop('buf_size', 256) + delim = tqdm_args.pop('delim', b'\\n') + tee = tqdm_args.pop('tee', False) + manpath = tqdm_args.pop('manpath', None) + comppath = tqdm_args.pop('comppath', None) + if tqdm_args.pop('null', False): + class stdout: + @staticmethod + def write(_): + pass + else: + stdout = sys.stdout + stdout = getattr(stdout, 'buffer', stdout) + stdin = getattr(sys.stdin, 'buffer', sys.stdin) + if manpath or comppath: + try: # py<3.9 + import importlib_resources as resources + except ImportError: + from importlib import resources + from pathlib import Path + + def cp(name, dst): + """copy resource `name` to `dst`""" + fi = resources.files('tqdm') / name + dst.write_bytes(fi.read_bytes()) + log.info("written:%s", dst) + if manpath is not None: + cp('tqdm.1', Path(manpath) / 'tqdm.1') + if comppath is not None: + cp('completion.sh', Path(comppath) / 'tqdm_completion.sh') + sys.exit(0) + if tee: + stdout_write = stdout.write + fp_write = getattr(fp, 'buffer', fp).write + + class stdout: # pylint: disable=function-redefined + @staticmethod + def write(x): + with tqdm.external_write_mode(file=fp): + fp_write(x) + stdout_write(x) + if delim_per_char: + tqdm_args.setdefault('unit', 'B') + tqdm_args.setdefault('unit_scale', True) + tqdm_args.setdefault('unit_divisor', 1024) + log.debug(tqdm_args) + with tqdm(**tqdm_args) as t: + posix_pipe(stdin, stdout, '', buf_size, t.update) + elif delim == b'\\n': + log.debug(tqdm_args) + write = stdout.write + if update or update_to: + with tqdm(**tqdm_args) as t: + if update: + def callback(i): + t.update(literal_eval(i.decode())) + else: # update_to + def callback(i): + t.update(literal_eval(i.decode()) - t.n) + for i in stdin: + write(i) + callback(i) + else: + for i in tqdm(stdin, **tqdm_args): + write(i) + else: + log.debug(tqdm_args) + with tqdm(**tqdm_args) as t: + callback_len = False + if update: + def callback(i): + t.update(literal_eval(i.decode())) + elif update_to: + def callback(i): + t.update(literal_eval(i.decode()) - t.n) + else: + callback = t.update + callback_len = True + posix_pipe(stdin, stdout, delim, buf_size, callback, callback_len) diff --git a/.venv/lib/python3.12/site-packages/tqdm/completion.sh b/.venv/lib/python3.12/site-packages/tqdm/completion.sh new file mode 100644 index 0000000000000000000000000000000000000000..9f61c7f14bb8c1f6099b9eb75dce28ece6a7ae96 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/completion.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +_tqdm(){ + local cur prv + cur="${COMP_WORDS[COMP_CWORD]}" + prv="${COMP_WORDS[COMP_CWORD - 1]}" + + case ${prv} in + --bar_format|--buf_size|--colour|--comppath|--delay|--delim|--desc|--initial|--lock_args|--manpath|--maxinterval|--mininterval|--miniters|--ncols|--nrows|--position|--postfix|--smoothing|--total|--unit|--unit_divisor) + # await user input + ;; + "--log") + COMPREPLY=($(compgen -W 'CRITICAL FATAL ERROR WARN WARNING INFO DEBUG NOTSET' -- ${cur})) + ;; + *) + COMPREPLY=($(compgen -W '--ascii --bar_format --buf_size --bytes --colour --comppath --delay --delim --desc --disable --dynamic_ncols --help --initial --leave --lock_args --log --manpath --maxinterval --mininterval --miniters --ncols --nrows --null --position --postfix --smoothing --tee --total --unit --unit_divisor --unit_scale --update --update_to --version --write_bytes -h -v' -- ${cur})) + ;; + esac +} +complete -F _tqdm tqdm diff --git a/.venv/lib/python3.12/site-packages/tqdm/contrib/__init__.py b/.venv/lib/python3.12/site-packages/tqdm/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..87ec4601fcff138e0882808237375aed93f5ef35 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/contrib/__init__.py @@ -0,0 +1,91 @@ +""" +Thin wrappers around common functions. + +Subpackages contain potentially unstable extensions. +""" +from warnings import warn + +from ..auto import tqdm as tqdm_auto +from ..std import TqdmDeprecationWarning, tqdm +from ..utils import ObjectWrapper + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['tenumerate', 'tzip', 'tmap'] + + +class DummyTqdmFile(ObjectWrapper): + """Dummy file-like that will write to tqdm""" + + def __init__(self, wrapped): + super().__init__(wrapped) + self._buf = [] + + def write(self, x, nolock=False): + nl = b"\n" if isinstance(x, bytes) else "\n" + pre, sep, post = x.rpartition(nl) + if sep: + blank = type(nl)() + tqdm.write(blank.join(self._buf + [pre, sep]), + end=blank, file=self._wrapped, nolock=nolock) + self._buf = [post] + else: + self._buf.append(x) + + def __del__(self): + if self._buf: + blank = type(self._buf[0])() + try: + tqdm.write(blank.join(self._buf), end=blank, file=self._wrapped) + except (OSError, ValueError): + pass + + +def builtin_iterable(func): + """Returns `func`""" + warn("This function has no effect, and will be removed in tqdm==5.0.0", + TqdmDeprecationWarning, stacklevel=2) + return func + + +def tenumerate(iterable, start=0, total=None, tqdm_class=tqdm_auto, **tqdm_kwargs): + """ + Equivalent of `numpy.ndenumerate` or builtin `enumerate`. + + Parameters + ---------- + tqdm_class : [default: tqdm.auto.tqdm]. + """ + try: + import numpy as np + except ImportError: + pass + else: + if isinstance(iterable, np.ndarray): + return tqdm_class(np.ndenumerate(iterable), total=total or iterable.size, + **tqdm_kwargs) + return enumerate(tqdm_class(iterable, total=total, **tqdm_kwargs), start) + + +def tzip(iter1, *iter2plus, **tqdm_kwargs): + """ + Equivalent of builtin `zip`. + + Parameters + ---------- + tqdm_class : [default: tqdm.auto.tqdm]. + """ + kwargs = tqdm_kwargs.copy() + tqdm_class = kwargs.pop("tqdm_class", tqdm_auto) + yield from zip(tqdm_class(iter1, **kwargs), *iter2plus) + + +def tmap(function, *sequences, **tqdm_kwargs): + """ + Equivalent of builtin `map`. + + Parameters + ---------- + tqdm_class : [default: tqdm.auto.tqdm]. + """ + for i in tzip(*sequences, **tqdm_kwargs): + yield function(*i) diff --git a/.venv/lib/python3.12/site-packages/tqdm/contrib/bells.py b/.venv/lib/python3.12/site-packages/tqdm/contrib/bells.py new file mode 100644 index 0000000000000000000000000000000000000000..e4968e7751920093aa6c3ddd72c5b5e2e29df8bc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/contrib/bells.py @@ -0,0 +1,28 @@ +""" +Even more features than `tqdm.auto` (all the bells & whistles): + +- `tqdm.auto` +- `tqdm.tqdm.pandas` +- `tqdm.contrib.slack` + + uses `${TQDM_SLACK_TOKEN}` and `${TQDM_SLACK_CHANNEL}` +- `tqdm.contrib.telegram` + + uses `${TQDM_TELEGRAM_TOKEN}` and `${TQDM_TELEGRAM_CHAT_ID}` +- `tqdm.contrib.discord` + + uses `${TQDM_DISCORD_TOKEN}` and `${TQDM_DISCORD_CHANNEL_ID}` +""" +__all__ = ['tqdm', 'trange'] +import warnings +from os import getenv + +if getenv("TQDM_SLACK_TOKEN") and getenv("TQDM_SLACK_CHANNEL"): + from .slack import tqdm, trange +elif getenv("TQDM_TELEGRAM_TOKEN") and getenv("TQDM_TELEGRAM_CHAT_ID"): + from .telegram import tqdm, trange +elif getenv("TQDM_DISCORD_TOKEN") and getenv("TQDM_DISCORD_CHANNEL_ID"): + from .discord import tqdm, trange +else: + from ..auto import tqdm, trange + +with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=FutureWarning) + tqdm.pandas() diff --git a/.venv/lib/python3.12/site-packages/tqdm/contrib/concurrent.py b/.venv/lib/python3.12/site-packages/tqdm/contrib/concurrent.py new file mode 100644 index 0000000000000000000000000000000000000000..955e9e3a1b034c875ed0d642cf436b6502d70bc2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/contrib/concurrent.py @@ -0,0 +1,259 @@ +""" +Thin wrappers around `concurrent.futures`. +""" +import sys +from contextlib import contextmanager +from operator import length_hint + +from ..auto import tqdm as tqdm_auto +from ..std import TqdmWarning + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['thread_map', 'process_map', 'interpreter_map'] + + +class _InterpreterLock: + """Reentrant lock backed by a cross-interpreter queue.""" + from threading import get_ident + from time import monotonic as _time + + def __init__(self, queue): + from threading import RLock + self._queue = queue + self._lock = RLock() + self._owner = None + self._depth = 0 + + def acquire(self, blocking=True, timeout=-1): + from queue import Empty + start = self._time() + if timeout == -1: + acquired = self._lock.acquire(blocking) + else: + acquired = self._lock.acquire(blocking, timeout) + if not acquired: + return False + if self._depth: + self._depth += 1 + return True + try: + if not blocking: + self._queue.get_nowait() + elif timeout == -1: + self._queue.get() + else: + remaining = max(0, timeout - (self._time() - start)) + self._queue.get(timeout=remaining) + except Empty: + self._lock.release() + return False + self._owner = self.get_ident() + self._depth = 1 + return True + + def release(self): + if self._owner != self.get_ident(): + raise RuntimeError("cannot release un-acquired lock") + self._depth -= 1 + if not self._depth: + self._owner = None + self._queue.put(None) + self._lock.release() + + def __enter__(self): + self.acquire() + return self + + def __exit__(self, *exc): + self.release() + + +@contextmanager +def ensure_lock(tqdm_class, lock_name="", lock=None): + """get (create if necessary) and then restore `tqdm_class`'s lock""" + old_lock = getattr(tqdm_class, '_lock', None) # don't create a new lock + if lock is None: + lock = old_lock or tqdm_class.get_lock() # maybe create a new lock + lock = getattr(lock, lock_name, lock) # maybe subtype + tqdm_class.set_lock(lock) + yield lock + if old_lock is None: + del tqdm_class._lock + else: + tqdm_class.set_lock(old_lock) + + +def _get_interpreter_init(tqdm_class, lock_queue_id): + """Return an initializer which bootstraps the parent import path and lock.""" + code = ( + "import sys\n" + f"sys.path[:] = {sys.path!r}\n" + "from concurrent import interpreters\n" + "from importlib import import_module\n" + "from tqdm.contrib.concurrent import _InterpreterLock\n" + f"tqdm_class = import_module({tqdm_class.__module__!r})\n" + f"for name in {tqdm_class.__qualname__.split('.')!r}:\n" + " tqdm_class = getattr(tqdm_class, name)\n" + "tqdm_class.monitor_interval = 0\n" + f"tqdm_class.set_lock(_InterpreterLock(interpreters.Queue({lock_queue_id!r})))") + return exec, (code,) + + +def _min_map_len(iterables): + """min(map(length_hint, iterables), default=0)""" + return min((n for it in iterables if (n := length_hint(it, -1)) >= 0), default=0) + + +def _executor_map( + PoolExecutor, fn, *iterables, max_workers=None, timeout=None, chunksize=1, lock_name="", + tqdm_class=tqdm_auto, smoothing=0.0, _lock=None, _initializer=None, _initargs=None, + **tqdm_kwargs +): + """ + Implementation of `thread_map`, `process_map` and `interpreter_map`. + + Parameters + ---------- + max_workers : int + timeout : int + buffersize : int + Requires Python>=3.14. + thread_name_prefix : str + max_tasks_per_child : int + mp_context : str + """ + kwargs = tqdm_kwargs.copy() + if 'total' not in kwargs: + kwargs['total'] = _min_map_len(iterables) + map_kwargs = {} + if 'buffersize' in kwargs: + map_kwargs['buffersize'] = kwargs.pop('buffersize') + pool_kwargs = {} + for k in ('thread_name_prefix', 'max_tasks_per_child', 'mp_context'): + if k in kwargs: + pool_kwargs[k] = kwargs.pop(k) + dynamic_miniters = None + if kwargs['total'] and 'miniters' not in kwargs: + try: + from os import process_cpu_count as cpu_count + except ImportError: + from os import cpu_count + # thread & process pools have different default workers, but we KISS here + rough_max = max_workers or min(32, (cpu_count() or 1) + 4) + if kwargs['total'] > rough_max: + kwargs['miniters'] = rough_max + dynamic_miniters = True + with ensure_lock(tqdm_class, lock_name=lock_name, lock=_lock) as lk: + # share lock in case workers are already using `tqdm` + if _initializer is None: + _initializer = tqdm_class.set_lock + _initargs = (lk,) + with PoolExecutor(max_workers=max_workers, initializer=_initializer, initargs=_initargs, + **pool_kwargs) as ex: + with tqdm_class(smoothing=smoothing, **kwargs) as pbar: + if dynamic_miniters is not None: + pbar.dynamic_miniters = True + orisubmit = ex.submit + + def patchsubmit(*args, **kwargs): + fut = orisubmit(*args, **kwargs) + fut.add_done_callback(lambda _: pbar.update()) + return fut + ex.submit = patchsubmit + return list(ex.map( + fn, *iterables, timeout=timeout, chunksize=chunksize, **map_kwargs)) + + +def thread_map(fn, *iterables, **tqdm_kwargs): + """ + Equivalent of `list(map(fn, *iterables))` + driven by `concurrent.futures.ThreadPoolExecutor`. + + Parameters + ---------- + max_workers : int, optional + Maximum number of workers to spawn; passed to `concurrent.futures.ThreadPoolExecutor`. + thread_name_prefix : str, optional + Passed to `concurrent.futures.ThreadPoolExecutor` [default: '']. + timeout : int or float, optional + Seconds to wait before raising `TimeoutError` if `__next__` is called and the + result isn't available. [default: None]. + buffersize : int, optional + Requires Python>=3.14 [default: None]. + tqdm_class : optional + `tqdm` class to use for bars [default: tqdm.auto.tqdm]. + smoothing : float, optional + Passed to `tqdm_class`; the [default: 0] is average (due to erratic update frequency). + lock_name : str, optional + Member of `tqdm_class.get_lock()` to use [default: '']. + """ + from concurrent.futures import ThreadPoolExecutor + return _executor_map(ThreadPoolExecutor, fn, *iterables, **tqdm_kwargs) + + +def interpreter_map(fn, *iterables, **tqdm_kwargs): + """ + Equivalent of `list(map(fn, *iterables))` + driven by `concurrent.futures.InterpreterPoolExecutor` (Python 3.14+). + + Parameters + ---------- + Same as `thread_map`. + + Notes + ----- + `fn`, its arguments, and its return values must be pickleable. + Worker progress bars using the same `tqdm_class` share a cross-interpreter write lock. + """ + from concurrent import interpreters + from concurrent.futures import InterpreterPoolExecutor + lock_queue = interpreters.create_queue() + lock_queue.put(None) + tqdm_class = tqdm_kwargs.get("tqdm_class", tqdm_auto) + initializer, initargs = _get_interpreter_init(tqdm_class, lock_queue.id) + return _executor_map( + InterpreterPoolExecutor, fn, *iterables, _lock=_InterpreterLock(lock_queue), + _initializer=initializer, _initargs=initargs, **tqdm_kwargs) + + +def process_map(fn, *iterables, lock_name="mp_lock", **tqdm_kwargs): + """ + Equivalent of `list(map(fn, *iterables))` + driven by `concurrent.futures.ProcessPoolExecutor`. + + Parameters + ---------- + max_workers : int, optional + Maximum number of workers to spawn; passed to `concurrent.futures.ProcessPoolExecutor`. + timeout : int or float, optional + Seconds to wait before raising `TimeoutError` if `__next__` is called and the + result isn't available. [default: None]. + chunksize : int, optional + Approximate size of chunks sent to worker processes; passed to + `concurrent.futures.ProcessPoolExecutor.map`. [default: 1]. + buffersize : int, optional + Requires Python>=3.14 [default: None]. + max_tasks_per_child : int, optional + Maximum number of tasks a worker process can complete before being replaced + with a new process; passed to `concurrent.futures.ProcessPoolExecutor`. + mp_context : multiprocessing.BaseContext, optional + Multiprocessing context to use, e.g. `multiprocessing.get_context('fork')`. + lock_name : str, optional + Member of `tqdm_class.get_lock()` to use [default: mp_lock]. + tqdm_class : optional + `tqdm` class to use for bars [default: tqdm.auto.tqdm]. + smoothing : float, optional + Passed to `tqdm_class`; the [default: 0] is average (due to erratic update frequency). + """ + from concurrent.futures import ProcessPoolExecutor + if iterables and 'chunksize' not in tqdm_kwargs: + # default `chunksize=1` has poor performance for large iterables + # (most time spent dispatching items to workers). + shortest_iterable_len = _min_map_len(iterables) + if shortest_iterable_len > 1000: + from warnings import warn + warn("Iterable length %d > 1000 but `chunksize` is not set." + " This may seriously degrade multiprocess performance." + " Set `chunksize=1` or more." % shortest_iterable_len, + TqdmWarning, stacklevel=2) + return _executor_map(ProcessPoolExecutor, fn, *iterables, lock_name=lock_name, **tqdm_kwargs) diff --git a/.venv/lib/python3.12/site-packages/tqdm/contrib/discord.py b/.venv/lib/python3.12/site-packages/tqdm/contrib/discord.py new file mode 100644 index 0000000000000000000000000000000000000000..f46a4992bcbaeb7f85d75f8e6c64dc6e09f5325b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/contrib/discord.py @@ -0,0 +1,155 @@ +""" +Sends updates to a Discord bot. + +Usage: +>>> from tqdm.contrib.discord import tqdm, trange +>>> for i in trange(10, token='{token}', channel_id='{channel_id}'): +... ... + +![screenshot](https://tqdm.github.io/img/screenshot-discord.png) +""" +from warnings import warn + +from requests import Session +from requests.utils import default_user_agent + +from ..auto import tqdm as tqdm_auto +from ..std import TqdmWarning +from ..utils import envwrap +from ..version import __version__ +from .utils_worker import MonoWorker + +__author__ = {"github.com/": ["casperdcl", "guigoruiz1"]} +__all__ = ['DiscordIO', 'tqdm_discord', 'tdrange', 'tqdm', 'trange'] + + +class DiscordIO(MonoWorker): + """Non-blocking file-like IO using a Discord Bot.""" + API = 'https://discord.com/api/v10' + UA = f"tqdm (https://tqdm.github.io, {__version__}) {default_user_agent()}" + + def __init__(self, token, channel_id): + """Creates a new message in the given `channel_id`.""" + super().__init__() + self.token = token + self.channel_id = channel_id + self.session = Session() + self.text = self.__class__.__name__ + self.message_id # pylint: disable=pointless-statement + + @property + def message_id(self): + if hasattr(self, '_message_id'): + return self._message_id # pylint: disable=access-member-before-definition + try: + req = self.session.post( + f'{self.API}/channels/{self.channel_id}/messages', + headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA}, + json={'content': f"`{self.text}`"}) + res = req.json() + req.raise_for_status() + except Exception as e: + if req.status_code == 429: + warn("Creation rate limit: try increasing `mininterval`.", + TqdmWarning, stacklevel=2) + else: + tqdm_auto.write(str(e)) + else: + self._message_id = res['id'] + return self._message_id + + def write(self, s): + """Replaces internal `message_id`'s text with `s`.""" + if not s: + s = "..." + s = s.replace('\r', '').strip() + if s == self.text: + return # avoid duplicate message Bot error + message_id = self.message_id + if message_id is None: + return + self.text = s + try: + future = self.submit( + self.session.patch, + f'{self.API}/channels/{self.channel_id}/messages/{message_id}', + headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA}, + json={'content': f"`{self.text}`"}) + except Exception as e: + tqdm_auto.write(str(e)) + else: + return future + + def delete(self): + """Deletes internal `message_id`.""" + try: + future = self.submit( + self.session.delete, + f'{self.API}/channels/{self.channel_id}/messages/{self.message_id}', + headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA}) + except Exception as e: + tqdm_auto.write(str(e)) + else: + return future + + +class tqdm_discord(tqdm_auto): # pylint: disable=inconsistent-mro + """ + Standard `tqdm.auto.tqdm` but also sends updates to a Discord Bot. + May take a few seconds to create (`__init__`). + + - create a discord bot (not public, no requirement of OAuth2 code + grant, only send message permissions) & invite it to a channel: + + - copy the bot `{token}` & `{channel_id}` and paste below + + >>> from tqdm.contrib.discord import tqdm, trange + >>> for i in tqdm(iterable, token='{token}', channel_id='{channel_id}'): + ... ... + """ + @envwrap("tqdm", "discord", is_method=True) + def __init__(self, *args, token=None, channel_id=None, **kwargs): + """ + Parameters + ---------- + token : str, required. Discord bot token + [default: ${TQDM_DISCORD_TOKEN}]. + channel_id : int, required. Discord channel ID + [default: ${TQDM_DISCORD_CHANNEL_ID}]. + + See `tqdm.auto.tqdm.__init__` for other parameters. + """ + if not kwargs.get('disable'): + kwargs = kwargs.copy() + self.dio = DiscordIO(token, channel_id) + super().__init__(*args, **kwargs) + + def display(self, **kwargs): # pylint: disable=arguments-differ + super().display(**kwargs) + fmt = self.format_dict + if fmt.get('bar_format', None): + fmt['bar_format'] = fmt['bar_format'].replace( + '', '{bar:10u}').replace('{bar}', '{bar:10u}') + self.dio.write(self.format_meter(**fmt)) + + def clear(self, *args, **kwargs): + super().clear(*args, **kwargs) + if not self.disable: + self.dio.write("") + + def close(self): + if self.disable: + return + super().close() + if not (self.leave or (self.leave is None and self.pos == 0)): + self.dio.delete() + + +def tdrange(*args, **kwargs): + """Shortcut for `tqdm.contrib.discord.tqdm(range(*args), **kwargs)`.""" + return tqdm_discord(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_discord +trange = tdrange diff --git a/.venv/lib/python3.12/site-packages/tqdm/contrib/itertools.py b/.venv/lib/python3.12/site-packages/tqdm/contrib/itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..469961867cbf2c22cb2b799ecb4736438a912520 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/contrib/itertools.py @@ -0,0 +1,92 @@ +""" +Thin wrappers around `itertools`. +""" +import itertools +import math + +from ..auto import tqdm as tqdm_auto + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = [ + 'chain', 'product', 'permutations', 'combinations', 'combinations_with_replacement', 'batched'] + + +def chain(*iterables, total=None, tqdm_class=tqdm_auto, **kwargs): + """Equivalent of `itertools.chain`.""" + if total is None: + try: + total = sum(map(len, iterables)) + except (TypeError, AttributeError): + pass + return tqdm_class(itertools.chain(*iterables), total=total, **kwargs) + + +def product(*iterables, repeat=1, total=None, tqdm_class=tqdm_auto, **kwargs): + """Equivalent of `itertools.product`.""" + if total is None: + try: + lens = list(map(len, iterables)) + except (TypeError, AttributeError): + pass + else: + total = math.prod(lens) ** repeat + yield from tqdm_class(itertools.product(*iterables, repeat=repeat), total=total, **kwargs) + + +def permutations(iterable, r=None, total=None, tqdm_class=tqdm_auto, **kwargs): + """Equivalent of `itertools.permutations`.""" + if total is None: + try: + n = len(iterable) + except (TypeError, AttributeError): + pass + else: + r = n if r is None else r + if r > n: + total = 0 + else: + total = math.perm(n, r) + return tqdm_class(itertools.permutations(iterable, r), total=total, **kwargs) + + +def combinations(iterable, r, total=None, tqdm_class=tqdm_auto, **kwargs): + """Equivalent of `itertools.combinations`.""" + if total is None: + try: + n = len(iterable) + except (TypeError, AttributeError): + pass + else: + if r > n: + total = 0 + else: + total = math.comb(n, r) + return tqdm_class(itertools.combinations(iterable, r), total=total, **kwargs) + + +def combinations_with_replacement(iterable, r, total=None, tqdm_class=tqdm_auto, **kwargs): + """Equivalent of `itertools.combinations_with_replacement`.""" + if total is None: + try: + n = len(iterable) + except (TypeError, AttributeError): + pass + else: + total = 1 + for i in range(n+r-1, n-1, -1): + total *= i + for i in range(1, r+1): + total //= i + return tqdm_class(itertools.combinations_with_replacement(iterable, r), total=total, **kwargs) + + +def batched(iterable, n, total=None, tqdm_class=tqdm_auto, **kwargs): + """Equivalent of `itertools.batched`.""" + if total is None: + try: + total = len(iterable) + except (TypeError, AttributeError): + pass + return tqdm_class(itertools.batched(iterable, n), unit_scale=n, + total=(total+n-1) // n if total is not None else None, + **kwargs) diff --git a/.venv/lib/python3.12/site-packages/tqdm/contrib/logging.py b/.venv/lib/python3.12/site-packages/tqdm/contrib/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..cb22940ed79cb69ed780be947978d8a785efa8a1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/contrib/logging.py @@ -0,0 +1,128 @@ +""" +Helper functionality for interoperability with stdlib `logging`. +""" +import logging +import sys +from contextlib import contextmanager + +try: + from typing import Iterator, List, Optional, Type # noqa: F401, pylint: disable=unused-import +except ImportError: + pass + +from ..std import tqdm as std_tqdm + + +class _TqdmLoggingHandler(logging.StreamHandler): + def __init__( + self, + tqdm_class=std_tqdm # type: Type[std_tqdm] + ): + super().__init__() + self.tqdm_class = tqdm_class + + def emit(self, record): + try: + msg = self.format(record) + self.tqdm_class.write(msg, file=self.stream) + self.flush() + except (KeyboardInterrupt, SystemExit): + raise + except: # noqa pylint: disable=bare-except + self.handleError(record) + + +def _is_console_logging_handler(handler): + return (isinstance(handler, logging.StreamHandler) + and handler.stream in {sys.stdout, sys.stderr}) + + +def _get_first_found_console_logging_handler(handlers): + for handler in handlers: + if _is_console_logging_handler(handler): + return handler + + +@contextmanager +def logging_redirect_tqdm( + loggers=None, # type: Optional[List[logging.Logger]], + tqdm_class=std_tqdm # type: Type[std_tqdm] +): + # type: (...) -> Iterator[None] + """ + Context manager redirecting console logging to `tqdm.write()`, leaving + other logging handlers (e.g. log files) unaffected. + + Parameters + ---------- + loggers : list, optional + Which handlers to redirect (default: [logging.root]). + tqdm_class : optional + + Example + ------- + ```python + import logging + from tqdm import trange + from tqdm.contrib.logging import logging_redirect_tqdm + + LOG = logging.getLogger(__name__) + + if __name__ == '__main__': + logging.basicConfig(level=logging.INFO) + with logging_redirect_tqdm(): + for i in trange(9): + if i == 4: + LOG.info("console logging redirected to `tqdm.write()`") + # logging restored + ``` + """ + if loggers is None: + loggers = [logging.root] + original_handlers_list = [logger.handlers for logger in loggers] + try: + for logger in loggers: + tqdm_handler = _TqdmLoggingHandler(tqdm_class) + orig_handler = _get_first_found_console_logging_handler(logger.handlers) + if orig_handler is not None: + tqdm_handler.setFormatter(orig_handler.formatter) + tqdm_handler.stream = orig_handler.stream + for log_filter in orig_handler.filters: + tqdm_handler.addFilter(log_filter) + logger.handlers = [ + handler for handler in logger.handlers + if not _is_console_logging_handler(handler)] + [tqdm_handler] + yield + finally: + for logger, original_handlers in zip(loggers, original_handlers_list): + logger.handlers = original_handlers + + +@contextmanager +def tqdm_logging_redirect( + *args, + # loggers=None, # type: Optional[List[logging.Logger]] + # tqdm=None, # type: Optional[Type[tqdm.tqdm]] + **kwargs +): + # type: (...) -> Iterator[None] + """ + Convenience shortcut for: + ```python + with tqdm_class(*args, **tqdm_kwargs) as pbar: + with logging_redirect_tqdm(loggers=loggers, tqdm_class=tqdm_class): + yield pbar + ``` + + Parameters + ---------- + tqdm_class : optional, (default: tqdm.std.tqdm). + loggers : optional, list. + **tqdm_kwargs : passed to `tqdm_class`. + """ + tqdm_kwargs = kwargs.copy() + loggers = tqdm_kwargs.pop('loggers', None) + tqdm_class = tqdm_kwargs.pop('tqdm_class', std_tqdm) + with tqdm_class(*args, **tqdm_kwargs) as pbar: + with logging_redirect_tqdm(loggers=loggers, tqdm_class=tqdm_class): + yield pbar diff --git a/.venv/lib/python3.12/site-packages/tqdm/contrib/slack.py b/.venv/lib/python3.12/site-packages/tqdm/contrib/slack.py new file mode 100644 index 0000000000000000000000000000000000000000..e9808f55ad0b074bfb66ae79df35de8bf629233c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/contrib/slack.py @@ -0,0 +1,119 @@ +""" +Sends updates to a Slack app. + +Usage: +>>> from tqdm.contrib.slack import tqdm, trange +>>> for i in trange(10, token='{token}', channel='{channel}'): +... ... + +![screenshot](https://tqdm.github.io/img/screenshot-slack.png) +""" +import logging + +try: + from slack_sdk import WebClient +except ImportError: + raise ImportError("Please `pip install slack-sdk`") + +from ..auto import tqdm as tqdm_auto +from ..utils import envwrap +from .utils_worker import MonoWorker + +__author__ = {"github.com/": ["0x2b3bfa0", "casperdcl"]} +__all__ = ['SlackIO', 'tqdm_slack', 'tsrange', 'tqdm', 'trange'] + + +class SlackIO(MonoWorker): + """Non-blocking file-like IO using a Slack app.""" + def __init__(self, token, channel): + """Creates a new message in the given `channel`.""" + super().__init__() + self.client = WebClient(token=token) + self.text = self.__class__.__name__ + try: + self.message = self.client.chat_postMessage(channel=channel, text=self.text) + except Exception as e: + tqdm_auto.write(str(e)) + self.message = None + + def write(self, s): + """Replaces internal `message`'s text with `s`.""" + if not s: + s = "..." + s = s.replace('\r', '').strip() + if s == self.text: + return # skip duplicate message + message = self.message + if message is None: + return + self.text = s + try: + future = self.submit(self.client.chat_update, channel=message['channel'], + ts=message['ts'], text='`' + s + '`') + except Exception as e: + tqdm_auto.write(str(e)) + else: + return future + + +class tqdm_slack(tqdm_auto): # pylint: disable=inconsistent-mro + """ + Standard `tqdm.auto.tqdm` but also sends updates to a Slack app. + May take a few seconds to create (`__init__`). + + - create a Slack app with the `chat:write` scope & invite it to a + channel: + - copy the bot `{token}` & `{channel}` and paste below + >>> from tqdm.contrib.slack import tqdm, trange + >>> for i in tqdm(iterable, token='{token}', channel='{channel}'): + ... ... + """ + @envwrap("tqdm", "slack", is_method=True) + def __init__(self, *args, token=None, channel=None, **kwargs): + """ + Parameters + ---------- + token : str, required. Slack token + [default: ${TQDM_SLACK_TOKEN}]. + channel : int, required. Slack channel + [default: ${TQDM_SLACK_CHANNEL}]. + mininterval : float, optional. + Minimum of [default: 1.5] to avoid rate limit. + + See `tqdm.auto.tqdm.__init__` for other parameters. + """ + if not kwargs.get('disable'): + kwargs = kwargs.copy() + logging.getLogger("HTTPClient").setLevel(logging.WARNING) + self.sio = SlackIO(token, channel) + kwargs['mininterval'] = max(1.5, kwargs.get('mininterval', 1.5)) + super().__init__(*args, **kwargs) + + def display(self, **kwargs): # pylint: disable=arguments-differ + super().display(**kwargs) + fmt = self.format_dict + if fmt.get('bar_format', None): + fmt['bar_format'] = fmt['bar_format'].replace( + '', '`{bar:10}`').replace('{bar}', '`{bar:10u}`') + elif self.total: + fmt['bar_format'] = '{l_bar}`{bar:10}`{r_bar}' + if fmt['ascii'] is False: + fmt['ascii'] = [":black_square:", ":small_blue_diamond:", ":large_blue_diamond:", + ":large_blue_square:"] + fmt['ncols'] = 336 + self.sio.write(self.format_meter(**fmt)) + + def clear(self, *args, **kwargs): + super().clear(*args, **kwargs) + if not self.disable: + self.sio.write("") + + +def tsrange(*args, **kwargs): + """Shortcut for `tqdm.contrib.slack.tqdm(range(*args), **kwargs)`.""" + return tqdm_slack(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_slack +trange = tsrange diff --git a/.venv/lib/python3.12/site-packages/tqdm/contrib/telegram.py b/.venv/lib/python3.12/site-packages/tqdm/contrib/telegram.py new file mode 100644 index 0000000000000000000000000000000000000000..c019248e322214aeccbfaf2d8dac97a69d11470f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/contrib/telegram.py @@ -0,0 +1,152 @@ +""" +Sends updates to a Telegram bot. + +Usage: +>>> from tqdm.contrib.telegram import tqdm, trange +>>> for i in trange(10, token='{token}', chat_id='{chat_id}'): +... ... + +![screenshot](https://tqdm.github.io/img/screenshot-telegram.gif) +""" +from warnings import warn + +from requests import Session + +from ..auto import tqdm as tqdm_auto +from ..std import TqdmWarning +from ..utils import envwrap +from .utils_worker import MonoWorker + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange'] + + +class TelegramIO(MonoWorker): + """Non-blocking file-like IO using a Telegram Bot.""" + API = 'https://api.telegram.org/bot' + + def __init__(self, token, chat_id): + """Creates a new message in the given `chat_id`.""" + super().__init__() + self.token = token + self.chat_id = chat_id + self.session = Session() + self.text = self.__class__.__name__ + self.message_id # pylint: disable=pointless-statement + + @property + def message_id(self): + if hasattr(self, '_message_id'): + return self._message_id # pylint: disable=access-member-before-definition + try: + req = self.session.post( + f'{self.API}{self.token}/sendMessage', + data={'text': f"`{self.text}`", 'chat_id': self.chat_id, + 'parse_mode': 'MarkdownV2'}) + res = req.json() + req.raise_for_status() + except Exception as e: + if req.status_code == 429: + warn("Creation rate limit: try increasing `mininterval`.", + TqdmWarning, stacklevel=2) + else: + tqdm_auto.write(str(e)) + else: + self._message_id = res['result']['message_id'] + return self._message_id + + def write(self, s): + """Replaces internal `message_id`'s text with `s`.""" + if not s: + s = "..." + s = s.replace('\r', '').strip() + if s == self.text: + return # avoid duplicate message Bot error + message_id = self.message_id + if message_id is None: + return + self.text = s + try: + future = self.submit( + self.session.post, f'{self.API}{self.token}/editMessageText', + data={'text': f"`{s}`", 'chat_id': self.chat_id, + 'message_id': message_id, 'parse_mode': 'MarkdownV2'}) + except Exception as e: + tqdm_auto.write(str(e)) + else: + return future + + def delete(self): + """Deletes internal `message_id`.""" + try: + future = self.submit( + self.session.post, '{self.API}{self.token}/deleteMessage', + data={'chat_id': self.chat_id, 'message_id': self.message_id}) + except Exception as e: + tqdm_auto.write(str(e)) + else: + return future + + +class tqdm_telegram(tqdm_auto): # pylint: disable=inconsistent-mro + """ + Standard `tqdm.auto.tqdm` but also sends updates to a Telegram Bot. + May take a few seconds to create (`__init__`). + + - create a bot + - copy its `{token}` + - add the bot to a chat and send it a message such as `/start` + - go to to find out + the `{chat_id}` + - paste the `{token}` & `{chat_id}` below + + >>> from tqdm.contrib.telegram import tqdm, trange + >>> for i in tqdm(iterable, token='{token}', chat_id='{chat_id}'): + ... ... + """ + @envwrap("tqdm", "telegram", is_method=True) + def __init__(self, *args, token=None, chat_id=None, **kwargs): + """ + Parameters + ---------- + token : str, required. Telegram token + [default: ${TQDM_TELEGRAM_TOKEN}]. + chat_id : str, required. Telegram chat ID + [default: ${TQDM_TELEGRAM_CHAT_ID}]. + + See `tqdm.auto.tqdm.__init__` for other parameters. + """ + if not kwargs.get('disable'): + kwargs = kwargs.copy() + self.tgio = TelegramIO(token, chat_id) + super().__init__(*args, **kwargs) + + def display(self, **kwargs): # pylint: disable=arguments-differ + super().display(**kwargs) + fmt = self.format_dict + if fmt.get('bar_format', None): + fmt['bar_format'] = fmt['bar_format'].replace( + '', '{bar:10u}').replace('{bar}', '{bar:10u}') + self.tgio.write(self.format_meter(**fmt)) + + def clear(self, *args, **kwargs): + super().clear(*args, **kwargs) + if not self.disable: + self.tgio.write("") + + def close(self): + if self.disable: + return + super().close() + if not (self.leave or (self.leave is None and self.pos == 0)): + self.tgio.delete() + + +def ttgrange(*args, **kwargs): + """Shortcut for `tqdm.contrib.telegram.tqdm(range(*args), **kwargs)`.""" + return tqdm_telegram(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_telegram +trange = ttgrange diff --git a/.venv/lib/python3.12/site-packages/tqdm/contrib/utils_worker.py b/.venv/lib/python3.12/site-packages/tqdm/contrib/utils_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..89fafc8c92f8ed085077b37eb58329f2588bd5d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/contrib/utils_worker.py @@ -0,0 +1,38 @@ +""" +IO/concurrency helpers for `tqdm.contrib`. +""" +from collections import deque +from concurrent.futures import ThreadPoolExecutor + +from ..auto import tqdm as tqdm_auto + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['MonoWorker'] + + +class MonoWorker: + """ + Supports one running task and one waiting task. + The waiting task is the most recent submitted (others are discarded). + """ + def __init__(self): + self.pool = ThreadPoolExecutor(max_workers=1) + self.futures = deque([], 2) + + def submit(self, func, *args, **kwargs): + """`func(*args, **kwargs)` may replace currently waiting task.""" + futures = self.futures + if len(futures) == futures.maxlen: + running = futures.popleft() + if not running.done(): + if len(futures): # clear waiting + waiting = futures.pop() + waiting.cancel() + futures.appendleft(running) # re-insert running + try: + waiting = self.pool.submit(func, *args, **kwargs) + except Exception as e: + tqdm_auto.write(str(e)) + else: + futures.append(waiting) + return waiting diff --git a/.venv/lib/python3.12/site-packages/tqdm/dask.py b/.venv/lib/python3.12/site-packages/tqdm/dask.py new file mode 100644 index 0000000000000000000000000000000000000000..57f1b668f59dc5991019eee34c7df3232a2c2cd7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/dask.py @@ -0,0 +1,44 @@ +from functools import partial + +from dask.callbacks import Callback + +from .auto import tqdm as tqdm_auto + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['TqdmCallback'] + + +class TqdmCallback(Callback): + """Dask callback for task progress.""" + def __init__(self, start=None, pretask=None, tqdm_class=tqdm_auto, + **tqdm_kwargs): + """ + Parameters + ---------- + tqdm_class : optional + `tqdm` class to use for bars [default: `tqdm.auto.tqdm`]. + tqdm_kwargs : optional + Any other arguments used for all bars. + """ + super().__init__(start=start, pretask=pretask) + if tqdm_kwargs: + tqdm_class = partial(tqdm_class, **tqdm_kwargs) + self.tqdm_class = tqdm_class + + def _start_state(self, _, state): + self.pbar = self.tqdm_class(total=sum( + len(state[k]) for k in ['ready', 'waiting', 'running', 'finished'])) + + def _posttask(self, *_, **__): + self.pbar.update() + + def _finish(self, *_, **__): + self.pbar.close() + + def display(self): + """Displays in the current cell in Notebooks.""" + container = getattr(self.bar, 'container', None) + if container is None: + return + from .notebook import display + display(container) diff --git a/.venv/lib/python3.12/site-packages/tqdm/gui.py b/.venv/lib/python3.12/site-packages/tqdm/gui.py new file mode 100644 index 0000000000000000000000000000000000000000..e7995089f09281d27d52eb082d935854360044a8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/gui.py @@ -0,0 +1,179 @@ +""" +Matplotlib GUI progress bar decorator for iterators. + +Usage: +>>> from tqdm.gui import trange, tqdm +>>> for i in trange(10): +... ... +""" +# future division is important to divide integers and get as +# a result precise floating numbers (instead of truncated int) +import re +from warnings import warn + +# to inherit from the tqdm class +from .std import TqdmExperimentalWarning +from .std import tqdm as std_tqdm + +# import compatibility functions and utilities + +__author__ = {"github.com/": ["casperdcl", "lrq3000"]} +__all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange'] + + +class tqdm_gui(std_tqdm): # pragma: no cover + """Experimental Matplotlib GUI version of tqdm!""" + # TODO: @classmethod: write() on GUI? + def __init__(self, *args, **kwargs): + from collections import deque + + import matplotlib as mpl + import matplotlib.pyplot as plt + kwargs = kwargs.copy() + kwargs['gui'] = True + colour = kwargs.pop('colour', 'g') + super().__init__(*args, **kwargs) + + if self.disable: + return + + warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2) + self.mpl = mpl + self.plt = plt + + # Remember if external environment uses toolbars + self.toolbar = self.mpl.rcParams['toolbar'] + self.mpl.rcParams['toolbar'] = 'None' + + self.mininterval = max(self.mininterval, 0.5) + self.fig, ax = plt.subplots(figsize=(9, 2.2)) + # self.fig.subplots_adjust(bottom=0.2) + total = self.__len__() # avoids TypeError on None #971 + if total is not None: + self.xdata = [] + self.ydata = [] + self.zdata = [] + else: + self.xdata = deque([]) + self.ydata = deque([]) + self.zdata = deque([]) + self.line1, = ax.plot(self.xdata, self.ydata, color='b') + self.line2, = ax.plot(self.xdata, self.zdata, color='k') + ax.set_ylim(0, 0.001) + if total is not None: + ax.set_xlim(0, 100) + ax.set_xlabel("percent") + self.fig.legend((self.line1, self.line2), ("cur", "est"), + loc='center right') + # progress bar + self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour) + else: + # ax.set_xlim(-60, 0) + ax.set_xlim(0, 60) + ax.invert_xaxis() + ax.set_xlabel("seconds") + ax.legend(("cur", "est"), loc='lower left') + ax.grid() + # ax.set_xlabel('seconds') + ax.set_ylabel((self.unit if self.unit else "it") + "/s") + if self.unit_scale: + plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) + ax.yaxis.get_offset_text().set_x(-0.15) + + # Remember if external environment is interactive + self.wasion = plt.isinteractive() + plt.ion() + self.ax = ax + + def close(self): + if self.disable: + return + + self.disable = True + + with self.get_lock(): + self._instances.remove(self) + + # Restore toolbars + self.mpl.rcParams['toolbar'] = self.toolbar + # Return to non-interactive mode + if not self.wasion: + self.plt.ioff() + if self.leave: + self.display() + else: + self.plt.close(self.fig) + + def clear(self, *_, **__): + pass + + def display(self, *_, **__): + n = self.n + cur_t = self._time() + elapsed = cur_t - self.start_t + delta_it = n - self.last_print_n + delta_t = cur_t - self.last_print_t + + # Inline due to multiple calls + total = self.total + xdata = self.xdata + ydata = self.ydata + zdata = self.zdata + ax = self.ax + line1 = self.line1 + line2 = self.line2 + hspan = getattr(self, 'hspan', None) + # instantaneous rate + y = delta_it / delta_t + # overall rate + z = n / elapsed + # update line data + xdata.append(n * 100.0 / total if total else cur_t) + ydata.append(y) + zdata.append(z) + + # Discard old values + # xmin, xmax = ax.get_xlim() + # if (not total) and elapsed > xmin * 1.1: + if (not total) and elapsed > 66: + xdata.popleft() + ydata.popleft() + zdata.popleft() + + ymin, ymax = ax.get_ylim() + if y > ymax or z > ymax: + ymax = 1.1 * y + ax.set_ylim(ymin, ymax) + ax.figure.canvas.draw() + + if total: + line1.set_data(xdata, ydata) + line2.set_data(xdata, zdata) + if hspan: + hspan.set_xy((0, ymin)) + hspan.set_height(ymax - ymin) + hspan.set_width(n / total) + else: + t_ago = [cur_t - i for i in xdata] + line1.set_data(t_ago, ydata) + line2.set_data(t_ago, zdata) + + d = self.format_dict + # remove {bar} + d['bar_format'] = (d['bar_format'] or "{l_bar}{r_bar}").replace( + "{bar}", "") + msg = self.format_meter(**d) + if '' in msg: + msg = "".join(re.split(r'\|?\|?', msg, maxsplit=1)) + ax.set_title(msg, fontname="DejaVu Sans Mono", fontsize=11) + self.plt.pause(1e-9) + + +def tgrange(*args, **kwargs): + """Shortcut for `tqdm.gui.tqdm(range(*args), **kwargs)`.""" + return tqdm_gui(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_gui +trange = tgrange diff --git a/.venv/lib/python3.12/site-packages/tqdm/keras.py b/.venv/lib/python3.12/site-packages/tqdm/keras.py new file mode 100644 index 0000000000000000000000000000000000000000..317b76a69539589f71334836cbe31fda063a7a46 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/keras.py @@ -0,0 +1,123 @@ +from copy import copy +from functools import partial + +from .auto import tqdm as tqdm_auto + +try: + import keras +except (ImportError, AttributeError) as e: + try: + from tensorflow import keras + except ImportError: + raise e +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['TqdmCallback'] + + +class TqdmCallback(keras.callbacks.Callback): + """Keras callback for epoch and batch progress.""" + @staticmethod + def bar2callback(bar, pop=None, delta=(lambda logs: 1)): + def callback(_, logs=None): + n = delta(logs) + if logs: + if pop: + logs = copy(logs) + for i in pop: + logs.pop(i, 0) + bar.set_postfix(logs, refresh=False) + bar.update(n) + + return callback + + def __init__(self, epochs=None, data_size=None, batch_size=None, verbose=1, + tqdm_class=tqdm_auto, **tqdm_kwargs): + """ + Parameters + ---------- + epochs : int, optional + data_size : int, optional + Number of training pairs. + batch_size : int, optional + Number of training pairs per batch. + verbose : int + 0: epoch, 1: batch (transient), 2: batch. [default: 1]. + Will be set to `0` unless both `data_size` and `batch_size` + are given. + tqdm_class : optional + `tqdm` class to use for bars [default: `tqdm.auto.tqdm`]. + tqdm_kwargs : optional + Any other arguments used for all bars. + """ + if tqdm_kwargs: + tqdm_class = partial(tqdm_class, **tqdm_kwargs) + self.tqdm_class = tqdm_class + self.epoch_bar = tqdm_class(total=epochs, unit='epoch') + self.on_epoch_end = self.bar2callback(self.epoch_bar) + if data_size and batch_size: + self.batches = batches = (data_size + batch_size - 1) // batch_size + else: + self.batches = batches = None + self.verbose = verbose + if verbose == 1: + self.batch_bar = tqdm_class(total=batches, unit='batch', leave=False) + self.on_batch_end = self.bar2callback( + self.batch_bar, pop=['batch', 'size'], + delta=lambda logs: logs.get('size', 1)) + + def on_train_begin(self, *_, **__): + params = self.params.get + auto_total = params('epochs', params('nb_epoch', None)) + if auto_total is not None and auto_total != self.epoch_bar.total: + self.epoch_bar.reset(total=auto_total) + + def on_epoch_begin(self, epoch, *_, **__): + if self.epoch_bar.n < epoch: + ebar = self.epoch_bar + ebar.n = ebar.last_print_n = ebar.initial = epoch + if self.verbose: + params = self.params.get + total = params('samples', params( + 'nb_sample', params('steps', None))) or self.batches + if self.verbose == 2: + if hasattr(self, 'batch_bar'): + self.batch_bar.close() + self.batch_bar = self.tqdm_class( + total=total, unit='batch', leave=True, + unit_scale=1 / (params('batch_size', 1) or 1)) + self.on_batch_end = self.bar2callback( + self.batch_bar, pop=['batch', 'size'], + delta=lambda logs: logs.get('size', 1)) + elif self.verbose == 1: + self.batch_bar.unit_scale = 1 / (params('batch_size', 1) or 1) + self.batch_bar.reset(total=total) + else: + raise KeyError('Unknown verbosity') + + def on_train_end(self, *_, **__): + if hasattr(self, 'batch_bar'): + self.batch_bar.close() + self.epoch_bar.close() + + def display(self): + """Displays in the current cell in Notebooks.""" + container = getattr(self.epoch_bar, 'container', None) + if container is None: + return + from .notebook import display + display(container) + batch_bar = getattr(self, 'batch_bar', None) + if batch_bar is not None: + display(batch_bar.container) + + @staticmethod + def _implements_train_batch_hooks(): + return True + + @staticmethod + def _implements_test_batch_hooks(): + return True + + @staticmethod + def _implements_predict_batch_hooks(): + return True diff --git a/.venv/lib/python3.12/site-packages/tqdm/notebook.py b/.venv/lib/python3.12/site-packages/tqdm/notebook.py new file mode 100644 index 0000000000000000000000000000000000000000..f6e1b0a6d15c5286354264116d2815b4285b8880 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/notebook.py @@ -0,0 +1,317 @@ +""" +IPython/Jupyter Notebook progress bar decorator for iterators. +Includes a default `range` iterator printing to `stderr`. + +Usage: +>>> from tqdm.notebook import trange, tqdm +>>> for i in trange(10): +... ... +""" +# import compatibility functions and utilities +import re +import sys +from html import escape +from weakref import proxy + +# to inherit from the tqdm class +from .std import tqdm as std_tqdm + +if True: # pragma: no cover + # import IPython/Jupyter base widget and display utilities + IPY = 0 + try: # IPython 4.x + import ipywidgets # noqa: F401, pylint: disable=unused-import + IPY = 4 + except ImportError: # IPython 3.x / 2.x + IPY = 32 + import warnings + with warnings.catch_warnings(): + warnings.filterwarnings( + 'ignore', message=".*The `IPython.html` package has been deprecated.*") + try: + import IPython.html.widgets + except ImportError: + pass + else: + ipywidgets = IPython.html.widgets + + try: # IPython 4.x / 3.x + if IPY == 32: + from IPython.html.widgets import HTML + from IPython.html.widgets import FloatProgress as IProgress + from IPython.html.widgets import HBox + IPY = 3 + else: + from ipywidgets import HTML + from ipywidgets import FloatProgress as IProgress + from ipywidgets import HBox + except ImportError: + try: # IPython 2.x + from IPython.html.widgets import HTML + from IPython.html.widgets import ContainerWidget as HBox + from IPython.html.widgets import FloatProgressWidget as IProgress + IPY = 2 + except ImportError: + IPY = 0 + IProgress = None + HBox = object + + try: + from IPython.display import display # , clear_output + except ImportError: + pass + +__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]} +__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange'] +WARN_NOIPYW = ("IProgress not found. Please update jupyter and ipywidgets." + " See https://ipywidgets.readthedocs.io/en/stable" + "/user_install.html") + + +class TqdmHBox(HBox): + """`ipywidgets.HBox` with a pretty representation""" + def _json_(self, pretty=None): + pbar = getattr(self, 'pbar', None) + if pbar is None: + return {} + d = pbar.format_dict + if pretty is not None: + d["ascii"] = not pretty + return d + + def __repr__(self, pretty=False): + pbar = getattr(self, 'pbar', None) + if pbar is None: + return super().__repr__() + return pbar.format_meter(**self._json_(pretty)) + + def _repr_pretty_(self, pp, *_, **__): + pp.text(self.__repr__(True)) + + +class tqdm_notebook(std_tqdm): + """ + Experimental IPython/Jupyter Notebook widget using tqdm! + """ + @staticmethod + def status_printer(_, total=None, desc=None, ncols=None): + """ + Manage the printing of an IPython/Jupyter Notebook progress bar widget. + """ + # Fallback to text bar if there's no total + # DEPRECATED: replaced with an 'info' style bar + # if not total: + # return super(tqdm_notebook, tqdm_notebook).status_printer(file) + + # fp = file + + # Prepare IPython progress bar + if IProgress is None: # #187 #451 #558 #872 + raise ImportError(WARN_NOIPYW) + if total: + pbar = IProgress(min=0, max=total) + else: # No total? Show info style bar with no progress tqdm status + pbar = IProgress(min=0, max=1) + pbar.value = 1 + pbar.bar_style = 'info' + if ncols is None: + pbar.layout.width = "20px" + + ltext = HTML() + rtext = HTML() + if desc: + ltext.value = desc + container = TqdmHBox(children=[ltext, pbar, rtext]) + # Prepare layout + if ncols is not None: # use default style of ipywidgets + # ncols could be 100, "100px", "100%" + ncols = str(ncols) # ipywidgets only accepts string + try: + if int(ncols) > 0: # isnumeric and positive + ncols += 'px' + except ValueError: + pass + pbar.layout.flex = '2' + container.layout.width = ncols + container.layout.display = 'inline-flex' + container.layout.flex_flow = 'row wrap' + + return container + + def display(self, msg=None, pos=None, + # additional signals + close=False, bar_style=None, check_delay=True): + # Note: contrary to native tqdm, msg='' does NOT clear bar + # goal is to keep all infos if error happens so user knows + # at which iteration the loop failed. + + # Clear previous output (really necessary?) + # clear_output(wait=1) + + if not msg and not close: + d = self.format_dict + # remove {bar} + d['bar_format'] = (d['bar_format'] or "{l_bar}{r_bar}").replace( + "{bar}", "") + msg = self.format_meter(**d) + + ltext, pbar, rtext = self.container.children + pbar.value = self.n + + if msg: + msg = msg.replace(' ', '\u2007') # fix html space padding + # html escape special characters (like '&') + if '' in msg: + left, right = map(escape, re.split(r'\|?\|?', msg, maxsplit=1)) + else: + left, right = '', escape(msg) + + # Update description + ltext.value = left + # never clear the bar (signal: msg='') + if right: + rtext.value = right + + # Change bar style + if bar_style: + # Hack-ish way to avoid the danger bar_style being overridden by + # success because the bar gets closed after the error... + if pbar.bar_style != 'danger' or bar_style != 'success': + pbar.bar_style = bar_style + + # Special signal to close the bar + if close and pbar.bar_style != 'danger': # hide only if no error + try: + self.container.close() + except AttributeError: + self.container.visible = False + self.container.layout.visibility = 'hidden' # IPYW>=8 + + if check_delay and self.delay > 0 and not self.displayed: + display(self.container) + self.displayed = True + + @property + def colour(self): + if hasattr(self, 'container'): + return self.container.children[-2].style.bar_color + + @colour.setter + def colour(self, bar_color): + if hasattr(self, 'container'): + self.container.children[-2].style.bar_color = bar_color + + def __init__(self, *args, **kwargs): + """ + Supports the usual `tqdm.tqdm` parameters as well as those listed below. + + Parameters + ---------- + display : Whether to call `display(self.container)` immediately + [default: True]. + """ + kwargs = kwargs.copy() + # Setup default output + file_kwarg = kwargs.get('file', sys.stderr) + if file_kwarg is sys.stderr or file_kwarg is None: + kwargs['file'] = sys.stdout # avoid the red block in IPython + + # Initialize parent class + avoid printing by using gui=True + kwargs['gui'] = True + # convert disable = None to False + kwargs['disable'] = bool(kwargs.get('disable', False)) + colour = kwargs.pop('colour', None) + display_here = kwargs.pop('display', True) + super().__init__(*args, **kwargs) + if self.disable or not kwargs['gui']: + self.disp = lambda *_, **__: None + return + + # Get bar width + self.ncols = '100%' if self.dynamic_ncols else kwargs.get("ncols", None) + + # Replace with IPython progress bar display (with correct total) + unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1 + total = self.total * unit_scale if self.total else self.total + self.container = self.status_printer(self.fp, total, self.desc, self.ncols) + self.container.pbar = proxy(self) + self.displayed = False + if display_here and self.delay <= 0: + display(self.container) + self.displayed = True + self.disp = self.display + self.colour = colour + + # Print initial bar state + if not self.disable: + self.display(check_delay=False) + + def __iter__(self): + try: + it = super().__iter__() + yield from it + # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt + except: # NOQA + self.disp(bar_style='danger') + raise + # NB: don't `finally: close()` + # since this could be a shared bar which the user will `reset()` + + def update(self, n=1): + try: + return super().update(n=n) + # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt + except: # NOQA + # cannot catch KeyboardInterrupt when using manual tqdm + # as the interrupt will most likely happen on another statement + self.disp(bar_style='danger') + raise + # NB: don't `finally: close()` + # since this could be a shared bar which the user will `reset()` + + def close(self): + if self.disable: + return + super().close() + # Try to detect if there was an error or KeyboardInterrupt + # in manual mode: if n < total, things probably got wrong + if self.total and self.n < self.total: + self.disp(bar_style='danger', check_delay=False) + else: + if self.leave: + self.disp(bar_style='success', check_delay=False) + else: + self.disp(close=True, check_delay=False) + + def clear(self, *_, **__): + pass + + def reset(self, total=None): + """ + Resets to 0 iterations for repeated use. + + Consider combining with `leave=True`. + + Parameters + ---------- + total : int or float, optional. Total to use for the new bar. + """ + if self.disable: + return super().reset(total=total) + _, pbar, _ = self.container.children + pbar.bar_style = '' + if total is not None: + pbar.max = total + if not self.total and self.ncols is None: # no longer unknown total + pbar.layout.width = None # reset width + return super().reset(total=total) + + +def tnrange(*args, **kwargs): + """Shortcut for `tqdm.notebook.tqdm(range(*args), **kwargs)`.""" + return tqdm_notebook(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_notebook +trange = tnrange diff --git a/.venv/lib/python3.12/site-packages/tqdm/rich.py b/.venv/lib/python3.12/site-packages/tqdm/rich.py new file mode 100644 index 0000000000000000000000000000000000000000..bddd1334c85a7ad306bcd152b260ebcefa595377 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/rich.py @@ -0,0 +1,154 @@ +""" +`rich.progress` decorator for iterators. + +Usage: +>>> from tqdm.rich import trange, tqdm +>>> for i in trange(10): +... ... +""" +from warnings import warn + +from rich.progress import ( + BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize) + +from .std import TqdmExperimentalWarning +from .std import tqdm as std_tqdm + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange'] + + +class FractionColumn(ProgressColumn): + """Renders completed/total, e.g. '0.5/2.3 G'.""" + def __init__(self, unit_scale=False, unit_divisor=1000): + self.unit_scale = unit_scale + self.unit_divisor = unit_divisor + super().__init__() + + def render(self, task): + """Calculate common unit for completed and total.""" + completed = int(task.completed) + # total is None when the iterable has no length (e.g. a generator) + total = int(task.total) if task.total is not None else None + base = total if total is not None else completed + if self.unit_scale: + unit, suffix = filesize.pick_unit_and_suffix( + base, + ["", "K", "M", "G", "T", "P", "E", "Z", "Y"], + self.unit_divisor, + ) + else: + unit, suffix = filesize.pick_unit_and_suffix(base, [""], 1) + precision = 0 if unit == 1 else 1 + total_str = f"{total/unit:,.{precision}f}" if total is not None else "?" + return Text( + f"{completed/unit:,.{precision}f}/{total_str} {suffix}", + style="progress.download") + + +class RateColumn(ProgressColumn): + """Renders human readable transfer speed.""" + def __init__(self, unit="", unit_scale=False, unit_divisor=1000): + self.unit = unit + self.unit_scale = unit_scale + self.unit_divisor = unit_divisor + super().__init__() + + def render(self, task): + """Show data transfer speed.""" + speed = task.speed + if speed is None: + return Text(f"? {self.unit}/s", style="progress.data.speed") + if self.unit_scale: + unit, suffix = filesize.pick_unit_and_suffix( + speed, + ["", "K", "M", "G", "T", "P", "E", "Z", "Y"], + self.unit_divisor, + ) + else: + unit, suffix = filesize.pick_unit_and_suffix(speed, [""], 1) + precision = 0 if unit == 1 else 1 + return Text(f"{speed/unit:,.{precision}f} {suffix}{self.unit}/s", + style="progress.data.speed") + + +class tqdm_rich(std_tqdm): # pragma: no cover + """Experimental rich.progress GUI version of tqdm!""" + # TODO: @classmethod: write()? + def __init__(self, *args, **kwargs): + """ + This class accepts the following parameters *in addition* to + the parameters accepted by `tqdm`. + + Parameters + ---------- + progress : tuple, optional + arguments for `rich.progress.Progress()`. + options : dict, optional + keyword arguments for `rich.progress.Progress()`. + """ + kwargs = kwargs.copy() + kwargs['gui'] = True + # convert disable = None to False + kwargs['disable'] = bool(kwargs.get('disable', False)) + progress = kwargs.pop('progress', None) + options = kwargs.pop('options', {}).copy() + super().__init__(*args, **kwargs) + + if self.disable: + return + + warn("rich is experimental/alpha", TqdmExperimentalWarning, stacklevel=2) + d = self.format_dict + if progress is None: + progress = ( + "[progress.description]{task.description}" + "[progress.percentage]{task.percentage:>4.0f}%", + BarColumn(bar_width=None), + FractionColumn( + unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']), + "[", TimeElapsedColumn(), "<", TimeRemainingColumn(), + ",", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'], + unit_divisor=d['unit_divisor']), "]" + ) + options.setdefault('transient', not self.leave) + self._prog = Progress(*progress, **options) + self._prog.__enter__() + self._task_id = self._prog.add_task(self.desc or "", **d) + + def close(self): + if self.disable: + return + self.display() # print 100%, vis #1306 + super().close() + self._prog.__exit__(None, None, None) + + def clear(self, *_, **__): + pass + + def display(self, *_, **__): + if not hasattr(self, '_task_id'): + return + self._prog.update(self._task_id, completed=self.n, description=self.desc) + + def reset(self, total=None): + """ + Resets to 0 iterations for repeated use. + + Parameters + ---------- + total : int or float, optional. Total to use for the new bar. + """ + if hasattr(self, '_prog'): + self._prog.reset(total=total) + super().reset(total=total) + + +def trrange(*args, **kwargs): + """Shortcut for `tqdm.rich.tqdm(range(*args), **kwargs)`.""" + return tqdm_rich(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_rich +trange = trrange diff --git a/.venv/lib/python3.12/site-packages/tqdm/std.py b/.venv/lib/python3.12/site-packages/tqdm/std.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a11dde4dd612a0d02c907190386548093bb64f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/std.py @@ -0,0 +1,1532 @@ +""" +Customisable progress bar decorator for iterators. +Includes a default `range` iterator printing to `stderr`. + +Usage: +>>> from tqdm import trange, tqdm +>>> for i in trange(10): +... ... +""" +import sys +from collections import OrderedDict, defaultdict +from contextlib import contextmanager +from datetime import datetime, timedelta, timezone +from numbers import Number +from time import time +from warnings import warn +from weakref import WeakSet + +from ._monitor import TMonitor +from .utils import ( + CallbackIOWrapper, Comparable, DisableOnWriteError, FormatReplace, SimpleTextIOWrapper, + _is_ascii, _screen_shape_wrapper, _supports_unicode, _term_move_up, disp_len, disp_trim, + envwrap) + +__author__ = "https://github.com/tqdm/tqdm#contributions" +__all__ = ['tqdm', 'trange', + 'TqdmTypeError', 'TqdmKeyError', 'TqdmWarning', + 'TqdmExperimentalWarning', 'TqdmDeprecationWarning', + 'TqdmMonitorWarning'] + + +class TqdmTypeError(TypeError): + pass + + +class TqdmKeyError(KeyError): + pass + + +class TqdmWarning(Warning): + """base class for all tqdm warnings. + + Used for non-external-code-breaking errors, such as garbled printing. + """ + def __init__(self, msg, fp_write=None): # noqa: B042 + if fp_write is not None: + fp_write("\n" + self.__class__.__name__ + ": " + str(msg).rstrip() + '\n') + else: + super().__init__(msg) + + +class TqdmExperimentalWarning(TqdmWarning, FutureWarning): + """beta feature, unstable API and behaviour""" + + +class TqdmDeprecationWarning(TqdmWarning, DeprecationWarning): + """may be removed in a future release""" + # not suppressed if raised + + +class TqdmMonitorWarning(TqdmWarning, RuntimeWarning): + """tqdm monitor errors which do not affect external functionality""" + + +def TRLock(*args, **kwargs): + """threading RLock""" + try: + from threading import RLock + return RLock(*args, **kwargs) + except (ImportError, OSError): # pragma: no cover + pass + + +class TqdmDefaultWriteLock: + """ + Provide a default write lock for thread and multiprocessing safety. + Works only on platforms supporting `fork` (so Windows is excluded). + You must initialise a `tqdm` or `TqdmDefaultWriteLock` instance + before forking in order for the write lock to work. + On Windows, you need to supply the lock from the parent to the children as + an argument to joblib or the parallelism lib you use. + """ + # global thread lock so no setup required for multithreading. + # NB: Do not create multiprocessing lock as it sets the multiprocessing + # context, disallowing `spawn()`/`forkserver()` + th_lock = TRLock() + + def __init__(self): + # Create global parallelism locks to avoid racing issues with parallel + # bars works only if fork available (Linux/MacOSX, but not Windows) + cls = type(self) + root_lock = cls.th_lock + if root_lock is not None: + root_lock.acquire() + cls.create_mp_lock() + self.locks = [lk for lk in [cls.mp_lock, cls.th_lock] if lk is not None] + if root_lock is not None: + root_lock.release() + + def acquire(self, *a, **k): + for lock in self.locks: + lock.acquire(*a, **k) + + def release(self): + for lock in self.locks[::-1]: # Release in inverse order of acquisition + lock.release() + + def __enter__(self): + self.acquire() + + def __exit__(self, *exc): + self.release() + + @classmethod + def create_mp_lock(cls): + if not hasattr(cls, 'mp_lock'): + try: + from multiprocessing import RLock + cls.mp_lock = RLock() + except (ImportError, OSError): # pragma: no cover + cls.mp_lock = None + + @classmethod + def create_th_lock(cls): + assert hasattr(cls, 'th_lock') + warn("create_th_lock not needed anymore", TqdmDeprecationWarning, stacklevel=2) + + +class Bar: + """ + `str.format`-able bar with format specifiers: `[width][type]` + + - `width` + + unspecified (default): use `self.default_len` + + `int >= 0`: overrides `self.default_len` + + `int < 0`: subtract from `self.default_len` + - `type` + + `a`: ascii (`charset=self.ASCII` override) + + `u`: unicode (`charset=self.UTF` override) + + `b`: blank (`charset=" "` override) + """ + ASCII = " 123456789#" + UTF = " " + ''.join(map(chr, range(0x258F, 0x2587, -1))) + BLANK = " " + COLOUR_RESET = '\x1b[0m' + COLOUR_RGB = '\x1b[38;2;%d;%d;%dm' + COLOURS = {'BLACK': '\x1b[30m', 'RED': '\x1b[31m', 'GREEN': '\x1b[32m', + 'YELLOW': '\x1b[33m', 'BLUE': '\x1b[34m', 'MAGENTA': '\x1b[35m', + 'CYAN': '\x1b[36m', 'WHITE': '\x1b[37m'} + + def __init__(self, frac, default_len=10, charset=UTF, colour=None): + if not 0 <= frac <= 1: + warn("clamping frac to range [0, 1]", TqdmWarning, stacklevel=2) + frac = max(0, min(1, frac)) + assert default_len > 0 + self.frac = frac + self.default_len = default_len + self.charset = charset + self.colour = colour + + @property + def colour(self): + return self._colour + + @colour.setter + def colour(self, value): + if not value: + self._colour = None + return + try: + if value.upper() in self.COLOURS: + self._colour = self.COLOURS[value.upper()] + elif value[0] == '#' and len(value) == 7: + self._colour = self.COLOUR_RGB % tuple( + int(i, 16) for i in (value[1:3], value[3:5], value[5:7])) + else: + raise KeyError + except (KeyError, AttributeError): + warn(f"Unknown colour ({value}); valid choices:" + f" [hex (#00ff00), {', '.join(self.COLOURS)}]", TqdmWarning, stacklevel=2) + self._colour = None + + def __format__(self, format_spec): + if format_spec: + _type = format_spec[-1].lower() + try: + charset = {'a': self.ASCII, 'u': self.UTF, 'b': self.BLANK}[_type] + except KeyError: + charset = self.charset + else: + format_spec = format_spec[:-1] + if format_spec: + N_BARS = int(format_spec) + if N_BARS < 0: + N_BARS += self.default_len + else: + N_BARS = self.default_len + else: + charset = self.charset + N_BARS = self.default_len + + nsyms = len(charset) - 1 + bar_length, frac_bar_length = divmod(int(self.frac * N_BARS * nsyms), nsyms) + + res = charset[-1] * bar_length + if bar_length < N_BARS: # whitespace padding + res = res + charset[frac_bar_length] + charset[0] * (N_BARS - bar_length - 1) + return self.colour + res + self.COLOUR_RESET if self.colour else res + + +class EMA: + """ + Exponential moving average: smoothing to give progressively lower + weights to older values. + + Parameters + ---------- + smoothing : float, optional + Smoothing factor in range [0, 1], [default: 0.3]. + Increase to give more weight to recent values. + Ranges from 0 (yields old value) to 1 (yields new value). + """ + def __init__(self, smoothing=0.3): + self.alpha = smoothing + self.last = 0 + self.calls = 0 + + def __call__(self, x=None): + """ + Parameters + ---------- + x : float + New value to include in EMA. + """ + beta = 1 - self.alpha + if x is not None: + self.last = self.alpha * x + beta * self.last + self.calls += 1 + return self.last / (1 - beta ** self.calls) if self.calls else self.last + + +class tqdm(Comparable): + """ + Decorate an iterable object, returning an iterator which acts exactly + like the original iterable, but prints a dynamically updating + progress bar every time a value is requested. + + Parameters + ---------- + iterable : iterable, optional + Iterable to decorate with a progress bar. + Leave blank to manually manage the updates. + desc : str, optional + Prefix for the progress bar. + total : int or float, optional + The number of expected iterations. If unspecified, + len(iterable) is used if possible. If float("inf") or as a last + resort, only basic progress statistics are displayed + (no ETA, no progress bar). + If `gui` is True and this parameter needs subsequent updating, + specify an initial arbitrary large positive number, + e.g. 9e9. + leave : bool, optional + If [default: True], keeps all traces of the progress bar + upon termination of iteration. + If `None`, will leave only if `position` is `0`. + file : `io.TextIOWrapper` or `io.StringIO`, optional + Specifies where to output the progress messages + (default: sys.stderr). Uses `file.write(str)` and `file.flush()` + methods. For encoding, see `write_bytes`. + ncols : int, optional + The width of the entire output message. If specified, + dynamically resizes the progress bar to stay within this bound. + If unspecified, attempts to use environment width. The + fallback is a meter width of 10 and no limit for the counter and + statistics. If 0, will not print any meter (only stats). + mininterval : float, optional + Minimum progress display update interval [default: 0.1] seconds. + maxinterval : float, optional + Maximum progress display update interval [default: 10] seconds. + Automatically adjusts `miniters` to correspond to `mininterval` + after long display update lag. Only works if `dynamic_miniters` + or monitor thread is enabled. + miniters : int or float, optional + Minimum progress display update interval, in iterations. + If 0 and `dynamic_miniters`, will automatically adjust to equal + `mininterval` (more CPU efficient, good for tight loops). + If > 0, will skip display of specified number of iterations. + Tweak this and `mininterval` to get very efficient loops. + If your progress is erratic with both fast and slow iterations + (network, skipping items, etc) you should set miniters=1. + ascii : bool or str, optional + If unspecified or False, use unicode (smooth blocks) to fill + the meter. The fallback is to use ASCII characters " 123456789#". + disable : bool, optional + Whether to disable the entire progress bar wrapper + [default: False]. If set to None, disable on non-TTY. + unit : str, optional + String that will be used to define the unit of each iteration + [default: it]. + unit_scale : bool or int or float, optional + If 1 or True, the number of iterations will be reduced/scaled + automatically and a metric prefix following the + International System of Units standard will be added + (kilo, mega, etc.) [default: False]. If any other non-zero + number, will scale `total` and `n`. + dynamic_ncols : bool, optional + If set, constantly alters `ncols` and `nrows` to the + environment (allowing for window resizes) [default: False]. + smoothing : float, optional + Exponential moving average smoothing factor for speed estimates + (ignored in GUI mode). Ranges from 0 (average speed) to 1 + (current/instantaneous speed) [default: 0.3]. + bar_format : str, optional + Specify a custom bar string formatting. May impact performance. + [default: '{l_bar}{bar}{r_bar}'], where + l_bar='{desc}: {percentage:3.0f}%|' and + r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ' + '{rate_fmt}{postfix}]' + Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, + percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, + rate, rate_fmt, rate_noinv, rate_noinv_fmt, + rate_inv, rate_inv_fmt, postfix, unit_divisor, + remaining, remaining_s, eta. + Note that a trailing ": " is automatically removed after {desc} + if the latter is empty. + initial : int or float, optional + The initial counter value. Useful when restarting a progress + bar [default: 0]. If using float, consider specifying `{n:.3f}` + or similar in `bar_format`, or specifying `unit_scale`. + position : int, optional + Specify the line offset to print this bar (starting from 0) + Automatic if unspecified. + Useful to manage multiple bars at once (eg, from threads). + postfix : dict or *, optional + Specify additional stats to display at the end of the bar. + Calls `set_postfix(**postfix)` if possible (dict). + unit_divisor : float, optional + [default: 1000], ignored unless `unit_scale` is True. + write_bytes : bool, optional + Whether to write bytes. If (default: False) will write unicode. + lock_args : tuple, optional + Passed to `refresh` for intermediate output + (initialisation, iterating, and updating). + nrows : int, optional + The screen height. If specified, hides nested bars outside this + bound. If unspecified, attempts to use environment height. + The fallback is 20. + colour : str, optional + Bar colour (e.g. 'green', '#00ff00'). + delay : float, optional + Don't display until [default: 0] seconds have elapsed. + gui : bool, optional + WARNING: internal parameter - do not use. + Use tqdm.gui.tqdm(...) instead. If set, will attempt to use + matplotlib animations for a graphical output [default: False]. + + Returns + ------- + out : decorated iterator. + """ + + monitor_interval = 10 # set to 0 to disable the thread + monitor = None + _instances = WeakSet() + + @staticmethod + def format_sizeof(num, suffix='', divisor=1000): + """ + Formats a number (greater than unity) with SI Order of Magnitude + prefixes. + + Parameters + ---------- + num : float + Number ( >= 1) to format. + suffix : str, optional + Post-postfix [default: '']. + divisor : float, optional + Divisor between prefixes [default: 1000]. + + Returns + ------- + out : str + Number with Order of Magnitude SI unit postfix. + """ + for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']: + if abs(num) < 999.5: + if abs(num) < 99.95: + if abs(num) < 9.995: + return f'{num:1.2f}{unit}{suffix}' + return f'{num:2.1f}{unit}{suffix}' + return f'{num:3.0f}{unit}{suffix}' + num /= divisor + return f'{num:3.1f}Y{suffix}' + + @staticmethod + def format_interval(t): + """ + Formats a number of seconds as a clock time, [H:]MM:SS + + Parameters + ---------- + t : int + Number of seconds. + + Returns + ------- + out : str + [H:]MM:SS + """ + sign = '-' if t < 0 else '' + mins, s = divmod(abs(int(t)), 60) + h, m = divmod(mins, 60) + return f'{sign}{h:d}:{m:02d}:{s:02d}' if h else f'{sign}{m:02d}:{s:02d}' + + @staticmethod + def format_num(n): + """ + Intelligent scientific notation (.3g). + + Parameters + ---------- + n : int or float or Numeric + A Number. + + Returns + ------- + out : str + Formatted number. + """ + f = f'{n:.3g}'.replace('e+0', 'e+').replace('e-0', 'e-') + n = str(n) + return f if len(f) < len(n) else n + + @staticmethod + def status_printer(file): + """ + Manage the printing and in-place updating of a line of characters. + Note that if the string is longer than a line, then in-place + updating may not work (it will print a new line at each refresh). + """ + fp = file + fp_flush = getattr(fp, 'flush', lambda: None) # pragma: no cover + if fp in (sys.stderr, sys.stdout): + getattr(sys.stderr, 'flush', lambda: None)() + getattr(sys.stdout, 'flush', lambda: None)() + + def fp_write(s): + fp.write(str(s)) + fp_flush() + + last_len = [0] + + def print_status(s): + len_s = disp_len(s) + fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0))) + last_len[0] = len_s + + return print_status + + @staticmethod + def format_meter(n, total, elapsed, ncols=None, prefix='', + ascii=False, # pylint: disable=redefined-builtin + unit='it', unit_scale=False, rate=None, bar_format=None, postfix=None, + unit_divisor=1000, initial=0, colour=None, **extra_kwargs): + """ + Return a string-based progress bar given some parameters + + Parameters + ---------- + n : int or float + Number of finished iterations. + total : int or float + The expected total number of iterations. If meaningless (None), + only basic progress statistics are displayed (no ETA). + elapsed : float + Number of seconds passed since start. + ncols : int, optional + The width of the entire output message. If specified, + dynamically resizes `{bar}` to stay within this bound + [default: None]. If `0`, will not print any bar (only stats). + The fallback is `{bar:10}`. + prefix : str, optional + Prefix message (included in total width) [default: '']. + Use as {desc} in bar_format string. + ascii : bool, optional or str, optional + If not set, use unicode (smooth blocks) to fill the meter + [default: False]. The fallback is to use ASCII characters + " 123456789#". + unit : str, optional + The iteration unit [default: 'it']. + unit_scale : bool or int or float, optional + If 1 or True, the number of iterations will be printed with an + appropriate SI metric prefix (k = 10^3, M = 10^6, etc.) + [default: False]. If any other non-zero number, will scale + `total` and `n`. + rate : float, optional + Manual override for iteration rate. + If [default: None], uses n/elapsed. + bar_format : str, optional + Specify a custom bar string formatting. May impact performance. + [default: '{l_bar}{bar}{r_bar}'], where + l_bar='{desc}: {percentage:3.0f}%|' and + r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ' + '{rate_fmt}{postfix}]' + Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, + percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, + rate, rate_fmt, rate_noinv, rate_noinv_fmt, + rate_inv, rate_inv_fmt, postfix, unit_divisor, + remaining, remaining_s, eta. + Note that a trailing ": " is automatically removed after {desc} + if the latter is empty. + postfix : *, optional + Similar to `prefix`, but placed at the end + (e.g. for additional stats). + Note: postfix is usually a string (not a dict) for this method, + and will if possible be set to postfix = ', ' + postfix. + However other types are supported (#382). + unit_divisor : float, optional + [default: 1000], ignored unless `unit_scale` is True. + initial : int or float, optional + The initial counter value [default: 0]. + colour : str, optional + Bar colour (e.g. 'green', '#00ff00'). + + Returns + ------- + out : Formatted meter and stats, ready to display. + """ + + # sanity check: total + if total and (n >= (total + 0.5) or total == float("inf")): + # allow float imprecision (#849) or inf (#651) + total = None + + # apply custom scale if necessary + if unit_scale and unit_scale not in (True, 1): + if total: + total *= unit_scale + n *= unit_scale + if rate: + rate *= unit_scale # by default rate = self.avg_dn / self.avg_dt + unit_scale = False + + elapsed_str = tqdm.format_interval(elapsed) + + # if unspecified, attempt to use rate = average speed + # (we allow manual override since predicting time is an arcane art) + if rate is None and elapsed: + rate = (n - initial) / elapsed + inv_rate = 1 / rate if rate else None + format_sizeof = tqdm.format_sizeof + rate_noinv_fmt = ((format_sizeof(rate) if unit_scale else f'{rate:5.2f}') + if rate else '?') + unit + '/s' + rate_inv_fmt = ( + (format_sizeof(inv_rate) if unit_scale else f'{inv_rate:5.2f}') + if inv_rate else '?') + 's/' + unit + rate_fmt = rate_inv_fmt if inv_rate and inv_rate > 1 else rate_noinv_fmt + + if unit_scale: + n_fmt = format_sizeof(n, divisor=unit_divisor) + total_fmt = format_sizeof(total, divisor=unit_divisor) if total is not None else '?' + else: + n_fmt = str(n) + total_fmt = str(total) if total is not None else '?' + + try: + postfix = ', ' + postfix if postfix else '' + except TypeError: + pass + + remaining = (total - n) / rate if rate and total else 0 + remaining_str = tqdm.format_interval(remaining) if rate else '?' + try: + eta_dt = (datetime.now() + timedelta(seconds=remaining) + if rate and total else datetime.fromtimestamp(0, timezone.utc)) + except OverflowError: + eta_dt = datetime.max + + # format the stats displayed to the left and right sides of the bar + if prefix: + # old prefix setup work around + bool_prefix_colon_already = (prefix[-2:] == ": ") + l_bar = prefix if bool_prefix_colon_already else prefix + ": " + else: + l_bar = '' + + r_bar = f'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}{postfix}]' + + # Custom bar formatting + # Populate a dict with all available progress indicators + format_dict = { + # slight extension of self.format_dict + 'n': n, 'n_fmt': n_fmt, 'total': total, 'total_fmt': total_fmt, + 'elapsed': elapsed_str, 'elapsed_s': elapsed, + 'ncols': ncols, 'desc': prefix or '', 'unit': unit, + 'rate': inv_rate if inv_rate and inv_rate > 1 else rate, + 'rate_fmt': rate_fmt, 'rate_noinv': rate, + 'rate_noinv_fmt': rate_noinv_fmt, 'rate_inv': inv_rate, + 'rate_inv_fmt': rate_inv_fmt, + 'postfix': postfix, 'unit_divisor': unit_divisor, + 'colour': colour, + # plus more useful definitions + 'remaining': remaining_str, 'remaining_s': remaining, + 'l_bar': l_bar, 'r_bar': r_bar, 'eta': eta_dt, + **extra_kwargs} + + # total is known: we can predict some stats + if total: + # fractional and percentage progress + frac = n / total + percentage = frac * 100 + + l_bar += f'{percentage:3.0f}%|' + + if ncols == 0: + return l_bar[:-1] + r_bar[1:] + + format_dict.update(l_bar=l_bar) + if bar_format: + format_dict.update(percentage=percentage) + + # auto-remove colon for empty `{desc}` + if not prefix: + bar_format = bar_format.replace("{desc}: ", '') + else: + bar_format = "{l_bar}{bar}{r_bar}" + + full_bar = FormatReplace() + nobar = bar_format.format(bar=full_bar, **format_dict) # no `{bar}` + if not full_bar.format_called: + return disp_trim(nobar, ncols) if ncols else nobar + + # Formatting progress bar space available for bar's display + full_bar = Bar(frac, + max(1, ncols - disp_len(nobar)) if ncols else 10, + charset=Bar.ASCII if ascii is True else ascii or Bar.UTF, + colour=colour) + if not _is_ascii(full_bar.charset) and _is_ascii(bar_format): + bar_format = str(bar_format) + res = bar_format.format(bar=full_bar, **format_dict) + return disp_trim(res, ncols) if ncols else res + + elif bar_format: + # user-specified bar_format but no total + l_bar += '|' + format_dict.update(l_bar=l_bar, percentage=0) + full_bar = FormatReplace() + nobar = bar_format.format(bar=full_bar, **format_dict) + if not full_bar.format_called: + return disp_trim(nobar, ncols) if ncols else nobar + full_bar = Bar(0, + max(1, ncols - disp_len(nobar)) if ncols else 10, + charset=Bar.BLANK, colour=colour) + res = bar_format.format(bar=full_bar, **format_dict) + return disp_trim(res, ncols) if ncols else res + else: + # no total: no bar & ETA, just progress stats + res = (f'{(prefix + ": ") if prefix else ""}' + f'{n_fmt}{unit} [{elapsed_str}, {rate_fmt}{postfix}]') + return disp_trim(res, ncols) if ncols else res + + def __new__(cls, *_, **__): + instance = object.__new__(cls) + with cls.get_lock(): # also constructs lock if non-existent + cls._instances.add(instance) + # create monitoring thread + if cls.monitor_interval and (cls.monitor is None + or not cls.monitor.report()): + try: + cls.monitor = TMonitor(cls, cls.monitor_interval) + except Exception as e: # pragma: nocover + warn("tqdm:disabling monitor support" + " (monitor_interval = 0) due to:\n" + str(e), + TqdmMonitorWarning, stacklevel=2) + cls.monitor_interval = 0 + return instance + + @classmethod + def _get_free_pos(cls, instance=None): + """Skips specified instance.""" + positions = {abs(inst.pos) for inst in cls._instances + if inst is not instance and hasattr(inst, "pos")} + return min(set(range(len(positions) + 1)).difference(positions)) + + @classmethod + def _decr_instances(cls, instance): + """ + Remove from list and reposition another unfixed bar + to fill the new gap. + + This means that by default (where all nested bars are unfixed), + order is not maintained but screen flicker/blank space is minimised. + (tqdm<=4.44.1 moved ALL subsequent unfixed bars up.) + """ + with cls._lock: + try: + cls._instances.remove(instance) + except KeyError: + # if not instance.gui: # pragma: no cover + # raise + pass # py2: maybe magically removed already + # else: + if not instance.gui: + last = (instance.nrows or 20) - 1 + # find unfixed (`pos >= 0`) overflow (`pos >= nrows - 1`) + instances = list(filter( + lambda i: hasattr(i, "pos") and last <= i.pos, + cls._instances)) + # set first found to current `pos` + if instances: + inst = min(instances, key=lambda i: i.pos) + inst.clear(nolock=True) + inst.pos = abs(instance.pos) + + @classmethod + def write(cls, s, file=None, end="\n", nolock=False): + """Print a message via tqdm (without overlap with bars).""" + fp = file if file is not None else sys.stdout + if fp is None: + return + with cls.external_write_mode(file=file, nolock=nolock): + # Write the message + fp.write(s) + fp.write(end) + + @classmethod + @contextmanager + def external_write_mode(cls, file=None, nolock=False): + """ + Disable tqdm within context and refresh tqdm when exits. + Useful when writing to standard output stream + """ + fp = file if file is not None else sys.stdout + if fp is None: + yield + return + + try: + if not nolock: + cls.get_lock().acquire() + # Clear all bars + inst_cleared = [] + for inst in getattr(cls, '_instances', []): + # Clear instance if in the target output file + # or if write output + tqdm output are both either + # sys.stdout or sys.stderr (because both are mixed in terminal) + if hasattr(inst, "start_t") and (inst.fp == fp or all( + f in (sys.stdout, sys.stderr) for f in (fp, inst.fp))): + inst.clear(nolock=True) + inst_cleared.append(inst) + yield + # Force refresh display of bars we cleared + for inst in inst_cleared: + inst.refresh(nolock=True) + finally: + if not nolock: + cls._lock.release() + + @classmethod + def set_lock(cls, lock): + """Set the global lock.""" + cls._lock = lock + + @classmethod + def get_lock(cls): + """Get the global lock. Construct it if it does not exist.""" + if not hasattr(cls, '_lock'): + cls._lock = TqdmDefaultWriteLock() + return cls._lock + + @classmethod + def pandas(cls, **tqdm_kwargs): + """ + Registers the current `tqdm` class with + pandas.core. + ( frame.DataFrame + | series.Series + | groupby.(generic.)DataFrameGroupBy + | groupby.(generic.)SeriesGroupBy + ).progress_apply + + A new instance will be created every time `progress_apply` is called, + and each instance will automatically `close()` upon completion. + + Parameters + ---------- + tqdm_kwargs : arguments for the tqdm instance + + Examples + -------- + >>> import pandas as pd + >>> import numpy as np + >>> from tqdm import tqdm + >>> from tqdm.gui import tqdm as tqdm_gui + >>> + >>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6))) + >>> tqdm.pandas(ncols=50) # can use tqdm_gui, optional kwargs, etc + >>> # Now you can use `progress_apply` instead of `apply` + >>> df.groupby(0).progress_apply(lambda x: x**2) + + References + ---------- + + """ + from warnings import catch_warnings, simplefilter + + from pandas.core.frame import DataFrame + from pandas.core.series import Series + try: + with catch_warnings(): + simplefilter("ignore", category=FutureWarning) + from pandas import Panel + except ImportError: # pandas>=1.2.0 + Panel = None + Rolling, Expanding = None, None + try: # pandas>=1.0.0 + from pandas.core.window.rolling import _Rolling_and_Expanding + except ImportError: + try: # pandas>=0.18.0 + from pandas.core.window import _Rolling_and_Expanding + except ImportError: # pandas>=1.2.0 + try: # pandas>=1.2.0 + from pandas.core.window.expanding import Expanding + from pandas.core.window.rolling import Rolling + _Rolling_and_Expanding = Rolling, Expanding + except ImportError: # pragma: no cover + _Rolling_and_Expanding = None + try: # pandas>=0.25.0 + from pandas.core.groupby.generic import SeriesGroupBy # , NDFrameGroupBy + from pandas.core.groupby.generic import DataFrameGroupBy + except ImportError: # pragma: no cover + try: # pandas>=0.23.0 + from pandas.core.groupby.groupby import DataFrameGroupBy, SeriesGroupBy + except ImportError: + from pandas.core.groupby import DataFrameGroupBy, SeriesGroupBy + try: # pandas>=0.23.0 + from pandas.core.groupby.groupby import GroupBy + except ImportError: # pragma: no cover + from pandas.core.groupby import GroupBy + + try: # pandas>=0.23.0 + from pandas.core.groupby.groupby import PanelGroupBy + except ImportError: + try: + from pandas.core.groupby import PanelGroupBy + except ImportError: # pandas>=0.25.0 + PanelGroupBy = None + + tqdm_kwargs = tqdm_kwargs.copy() + deprecated_t = [tqdm_kwargs.pop('deprecated_t', None)] + + def inner_generator(df_function='apply'): + def inner(df, func, *args, **kwargs): + """ + Parameters + ---------- + df : (DataFrame|Series)[GroupBy] + Data (may be grouped). + func : function + To be applied on the (grouped) data. + **kwargs : optional + Transmitted to `df.apply()`. + """ + + # Precompute total iterations + total = tqdm_kwargs.pop("total", getattr(df, 'ngroups', None)) + if total is None: # not grouped + if df_function == 'applymap': + total = df.size + elif isinstance(df, Series): + total = len(df) + elif (_Rolling_and_Expanding is None or + not isinstance(df, _Rolling_and_Expanding)): + # DataFrame or Panel + axis = kwargs.get('axis', 0) + if axis == 'index': + axis = 0 + elif axis == 'columns': + axis = 1 + # when axis=0, total is shape[axis1] + total = df.size // df.shape[axis] + + # Init bar + if deprecated_t[0] is not None: + t = deprecated_t[0] + deprecated_t[0] = None + else: + t = cls(total=total, **tqdm_kwargs) + + if len(args) > 0: + # *args intentionally not supported (see #244, #299) + TqdmDeprecationWarning( + "Except func, normal arguments are intentionally" + + " not supported by" + + " `(DataFrame|Series|GroupBy).progress_apply`." + + " Use keyword arguments instead.", + fp_write=getattr(t.fp, 'write', sys.stderr.write)) + + try: # pandas>=1.3.0,<3.0 + from pandas.core.common import is_builtin_func + except ImportError: # pandas<1.3.0 + is_builtin_func = getattr(df, '_is_builtin_func', lambda f: f) + try: + func = is_builtin_func(func) + except TypeError: + pass + + # Define bar updating wrapper + def wrapper(*args, **kwargs): + # update tbar correctly + # it seems `pandas apply` calls `func` twice + # on the first column/row to decide whether it can + # take a fast or slow code path; so stop when t.total==t.n + t.update(n=1 if not t.total or t.n < t.total else 0) + return func(*args, **kwargs) + + # Apply the provided function (in **kwargs) + # on the df using our wrapper (which provides bar updating) + try: + return getattr(df, df_function)(wrapper, **kwargs) + finally: + t.close() + + return inner + + # Monkeypatch pandas to provide easy methods + # Enable custom tqdm progress in pandas! + Series.progress_apply = inner_generator() + SeriesGroupBy.progress_apply = inner_generator() + Series.progress_map = inner_generator('map') + SeriesGroupBy.progress_map = inner_generator('map') + + DataFrame.progress_apply = inner_generator() + DataFrameGroupBy.progress_apply = inner_generator() + DataFrame.progress_applymap = inner_generator('applymap') + DataFrame.progress_map = inner_generator('map') + DataFrameGroupBy.progress_map = inner_generator('map') + + if Panel is not None: + Panel.progress_apply = inner_generator() + if PanelGroupBy is not None: + PanelGroupBy.progress_apply = inner_generator() + + GroupBy.progress_apply = inner_generator() + GroupBy.progress_aggregate = inner_generator('aggregate') + GroupBy.progress_transform = inner_generator('transform') + + if Rolling is not None and Expanding is not None: + Rolling.progress_apply = inner_generator() + Expanding.progress_apply = inner_generator() + elif _Rolling_and_Expanding is not None: + _Rolling_and_Expanding.progress_apply = inner_generator() + + # override defaults via env vars + @envwrap("tqdm", is_method=True, types={'total': float, 'ncols': int, 'miniters': float, + 'position': int, 'nrows': int}) + def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None, + ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None, + ascii=None, # pylint: disable=redefined-builtin + disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3, + bar_format=None, initial=0, position=None, postfix=None, unit_divisor=1000, + write_bytes=False, lock_args=None, nrows=None, colour=None, delay=0.0, gui=False, + **kwargs): + """see tqdm.tqdm for arguments""" + if file is None: + file = sys.stderr + + if write_bytes: + # Despite coercing unicode into bytes, py2 sys.std* streams + # should have bytes written to them. + file = SimpleTextIOWrapper( + file, encoding=getattr(file, 'encoding', None) or 'utf-8') + + file = DisableOnWriteError(file, tqdm_instance=self) + + if disable is None and hasattr(file, "isatty") and not file.isatty(): + disable = True + + if total is None and iterable is not None: + try: + total = len(iterable) + except (TypeError, AttributeError): + total = None + if total == float("inf"): + total = None # same as unknown + + if disable: + self.iterable = iterable + self.disable = disable + with self._lock: + self.pos = self._get_free_pos(self) + self._instances.remove(self) + self.n = initial + self.total = total + self.leave = leave + return + + if kwargs: + self.disable = True + with self._lock: + self.pos = self._get_free_pos(self) + self._instances.remove(self) + raise ( + TqdmDeprecationWarning( + "`nested` is deprecated and automated.\n" + "Use `position` instead for manual control.\n", + fp_write=getattr(file, 'write', sys.stderr.write)) + if "nested" in kwargs else + TqdmKeyError("Unknown argument(s): " + str(kwargs))) + + # Preprocess the arguments + if ( + (ncols is None or nrows is None) and (file in (sys.stderr, sys.stdout)) + ) or dynamic_ncols: # pragma: no cover + if dynamic_ncols: + dynamic_ncols = _screen_shape_wrapper() + if dynamic_ncols: + ncols, nrows = dynamic_ncols(file) + else: + _dynamic_ncols = _screen_shape_wrapper() + if _dynamic_ncols: + _ncols, _nrows = _dynamic_ncols(file) + if ncols is None: + ncols = _ncols + if nrows is None: + nrows = _nrows + + if miniters is None: + miniters = 0 + dynamic_miniters = True + else: + dynamic_miniters = False + + if mininterval is None: + mininterval = 0 + + if maxinterval is None: + maxinterval = 0 + + if ascii is None: + ascii = not _supports_unicode(file) + + if bar_format and ascii is not True and not _is_ascii(ascii): + # Convert bar format into unicode since terminal uses unicode + bar_format = str(bar_format) + + if smoothing is None: + smoothing = 0 + + # Store the arguments + self.iterable = iterable + self.desc = desc or '' + self.total = total + self.leave = leave + self.fp = file + self.ncols = ncols + self.nrows = nrows + self.mininterval = mininterval + self.maxinterval = maxinterval + self.miniters = miniters + self.dynamic_miniters = dynamic_miniters + self.ascii = ascii + self.disable = disable + self.unit = unit + self.unit_scale = unit_scale + self.unit_divisor = unit_divisor + self.initial = initial + self.lock_args = lock_args + self.delay = delay + self.gui = gui + self.dynamic_ncols = dynamic_ncols + self.smoothing = smoothing + self._ema_dn = EMA(smoothing) + self._ema_dt = EMA(smoothing) + self._ema_miniters = EMA(smoothing) + self.bar_format = bar_format + self.postfix = None + self.colour = colour + self._time = time + if postfix: + try: + self.set_postfix(refresh=False, **postfix) + except TypeError: + self.postfix = postfix + + # Init the iterations counters + self.last_print_n = initial + self.n = initial + + # if nested, at initial sp() call we replace '\r' by '\n' to + # not overwrite the outer progress bar + with self._lock: + # mark fixed positions as negative + self.pos = self._get_free_pos(self) if position is None else -position + + if not gui: + # Initialize the screen printer + self.sp = self.status_printer(self.fp) + if delay <= 0: + self.refresh(lock_args=self.lock_args) + + # Init the time counter + self.last_print_t = self._time() + # NB: Avoid race conditions by setting start_t at the very end of init + self.start_t = self.last_print_t + + def __bool__(self): + if self.total is not None: + return self.total > 0 + if self.iterable is None: + raise TypeError('bool() undefined when iterable == total == None') + return bool(self.iterable) + + def __len__(self): + return ( + self.total if self.iterable is None + else self.iterable.shape[0] if hasattr(self.iterable, "shape") + else len(self.iterable) if hasattr(self.iterable, "__len__") + else self.iterable.__length_hint__() if hasattr(self.iterable, "__length_hint__") + else getattr(self, "total", None)) + + def __reversed__(self): + try: + orig = self.iterable + except AttributeError: + raise TypeError("'tqdm' object is not reversible") + else: + self.iterable = reversed(self.iterable) + return self.__iter__() + finally: + self.iterable = orig + + def __contains__(self, item): + contains = getattr(self.iterable, '__contains__', None) + return (contains(item) if contains is not None # pylint: disable=not-callable + else item in self.__iter__()) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + try: + self.close() + except AttributeError: + # maybe eager thread cleanup upon external error + if (exc_type, exc_value, traceback) == (None, None, None): + raise + warn("AttributeError ignored", TqdmWarning, stacklevel=2) + + def __del__(self): + self.close() + + def __str__(self): + return self.format_meter(**self.format_dict) + + @property + def _comparable(self): + return abs(getattr(self, "pos", 1 << 31)) + + def __hash__(self): + return id(self) + + def __iter__(self): + """Backward-compatibility to use: for x in tqdm(iterable)""" + + # Inlining instance variables as locals (speed optimisation) + iterable = self.iterable + + # If the bar is disabled, then just walk the iterable + # (note: keep this check outside the loop for performance) + if self.disable: + yield from iterable + return + + mininterval = self.mininterval + last_print_t = self.last_print_t + last_print_n = self.last_print_n + min_start_t = self.start_t + self.delay + n = self.n + time = self._time + + try: + for obj in iterable: + yield obj + # Update and possibly print the progress bar. + # Note: does not call self.update(1) for speed optimisation. + n += 1 + + if n - last_print_n >= self.miniters: + cur_t = time() + dt = cur_t - last_print_t + if dt >= mininterval and cur_t >= min_start_t: + self.update(n - last_print_n) + last_print_n = self.last_print_n + last_print_t = self.last_print_t + finally: + self.n = n + self.close() + + def update(self, n=1): + """ + Manually update the progress bar, useful for streams + such as reading files. + E.g.: + >>> t = tqdm(total=filesize) # Initialise + >>> for current_buffer in stream: + ... ... + ... t.update(len(current_buffer)) + >>> t.close() + The last line is highly recommended, but possibly not necessary if + `t.update()` will be called in such a way that `filesize` will be + exactly reached and printed. + + Parameters + ---------- + n : int or float, optional + Increment to add to the internal counter of iterations + [default: 1]. If using float, consider specifying `{n:.3f}` + or similar in `bar_format`, or specifying `unit_scale`. + + Returns + ------- + out : bool or None + True if a `display()` was triggered. + """ + if self.disable: + return + + if n < 0: + self.last_print_n += n # for auto-refresh logic to work + self.n += n + + # check counter first to reduce calls to time() + if self.n - self.last_print_n >= self.miniters: + cur_t = self._time() + dt = cur_t - self.last_print_t + if dt >= self.mininterval and cur_t >= self.start_t + self.delay: + cur_t = self._time() + dn = self.n - self.last_print_n # >= n + if self.smoothing and dt and dn: + # EMA (not just overall average) + self._ema_dn(dn) + self._ema_dt(dt) + self.refresh(lock_args=self.lock_args) + if self.dynamic_miniters: + # If no `miniters` was specified, adjust automatically to the + # maximum iteration rate seen so far between two prints. + # e.g.: After running `tqdm.update(5)`, subsequent + # calls to `tqdm.update()` will only cause an update after + # at least 5 more iterations. + if self.maxinterval and dt >= self.maxinterval: + self.miniters = dn * (self.mininterval or self.maxinterval) / dt + elif self.smoothing: + # EMA miniters update + self.miniters = self._ema_miniters( + dn * (self.mininterval / dt if self.mininterval and dt + else 1)) + else: + # max iters between two prints + self.miniters = max(self.miniters, dn) + + # Store old values for next call + self.last_print_n = self.n + self.last_print_t = cur_t + return True + + def close(self): + """Cleanup and (if leave=False) close the progress bar.""" + if getattr(self, 'disable', True): + return + + # Prevent multiple closures + self.disable = True + + # decrement instance pos and remove from internal set + pos = abs(self.pos) + self._decr_instances(self) + + if not hasattr(self, 'last_print_t'): + return + if self.last_print_t < self.start_t + self.delay: + # haven't ever displayed; nothing to clear + return + + # GUI mode + if getattr(self, 'sp', None) is None: + return + + # annoyingly, _supports_unicode isn't good enough + def fp_write(s): + self.fp.write(str(s)) + + try: + fp_write('') + except ValueError as e: + if 'closed' in str(e): + return + raise # pragma: no cover + + leave = pos == 0 if self.leave is None else self.leave + + with self._lock: + if leave: + # stats for overall rate (no weighted average) + self._ema_dt = lambda: None + self.display(pos=0) + fp_write('\n') + else: + # clear previous display + if self.display(msg='', pos=pos) and not pos: + fp_write('\r') + + def clear(self, nolock=False): + """Clear current bar display.""" + if self.disable: + return + + if not nolock: + self._lock.acquire() + pos = abs(self.pos) + if pos < (self.nrows or 20): + self.moveto(pos) + self.sp('') + self.fp.write('\r') # place cursor back at the beginning of line + self.moveto(-pos) + if not nolock: + self._lock.release() + + def refresh(self, nolock=False, lock_args=None): + """ + Force refresh the display of this bar. + + Parameters + ---------- + nolock : bool, optional + If `True`, does not lock. + If [default: `False`]: calls `acquire()` on internal lock. + lock_args : tuple, optional + Passed to internal lock's `acquire()`. + If specified, will only `display()` if `acquire()` returns `True`. + """ + if self.disable: + return + + if not nolock: + if lock_args: + if not self._lock.acquire(*lock_args): + return False + else: + self._lock.acquire() + self.display() + if not nolock: + self._lock.release() + return True + + def unpause(self): + """Restart tqdm timer from last print time.""" + if self.disable: + return + cur_t = self._time() + self.start_t += cur_t - self.last_print_t + self.last_print_t = cur_t + + def reset(self, total=None): + """ + Resets to 0 iterations for repeated use. + + Consider combining with `leave=True`. + + Parameters + ---------- + total : int or float, optional. Total to use for the new bar. + """ + self.n = 0 + if total is not None: + self.total = None if total == float("inf") else total + if self.disable: + return + self.last_print_n = 0 + self.last_print_t = self.start_t = self._time() + self._ema_dn = EMA(self.smoothing) + self._ema_dt = EMA(self.smoothing) + self._ema_miniters = EMA(self.smoothing) + self.refresh() + + def set_description(self, desc=None, refresh=True): + """ + Set/modify description of the progress bar. + + Parameters + ---------- + desc : str, optional + refresh : bool, optional + Forces refresh [default: True]. + """ + self.desc = desc + ': ' if desc else '' + if refresh: + self.refresh() + + def set_description_str(self, desc=None, refresh=True): + """Set/modify description without ': ' appended.""" + self.desc = desc or '' + if refresh: + self.refresh() + + def set_postfix(self, ordered_dict=None, refresh=True, **kwargs): + """ + Set/modify postfix (additional stats) + with automatic formatting based on datatype. + + Parameters + ---------- + ordered_dict : dict or OrderedDict, optional + refresh : bool, optional + Forces refresh [default: True]. + kwargs : dict, optional + """ + # Sort in alphabetical order to be more deterministic + postfix = OrderedDict([] if ordered_dict is None else ordered_dict) + for key in sorted(kwargs.keys()): + postfix[key] = kwargs[key] + # Preprocess stats according to datatype + for key in postfix.keys(): + # Number: limit the length of the string + if isinstance(postfix[key], Number): + postfix[key] = self.format_num(postfix[key]) + # Else for any other type, try to get the string conversion + elif not isinstance(postfix[key], str): + postfix[key] = str(postfix[key]) + # Else if it's a string, don't need to preprocess anything + # Stitch together to get the final postfix + self.postfix = ', '.join(key + '=' + postfix[key].strip() + for key in postfix.keys()) + if refresh: + self.refresh() + + def set_postfix_str(self, s='', refresh=True): + """ + Postfix without dictionary expansion, similar to prefix handling. + """ + self.postfix = str(s) + if refresh: + self.refresh() + + def moveto(self, n): + # TODO: private method + self.fp.write('\n' * n + _term_move_up() * -n) + getattr(self.fp, 'flush', lambda: None)() + + @property + def format_dict(self): + """Public API for read-only member access.""" + if self.disable and not hasattr(self, 'unit'): + return defaultdict(lambda: None, { + 'n': self.n, 'total': self.total, 'elapsed': 0, 'unit': 'it'}) + if self.dynamic_ncols: + self.ncols, self.nrows = self.dynamic_ncols(self.fp) + return { + 'n': self.n, 'total': self.total, + 'elapsed': self._time() - self.start_t if hasattr(self, 'start_t') else 0, + 'ncols': self.ncols, 'nrows': self.nrows, 'prefix': self.desc, + 'ascii': self.ascii, 'unit': self.unit, 'unit_scale': self.unit_scale, + 'rate': self._ema_dn() / self._ema_dt() if self._ema_dt() else None, + 'bar_format': self.bar_format, 'postfix': self.postfix, + 'unit_divisor': self.unit_divisor, 'initial': self.initial, + 'colour': self.colour} + + def display(self, msg=None, pos=None): + """ + Use `self.sp` to display `msg` in the specified `pos`. + + Consider overloading this function when inheriting to use e.g.: + `self.some_frontend(**self.format_dict)` instead of `self.sp`. + + Parameters + ---------- + msg : str, optional. What to display (default: `repr(self)`). + pos : int, optional. Position to `moveto` + (default: `abs(self.pos)`). + """ + if pos is None: + pos = abs(self.pos) + + nrows = self.nrows or 20 + if pos >= nrows - 1: + if pos >= nrows: + return False + if msg or msg is None: # override at `nrows - 1` + msg = " ... (more hidden) ..." + + if not hasattr(self, "sp"): + raise TqdmDeprecationWarning( + "Please use `tqdm.gui.tqdm(...)`" + " instead of `tqdm(..., gui=True)`\n", + fp_write=getattr(self.fp, 'write', sys.stderr.write)) + + if pos: + self.moveto(pos) + self.sp(self.__str__() if msg is None else msg) + if pos: + self.moveto(-pos) + return True + + @classmethod + @contextmanager + def wrapattr(cls, stream, method, total=None, bytes=True, # pylint: disable=redefined-builtin + **tqdm_kwargs): + """ + stream : file-like object. + method : str, "read" or "write". The result of `read()` and + the first argument of `write()` should have a `len()`. + + >>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj: + ... while True: + ... chunk = fobj.read(chunk_size) + ... if not chunk: + ... break + """ + with cls(total=total, **tqdm_kwargs) as t: + if bytes: + t.unit = "B" + t.unit_scale = True + t.unit_divisor = 1024 + yield CallbackIOWrapper(t.update, stream, method) + + +def trange(*args, **kwargs): + """Shortcut for tqdm(range(*args), **kwargs).""" + return tqdm(range(*args), **kwargs) diff --git a/.venv/lib/python3.12/site-packages/tqdm/tk.py b/.venv/lib/python3.12/site-packages/tqdm/tk.py new file mode 100644 index 0000000000000000000000000000000000000000..6607cc7f55e9bcdd177ef57dae4dbc06c7e33951 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/tk.py @@ -0,0 +1,196 @@ +""" +Tkinter GUI progress bar decorator for iterators. + +Usage: +>>> from tqdm.tk import trange, tqdm +>>> for i in trange(10): +... ... +""" +import re +import sys +import tkinter +import tkinter.ttk as ttk +from warnings import warn + +from .std import TqdmExperimentalWarning, TqdmWarning +from .std import tqdm as std_tqdm + +__author__ = {"github.com/": ["richardsheridan", "casperdcl"]} +__all__ = ['tqdm_tk', 'ttkrange', 'tqdm', 'trange'] + + +class tqdm_tk(std_tqdm): # pragma: no cover + """ + Experimental Tkinter GUI version of tqdm! + + Note: Window interactivity suffers if `tqdm_tk` is not running within + a Tkinter mainloop and values are generated infrequently. In this case, + consider calling `tqdm_tk.refresh()` frequently in the Tk thread. + """ + + # TODO: @classmethod: write()? + + def __init__(self, *args, **kwargs): + """ + This class accepts the following parameters *in addition* to + the parameters accepted by `tqdm`. + + Parameters + ---------- + grab : bool, optional + Grab the input across all windows of the process. + tk_parent : `tkinter.Wm`, optional + Parent Tk window. + cancel_callback : Callable, optional + Create a cancel button and set `cancel_callback` to be called + when the cancel or window close button is clicked. + """ + kwargs = kwargs.copy() + kwargs['gui'] = True + # convert disable = None to False + kwargs['disable'] = bool(kwargs.get('disable', False)) + self._warn_leave = 'leave' in kwargs + grab = kwargs.pop('grab', False) + tk_parent = kwargs.pop('tk_parent', None) + self._cancel_callback = kwargs.pop('cancel_callback', None) + super().__init__(*args, **kwargs) + + if self.disable: + return + + if tk_parent is None: # Discover parent widget + try: + tk_parent = tkinter._default_root + except AttributeError: + raise AttributeError( + "`tk_parent` required when using `tkinter.NoDefaultRoot()`") + if tk_parent is None: # use new default root window as display + self._tk_window = tkinter.Tk() + else: # some other windows already exist + self._tk_window = tkinter.Toplevel() + else: + self._tk_window = tkinter.Toplevel(tk_parent) + + warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2) + self._tk_dispatching = self._tk_dispatching_helper() + + self._tk_window.protocol("WM_DELETE_WINDOW", self.cancel) + self._tk_window.wm_title(self.desc) + self._tk_window.wm_attributes("-topmost", 1) + self._tk_window.after(0, lambda: self._tk_window.wm_attributes("-topmost", 0)) + self._tk_n_var = tkinter.DoubleVar(self._tk_window, value=0) + self._tk_text_var = tkinter.StringVar(self._tk_window) + pbar_frame = ttk.Frame(self._tk_window, padding=5) + pbar_frame.pack() + _tk_label = ttk.Label(pbar_frame, textvariable=self._tk_text_var, + wraplength=600, anchor="center", justify="center") + _tk_label.pack() + self._tk_pbar = ttk.Progressbar( + pbar_frame, variable=self._tk_n_var, length=450) + if self.total is not None: + self._tk_pbar.configure(maximum=self.total) + else: + self._tk_pbar.configure(mode="indeterminate") + self._tk_pbar.pack() + if self._cancel_callback is not None: + _tk_button = ttk.Button(pbar_frame, text="Cancel", command=self.cancel) + _tk_button.pack() + if grab: + self._tk_window.grab_set() + + def close(self): + if self.disable: + return + + self.disable = True + + with self.get_lock(): + self._instances.remove(self) + + def _close(): + self._tk_window.after('idle', self._tk_window.destroy) + if not self._tk_dispatching: + self._tk_window.update() + + self._tk_window.protocol("WM_DELETE_WINDOW", _close) + + # if leave is set but we are self-dispatching, the left window is + # totally unresponsive unless the user manually dispatches + if not self.leave: + _close() + elif not self._tk_dispatching: + if self._warn_leave: + warn("leave flag ignored if not in tkinter mainloop", + TqdmWarning, stacklevel=2) + _close() + + def clear(self, *_, **__): + pass + + def display(self, *_, **__): + self._tk_n_var.set(self.n) + d = self.format_dict + # remove {bar} + d['bar_format'] = (d['bar_format'] or "{l_bar}{r_bar}").replace( + "{bar}", "") + msg = self.format_meter(**d) + if '' in msg: + msg = "".join(re.split(r'\|?\|?', msg, maxsplit=1)) + self._tk_text_var.set(msg) + if not self._tk_dispatching: + self._tk_window.update() + + def set_description(self, desc=None, refresh=True): + self.set_description_str(desc, refresh) + + def set_description_str(self, desc=None, refresh=True): + self.desc = desc + if not self.disable: + self._tk_window.wm_title(desc) + if refresh and not self._tk_dispatching: + self._tk_window.update() + + def cancel(self): + """ + `cancel_callback()` followed by `close()` + when close/cancel buttons clicked. + """ + if self._cancel_callback is not None: + self._cancel_callback() + self.close() + + def reset(self, total=None): + """ + Resets to 0 iterations for repeated use. + + Parameters + ---------- + total : int or float, optional. Total to use for the new bar. + """ + if hasattr(self, '_tk_pbar'): + if total is None: + self._tk_pbar.configure(maximum=100, mode="indeterminate") + else: + self._tk_pbar.configure(maximum=total, mode="determinate") + super().reset(total=total) + + @staticmethod + def _tk_dispatching_helper(): + """determine if Tkinter mainloop is dispatching events""" + codes = {tkinter.mainloop.__code__, tkinter.Misc.mainloop.__code__} + for frame in sys._current_frames().values(): + while frame: + if frame.f_code in codes: + return True + frame = frame.f_back + return False + + +def ttkrange(*args, **kwargs): + """Shortcut for `tqdm.tk.tqdm(range(*args), **kwargs)`.""" + return tqdm_tk(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_tk +trange = ttkrange diff --git a/.venv/lib/python3.12/site-packages/tqdm/tqdm.1 b/.venv/lib/python3.12/site-packages/tqdm/tqdm.1 new file mode 100644 index 0000000000000000000000000000000000000000..b134ddd74c2095149e0c902f004a162c3be9d2ed --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/tqdm.1 @@ -0,0 +1,241 @@ +.TH "TQDM" "1" "2015\-2026" "tqdm User Manuals" +.SH NAME +tqdm \- fast, extensible progress bar for Python and CLI +.SH SYNOPSIS +tqdm [\f[I]options\f[R]] +.SH DESCRIPTION +See \c +.UR https://github.com/tqdm/tqdm +.UE \c +\&. +Can be used as a pipe: +.IP +.EX +$ \f[I]# count lines of code\f[R] +$ cat *.py \f[B]|\f[R] tqdm \f[B]|\f[R] wc \-l +327it [00:00, 981773.38it/s] +327 + +$ \f[I]# find all files\f[R] +$ find . \-name \(dq*.py\(dq \f[B]|\f[R] tqdm \f[B]|\f[R] wc \-l +432it [00:00, 833842.30it/s] +432 + +\f[I]# ... and more info\f[R] +$ find . \-name \(aq*.py\(aq \-exec wc \-l \(rs{} \(rs; \(rs + \f[B]|\f[R] tqdm \-\-total 432 \-\-unit files \-\-desc counting \(rs + \f[B]|\f[R] awk \(aq{ sum += $1 }; END { print sum }\(aq +counting: 100%\f[B]|\f[R]█████████\f[B]|\f[R] 432/432 [00:00<00:00, 794361.83files/s] +131998 +.EE +.SH OPTIONS +.TP +\-h, \-\-help +Print this help and exit. +.TP +\-v, \-\-version +Print version and exit. +.TP +\-\-desc=\f[I]desc\f[R] +str, optional. +Prefix for the progress bar. +.TP +\-\-total=\f[I]total\f[R] +int or float, optional. +The number of expected iterations. +If unspecified, len(iterable) is used if possible. +If float(\(lqinf\(rq) or as a last resort, only basic progress +statistics are displayed (no ETA, no progress bar). +If \f[CR]gui\f[R] is True and this parameter needs subsequent updating, +specify an initial arbitrary large positive number, e.g.\ 9e9. +.TP +\-\-leave +bool, optional. +If [default: True], keeps all traces of the progress bar upon +termination of iteration. +If \f[CR]None\f[R], will leave only if \f[CR]position\f[R] is +\f[CR]0\f[R]. +.TP +\-\-ncols=\f[I]ncols\f[R] +int, optional. +The width of the entire output message. +If specified, dynamically resizes the progress bar to stay within this +bound. +If unspecified, attempts to use environment width. +The fallback is a meter width of 10 and no limit for the counter and +statistics. +If 0, will not print any meter (only stats). +.TP +\-\-mininterval=\f[I]mininterval\f[R] +float, optional. +Minimum progress display update interval [default: 0.1] seconds. +.TP +\-\-maxinterval=\f[I]maxinterval\f[R] +float, optional. +Maximum progress display update interval [default: 10] seconds. +Automatically adjusts \f[CR]miniters\f[R] to correspond to +\f[CR]mininterval\f[R] after long display update lag. +Only works if \f[CR]dynamic_miniters\f[R] or monitor thread is enabled. +.TP +\-\-miniters=\f[I]miniters\f[R] +int or float, optional. +Minimum progress display update interval, in iterations. +If 0 and \f[CR]dynamic_miniters\f[R], will automatically adjust to equal +\f[CR]mininterval\f[R] (more CPU efficient, good for tight loops). +If > 0, will skip display of specified number of iterations. +Tweak this and \f[CR]mininterval\f[R] to get very efficient loops. +If your progress is erratic with both fast and slow iterations (network, +skipping items, etc) you should set miniters=1. +.TP +\-\-ascii=\f[I]ascii\f[R] +bool or str, optional. +If unspecified or False, use unicode (smooth blocks) to fill the meter. +The fallback is to use ASCII characters \(rq 123456789#\(lq. +.TP +\-\-disable +bool, optional. +Whether to disable the entire progress bar wrapper [default: False]. +If set to None, disable on non\-TTY. +.TP +\-\-unit=\f[I]unit\f[R] +str, optional. +String that will be used to define the unit of each iteration [default: +it]. +.TP +\-\-unit\-scale=\f[I]unit_scale\f[R] +bool or int or float, optional. +If 1 or True, the number of iterations will be reduced/scaled +automatically and a metric prefix following the International System of +Units standard will be added (kilo, mega, etc.) +[default: False]. +If any other non\-zero number, will scale \f[CR]total\f[R] and +\f[CR]n\f[R]. +.TP +\-\-dynamic\-ncols +bool, optional. +If set, constantly alters \f[CR]ncols\f[R] and \f[CR]nrows\f[R] to the +environment (allowing for window resizes) [default: False]. +.TP +\-\-smoothing=\f[I]smoothing\f[R] +float, optional. +Exponential moving average smoothing factor for speed estimates (ignored +in GUI mode). +Ranges from 0 (average speed) to 1 (current/instantaneous speed) +[default: 0.3]. +.TP +\-\-bar\-format=\f[I]bar_format\f[R] +str, optional. +Specify a custom bar string formatting. +May impact performance. +[default: `{l_bar}{bar}{r_bar}'], where l_bar=`{desc}: +{percentage:3.0f}%|' and r_bar=`| {n_fmt}/{total_fmt} +[{elapsed}<{remaining}, \(cq \(cq{rate_fmt}{postfix}]' Possible vars: +l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage, elapsed, +elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, +rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, +remaining, remaining_s, eta. +Note that a trailing \(lq:\(rq is automatically removed after {desc} if +the latter is empty. +.TP +\-\-initial=\f[I]initial\f[R] +int or float, optional. +The initial counter value. +Useful when restarting a progress bar [default: 0]. +If using float, consider specifying \f[CR]{n:.3f}\f[R] or similar in +\f[CR]bar_format\f[R], or specifying \f[CR]unit_scale\f[R]. +.TP +\-\-position=\f[I]position\f[R] +int, optional. +Specify the line offset to print this bar (starting from 0) Automatic if +unspecified. +Useful to manage multiple bars at once (eg, from threads). +.TP +\-\-postfix=\f[I]postfix\f[R] +dict or *, optional. +Specify additional stats to display at the end of the bar. +Calls \f[CR]set_postfix(**postfix)\f[R] if possible (dict). +.TP +\-\-unit\-divisor=\f[I]unit_divisor\f[R] +float, optional. +[default: 1000], ignored unless \f[CR]unit_scale\f[R] is True. +.TP +\-\-write\-bytes +bool, optional. +Whether to write bytes. +If (default: False) will write unicode. +.TP +\-\-lock\-args=\f[I]lock_args\f[R] +tuple, optional. +Passed to \f[CR]refresh\f[R] for intermediate output (initialisation, +iterating, and updating). +.TP +\-\-nrows=\f[I]nrows\f[R] +int, optional. +The screen height. +If specified, hides nested bars outside this bound. +If unspecified, attempts to use environment height. +The fallback is 20. +.TP +\-\-colour=\f[I]colour\f[R] +str, optional. +Bar colour (e.g.\ `green', `#00ff00'). +.TP +\-\-delay=\f[I]delay\f[R] +float, optional. +Don\(cqt display until [default: 0] seconds have elapsed. +.TP +\-\-delim=\f[I]delim\f[R] +chr, optional. +Delimiting character [default: `\(rsn']. +Use `\(rs0' for null. +N.B.: on Windows systems, Python converts `\(rsn' to `\(rsr\(rsn'. +.TP +\-\-buf\-size=\f[I]buf_size\f[R] +int, optional. +String buffer size in bytes [default: 256] used when \f[CR]delim\f[R] is +specified. +.TP +\-\-bytes +bool, optional. +If true, will count bytes, ignore \f[CR]delim\f[R], and default +\f[CR]unit_scale\f[R] to True, \f[CR]unit_divisor\f[R] to 1024, and +\f[CR]unit\f[R] to `B'. +.TP +\-\-tee +bool, optional. +If true, passes \f[CR]stdin\f[R] to both \f[CR]stderr\f[R] and +\f[CR]stdout\f[R]. +.TP +\-\-update +bool, optional. +If true, will treat input as newly elapsed iterations, i.e.\ numbers to +pass to \f[CR]update()\f[R]. +Note that this is slow (\(ti2e5 it/s) since every input must be decoded +as a number. +.TP +\-\-update\-to +bool, optional. +If true, will treat input as total elapsed iterations, i.e.\ numbers to +assign to \f[CR]self.n\f[R]. +Note that this is slow (\(ti2e5 it/s) since every input must be decoded +as a number. +.TP +\-\-null +bool, optional. +If true, will discard input (no stdout). +.TP +\-\-manpath=\f[I]manpath\f[R] +str, optional. +Directory in which to install tqdm man pages. +.TP +\-\-comppath=\f[I]comppath\f[R] +str, optional. +Directory in which to place tqdm completion. +.TP +\-\-log=\f[I]log\f[R] +str, optional. +CRITICAL|FATAL|ERROR|WARN(ING)|[default: `INFO']|DEBUG|NOTSET. +.SH AUTHORS +tqdm developers \c +.UR https://github.com/tqdm +.UE \c. diff --git a/.venv/lib/python3.12/site-packages/tqdm/utils.py b/.venv/lib/python3.12/site-packages/tqdm/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..329c064478e4c6f094249d85732d818fc400720b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/utils.py @@ -0,0 +1,328 @@ +""" +General helpers required for `tqdm.std`. +""" +import os +import re +import sys +from functools import partial, partialmethod, wraps +from inspect import signature +# TODO consider using wcswidth third-party package for 0-width characters +from unicodedata import east_asian_width +from warnings import warn +from weakref import proxy + +_range, _unich, _unicode, _basestring = range, chr, str, str +CUR_OS = sys.platform +IS_WIN = any(CUR_OS.startswith(i) for i in ['win32', 'cygwin']) +IS_NIX = any(CUR_OS.startswith(i) for i in ['aix', 'linux', 'darwin', 'freebsd']) +RE_ANSI = re.compile(r"\x1b\[[;\d]*[A-Za-z]") + +try: + if IS_WIN: + import colorama + else: + raise ImportError +except ImportError: + colorama = None +else: + try: + colorama.init(strip=False) + except TypeError: + colorama.init() + + +def envwrap(name, app="", types=None, is_method=False): + """ + Basic (env-only) version of [envwrap](https://github.com/tqdm/envwrap). + Install `envwrap` for config file support. + """ + if types is None: + types = {} + if name[-1] == "_": + name = name[:-1] + warn("Trailing underscore in `name` is automatic", DeprecationWarning, stacklevel=2) + prefixes = (name, f"{name}_{app}") if app else (name,) + env_overrides = {} + for prefix in prefixes: + prefix = prefix.upper() + "_" + i = len(prefix) + env_overrides.update( + (k[i:].lower(), v) for k, v in os.environ.items() if k.startswith(prefix)) + part = partialmethod if is_method else partial + + def wrap(func): + params = signature(func).parameters + # ignore unknown env vars + overrides = {k: v for k, v in env_overrides.items() if k in params} + # infer overrides' `type`s + for k in overrides: + param = params[k] + if param.annotation is not param.empty: # typehints + for typ in getattr(param.annotation, '__args__', (param.annotation,)): + try: + overrides[k] = typ(overrides[k]) + except Exception: # nosec B110 + pass + else: + break + elif param.default is not None: # type of default value + overrides[k] = type(param.default)(overrides[k]) + else: + try: # `types` fallback + overrides[k] = types[k](overrides[k]) + except KeyError: # keep unconverted (`str`) + pass + return part(func, **overrides) + return wrap + + +try: + from envwrap import envwrap # noqa: F401, F811, pylint: disable=unused-import +except ModuleNotFoundError: + pass + + +class FormatReplace: + """ + >>> a = FormatReplace('something') + >>> f"{a:5d}" + 'something' + """ # NOQA: P102 + def __init__(self, replace=''): + self.replace = replace + self.format_called = 0 + + def __format__(self, _): + self.format_called += 1 + return self.replace + + +class Comparable: + """Assumes child has self._comparable attr/@property""" + def __lt__(self, other): + return self._comparable < other._comparable + + def __le__(self, other): + return (self < other) or (self == other) + + def __eq__(self, other): + return self._comparable == other._comparable + + def __ne__(self, other): + return not self == other + + def __gt__(self, other): + return not self <= other + + def __ge__(self, other): + return not self < other + + +class ObjectWrapper: + def __getattr__(self, name): + return getattr(self._wrapped, name) + + def __setattr__(self, name, value): + return setattr(self._wrapped, name, value) + + def wrapper_getattr(self, name): + """Actual `self.getattr` rather than self._wrapped.getattr""" + try: + return object.__getattr__(self, name) + except AttributeError: # py2 + return getattr(self, name) + + def wrapper_setattr(self, name, value): + """Actual `self.setattr` rather than self._wrapped.setattr""" + return object.__setattr__(self, name, value) + + def __init__(self, wrapped): + """ + Thin wrapper around a given object + """ + self.wrapper_setattr('_wrapped', wrapped) + + +class SimpleTextIOWrapper(ObjectWrapper): + """ + Change only `.write()` of the wrapped object by encoding the passed + value and passing the result to the wrapped object's `.write()` method. + """ + # pylint: disable=too-few-public-methods + def __init__(self, wrapped, encoding): + super().__init__(wrapped) + self.wrapper_setattr('encoding', encoding) + + def write(self, s): + """ + Encode `s` and pass to the wrapped object's `.write()` method. + """ + return self._wrapped.write(s.encode(self.wrapper_getattr('encoding'))) + + def __eq__(self, other): + return self._wrapped == getattr(other, '_wrapped', other) + + +class DisableOnWriteError(ObjectWrapper): + """ + Disable the given `tqdm_instance` upon `write()` or `flush()` errors. + """ + @staticmethod + def disable_on_exception(tqdm_instance, func): + """ + Quietly set `tqdm_instance.miniters=inf` if `func` raises `errno=5`. + """ + tqdm_instance = proxy(tqdm_instance) + + def inner(*args, **kwargs): + try: + return func(*args, **kwargs) + except OSError as e: + if e.errno != 5: + raise + try: + tqdm_instance.miniters = float('inf') + except ReferenceError: + pass + except ValueError as e: + if 'closed' not in str(e): + raise + try: + tqdm_instance.miniters = float('inf') + except ReferenceError: + pass + return inner + + def __init__(self, wrapped, tqdm_instance): # noqa: B042 + super().__init__(wrapped) + if hasattr(wrapped, 'write'): + self.wrapper_setattr( + 'write', self.disable_on_exception(tqdm_instance, wrapped.write)) + if hasattr(wrapped, 'flush'): + self.wrapper_setattr( + 'flush', self.disable_on_exception(tqdm_instance, wrapped.flush)) + + def __eq__(self, other): + return self._wrapped == getattr(other, '_wrapped', other) + + +class CallbackIOWrapper(ObjectWrapper): + def __init__(self, callback, stream, method="read"): + """ + Wrap a given `file`-like object's `read()` or `write()` to report + lengths to the given `callback` + """ + super().__init__(stream) + func = getattr(stream, method) + if method == "write": + @wraps(func) + def write(data, *args, **kwargs): + res = func(data, *args, **kwargs) + callback(len(data)) + return res + self.wrapper_setattr('write', write) + elif method == "read": + @wraps(func) + def read(*args, **kwargs): + data = func(*args, **kwargs) + callback(len(data)) + return data + self.wrapper_setattr('read', read) + else: + raise KeyError("Can only wrap read/write methods") + + +def _is_utf(encoding): + try: + '\u2588\u2589'.encode(encoding) + except UnicodeEncodeError: + return False + except Exception: + try: + return encoding.lower().startswith('utf-') or ('U8' == encoding) + except Exception: + return False + else: + return True + + +def _supports_unicode(fp): + try: + return _is_utf(fp.encoding) + except AttributeError: + return False + + +def _is_ascii(s): + if isinstance(s, str): + for c in s: + if ord(c) > 255: + return False + return True + return _supports_unicode(s) + + +def _screen_shape_wrapper(): # pragma: no cover + """ + Return a function which returns console dimensions (width, height). + Supported: linux, osx, windows, cygwin. + """ + def inner(fp): + try: + from os import get_terminal_size + cols, lines = get_terminal_size(getattr(fp, 'fileno', lambda: None)()) + return cols - 1, lines - 1 + except Exception: + return None, None + + return inner + + +def _environ_cols_wrapper(): # pragma: no cover + """ + Return a function which returns console width. + Supported: linux, osx, windows, cygwin. + """ + warn("Use `_screen_shape_wrapper()(file)[0]` instead of" + " `_environ_cols_wrapper()(file)`", DeprecationWarning, stacklevel=2) + shape = _screen_shape_wrapper() + if not shape: + return None + + @wraps(shape) + def inner(fp): + return shape(fp)[0] + + return inner + + +def _term_move_up(): # pragma: no cover + return '' if (os.name == 'nt') and (colorama is None) else '\x1b[A' + + +def _text_width(s): + return sum(2 if east_asian_width(ch) in 'FW' else 1 for ch in str(s)) + + +def disp_len(data): + """ + Returns the real on-screen length of a string which may contain + ANSI control codes and wide chars. + """ + return _text_width(RE_ANSI.sub('', data)) + + +def disp_trim(data, length): + """ + Trim a string which may contain ANSI control characters. + """ + if len(data) == disp_len(data): + return data[:length] + + ansi_present = bool(RE_ANSI.search(data)) + while disp_len(data) > length: # carefully delete one char at a time + data = data[:-1] + if ansi_present and bool(RE_ANSI.search(data)): + # assume ANSI reset is required + return data if data.endswith("\033[0m") else data + "\033[0m" + return data diff --git a/.venv/lib/python3.12/site-packages/tqdm/version.py b/.venv/lib/python3.12/site-packages/tqdm/version.py new file mode 100644 index 0000000000000000000000000000000000000000..84739ef244b0504c9705b40b72f7f229584b24ca --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/version.py @@ -0,0 +1,7 @@ +"""`tqdm` version detector. Precedence: installed dist, git, 'UNKNOWN'.""" +from importlib.metadata import PackageNotFoundError, version + +try: + __version__ = version('tqdm') +except PackageNotFoundError: + __version__ = "UNKNOWN" diff --git a/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..97fd818b909551186a659e13240c49c2187d0cdc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/METADATA @@ -0,0 +1,73 @@ +Metadata-Version: 2.4 +Name: typing_extensions +Version: 4.16.0 +Summary: Backported and Experimental Type Hints for Python 3.9+ +Keywords: annotations,backport,checker,checking,function,hinting,hints,type,typechecking,typehinting,typehints,typing +Author-email: "Guido van Rossum, Jukka Lehtosalo, Łukasz Langa, Michael Lee" +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-Expression: PSF-2.0 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 +Classifier: Topic :: Software Development +License-File: LICENSE +Project-URL: Bug Tracker, https://github.com/python/typing_extensions/issues +Project-URL: Changes, https://github.com/python/typing_extensions/blob/main/CHANGELOG.md +Project-URL: Documentation, https://typing-extensions.readthedocs.io/ +Project-URL: Home, https://github.com/python/typing_extensions +Project-URL: Q & A, https://github.com/python/typing/discussions +Project-URL: Repository, https://github.com/python/typing_extensions + +# Typing Extensions + +[![Chat at https://gitter.im/python/typing](https://badges.gitter.im/python/typing.svg)](https://gitter.im/python/typing) + +[Documentation](https://typing-extensions.readthedocs.io/en/latest/#) – +[PyPI](https://pypi.org/project/typing-extensions/) + +## Overview + +The `typing_extensions` module serves two related purposes: + +- Enable use of new type system features on older Python versions. For example, + `typing.TypeGuard` is new in Python 3.10, but `typing_extensions` allows + users on previous Python versions to use it too. +- Enable experimentation with new type system PEPs before they are accepted and + added to the `typing` module. + +`typing_extensions` is treated specially by static type checkers such as +mypy and pyright. Objects defined in `typing_extensions` are treated the same +way as equivalent forms in `typing`. + +`typing_extensions` uses +[Semantic Versioning](https://semver.org/). The +major version will be incremented only for backwards-incompatible changes. +Therefore, it's safe to depend +on `typing_extensions` like this: `typing_extensions ~=x.y`, +where `x.y` is the first version that includes all features you need. +[This](https://packaging.python.org/en/latest/specifications/version-specifiers/#compatible-release) +is equivalent to `typing_extensions >=x.y, <(x+1)`. Do not depend on `~= x.y.z` +unless you really know what you're doing; that defeats the purpose of +semantic versioning. + +## Included items + +See [the documentation](https://typing-extensions.readthedocs.io/en/latest/#) for a +complete listing of module contents. + +## Contributing + +See [CONTRIBUTING.md](https://github.com/python/typing_extensions/blob/main/CONTRIBUTING.md) +for how to contribute to `typing_extensions`. + diff --git a/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..93b0fa18522176e2d4f8e07d91666eef358506db --- /dev/null +++ b/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/RECORD @@ -0,0 +1,7 @@ +__pycache__/typing_extensions.cpython-312.pyc,, +typing_extensions-4.16.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +typing_extensions-4.16.0.dist-info/METADATA,sha256=sFCEyh1Qh5hlF42f_5-r6rYb37HzYb-96VQh_8j5vkY,3310 +typing_extensions-4.16.0.dist-info/RECORD,, +typing_extensions-4.16.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +typing_extensions-4.16.0.dist-info/licenses/LICENSE,sha256=Oy-B_iHRgcSZxZolbI4ZaEVdZonSaaqFNzv7avQdo78,13936 +typing_extensions.py,sha256=QEDKGh7L7gDROFwSqTCE0cW9RvC3dPB-WufpHE9V5pY,165012 diff --git a/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f26bcf4d2de6eb136e31006ca3ab447d5e488adf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/typing_extensions-4.16.0.dist-info/licenses/LICENSE @@ -0,0 +1,279 @@ +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see https://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations, which became +Zope Corporation. In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization +created specifically to own Python-related Intellectual Property. +Zope Corporation was a sponsoring member of the PSF. + +All Python releases are Open Source (see https://opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2 and above 2.1.1 2001-now PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +Python software and documentation are licensed under the +Python Software Foundation License Version 2. + +Starting with Python 3.8.6, examples, recipes, and other code in +the documentation are dual licensed under the PSF License Version 2 +and the Zero-Clause BSD license. + +Some software incorporated into Python is under different licenses. +The licenses are listed with code falling under that license. + + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION +---------------------------------------------------------------------- + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/typing_extensions.py b/.venv/lib/python3.12/site-packages/typing_extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..ced78373258ef307c9a94ef15286e6da359e7a80 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/typing_extensions.py @@ -0,0 +1,4422 @@ +import abc +import builtins +import collections +import collections.abc +import contextlib +import enum +import functools +import inspect +import io +import keyword +import operator +import sys +import types as _types +import typing +import warnings + +# Breakpoint: https://github.com/python/cpython/pull/119891 +if sys.version_info >= (3, 14): + import annotationlib + +__all__ = [ + # Super-special typing primitives. + 'Any', + 'ClassVar', + 'Concatenate', + 'Final', + 'LiteralString', + 'ParamSpec', + 'ParamSpecArgs', + 'ParamSpecKwargs', + 'Self', + 'Type', + 'TypeVar', + 'TypeVarTuple', + 'Unpack', + + # ABCs (from collections.abc). + 'Awaitable', + 'AsyncIterator', + 'AsyncIterable', + 'Coroutine', + 'AsyncGenerator', + 'AsyncContextManager', + 'Buffer', + 'ChainMap', + + # Concrete collection types. + 'ContextManager', + 'Counter', + 'Deque', + 'DefaultDict', + 'NamedTuple', + 'OrderedDict', + 'TypedDict', + + # Structural checks, a.k.a. protocols. + 'SupportsAbs', + 'SupportsBytes', + 'SupportsComplex', + 'SupportsFloat', + 'SupportsIndex', + 'SupportsInt', + 'SupportsRound', + 'Reader', + 'Writer', + + # One-off things. + 'Annotated', + 'assert_never', + 'assert_type', + 'clear_overloads', + 'dataclass_transform', + 'deprecated', + 'disjoint_base', + 'Doc', + 'evaluate_forward_ref', + 'get_overloads', + 'final', + 'Format', + 'get_annotations', + 'get_args', + 'get_origin', + 'get_original_bases', + 'get_protocol_members', + 'get_type_hints', + 'IntVar', + 'is_protocol', + 'is_typeddict', + 'Literal', + 'NewType', + 'overload', + 'override', + 'Protocol', + 'sentinel', + 'Sentinel', + 'reveal_type', + 'runtime', + 'runtime_checkable', + 'Text', + 'TypeAlias', + 'TypeAliasType', + 'TypeForm', + 'TypeGuard', + 'TypeIs', + 'TYPE_CHECKING', + 'type_repr', + 'Never', + 'NoReturn', + 'ReadOnly', + 'Required', + 'NotRequired', + 'NoDefault', + 'NoExtraItems', + + # Pure aliases, have always been in typing + 'AbstractSet', + 'AnyStr', + 'BinaryIO', + 'Callable', + 'Collection', + 'Container', + 'Dict', + 'ForwardRef', + 'FrozenSet', + 'Generator', + 'Generic', + 'Hashable', + 'IO', + 'ItemsView', + 'Iterable', + 'Iterator', + 'KeysView', + 'List', + 'Mapping', + 'MappingView', + 'Match', + 'MutableMapping', + 'MutableSequence', + 'MutableSet', + 'Optional', + 'Pattern', + 'Reversible', + 'Sequence', + 'Set', + 'Sized', + 'TextIO', + 'Tuple', + 'Union', + 'ValuesView', + 'cast', + 'no_type_check', +] + +# for backward compatibility +PEP_560 = True +GenericMeta = type +# Breakpoint: https://github.com/python/cpython/pull/116129 +_PEP_696_IMPLEMENTED = sys.version_info >= (3, 13, 0, "beta") + +# Added with bpo-45166 to 3.10.1+ and some 3.9 versions +_FORWARD_REF_HAS_CLASS = "__forward_is_class__" in typing.ForwardRef.__slots__ + + +def _caller(depth=1, default='__main__'): + try: + return sys._getframemodulename(depth + 1) or default + except AttributeError: # For platforms without _getframemodulename() + pass + try: + return sys._getframe(depth + 1).f_globals.get('__name__', default) + except (AttributeError, ValueError): # For platforms without _getframe() + pass + return None + + +# Placeholder for sentinel methods, because sentinels can not have their own sentinels +_sentinel_placeholder = object() + +if hasattr(builtins, "sentinel"): # 3.15+ + sentinel = builtins.sentinel +else: + class sentinel: + """Create a unique sentinel object. + + *name* should be the name of the variable to which the return value + shall be assigned. + """ + + def __init__( + self, + __name: str = _sentinel_placeholder, + __repr: typing.Optional[str] = _sentinel_placeholder, + /, + *, + repr: typing.Optional[str] = None, + name: str = _sentinel_placeholder, + ) -> None: + if name is not _sentinel_placeholder: + warnings.warn( + "Passing 'name' as a keyword argument is deprecated; " + "pass it positionally instead.", + DeprecationWarning, + stacklevel=2, + ) + __name = name + if __name is _sentinel_placeholder: + raise TypeError("First parameter 'name' is required") + if __repr is not _sentinel_placeholder: + warnings.warn( + "Passing 'repr' as a positional argument is deprecated; " + "pass it by keyword instead.", + DeprecationWarning, + stacklevel=2, + ) + repr = __repr + + self._name = __name + self._repr = repr if repr is not None else __name + + # For pickling as a singleton: + self.__module__ = _caller() + + def __init_subclass__(cls): + warnings.warn( + "Subclassing sentinel is deprecated " + "and will be disallowed in Python 3.15", + DeprecationWarning, + stacklevel=2, + ) + super().__init_subclass__() + + def __setattr__(self, attr: str, value: object) -> None: + if attr not in {"_name", "_repr", "__module__"}: + warnings.warn( + f"Setting attribute {attr!r} on sentinel objects is deprecated " + "and will be disallowed in Python 3.15.", + DeprecationWarning, + stacklevel=2, + ) + super().__setattr__(attr, value) + + @property + def __name__(self) -> str: + return self._name + + @__name__.setter + def __name__(self, value: str) -> None: + self._name = value + + def __repr__(self) -> str: + return self._repr + + if sys.version_info < (3, 11): + # The presence of this method convinces typing._type_check + # that Sentinels are types. + def __call__(self, *args, **kwargs): + raise TypeError(f"{type(self).__name__!r} object is not callable") + + # Breakpoint: https://github.com/python/cpython/pull/21515 + if sys.version_info >= (3, 10): + def __or__(self, other): + return typing.Union[self, other] + + def __ror__(self, other): + return typing.Union[other, self] + + def __reduce__(self) -> str: + """Reduce this sentinel to a singleton.""" + return self.__name__ # Module is taken from the __module__ attribute + +Sentinel = sentinel + +_marker = sentinel("sentinel") + + +# The functions below are modified copies of typing internal helpers. +# They are needed by _ProtocolMeta and they provide support for PEP 646. + +# Breakpoint: https://github.com/python/cpython/pull/27342 +if sys.version_info >= (3, 10): + def _should_collect_from_parameters(t): + return isinstance( + t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType) + ) +else: + def _should_collect_from_parameters(t): + return isinstance(t, (typing._GenericAlias, _types.GenericAlias)) + + +NoReturn = typing.NoReturn + +# Some unconstrained type variables. These are used by the container types. +# (These are not for export.) +T = typing.TypeVar('T') # Any type. +KT = typing.TypeVar('KT') # Key type. +VT = typing.TypeVar('VT') # Value type. +T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers. +T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant. + + +# Breakpoint: https://github.com/python/cpython/pull/31841 +if sys.version_info >= (3, 11): + from typing import Any +else: + + class _AnyMeta(type): + def __instancecheck__(self, obj): + if self is Any: + raise TypeError("typing_extensions.Any cannot be used with isinstance()") + return super().__instancecheck__(obj) + + def __repr__(self): + if self is Any: + return "typing_extensions.Any" + return super().__repr__() + + class Any(metaclass=_AnyMeta): + """Special type indicating an unconstrained type. + - Any is compatible with every type. + - Any assumed to have all methods. + - All values assumed to be instances of Any. + Note that all the above statements are true from the point of view of + static type checkers. At runtime, Any should not be used with instance + checks. + """ + def __new__(cls, *args, **kwargs): + if cls is Any: + raise TypeError("Any cannot be instantiated") + return super().__new__(cls, *args, **kwargs) + + +ClassVar = typing.ClassVar + +# Vendored from cpython typing._SpecialFrom +# Having a separate class means that instances will not be rejected by +# typing._type_check. +class _SpecialForm(typing._Final, _root=True): + __slots__ = ('_name', '__doc__', '_getitem') + + def __init__(self, getitem): + self._getitem = getitem + self._name = getitem.__name__ + self.__doc__ = getitem.__doc__ + + def __getattr__(self, item): + if item in {'__name__', '__qualname__'}: + return self._name + + raise AttributeError(item) + + def __mro_entries__(self, bases): + raise TypeError(f"Cannot subclass {self!r}") + + def __repr__(self): + return f'typing_extensions.{self._name}' + + def __reduce__(self): + return self._name + + def __call__(self, *args, **kwds): + raise TypeError(f"Cannot instantiate {self!r}") + + def __or__(self, other): + return typing.Union[self, other] + + def __ror__(self, other): + return typing.Union[other, self] + + def __instancecheck__(self, obj): + raise TypeError(f"{self} cannot be used with isinstance()") + + def __subclasscheck__(self, cls): + raise TypeError(f"{self} cannot be used with issubclass()") + + @typing._tp_cache + def __getitem__(self, parameters): + return self._getitem(self, parameters) + + +# Note that inheriting from this class means that the object will be +# rejected by typing._type_check, so do not use it if the special form +# is arguably valid as a type by itself. +class _ExtensionsSpecialForm(typing._SpecialForm, _root=True): + def __repr__(self): + return 'typing_extensions.' + self._name + + +Final = typing.Final + +# Breakpoint: https://github.com/python/cpython/pull/30530 +if sys.version_info >= (3, 11): + final = typing.final +else: + # @final exists in 3.8+, but we backport it for all versions + # before 3.11 to keep support for the __final__ attribute. + # See https://bugs.python.org/issue46342 + def final(f): + """This decorator can be used to indicate to type checkers that + the decorated method cannot be overridden, and decorated class + cannot be subclassed. For example: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. The decorator + sets the ``__final__`` attribute to ``True`` on the decorated object + to allow runtime introspection. + """ + try: + f.__final__ = True + except (AttributeError, TypeError): + # Skip the attribute silently if it is not writable. + # AttributeError happens if the object has __slots__ or a + # read-only property, TypeError if it's a builtin class. + pass + return f + + +if hasattr(typing, "disjoint_base"): # 3.15 + disjoint_base = typing.disjoint_base +else: + def disjoint_base(cls): + """This decorator marks a class as a disjoint base. + + Child classes of a disjoint base cannot inherit from other disjoint bases that are + not parent classes of the disjoint base. + + For example: + + @disjoint_base + class Disjoint1: pass + + @disjoint_base + class Disjoint2: pass + + class Disjoint3(Disjoint1, Disjoint2): pass # Type checker error + + Type checkers can use knowledge of disjoint bases to detect unreachable code + and determine when two types can overlap. + + See PEP 800.""" + cls.__disjoint_base__ = True + return cls + + +def IntVar(name): + return typing.TypeVar(name) + + +# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8 +# Breakpoint: https://github.com/python/cpython/pull/29334 +if sys.version_info >= (3, 10, 1): + Literal = typing.Literal +else: + def _flatten_literal_params(parameters): + """An internal helper for Literal creation: flatten Literals among parameters""" + params = [] + for p in parameters: + if isinstance(p, _LiteralGenericAlias): + params.extend(p.__args__) + else: + params.append(p) + return tuple(params) + + def _value_and_type_iter(params): + for p in params: + yield p, type(p) + + class _LiteralGenericAlias(typing._GenericAlias, _root=True): + def __eq__(self, other): + if not isinstance(other, _LiteralGenericAlias): + return NotImplemented + these_args_deduped = set(_value_and_type_iter(self.__args__)) + other_args_deduped = set(_value_and_type_iter(other.__args__)) + return these_args_deduped == other_args_deduped + + def __hash__(self): + return hash(frozenset(_value_and_type_iter(self.__args__))) + + class _LiteralForm(_ExtensionsSpecialForm, _root=True): + def __init__(self, doc: str): + self._name = 'Literal' + self._doc = self.__doc__ = doc + + def __getitem__(self, parameters): + if not isinstance(parameters, tuple): + parameters = (parameters,) + + parameters = _flatten_literal_params(parameters) + + val_type_pairs = list(_value_and_type_iter(parameters)) + try: + deduped_pairs = set(val_type_pairs) + except TypeError: + # unhashable parameters + pass + else: + # similar logic to typing._deduplicate on Python 3.9+ + if len(deduped_pairs) < len(val_type_pairs): + new_parameters = [] + for pair in val_type_pairs: + if pair in deduped_pairs: + new_parameters.append(pair[0]) + deduped_pairs.remove(pair) + assert not deduped_pairs, deduped_pairs + parameters = tuple(new_parameters) + + return _LiteralGenericAlias(self, parameters) + + Literal = _LiteralForm(doc="""\ + A type that can be used to indicate to type checkers + that the corresponding value has a value literally equivalent + to the provided parameter. For example: + + var: Literal[4] = 4 + + The type checker understands that 'var' is literally equal to + the value 4 and no other value. + + Literal[...] cannot be subclassed. There is no runtime + checking verifying that the parameter is actually a value + instead of a type.""") + + +_overload_dummy = typing._overload_dummy + + +if hasattr(typing, "get_overloads"): # 3.11+ + overload = typing.overload + get_overloads = typing.get_overloads + clear_overloads = typing.clear_overloads +else: + # {module: {qualname: {firstlineno: func}}} + _overload_registry = collections.defaultdict( + functools.partial(collections.defaultdict, dict) + ) + + def overload(func): + """Decorator for overloaded functions/methods. + + In a stub file, place two or more stub definitions for the same + function in a row, each decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + + In a non-stub file (i.e. a regular .py file), do the same but + follow it with an implementation. The implementation should *not* + be decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + def utf8(value): + # implementation goes here + + The overloads for a function can be retrieved at runtime using the + get_overloads() function. + """ + # classmethod and staticmethod + f = getattr(func, "__func__", func) + try: + _overload_registry[f.__module__][f.__qualname__][ + f.__code__.co_firstlineno + ] = func + except AttributeError: + # Not a normal function; ignore. + pass + return _overload_dummy + + def get_overloads(func): + """Return all defined overloads for *func* as a sequence.""" + # classmethod and staticmethod + f = getattr(func, "__func__", func) + if f.__module__ not in _overload_registry: + return [] + mod_dict = _overload_registry[f.__module__] + if f.__qualname__ not in mod_dict: + return [] + return list(mod_dict[f.__qualname__].values()) + + def clear_overloads(): + """Clear all overloads in the registry.""" + _overload_registry.clear() + + +# This is not a real generic class. Don't use outside annotations. +Type = typing.Type + +# Various ABCs mimicking those in collections.abc. +# A few are simply re-exported for completeness. +Awaitable = typing.Awaitable +Coroutine = typing.Coroutine +AsyncIterable = typing.AsyncIterable +AsyncIterator = typing.AsyncIterator +Deque = typing.Deque +DefaultDict = typing.DefaultDict +OrderedDict = typing.OrderedDict +Counter = typing.Counter +ChainMap = typing.ChainMap +Text = typing.Text +TYPE_CHECKING = typing.TYPE_CHECKING + + +# Breakpoint: https://github.com/python/cpython/pull/118681 +if sys.version_info >= (3, 13, 0, "beta"): + from typing import AsyncContextManager, AsyncGenerator, ContextManager, Generator +else: + def _is_dunder(attr): + return attr.startswith('__') and attr.endswith('__') + + + class _SpecialGenericAlias(typing._SpecialGenericAlias, _root=True): + def __init__(self, origin, nparams, *, defaults, inst=True, name=None): + assert nparams > 0, "`nparams` must be a positive integer" + assert defaults, "Must always specify a non-empty sequence for `defaults`" + super().__init__(origin, nparams, inst=inst, name=name) + self._defaults = defaults + + def __setattr__(self, attr, val): + allowed_attrs = {'_name', '_inst', '_nparams', '_defaults'} + if _is_dunder(attr) or attr in allowed_attrs: + object.__setattr__(self, attr, val) + else: + setattr(self.__origin__, attr, val) + + @typing._tp_cache + def __getitem__(self, params): + if not isinstance(params, tuple): + params = (params,) + msg = "Parameters to generic types must be types." + params = tuple(typing._type_check(p, msg) for p in params) + if ( + len(params) < self._nparams + and len(params) + len(self._defaults) >= self._nparams + ): + params = (*params, *self._defaults[len(params) - self._nparams:]) + actual_len = len(params) + + if actual_len != self._nparams: + expected = f"at least {self._nparams - len(self._defaults)}" + raise TypeError( + f"Too {'many' if actual_len > self._nparams else 'few'}" + f" arguments for {self};" + f" actual {actual_len}, expected {expected}" + ) + return self.copy_with(params) + + _NoneType = type(None) + Generator = _SpecialGenericAlias( + collections.abc.Generator, 3, defaults=(_NoneType, _NoneType) + ) + AsyncGenerator = _SpecialGenericAlias( + collections.abc.AsyncGenerator, 2, defaults=(_NoneType,) + ) + ContextManager = _SpecialGenericAlias( + contextlib.AbstractContextManager, + 2, + name="ContextManager", + defaults=(typing.Optional[bool],) + ) + AsyncContextManager = _SpecialGenericAlias( + contextlib.AbstractAsyncContextManager, + 2, + name="AsyncContextManager", + defaults=(typing.Optional[bool],) + ) + + +_PROTO_ALLOWLIST = { + 'collections.abc': [ + 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable', + 'AsyncIterator', 'Hashable', 'Sized', 'Container', 'Collection', + 'Reversible', 'Buffer', + ], + 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'], + 'io': ['Reader', 'Writer'], + 'typing_extensions': ['Buffer'], + 'os': ['PathLike'], +} + + +_EXCLUDED_ATTRS = frozenset(typing.EXCLUDED_ATTRIBUTES) | { + "__match_args__", "__protocol_attrs__", "__non_callable_proto_members__", + "__final__", +} + + +def _get_protocol_attrs(cls): + attrs = set() + for base in cls.__mro__[:-1]: # without object + if base.__name__ in {'Protocol', 'Generic'}: + continue + annotations = getattr(base, '__annotations__', {}) + for attr in (*base.__dict__, *annotations): + if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS): + attrs.add(attr) + return attrs + + +# `__match_args__` attribute was removed from protocol members in 3.13, +# we want to backport this change to older Python versions. +# 3.14 additionally added `io.Reader`, `io.Writer` and `os.PathLike` to +# the list of allowed protocol allowlist. +# https://github.com/python/cpython/issues/127647 +if sys.version_info >= (3, 14): + Protocol = typing.Protocol +else: + def _allow_reckless_class_checks(depth=2): + """Allow instance and class checks for special stdlib modules. + The abc and functools modules indiscriminately call isinstance() and + issubclass() on the whole MRO of a user class, which may contain protocols. + """ + return _caller(depth) in {'abc', 'functools', None} + + def _no_init(self, *args, **kwargs): + if type(self)._is_protocol: + raise TypeError('Protocols cannot be instantiated') + + def _type_check_issubclass_arg_1(arg): + """Raise TypeError if `arg` is not an instance of `type` + in `issubclass(arg, )`. + + In most cases, this is verified by type.__subclasscheck__. + Checking it again unnecessarily would slow down issubclass() checks, + so, we don't perform this check unless we absolutely have to. + + For various error paths, however, + we want to ensure that *this* error message is shown to the user + where relevant, rather than a typing.py-specific error message. + """ + if not isinstance(arg, type): + # Same error message as for issubclass(1, int). + raise TypeError('issubclass() arg 1 must be a class') + + # Inheriting from typing._ProtocolMeta isn't actually desirable, + # but is necessary to allow typing.Protocol and typing_extensions.Protocol + # to mix without getting TypeErrors about "metaclass conflict" + class _ProtocolMeta(type(typing.Protocol)): + # This metaclass is somewhat unfortunate, + # but is necessary for several reasons... + # + # NOTE: DO NOT call super() in any methods in this class + # That would call the methods on typing._ProtocolMeta on Python <=3.11 + # and those are slow + def __new__(mcls, name, bases, namespace, **kwargs): + if name == "Protocol" and len(bases) < 2: + pass + elif {Protocol, typing.Protocol} & set(bases): + for base in bases: + if not ( + base in {object, typing.Generic, Protocol, typing.Protocol} + or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, []) + or is_protocol(base) + ): + raise TypeError( + f"Protocols can only inherit from other protocols, " + f"got {base!r}" + ) + return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs) + + def __init__(cls, *args, **kwargs): + abc.ABCMeta.__init__(cls, *args, **kwargs) + if getattr(cls, "_is_protocol", False): + cls.__protocol_attrs__ = _get_protocol_attrs(cls) + + def __subclasscheck__(cls, other): + if cls is Protocol: + return type.__subclasscheck__(cls, other) + if ( + getattr(cls, '_is_protocol', False) + and not _allow_reckless_class_checks() + ): + if not getattr(cls, '_is_runtime_protocol', False): + _type_check_issubclass_arg_1(other) + raise TypeError( + "Instance and class checks can only be used with " + "@runtime_checkable protocols" + ) + if ( + # this attribute is set by @runtime_checkable: + cls.__non_callable_proto_members__ + and cls.__dict__.get("__subclasshook__") is _proto_hook + ): + _type_check_issubclass_arg_1(other) + non_method_attrs = sorted(cls.__non_callable_proto_members__) + raise TypeError( + "Protocols with non-method members don't support issubclass()." + f" Non-method members: {str(non_method_attrs)[1:-1]}." + ) + return abc.ABCMeta.__subclasscheck__(cls, other) + + def __instancecheck__(cls, instance): + # We need this method for situations where attributes are + # assigned in __init__. + if cls is Protocol: + return type.__instancecheck__(cls, instance) + if not getattr(cls, "_is_protocol", False): + # i.e., it's a concrete subclass of a protocol + return abc.ABCMeta.__instancecheck__(cls, instance) + + if ( + not getattr(cls, '_is_runtime_protocol', False) and + not _allow_reckless_class_checks() + ): + raise TypeError("Instance and class checks can only be used with" + " @runtime_checkable protocols") + + if abc.ABCMeta.__instancecheck__(cls, instance): + return True + + for attr in cls.__protocol_attrs__: + try: + val = inspect.getattr_static(instance, attr) + except AttributeError: + break + # this attribute is set by @runtime_checkable: + if val is None and attr not in cls.__non_callable_proto_members__: + break + else: + return True + + return False + + def __eq__(cls, other): + # Hack so that typing.Generic.__class_getitem__ + # treats typing_extensions.Protocol + # as equivalent to typing.Protocol + if abc.ABCMeta.__eq__(cls, other) is True: + return True + return cls is Protocol and other is typing.Protocol + + # This has to be defined, or the abc-module cache + # complains about classes with this metaclass being unhashable, + # if we define only __eq__! + def __hash__(cls) -> int: + return type.__hash__(cls) + + @classmethod + def _proto_hook(cls, other): + if not cls.__dict__.get('_is_protocol', False): + return NotImplemented + + for attr in cls.__protocol_attrs__: + for base in other.__mro__: + # Check if the members appears in the class dictionary... + if attr in base.__dict__: + if base.__dict__[attr] is None: + return NotImplemented + break + + # ...or in annotations, if it is a sub-protocol. + annotations = getattr(base, '__annotations__', {}) + if ( + isinstance(annotations, collections.abc.Mapping) + and attr in annotations + and is_protocol(other) + ): + break + else: + return NotImplemented + return True + + class Protocol(typing.Generic, metaclass=_ProtocolMeta): + __doc__ = typing.Protocol.__doc__ + __slots__ = () + _is_protocol = True + _is_runtime_protocol = False + + def __init_subclass__(cls, *args, **kwargs): + super().__init_subclass__(*args, **kwargs) + + # Determine if this is a protocol or a concrete subclass. + if not cls.__dict__.get('_is_protocol', False): + cls._is_protocol = any(b is Protocol for b in cls.__bases__) + + # Set (or override) the protocol subclass hook. + if '__subclasshook__' not in cls.__dict__: + cls.__subclasshook__ = _proto_hook + + # Prohibit instantiation for protocol classes + if cls._is_protocol and cls.__init__ is Protocol.__init__: + cls.__init__ = _no_init + + +# Breakpoint: https://github.com/python/cpython/pull/113401 +if sys.version_info >= (3, 13): + runtime_checkable = typing.runtime_checkable +else: + def runtime_checkable(cls): + """Mark a protocol class as a runtime protocol. + + Such protocol can be used with isinstance() and issubclass(). + Raise TypeError if applied to a non-protocol class. + This allows a simple-minded structural check very similar to + one trick ponies in collections.abc such as Iterable. + + For example:: + + @runtime_checkable + class Closable(Protocol): + def close(self): ... + + assert isinstance(open('/some/file'), Closable) + + Warning: this will check only the presence of the required methods, + not their type signatures! + """ + if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', False): + raise TypeError(f'@runtime_checkable can be only applied to protocol classes,' + f' got {cls!r}') + cls._is_runtime_protocol = True + + # typing.Protocol classes on <=3.11 break if we execute this block, + # because typing.Protocol classes on <=3.11 don't have a + # `__protocol_attrs__` attribute, and this block relies on the + # `__protocol_attrs__` attribute. Meanwhile, typing.Protocol classes on 3.12.2+ + # break if we *don't* execute this block, because *they* assume that all + # protocol classes have a `__non_callable_proto_members__` attribute + # (which this block sets) + if isinstance(cls, _ProtocolMeta) or sys.version_info >= (3, 12, 2): + # PEP 544 prohibits using issubclass() + # with protocols that have non-method members. + # See gh-113320 for why we compute this attribute here, + # rather than in `_ProtocolMeta.__init__` + cls.__non_callable_proto_members__ = set() + for attr in cls.__protocol_attrs__: + try: + is_callable = callable(getattr(cls, attr, None)) + except Exception as e: + raise TypeError( + f"Failed to determine whether protocol member {attr!r} " + "is a method member" + ) from e + else: + if not is_callable: + cls.__non_callable_proto_members__.add(attr) + + return cls + + +# The "runtime" alias exists for backwards compatibility. +runtime = runtime_checkable + + +# Our version of runtime-checkable protocols is faster on Python <=3.11 +# Breakpoint: https://github.com/python/cpython/pull/112717 +if sys.version_info >= (3, 12): + SupportsInt = typing.SupportsInt + SupportsFloat = typing.SupportsFloat + SupportsComplex = typing.SupportsComplex + SupportsBytes = typing.SupportsBytes + SupportsIndex = typing.SupportsIndex + SupportsAbs = typing.SupportsAbs + SupportsRound = typing.SupportsRound +else: + @runtime_checkable + class SupportsInt(Protocol): + """An ABC with one abstract method __int__.""" + __slots__ = () + + @abc.abstractmethod + def __int__(self) -> int: + pass + + @runtime_checkable + class SupportsFloat(Protocol): + """An ABC with one abstract method __float__.""" + __slots__ = () + + @abc.abstractmethod + def __float__(self) -> float: + pass + + @runtime_checkable + class SupportsComplex(Protocol): + """An ABC with one abstract method __complex__.""" + __slots__ = () + + @abc.abstractmethod + def __complex__(self) -> complex: + pass + + @runtime_checkable + class SupportsBytes(Protocol): + """An ABC with one abstract method __bytes__.""" + __slots__ = () + + @abc.abstractmethod + def __bytes__(self) -> bytes: + pass + + @runtime_checkable + class SupportsIndex(Protocol): + __slots__ = () + + @abc.abstractmethod + def __index__(self) -> int: + pass + + @runtime_checkable + class SupportsAbs(Protocol[T_co]): + """ + An ABC with one abstract method __abs__ that is covariant in its return type. + """ + __slots__ = () + + @abc.abstractmethod + def __abs__(self) -> T_co: + pass + + @runtime_checkable + class SupportsRound(Protocol[T_co]): + """ + An ABC with one abstract method __round__ that is covariant in its return type. + """ + __slots__ = () + + @abc.abstractmethod + def __round__(self, ndigits: int = 0) -> T_co: + pass + + +if hasattr(io, "Reader") and hasattr(io, "Writer"): + Reader = io.Reader + Writer = io.Writer +else: + @runtime_checkable + class Reader(Protocol[T_co]): + """Protocol for simple I/O reader instances. + + This protocol only supports blocking I/O. + """ + + __slots__ = () + + @abc.abstractmethod + def read(self, size: int = ..., /) -> T_co: + """Read data from the input stream and return it. + + If *size* is specified, at most *size* items (bytes/characters) will be + read. + """ + + @runtime_checkable + class Writer(Protocol[T_contra]): + """Protocol for simple I/O writer instances. + + This protocol only supports blocking I/O. + """ + + __slots__ = () + + @abc.abstractmethod + def write(self, data: T_contra, /) -> int: + """Write *data* to the output stream and return the number of items written.""" # noqa: E501 + + +_NEEDS_SINGLETONMETA = ( + not hasattr(typing, "NoDefault") or not hasattr(typing, "NoExtraItems") +) + +if _NEEDS_SINGLETONMETA: + class SingletonMeta(type): + def __setattr__(cls, attr, value): + # TypeError is consistent with the behavior of NoneType + raise TypeError( + f"cannot set {attr!r} attribute of immutable type {cls.__name__!r}" + ) + + +if hasattr(typing, "NoDefault"): + NoDefault = typing.NoDefault +else: + class NoDefaultType(metaclass=SingletonMeta): + """The type of the NoDefault singleton.""" + + __slots__ = () + + def __new__(cls): + return globals().get("NoDefault") or object.__new__(cls) + + def __repr__(self): + return "typing_extensions.NoDefault" + + def __reduce__(self): + return "NoDefault" + + NoDefault = NoDefaultType() + del NoDefaultType + +if hasattr(typing, "NoExtraItems"): + NoExtraItems = typing.NoExtraItems +else: + class NoExtraItemsType(metaclass=SingletonMeta): + """The type of the NoExtraItems singleton.""" + + __slots__ = () + + def __new__(cls): + return globals().get("NoExtraItems") or object.__new__(cls) + + def __repr__(self): + return "typing_extensions.NoExtraItems" + + def __reduce__(self): + return "NoExtraItems" + + NoExtraItems = NoExtraItemsType() + del NoExtraItemsType + +if _NEEDS_SINGLETONMETA: + del SingletonMeta + + +# Update this to something like >=3.13.0b1 if and when +# PEP 764 is implemented in CPython +_PEP_764_IMPLEMENTED = False + +if _PEP_764_IMPLEMENTED: + # The standard library TypedDict in Python 3.9.0/1 does not honour the "total" + # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059 + # The standard library TypedDict below Python 3.11 does not store runtime + # information about optional and required keys when using Required or NotRequired. + # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11. + # Aaaand on 3.12 we add __orig_bases__ to TypedDict + # to enable better runtime introspection. + # On 3.13 we deprecate some odd ways of creating TypedDicts. + # Also on 3.13, PEP 705 adds the ReadOnly[] qualifier. + # PEP 728 (Python 3.15+) adds the `extra_items` and `closed` keywords. + # PEP 764 (still pending) allows the `TypedDict` special form to be subscripted. + TypedDict = typing.TypedDict + _TypedDictMeta = typing._TypedDictMeta + is_typeddict = typing.is_typeddict +else: + # 3.10.0 and later + _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters + + def _get_typeddict_qualifiers(annotation_type): + while True: + annotation_origin = get_origin(annotation_type) + if annotation_origin is Annotated: + annotation_args = get_args(annotation_type) + if annotation_args: + annotation_type = annotation_args[0] + else: + break + elif annotation_origin is Required: + yield Required + annotation_type, = get_args(annotation_type) + elif annotation_origin is NotRequired: + yield NotRequired + annotation_type, = get_args(annotation_type) + elif annotation_origin is ReadOnly: + yield ReadOnly + annotation_type, = get_args(annotation_type) + else: + break + + class _TypedDictMeta(type): + + def __new__(cls, name, bases, ns, *, total=True, closed=None, + extra_items=NoExtraItems): + """Create new typed dict class object. + + This method is called when TypedDict is subclassed, + or when TypedDict is instantiated. This way + TypedDict supports all three syntax forms described in its docstring. + Subclasses and instances of TypedDict return actual dictionaries. + """ + for base in bases: + if type(base) is not _TypedDictMeta and base is not typing.Generic: + raise TypeError('cannot inherit from both a TypedDict type ' + 'and a non-TypedDict base class') + if closed is not None and extra_items is not NoExtraItems: + raise TypeError(f"Cannot combine closed={closed!r} and extra_items") + + if any(issubclass(b, typing.Generic) for b in bases): + generic_base = (typing.Generic,) + else: + generic_base = () + + ns_annotations = ns.pop('__annotations__', None) + + # typing.py generally doesn't let you inherit from plain Generic, unless + # the name of the class happens to be "Protocol" + tp_dict = type.__new__(_TypedDictMeta, "Protocol", (*generic_base, dict), ns) + tp_dict.__name__ = name + if tp_dict.__qualname__ == "Protocol": + tp_dict.__qualname__ = name + + if not hasattr(tp_dict, '__orig_bases__'): + tp_dict.__orig_bases__ = bases + + annotations = {} + own_annotate = None + if ns_annotations is not None: + own_annotations = ns_annotations + elif sys.version_info >= (3, 14): + if hasattr(annotationlib, "get_annotate_from_class_namespace"): + own_annotate = annotationlib.get_annotate_from_class_namespace(ns) + else: + # 3.14.0a7 and earlier + own_annotate = ns.get("__annotate__") + if own_annotate is not None: + own_annotations = annotationlib.call_annotate_function( + own_annotate, Format.FORWARDREF, owner=tp_dict + ) + else: + own_annotations = {} + else: + own_annotations = {} + msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" + if _TAKES_MODULE: + own_checked_annotations = { + n: typing._type_check(tp, msg, module=tp_dict.__module__) + for n, tp in own_annotations.items() + } + else: + own_checked_annotations = { + n: typing._type_check(tp, msg) + for n, tp in own_annotations.items() + } + required_keys = set() + optional_keys = set() + readonly_keys = set() + mutable_keys = set() + extra_items_type = extra_items + + for base in bases: + base_dict = base.__dict__ + + if sys.version_info <= (3, 14): + annotations.update(base_dict.get('__annotations__', {})) + base_required = base_dict.get('__required_keys__', set()) + required_keys |= base_required + optional_keys -= base_required + + base_optional = base_dict.get('__optional_keys__', set()) + required_keys -= base_optional + optional_keys |= base_optional + + readonly_keys.update(base_dict.get('__readonly_keys__', ())) + mutable_keys.update(base_dict.get('__mutable_keys__', ())) + + # This was specified in an earlier version of PEP 728. Support + # is retained for backwards compatibility, but only for Python + # 3.13 and lower. + if (closed and sys.version_info < (3, 14) + and "__extra_items__" in own_checked_annotations): + annotation_type = own_checked_annotations.pop("__extra_items__") + qualifiers = set(_get_typeddict_qualifiers(annotation_type)) + if Required in qualifiers: + raise TypeError( + "Special key __extra_items__ does not support " + "Required" + ) + if NotRequired in qualifiers: + raise TypeError( + "Special key __extra_items__ does not support " + "NotRequired" + ) + extra_items_type = annotation_type + + annotations.update(own_checked_annotations) + for annotation_key, annotation_type in own_checked_annotations.items(): + qualifiers = set(_get_typeddict_qualifiers(annotation_type)) + + if Required in qualifiers: + is_required = True + elif NotRequired in qualifiers: + is_required = False + else: + is_required = total + + if is_required: + required_keys.add(annotation_key) + optional_keys.discard(annotation_key) + else: + optional_keys.add(annotation_key) + required_keys.discard(annotation_key) + + if ReadOnly in qualifiers: + mutable_keys.discard(annotation_key) + readonly_keys.add(annotation_key) + else: + mutable_keys.add(annotation_key) + readonly_keys.discard(annotation_key) + + # Breakpoint: https://github.com/python/cpython/pull/119891 + if sys.version_info >= (3, 14): + def __annotate__(format): + annos = {} + for base in bases: + if base is Generic: + continue + base_annotate = base.__annotate__ + if base_annotate is None: + continue + base_annos = annotationlib.call_annotate_function( + base_annotate, format, owner=base) + annos.update(base_annos) + if own_annotate is not None: + own = annotationlib.call_annotate_function( + own_annotate, format, owner=tp_dict) + if format != Format.STRING: + own = { + n: typing._type_check(tp, msg, module=tp_dict.__module__) + for n, tp in own.items() + } + elif format == Format.STRING: + own = annotationlib.annotations_to_string(own_annotations) + elif format in (Format.FORWARDREF, Format.VALUE): + own = own_checked_annotations + else: + raise NotImplementedError(format) + annos.update(own) + return annos + + tp_dict.__annotate__ = __annotate__ + else: + tp_dict.__annotations__ = annotations + tp_dict.__required_keys__ = frozenset(required_keys) + tp_dict.__optional_keys__ = frozenset(optional_keys) + tp_dict.__readonly_keys__ = frozenset(readonly_keys) + tp_dict.__mutable_keys__ = frozenset(mutable_keys) + tp_dict.__total__ = total + tp_dict.__closed__ = closed + tp_dict.__extra_items__ = extra_items_type + return tp_dict + + __call__ = dict # static method + + def __subclasscheck__(cls, other): + # Typed dicts are only for static structural subtyping. + raise TypeError('TypedDict does not support instance and class checks') + + __instancecheck__ = __subclasscheck__ + + _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {}) + + def _create_typeddict( + typename, + fields, + /, + *, + typing_is_inline, + total, + closed, + extra_items, + **kwargs, + ): + if fields is _marker or fields is None: + if fields is _marker: + deprecated_thing = ( + "Failing to pass a value for the 'fields' parameter" + ) + else: + deprecated_thing = "Passing `None` as the 'fields' parameter" + + example = f"`{typename} = TypedDict({typename!r}, {{}})`" + deprecation_msg = ( + f"{deprecated_thing} is deprecated and will be disallowed in " + "Python 3.15. To create a TypedDict class with 0 fields " + "using the functional syntax, pass an empty dictionary, e.g. " + ) + example + "." + warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2) + # Support a field called "closed" + if closed is not False and closed is not True and closed is not None: + kwargs["closed"] = closed + closed = None + # Or "extra_items" + if extra_items is not NoExtraItems: + kwargs["extra_items"] = extra_items + extra_items = NoExtraItems + fields = kwargs + elif kwargs: + raise TypeError("TypedDict takes either a dict or keyword arguments," + " but not both") + if kwargs: + # Breakpoint: https://github.com/python/cpython/pull/104891 + if sys.version_info >= (3, 13): + raise TypeError("TypedDict takes no keyword arguments") + warnings.warn( + "The kwargs-based syntax for TypedDict definitions is deprecated " + "in Python 3.11, will be removed in Python 3.13, and may not be " + "understood by third-party type checkers.", + DeprecationWarning, + stacklevel=2, + ) + + ns = {'__annotations__': dict(fields)} + module = _caller(depth=4 if typing_is_inline else 2) + if module is not None: + # Setting correct module is necessary to make typed dict classes + # pickleable. + ns['__module__'] = module + + td = _TypedDictMeta(typename, (), ns, total=total, closed=closed, + extra_items=extra_items) + td.__orig_bases__ = (TypedDict,) + return td + + class _TypedDictSpecialForm(_SpecialForm, _root=True): + def __call__( + self, + typename, + fields=_marker, + /, + *, + total=True, + closed=None, + extra_items=NoExtraItems, + **kwargs + ): + return _create_typeddict( + typename, + fields, + typing_is_inline=False, + total=total, + closed=closed, + extra_items=extra_items, + **kwargs, + ) + + def __mro_entries__(self, bases): + return (_TypedDict,) + + @_TypedDictSpecialForm + def TypedDict(self, args): + """A simple typed namespace. At runtime it is equivalent to a plain dict. + + TypedDict creates a dictionary type such that a type checker will expect all + instances to have a certain set of keys, where each key is + associated with a value of a consistent type. This expectation + is not checked at runtime. + + Usage:: + + class Point2D(TypedDict): + x: int + y: int + label: str + + a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK + b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check + + assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') + + The type info can be accessed via the Point2D.__annotations__ dict, and + the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. + TypedDict supports an additional equivalent form:: + + Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) + + By default, all keys must be present in a TypedDict. It is possible + to override this by specifying totality:: + + class Point2D(TypedDict, total=False): + x: int + y: int + + This means that a Point2D TypedDict can have any of the keys omitted. A type + checker is only expected to support a literal False or True as the value of + the total argument. True is the default, and makes all items defined in the + class body be required. + + The Required and NotRequired special forms can also be used to mark + individual keys as being required or not required:: + + class Point2D(TypedDict): + x: int # the "x" key must always be present (Required is the default) + y: NotRequired[int] # the "y" key can be omitted + + See PEP 655 for more details on Required and NotRequired. + """ + # This runs when creating inline TypedDicts: + if not isinstance(args, dict): + raise TypeError( + "TypedDict[...] should be used with a single dict argument" + ) + + return _create_typeddict( + "", + args, + typing_is_inline=True, + total=True, + closed=True, + extra_items=NoExtraItems, + ) + + _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta) + + def is_typeddict(tp): + """Check if an annotation is a TypedDict class + + For example:: + class Film(TypedDict): + title: str + year: int + + is_typeddict(Film) # => True + is_typeddict(Union[list, str]) # => False + """ + return isinstance(tp, _TYPEDDICT_TYPES) + + +if hasattr(typing, "assert_type"): + assert_type = typing.assert_type + +else: + def assert_type(val, typ, /): + """Assert (to the type checker) that the value is of the given type. + + When the type checker encounters a call to assert_type(), it + emits an error if the value is not of the specified type:: + + def greet(name: str) -> None: + assert_type(name, str) # ok + assert_type(name, int) # type checker error + + At runtime this returns the first argument unchanged and otherwise + does nothing. + """ + return val + + +if hasattr(typing, "ReadOnly"): # 3.13+ + get_type_hints = typing.get_type_hints +else: # <=3.13 + # replaces _strip_annotations() + def _strip_extras(t): + """Strips Annotated, Required and NotRequired from a given type.""" + if isinstance(t, typing._AnnotatedAlias): + return _strip_extras(t.__origin__) + if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly): + return _strip_extras(t.__args__[0]) + if isinstance(t, typing._GenericAlias): + stripped_args = tuple(_strip_extras(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return t.copy_with(stripped_args) + if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias): + stripped_args = tuple(_strip_extras(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return _types.GenericAlias(t.__origin__, stripped_args) + if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType): + stripped_args = tuple(_strip_extras(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return functools.reduce(operator.or_, stripped_args) + + return t + + def get_type_hints(obj, globalns=None, localns=None, include_extras=False): + """Return type hints for an object. + + This is often the same as obj.__annotations__, but it handles + forward references encoded as string literals, adds Optional[t] if a + default value equal to None is set and recursively replaces all + 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T' + (unless 'include_extras=True'). + + The argument may be a module, class, method, or function. The annotations + are returned as a dictionary. For classes, annotations include also + inherited members. + + TypeError is raised if the argument is not of a type that can contain + annotations, and an empty dictionary is returned if no annotations are + present. + + BEWARE -- the behavior of globalns and localns is counterintuitive + (unless you are familiar with how eval() and exec() work). The + search order is locals first, then globals. + + - If no dict arguments are passed, an attempt is made to use the + globals from obj (or the respective module's globals for classes), + and these are also used as the locals. If the object does not appear + to have globals, an empty dictionary is used. + + - If one dict argument is passed, it is used for both globals and + locals. + + - If two dict arguments are passed, they specify globals and + locals, respectively. + """ + hint = typing.get_type_hints( + obj, globalns=globalns, localns=localns, include_extras=True + ) + # Breakpoint: https://github.com/python/cpython/pull/30304 + if sys.version_info < (3, 11): + _clean_optional(obj, hint, globalns, localns) + if include_extras: + return hint + return {k: _strip_extras(t) for k, t in hint.items()} + + _NoneType = type(None) + + def _could_be_inserted_optional(t): + """detects Union[..., None] pattern""" + if not isinstance(t, typing._UnionGenericAlias): + return False + # Assume if last argument is not None they are user defined + if t.__args__[-1] is not _NoneType: + return False + return True + + # < 3.11 + def _clean_optional(obj, hints, globalns=None, localns=None): + # reverts injected Union[..., None] cases from typing.get_type_hints + # when a None default value is used. + # see https://github.com/python/typing_extensions/issues/310 + if not hints or isinstance(obj, type): + return + defaults = typing._get_defaults(obj) # avoid accessing __annotations___ + if not defaults: + return + original_hints = obj.__annotations__ + for name, value in hints.items(): + # Not a Union[..., None] or replacement conditions not fullfilled + if (not _could_be_inserted_optional(value) + or name not in defaults + or defaults[name] is not None + ): + continue + original_value = original_hints[name] + # value=NoneType should have caused a skip above but check for safety + if original_value is None: + original_value = _NoneType + # Forward reference + if isinstance(original_value, str): + if globalns is None: + if isinstance(obj, _types.ModuleType): + globalns = obj.__dict__ + else: + nsobj = obj + # Find globalns for the unwrapped object. + while hasattr(nsobj, '__wrapped__'): + nsobj = nsobj.__wrapped__ + globalns = getattr(nsobj, '__globals__', {}) + if localns is None: + localns = globalns + elif localns is None: + localns = globalns + + original_value = ForwardRef( + original_value, + is_argument=not isinstance(obj, _types.ModuleType) + ) + original_evaluated = typing._eval_type(original_value, globalns, localns) + # Compare if values differ. Note that even if equal + # value might be cached by typing._tp_cache contrary to original_evaluated + if original_evaluated != value or ( + # 3.10: ForwardRefs of UnionType might be turned into _UnionGenericAlias + hasattr(_types, "UnionType") + and isinstance(original_evaluated, _types.UnionType) + and not isinstance(value, _types.UnionType) + ): + hints[name] = original_evaluated + +# Python 3.9 has get_origin() and get_args() but those implementations don't support +# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do. +# Breakpoint: https://github.com/python/cpython/pull/25298 +if sys.version_info >= (3, 10): + get_origin = typing.get_origin + get_args = typing.get_args +# 3.9 +else: + def get_origin(tp): + """Get the unsubscripted version of a type. + + This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar + and Annotated. Return None for unsupported types. Examples:: + + get_origin(Literal[42]) is Literal + get_origin(int) is None + get_origin(ClassVar[int]) is ClassVar + get_origin(Generic) is Generic + get_origin(Generic[T]) is Generic + get_origin(Union[T, int]) is Union + get_origin(List[Tuple[T, T]][int]) == list + get_origin(P.args) is P + """ + if isinstance(tp, typing._AnnotatedAlias): + return Annotated + if isinstance(tp, (typing._BaseGenericAlias, _types.GenericAlias, + ParamSpecArgs, ParamSpecKwargs)): + return tp.__origin__ + if tp is typing.Generic: + return typing.Generic + return None + + def get_args(tp): + """Get type arguments with all substitutions performed. + + For unions, basic simplifications used by Union constructor are performed. + Examples:: + get_args(Dict[str, int]) == (str, int) + get_args(int) == () + get_args(Union[int, Union[T, int], str][int]) == (int, str) + get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) + get_args(Callable[[], T][int]) == ([], int) + """ + if isinstance(tp, typing._AnnotatedAlias): + return (tp.__origin__, *tp.__metadata__) + if isinstance(tp, (typing._GenericAlias, _types.GenericAlias)): + res = tp.__args__ + if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: + res = (list(res[:-1]), res[-1]) + return res + return () + + +# 3.10+ +if hasattr(typing, 'TypeAlias'): + TypeAlias = typing.TypeAlias +# 3.9 +else: + @_ExtensionsSpecialForm + def TypeAlias(self, parameters): + """Special marker indicating that an assignment should + be recognized as a proper type alias definition by type + checkers. + + For example:: + + Predicate: TypeAlias = Callable[..., bool] + + It's invalid when used anywhere except as in the example above. + """ + raise TypeError(f"{self} is not subscriptable") + + +def _set_default(type_param, default): + type_param.has_default = lambda: default is not NoDefault + type_param.__default__ = default + + +def _set_module(typevarlike): + # for pickling: + def_mod = _caller(depth=2) + if def_mod != 'typing_extensions': + typevarlike.__module__ = def_mod + + +class _DefaultMixin: + """Mixin for TypeVarLike defaults.""" + + __slots__ = () + __init__ = _set_default + + +# Classes using this metaclass must provide a _backported_typevarlike ClassVar +class _TypeVarLikeMeta(type): + def __instancecheck__(cls, __instance: Any) -> bool: + return isinstance(__instance, cls._backported_typevarlike) + + +if _PEP_696_IMPLEMENTED: + from typing import TypeVar +else: + # Add default and infer_variance parameters from PEP 696 and 695 + class TypeVar(metaclass=_TypeVarLikeMeta): + """Type variable.""" + + _backported_typevarlike = typing.TypeVar + + def __new__(cls, name, *constraints, bound=None, + covariant=False, contravariant=False, + default=NoDefault, infer_variance=False): + if hasattr(typing, "TypeAliasType"): + # PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar + typevar = typing.TypeVar(name, *constraints, bound=bound, + covariant=covariant, contravariant=contravariant, + infer_variance=infer_variance) + else: + typevar = typing.TypeVar(name, *constraints, bound=bound, + covariant=covariant, contravariant=contravariant) + if infer_variance and (covariant or contravariant): + raise ValueError("Variance cannot be specified with infer_variance.") + typevar.__infer_variance__ = infer_variance + + _set_default(typevar, default) + _set_module(typevar) + + def _tvar_prepare_subst(alias, args): + if ( + typevar.has_default() + and alias.__parameters__.index(typevar) == len(args) + ): + args += (typevar.__default__,) + return args + + typevar.__typing_prepare_subst__ = _tvar_prepare_subst + return typevar + + def __init_subclass__(cls) -> None: + raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type") + + +# Python 3.10+ has PEP 612 +if hasattr(typing, 'ParamSpecArgs'): + ParamSpecArgs = typing.ParamSpecArgs + ParamSpecKwargs = typing.ParamSpecKwargs +# 3.9 +else: + class _Immutable: + """Mixin to indicate that object should not be copied.""" + __slots__ = () + + def __copy__(self): + return self + + def __deepcopy__(self, memo): + return self + + class ParamSpecArgs(_Immutable): + """The args for a ParamSpec object. + + Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. + + ParamSpecArgs objects have a reference back to their ParamSpec: + + P.args.__origin__ is P + + This type is meant for runtime introspection and has no special meaning to + static type checkers. + """ + def __init__(self, origin): + self.__origin__ = origin + + def __repr__(self): + return f"{self.__origin__.__name__}.args" + + def __eq__(self, other): + if not isinstance(other, ParamSpecArgs): + return NotImplemented + return self.__origin__ == other.__origin__ + + class ParamSpecKwargs(_Immutable): + """The kwargs for a ParamSpec object. + + Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. + + ParamSpecKwargs objects have a reference back to their ParamSpec: + + P.kwargs.__origin__ is P + + This type is meant for runtime introspection and has no special meaning to + static type checkers. + """ + def __init__(self, origin): + self.__origin__ = origin + + def __repr__(self): + return f"{self.__origin__.__name__}.kwargs" + + def __eq__(self, other): + if not isinstance(other, ParamSpecKwargs): + return NotImplemented + return self.__origin__ == other.__origin__ + + +if _PEP_696_IMPLEMENTED: + from typing import ParamSpec + +# 3.10+ +elif hasattr(typing, 'ParamSpec'): + + # Add default parameter - PEP 696 + class ParamSpec(metaclass=_TypeVarLikeMeta): + """Parameter specification.""" + + _backported_typevarlike = typing.ParamSpec + + def __new__(cls, name, *, bound=None, + covariant=False, contravariant=False, + infer_variance=False, default=NoDefault): + if hasattr(typing, "TypeAliasType"): + # PEP 695 implemented, can pass infer_variance to typing.TypeVar + paramspec = typing.ParamSpec(name, bound=bound, + covariant=covariant, + contravariant=contravariant, + infer_variance=infer_variance) + else: + paramspec = typing.ParamSpec(name, bound=bound, + covariant=covariant, + contravariant=contravariant) + paramspec.__infer_variance__ = bool(infer_variance) + + _set_default(paramspec, default) + _set_module(paramspec) + + def _paramspec_prepare_subst(alias, args): + params = alias.__parameters__ + i = params.index(paramspec) + if i == len(args) and paramspec.has_default(): + args = [*args, paramspec.__default__] + if i >= len(args): + raise TypeError(f"Too few arguments for {alias}") + # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612. + if len(params) == 1 and not typing._is_param_expr(args[0]): + assert i == 0 + args = (args,) + # Convert lists to tuples to help other libraries cache the results. + elif isinstance(args[i], list): + args = (*args[:i], tuple(args[i]), *args[i + 1:]) + return args + + paramspec.__typing_prepare_subst__ = _paramspec_prepare_subst + return paramspec + + def __init_subclass__(cls) -> None: + raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type") + +# 3.9 +else: + + # Inherits from list as a workaround for Callable checks in Python < 3.9.2. + class ParamSpec(list, _DefaultMixin): + """Parameter specification variable. + + Usage:: + + P = ParamSpec('P') + + Parameter specification variables exist primarily for the benefit of static + type checkers. They are used to forward the parameter types of one + callable to another callable, a pattern commonly found in higher order + functions and decorators. They are only valid when used in ``Concatenate``, + or s the first argument to ``Callable``. In Python 3.10 and higher, + they are also supported in user-defined Generics at runtime. + See class Generic for more information on generic types. An + example for annotating a decorator:: + + T = TypeVar('T') + P = ParamSpec('P') + + def add_logging(f: Callable[P, T]) -> Callable[P, T]: + '''A type-safe decorator to add logging to a function.''' + def inner(*args: P.args, **kwargs: P.kwargs) -> T: + logging.info(f'{f.__name__} was called') + return f(*args, **kwargs) + return inner + + @add_logging + def add_two(x: float, y: float) -> float: + '''Add two numbers together.''' + return x + y + + Parameter specification variables defined with covariant=True or + contravariant=True can be used to declare covariant or contravariant + generic types. These keyword arguments are valid, but their actual semantics + are yet to be decided. See PEP 612 for details. + + Parameter specification variables can be introspected. e.g.: + + P.__name__ == 'T' + P.__bound__ == None + P.__covariant__ == False + P.__contravariant__ == False + + Note that only parameter specification variables defined in global scope can + be pickled. + """ + + # Trick Generic __parameters__. + __class__ = typing.TypeVar + + @property + def args(self): + return ParamSpecArgs(self) + + @property + def kwargs(self): + return ParamSpecKwargs(self) + + def __init__(self, name, *, bound=None, covariant=False, contravariant=False, + infer_variance=False, default=NoDefault): + list.__init__(self, [self]) + self.__name__ = name + self.__covariant__ = bool(covariant) + self.__contravariant__ = bool(contravariant) + self.__infer_variance__ = bool(infer_variance) + self.__bound__ = bound + _DefaultMixin.__init__(self, default) + + # for pickling: + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + + def __repr__(self): + if self.__infer_variance__: + prefix = '' + elif self.__covariant__: + prefix = '+' + elif self.__contravariant__: + prefix = '-' + else: + prefix = '~' + return prefix + self.__name__ + + def __hash__(self): + return object.__hash__(self) + + def __eq__(self, other): + return self is other + + def __reduce__(self): + return self.__name__ + + # Hack to get typing._type_check to pass. + def __call__(self, *args, **kwargs): + pass + + def __init_subclass__(cls) -> None: + raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type") + + +# 3.9 +if not hasattr(typing, 'Concatenate'): + # Inherits from list as a workaround for Callable checks in Python < 3.9.2. + + # 3.9.0-1 + if not hasattr(typing, '_type_convert'): + def _type_convert(arg, module=None, *, allow_special_forms=False): + """For converting None to type(None), and strings to ForwardRef.""" + if arg is None: + return type(None) + if isinstance(arg, str): + if sys.version_info <= (3, 9, 6): + return ForwardRef(arg) + if sys.version_info <= (3, 9, 7): + return ForwardRef(arg, module=module) + return ForwardRef(arg, module=module, is_class=allow_special_forms) + return arg + else: + _type_convert = typing._type_convert + + class _ConcatenateGenericAlias(list): + + # Trick Generic into looking into this for __parameters__. + __class__ = typing._GenericAlias + + def __init__(self, origin, args): + # Cannot use `super().__init__` here because of the `__class__` assignment + # in the class body (https://github.com/python/typing_extensions/issues/661) + list.__init__(self, args) + self.__origin__ = origin + self.__args__ = args + + def __repr__(self): + _type_repr = typing._type_repr + return (f'{_type_repr(self.__origin__)}' + f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]') + + def __hash__(self): + return hash((self.__origin__, self.__args__)) + + # Hack to get typing._type_check to pass in Generic. + def __call__(self, *args, **kwargs): + pass + + @property + def __parameters__(self): + return tuple( + tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec)) + ) + + # 3.9 used by __getitem__ below + def copy_with(self, params): + if isinstance(params[-1], _ConcatenateGenericAlias): + params = (*params[:-1], *params[-1].__args__) + elif isinstance(params[-1], (list, tuple)): + return (*params[:-1], *params[-1]) + elif (not (params[-1] is ... or isinstance(params[-1], ParamSpec))): + raise TypeError("The last parameter to Concatenate should be a " + "ParamSpec variable or ellipsis.") + return self.__class__(self.__origin__, params) + + # 3.9; accessed during GenericAlias.__getitem__ when substituting + def __getitem__(self, args): + if self.__origin__ in (Generic, Protocol): + # Can't subscript Generic[...] or Protocol[...]. + raise TypeError(f"Cannot subscript already-subscripted {self}") + if not self.__parameters__: + raise TypeError(f"{self} is not a generic class") + + if not isinstance(args, tuple): + args = (args,) + args = _unpack_args(*(_type_convert(p) for p in args)) + params = self.__parameters__ + for param in params: + prepare = getattr(param, "__typing_prepare_subst__", None) + if prepare is not None: + args = prepare(self, args) + # 3.9 & typing.ParamSpec + elif isinstance(param, ParamSpec): + i = params.index(param) + if ( + i == len(args) + and getattr(param, '__default__', NoDefault) is not NoDefault + ): + args = [*args, param.__default__] + if i >= len(args): + raise TypeError(f"Too few arguments for {self}") + # Special case for Z[[int, str, bool]] == Z[int, str, bool] + if len(params) == 1 and not _is_param_expr(args[0]): + assert i == 0 + args = (args,) + elif ( + isinstance(args[i], list) + # 3.9 + # This class inherits from list do not convert + and not isinstance(args[i], _ConcatenateGenericAlias) + ): + args = (*args[:i], tuple(args[i]), *args[i + 1:]) + + alen = len(args) + plen = len(params) + if alen != plen: + raise TypeError( + f"Too {'many' if alen > plen else 'few'} arguments for {self};" + f" actual {alen}, expected {plen}" + ) + + subst = dict(zip(self.__parameters__, args)) + # determine new args + new_args = [] + for arg in self.__args__: + if isinstance(arg, type): + new_args.append(arg) + continue + if isinstance(arg, TypeVar): + arg = subst[arg] + if ( + (isinstance(arg, typing._GenericAlias) and _is_unpack(arg)) + or ( + hasattr(_types, "GenericAlias") + and isinstance(arg, _types.GenericAlias) + and getattr(arg, "__unpacked__", False) + ) + ): + raise TypeError(f"{arg} is not valid as type argument") + + elif isinstance(arg, + typing._GenericAlias + if not hasattr(_types, "GenericAlias") else + (typing._GenericAlias, _types.GenericAlias) + ): + subparams = arg.__parameters__ + if subparams: + subargs = tuple(subst[x] for x in subparams) + arg = arg[subargs] + new_args.append(arg) + return self.copy_with(tuple(new_args)) + +# 3.10+ +else: + _ConcatenateGenericAlias = typing._ConcatenateGenericAlias + + # 3.10 + if sys.version_info < (3, 11): + + class _ConcatenateGenericAlias(typing._ConcatenateGenericAlias, _root=True): + # needed for checks in collections.abc.Callable to accept this class + __module__ = "typing" + + def copy_with(self, params): + if isinstance(params[-1], (list, tuple)): + return (*params[:-1], *params[-1]) + if isinstance(params[-1], typing._ConcatenateGenericAlias): + params = (*params[:-1], *params[-1].__args__) + elif not (params[-1] is ... or isinstance(params[-1], ParamSpec)): + raise TypeError("The last parameter to Concatenate should be a " + "ParamSpec variable or ellipsis.") + return super(typing._ConcatenateGenericAlias, self).copy_with(params) + + def __getitem__(self, args): + value = super().__getitem__(args) + if isinstance(value, tuple) and any(_is_unpack(t) for t in value): + return tuple(_unpack_args(*(n for n in value))) + return value + + +# 3.9.2 +class _EllipsisDummy: ... + + +# <=3.10 +def _create_concatenate_alias(origin, parameters): + if parameters[-1] is ... and sys.version_info < (3, 9, 2): + # Hack: Arguments must be types, replace it with one. + parameters = (*parameters[:-1], _EllipsisDummy) + if sys.version_info >= (3, 10, 3): + concatenate = _ConcatenateGenericAlias(origin, parameters, + _typevar_types=(TypeVar, ParamSpec), + _paramspec_tvars=True) + else: + concatenate = _ConcatenateGenericAlias(origin, parameters) + if parameters[-1] is not _EllipsisDummy: + return concatenate + # Remove dummy again + concatenate.__args__ = tuple(p if p is not _EllipsisDummy else ... + for p in concatenate.__args__) + if sys.version_info < (3, 10): + # backport needs __args__ adjustment only + return concatenate + concatenate.__parameters__ = tuple(p for p in concatenate.__parameters__ + if p is not _EllipsisDummy) + return concatenate + + +# <=3.10 +@typing._tp_cache +def _concatenate_getitem(self, parameters): + if parameters == (): + raise TypeError("Cannot take a Concatenate of no types.") + if not isinstance(parameters, tuple): + parameters = (parameters,) + if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)): + raise TypeError("The last parameter to Concatenate should be a " + "ParamSpec variable or ellipsis.") + msg = "Concatenate[arg, ...]: each arg must be a type." + parameters = (*(typing._type_check(p, msg) for p in parameters[:-1]), + parameters[-1]) + return _create_concatenate_alias(self, parameters) + + +# 3.11+; Concatenate does not accept ellipsis in 3.10 +# Breakpoint: https://github.com/python/cpython/pull/30969 +if sys.version_info >= (3, 11): + Concatenate = typing.Concatenate +# <=3.10 +else: + @_ExtensionsSpecialForm + def Concatenate(self, parameters): + """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a + higher order function which adds, removes or transforms parameters of a + callable. + + For example:: + + Callable[Concatenate[int, P], int] + + See PEP 612 for detailed information. + """ + return _concatenate_getitem(self, parameters) + + +# 3.10+ +if hasattr(typing, 'TypeGuard'): + TypeGuard = typing.TypeGuard +# 3.9 +else: + @_ExtensionsSpecialForm + def TypeGuard(self, parameters): + """Special typing form used to annotate the return type of a user-defined + type guard function. ``TypeGuard`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeGuard[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeGuard`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the type inside ``TypeGuard``. + + For example:: + + def is_str(val: Union[str, float]): + # "isinstance" type guard + if isinstance(val, str): + # Type of ``val`` is narrowed to ``str`` + ... + else: + # Else, type of ``val`` is narrowed to ``float``. + ... + + Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower + form of ``TypeA`` (it can even be a wider form) and this may lead to + type-unsafe results. The main reason is to allow for things like + narrowing ``List[object]`` to ``List[str]`` even though the latter is not + a subtype of the former, since ``List`` is invariant. The responsibility of + writing type-safe type guards is left to the user. + + ``TypeGuard`` also works with type variables. For more information, see + PEP 647 (User-Defined Type Guards). + """ + item = typing._type_check(parameters, f'{self} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + +# 3.13+ +if hasattr(typing, 'TypeIs'): + TypeIs = typing.TypeIs +# <=3.12 +else: + @_ExtensionsSpecialForm + def TypeIs(self, parameters): + """Special typing form used to annotate the return type of a user-defined + type narrower function. ``TypeIs`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeIs[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeIs`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the intersection of the type inside ``TypeIs`` and the argument's + previously known type. + + For example:: + + def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]: + return hasattr(val, '__await__') + + def f(val: Union[int, Awaitable[int]]) -> int: + if is_awaitable(val): + assert_type(val, Awaitable[int]) + else: + assert_type(val, int) + + ``TypeIs`` also works with type variables. For more information, see + PEP 742 (Narrowing types with TypeIs). + """ + item = typing._type_check(parameters, f'{self} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + +# 3.15+? +if hasattr(typing, 'TypeForm'): + TypeForm = typing.TypeForm +# <=3.14 +else: + class _TypeFormForm(_ExtensionsSpecialForm, _root=True): + # TypeForm(X) is equivalent to X but indicates to the type checker + # that the object is a TypeForm. + def __call__(self, obj, /): + return obj + + @_TypeFormForm + def TypeForm(self, parameters): + """A special form representing the value that results from the evaluation + of a type expression. This value encodes the information supplied in the + type expression, and it represents the type described by that type expression. + + When used in a type expression, TypeForm describes a set of type form objects. + It accepts a single type argument, which must be a valid type expression. + ``TypeForm[T]`` describes the set of all type form objects that represent + the type T or types that are assignable to T. + + Usage: + + def cast[T](typ: TypeForm[T], value: Any) -> T: ... + + reveal_type(cast(int, "x")) # int + + See PEP 747 for more information. + """ + item = typing._type_check(parameters, f'{self} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + + + +if hasattr(typing, "LiteralString"): # 3.11+ + LiteralString = typing.LiteralString +else: + @_SpecialForm + def LiteralString(self, params): + """Represents an arbitrary literal string. + + Example:: + + from typing_extensions import LiteralString + + def query(sql: LiteralString) -> ...: + ... + + query("SELECT * FROM table") # ok + query(f"SELECT * FROM {input()}") # not ok + + See PEP 675 for details. + + """ + raise TypeError(f"{self} is not subscriptable") + + +if hasattr(typing, "Self"): # 3.11+ + Self = typing.Self +else: + @_SpecialForm + def Self(self, params): + """Used to spell the type of "self" in classes. + + Example:: + + from typing import Self + + class ReturnsSelf: + def parse(self, data: bytes) -> Self: + ... + return self + + """ + + raise TypeError(f"{self} is not subscriptable") + + +if hasattr(typing, "Never"): # 3.11+ + Never = typing.Never +else: + @_SpecialForm + def Never(self, params): + """The bottom type, a type that has no members. + + This can be used to define a function that should never be + called, or a function that never returns:: + + from typing_extensions import Never + + def never_call_me(arg: Never) -> None: + pass + + def int_or_str(arg: int | str) -> None: + never_call_me(arg) # type checker error + match arg: + case int(): + print("It's an int") + case str(): + print("It's a str") + case _: + never_call_me(arg) # ok, arg is of type Never + + """ + + raise TypeError(f"{self} is not subscriptable") + + +if hasattr(typing, 'Required'): # 3.11+ + Required = typing.Required + NotRequired = typing.NotRequired +else: # <=3.10 + @_ExtensionsSpecialForm + def Required(self, parameters): + """A special typing construct to mark a key of a total=False TypedDict + as required. For example: + + class Movie(TypedDict, total=False): + title: Required[str] + year: int + + m = Movie( + title='The Matrix', # typechecker error if key is omitted + year=1999, + ) + + There is no runtime checking that a required key is actually provided + when instantiating a related TypedDict. + """ + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + @_ExtensionsSpecialForm + def NotRequired(self, parameters): + """A special typing construct to mark a key of a TypedDict as + potentially missing. For example: + + class Movie(TypedDict): + title: str + year: NotRequired[int] + + m = Movie( + title='The Matrix', # typechecker error if key is omitted + year=1999, + ) + """ + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + +if hasattr(typing, 'ReadOnly'): + ReadOnly = typing.ReadOnly +else: # <=3.12 + @_ExtensionsSpecialForm + def ReadOnly(self, parameters): + """A special typing construct to mark an item of a TypedDict as read-only. + + For example: + + class Movie(TypedDict): + title: ReadOnly[str] + year: int + + def mutate_movie(m: Movie) -> None: + m["year"] = 1992 # allowed + m["title"] = "The Matrix" # typechecker error + + There is no runtime checking for this property. + """ + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + +_UNPACK_DOC = """\ +Type unpack operator. + +The type unpack operator takes the child types from some container type, +such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For +example: + + # For some generic class `Foo`: + Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str] + + Ts = TypeVarTuple('Ts') + # Specifies that `Bar` is generic in an arbitrary number of types. + # (Think of `Ts` as a tuple of an arbitrary number of individual + # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the + # `Generic[]`.) + class Bar(Generic[Unpack[Ts]]): ... + Bar[int] # Valid + Bar[int, str] # Also valid + +From Python 3.11, this can also be done using the `*` operator: + + Foo[*tuple[int, str]] + class Bar(Generic[*Ts]): ... + +The operator can also be used along with a `TypedDict` to annotate +`**kwargs` in a function signature. For instance: + + class Movie(TypedDict): + name: str + year: int + + # This function expects two keyword arguments - *name* of type `str` and + # *year* of type `int`. + def foo(**kwargs: Unpack[Movie]): ... + +Note that there is only some runtime checking of this operator. Not +everything the runtime allows may be accepted by static type checkers. + +For more information, see PEP 646 and PEP 692. +""" + + +# PEP 692 changed the repr of Unpack[] +# Breakpoint: https://github.com/python/cpython/pull/104048 +if sys.version_info >= (3, 12): + Unpack = typing.Unpack + + def _is_unpack(obj): + return get_origin(obj) is Unpack + +else: # <=3.11 + class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True): + def __init__(self, getitem): + super().__init__(getitem) + self.__doc__ = _UNPACK_DOC + + class _UnpackAlias(typing._GenericAlias, _root=True): + if sys.version_info < (3, 11): + # needed for compatibility with Generic[Unpack[Ts]] + __class__ = typing.TypeVar + + @property + def __typing_unpacked_tuple_args__(self): + assert self.__origin__ is Unpack + assert len(self.__args__) == 1 + arg, = self.__args__ + if isinstance(arg, (typing._GenericAlias, _types.GenericAlias)): + if arg.__origin__ is not tuple: + raise TypeError("Unpack[...] must be used with a tuple type") + return arg.__args__ + return None + + @property + def __typing_is_unpacked_typevartuple__(self): + assert self.__origin__ is Unpack + assert len(self.__args__) == 1 + return isinstance(self.__args__[0], TypeVarTuple) + + def __getitem__(self, args): + if self.__typing_is_unpacked_typevartuple__: + return args + # Cannot use `super().__getitem__` here because of the `__class__` assignment + # in the class body on Python <=3.11 + # (https://github.com/python/typing_extensions/issues/661) + return typing._GenericAlias.__getitem__(self, args) + + @_UnpackSpecialForm + def Unpack(self, parameters): + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return _UnpackAlias(self, (item,)) + + def _is_unpack(obj): + return isinstance(obj, _UnpackAlias) + + +def _unpack_args(*args): + newargs = [] + for arg in args: + subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) + if subargs is not None and (not (subargs and subargs[-1] is ...)): + newargs.extend(subargs) + else: + newargs.append(arg) + return newargs + + +if sys.version_info >= (3, 15): + from typing import TypeVarTuple + +elif hasattr(typing, "TypeVarTuple"): # 3.11+ + + # Add default parameter - PEP 696 and bound/variance parameters + class TypeVarTuple(metaclass=_TypeVarLikeMeta): + """Type variable tuple.""" + + _backported_typevarlike = typing.TypeVarTuple + + def __new__(cls, name, *, bound=None, + covariant=False, contravariant=False, + infer_variance=False, default=NoDefault): + + if _PEP_696_IMPLEMENTED: + # can pass default argument + tvt = typing.TypeVarTuple(name, default=default) + else: + tvt = typing.TypeVarTuple(name) + _set_default(tvt, default) + + tvt.__bound__ = bound + tvt.__covariant__ = bool(covariant) + tvt.__contravariant__ = bool(contravariant) + tvt.__infer_variance__ = bool(infer_variance) + + _set_module(tvt) + + def _typevartuple_prepare_subst(alias, args): + params = alias.__parameters__ + typevartuple_index = params.index(tvt) + for param in params[typevartuple_index + 1:]: + if isinstance(param, TypeVarTuple): + raise TypeError( + f"More than one TypeVarTuple parameter in {alias}" + ) + + alen = len(args) + plen = len(params) + left = typevartuple_index + right = plen - typevartuple_index - 1 + var_tuple_index = None + fillarg = None + for k, arg in enumerate(args): + if not isinstance(arg, type): + subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) + if subargs and len(subargs) == 2 and subargs[-1] is ...: + if var_tuple_index is not None: + raise TypeError( + "More than one unpacked " + "arbitrary-length tuple argument" + ) + var_tuple_index = k + fillarg = subargs[0] + if var_tuple_index is not None: + left = min(left, var_tuple_index) + right = min(right, alen - var_tuple_index - 1) + elif left + right > alen: + raise TypeError(f"Too few arguments for {alias};" + f" actual {alen}, expected at least {plen - 1}") + if left == alen - right and tvt.has_default(): + replacement = _unpack_args(tvt.__default__) + else: + replacement = args[left: alen - right] + + return ( + *args[:left], + *([fillarg] * (typevartuple_index - left)), + replacement, + *([fillarg] * (plen - right - left - typevartuple_index - 1)), + *args[alen - right:], + ) + + tvt.__typing_prepare_subst__ = _typevartuple_prepare_subst + return tvt + + def __init_subclass__(self, *args, **kwds): + raise TypeError("Cannot subclass special typing classes") + +else: # <=3.10 + class TypeVarTuple(_DefaultMixin): + """Type variable tuple. + + Usage:: + + Ts = TypeVarTuple('Ts') + + In the same way that a normal type variable is a stand-in for a single + type such as ``int``, a type variable *tuple* is a stand-in for a *tuple* + type such as ``Tuple[int, str]``. + + Type variable tuples can be used in ``Generic`` declarations. + Consider the following example:: + + class Array(Generic[*Ts]): ... + + The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``, + where ``T1`` and ``T2`` are type variables. To use these type variables + as type parameters of ``Array``, we must *unpack* the type variable tuple using + the star operator: ``*Ts``. The signature of ``Array`` then behaves + as if we had simply written ``class Array(Generic[T1, T2]): ...``. + In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows + us to parameterise the class with an *arbitrary* number of type parameters. + + Type variable tuples can be used anywhere a normal ``TypeVar`` can. + This includes class definitions, as shown above, as well as function + signatures and variable annotations:: + + class Array(Generic[*Ts]): + + def __init__(self, shape: Tuple[*Ts]): + self._shape: Tuple[*Ts] = shape + + def get_shape(self) -> Tuple[*Ts]: + return self._shape + + shape = (Height(480), Width(640)) + x: Array[Height, Width] = Array(shape) + y = abs(x) # Inferred type is Array[Height, Width] + z = x + x # ... is Array[Height, Width] + x.get_shape() # ... is tuple[Height, Width] + + """ + + # Trick Generic __parameters__. + __class__ = typing.TypeVar + + def __iter__(self): + yield self.__unpacked__ + + def __init__(self, name, *, bound=None, covariant=False, contravariant=False, + infer_variance=False, default=NoDefault): + self.__name__ = name + self.__covariant__ = bool(covariant) + self.__contravariant__ = bool(contravariant) + self.__infer_variance__ = bool(infer_variance) + self.__bound__ = bound + _DefaultMixin.__init__(self, default) + + # for pickling: + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + + self.__unpacked__ = Unpack[self] + + def __repr__(self): + if self.__infer_variance__: + prefix = '' + elif self.__covariant__: + prefix = '+' + elif self.__contravariant__: + prefix = '-' + else: + prefix = '~' + return prefix + self.__name__ + + def __hash__(self): + return object.__hash__(self) + + def __eq__(self, other): + return self is other + + def __reduce__(self): + return self.__name__ + + def __init_subclass__(self, *args, **kwds): + if '_root' not in kwds: + raise TypeError("Cannot subclass special typing classes") + + +if hasattr(typing, "reveal_type"): # 3.11+ + reveal_type = typing.reveal_type +else: # <=3.10 + def reveal_type(obj: T, /) -> T: + """Reveal the inferred type of a variable. + + When a static type checker encounters a call to ``reveal_type()``, + it will emit the inferred type of the argument:: + + x: int = 1 + reveal_type(x) + + Running a static type checker (e.g., ``mypy``) on this example + will produce output similar to 'Revealed type is "builtins.int"'. + + At runtime, the function prints the runtime type of the + argument and returns it unchanged. + + """ + print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr) + return obj + + +if hasattr(typing, "_ASSERT_NEVER_REPR_MAX_LENGTH"): # 3.11+ + _ASSERT_NEVER_REPR_MAX_LENGTH = typing._ASSERT_NEVER_REPR_MAX_LENGTH +else: # <=3.10 + _ASSERT_NEVER_REPR_MAX_LENGTH = 100 + + +if hasattr(typing, "assert_never"): # 3.11+ + assert_never = typing.assert_never +else: # <=3.10 + def assert_never(arg: Never, /) -> Never: + """Assert to the type checker that a line of code is unreachable. + + Example:: + + def int_or_str(arg: int | str) -> None: + match arg: + case int(): + print("It's an int") + case str(): + print("It's a str") + case _: + assert_never(arg) + + If a type checker finds that a call to assert_never() is + reachable, it will emit an error. + + At runtime, this throws an exception when called. + + """ + value = repr(arg) + if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH: + value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...' + raise AssertionError(f"Expected code to be unreachable, but got: {value}") + + +# dataclass_transform exists in 3.11 but lacks the frozen_default parameter +# Breakpoint: https://github.com/python/cpython/pull/99958 +if sys.version_info >= (3, 12): # 3.12+ + dataclass_transform = typing.dataclass_transform +else: # <=3.11 + def dataclass_transform( + *, + eq_default: bool = True, + order_default: bool = False, + kw_only_default: bool = False, + frozen_default: bool = False, + field_specifiers: typing.Tuple[ + typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]], + ... + ] = (), + **kwargs: typing.Any, + ) -> typing.Callable[[T], T]: + """Decorator that marks a function, class, or metaclass as providing + dataclass-like behavior. + + Example: + + from typing_extensions import dataclass_transform + + _T = TypeVar("_T") + + # Used on a decorator function + @dataclass_transform() + def create_model(cls: type[_T]) -> type[_T]: + ... + return cls + + @create_model + class CustomerModel: + id: int + name: str + + # Used on a base class + @dataclass_transform() + class ModelBase: ... + + class CustomerModel(ModelBase): + id: int + name: str + + # Used on a metaclass + @dataclass_transform() + class ModelMeta(type): ... + + class ModelBase(metaclass=ModelMeta): ... + + class CustomerModel(ModelBase): + id: int + name: str + + Each of the ``CustomerModel`` classes defined in this example will now + behave similarly to a dataclass created with the ``@dataclasses.dataclass`` + decorator. For example, the type checker will synthesize an ``__init__`` + method. + + The arguments to this decorator can be used to customize this behavior: + - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be + True or False if it is omitted by the caller. + - ``order_default`` indicates whether the ``order`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``kw_only_default`` indicates whether the ``kw_only`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``frozen_default`` indicates whether the ``frozen`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``field_specifiers`` specifies a static list of supported classes + or functions that describe fields, similar to ``dataclasses.field()``. + + At runtime, this decorator records its arguments in the + ``__dataclass_transform__`` attribute on the decorated object. + + See PEP 681 for details. + + """ + def decorator(cls_or_fn): + cls_or_fn.__dataclass_transform__ = { + "eq_default": eq_default, + "order_default": order_default, + "kw_only_default": kw_only_default, + "frozen_default": frozen_default, + "field_specifiers": field_specifiers, + "kwargs": kwargs, + } + return cls_or_fn + return decorator + + +if hasattr(typing, "override"): # 3.12+ + override = typing.override +else: # <=3.11 + _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any]) + + def override(arg: _F, /) -> _F: + """Indicate that a method is intended to override a method in a base class. + + Usage: + + class Base: + def method(self) -> None: + pass + + class Child(Base): + @override + def method(self) -> None: + super().method() + + When this decorator is applied to a method, the type checker will + validate that it overrides a method with the same name on a base class. + This helps prevent bugs that may occur when a base class is changed + without an equivalent change to a child class. + + There is no runtime checking of these properties. The decorator + sets the ``__override__`` attribute to ``True`` on the decorated object + to allow runtime introspection. + + See PEP 698 for details. + + """ + try: + arg.__override__ = True + except (AttributeError, TypeError): + # Skip the attribute silently if it is not writable. + # AttributeError happens if the object has __slots__ or a + # read-only property, TypeError if it's a builtin class. + pass + return arg + + +# Python 3.13.8+ and 3.14.1+ contain a fix for the wrapped __init_subclass__ +# Breakpoint: https://github.com/python/cpython/pull/138210 +if ((3, 13, 8) <= sys.version_info < (3, 14)) or sys.version_info >= (3, 14, 1): + deprecated = warnings.deprecated +else: + _T = typing.TypeVar("_T") + + class deprecated: + """Indicate that a class, function or overload is deprecated. + + When this decorator is applied to an object, the type checker + will generate a diagnostic on usage of the deprecated object. + + Usage: + + @deprecated("Use B instead") + class A: + pass + + @deprecated("Use g instead") + def f(): + pass + + @overload + @deprecated("int support is deprecated") + def g(x: int) -> int: ... + @overload + def g(x: str) -> int: ... + + The warning specified by *category* will be emitted at runtime + on use of deprecated objects. For functions, that happens on calls; + for classes, on instantiation and on creation of subclasses. + If the *category* is ``None``, no warning is emitted at runtime. + The *stacklevel* determines where the + warning is emitted. If it is ``1`` (the default), the warning + is emitted at the direct caller of the deprecated object; if it + is higher, it is emitted further up the stack. + Static type checker behavior is not affected by the *category* + and *stacklevel* arguments. + + The deprecation message passed to the decorator is saved in the + ``__deprecated__`` attribute on the decorated object. + If applied to an overload, the decorator + must be after the ``@overload`` decorator for the attribute to + exist on the overload as returned by ``get_overloads()``. + + See PEP 702 for details. + + """ + def __init__( + self, + message: str, + /, + *, + category: typing.Optional[typing.Type[Warning]] = DeprecationWarning, + stacklevel: int = 1, + ) -> None: + if not isinstance(message, str): + raise TypeError( + "Expected an object of type str for 'message', not " + f"{type(message).__name__!r}" + ) + self.message = message + self.category = category + self.stacklevel = stacklevel + + def __call__(self, arg: _T, /) -> _T: + # Make sure the inner functions created below don't + # retain a reference to self. + msg = self.message + category = self.category + stacklevel = self.stacklevel + if category is None: + arg.__deprecated__ = msg + return arg + elif isinstance(arg, type): + import functools + from types import MethodType + + original_new = arg.__new__ + + @functools.wraps(original_new) + def __new__(cls, /, *args, **kwargs): + if cls is arg: + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + if original_new is not object.__new__: + return original_new(cls, *args, **kwargs) + # Mirrors a similar check in object.__new__. + elif cls.__init__ is object.__init__ and (args or kwargs): + raise TypeError(f"{cls.__name__}() takes no arguments") + else: + return original_new(cls) + + arg.__new__ = staticmethod(__new__) + + if "__init_subclass__" in arg.__dict__: + # __init_subclass__ is directly present on the decorated class. + # Synthesize a wrapper that calls this method directly. + original_init_subclass = arg.__init_subclass__ + # We need slightly different behavior if __init_subclass__ + # is a bound method (likely if it was implemented in Python). + # Otherwise, it likely means it's a builtin such as + # object's implementation of __init_subclass__. + if isinstance(original_init_subclass, MethodType): + original_init_subclass = original_init_subclass.__func__ + + @functools.wraps(original_init_subclass) + def __init_subclass__(*args, **kwargs): + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + return original_init_subclass(*args, **kwargs) + else: + def __init_subclass__(cls, *args, **kwargs): + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + return super(arg, cls).__init_subclass__(*args, **kwargs) + + arg.__init_subclass__ = classmethod(__init_subclass__) + + arg.__deprecated__ = __new__.__deprecated__ = msg + __init_subclass__.__deprecated__ = msg + return arg + elif callable(arg): + import functools + import inspect + + @functools.wraps(arg) + def wrapper(*args, **kwargs): + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + return arg(*args, **kwargs) + + if inspect.iscoroutinefunction(arg): + # Breakpoint: https://github.com/python/cpython/pull/99247 + if sys.version_info >= (3, 12): + wrapper = inspect.markcoroutinefunction(wrapper) + else: + import asyncio.coroutines + + wrapper._is_coroutine = asyncio.coroutines._is_coroutine + + arg.__deprecated__ = wrapper.__deprecated__ = msg + return wrapper + else: + raise TypeError( + "@deprecated decorator with non-None category must be applied to " + f"a class or callable, not {arg!r}" + ) + +# Breakpoint: https://github.com/python/cpython/pull/23702 +if sys.version_info < (3, 10): + def _is_param_expr(arg): + return arg is ... or isinstance( + arg, (tuple, list, ParamSpec, _ConcatenateGenericAlias) + ) +else: + def _is_param_expr(arg): + return arg is ... or isinstance( + arg, + ( + tuple, + list, + ParamSpec, + _ConcatenateGenericAlias, + typing._ConcatenateGenericAlias, + ), + ) + + +# We have to do some monkey patching to deal with the dual nature of +# Unpack/TypeVarTuple: +# - We want Unpack to be a kind of TypeVar so it gets accepted in +# Generic[Unpack[Ts]] +# - We want it to *not* be treated as a TypeVar for the purposes of +# counting generic parameters, so that when we subscript a generic, +# the runtime doesn't try to substitute the Unpack with the subscripted type. +if not hasattr(typing, "TypeVarTuple"): + def _check_generic(cls, parameters, elen=_marker): + """Check correct count for parameters of a generic cls (internal helper). + + This gives a nice error message in case of count mismatch. + """ + # If substituting a single ParamSpec with multiple arguments + # we do not check the count + if (inspect.isclass(cls) and issubclass(cls, typing.Generic) + and len(cls.__parameters__) == 1 + and isinstance(cls.__parameters__[0], ParamSpec) + and parameters + and not _is_param_expr(parameters[0]) + ): + # Generic modifies parameters variable, but here we cannot do this + return + + if not elen: + raise TypeError(f"{cls} is not a generic class") + if elen is _marker: + if not hasattr(cls, "__parameters__") or not cls.__parameters__: + raise TypeError(f"{cls} is not a generic class") + elen = len(cls.__parameters__) + alen = len(parameters) + if alen != elen: + expect_val = elen + if hasattr(cls, "__parameters__"): + parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] + num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters) + if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples): + return + + # deal with TypeVarLike defaults + # required TypeVarLikes cannot appear after a defaulted one. + if alen < elen: + # since we validate TypeVarLike default in _collect_type_vars + # or _collect_parameters we can safely check parameters[alen] + if ( + getattr(parameters[alen], '__default__', NoDefault) + is not NoDefault + ): + return + + num_default_tv = sum(getattr(p, '__default__', NoDefault) + is not NoDefault for p in parameters) + + elen -= num_default_tv + + expect_val = f"at least {elen}" + + # Breakpoint: https://github.com/python/cpython/pull/27515 + things = "arguments" if sys.version_info >= (3, 10) else "parameters" + raise TypeError(f"Too {'many' if alen > elen else 'few'} {things}" + f" for {cls}; actual {alen}, expected {expect_val}") +else: + # Python 3.11+ + + def _check_generic(cls, parameters, elen): + """Check correct count for parameters of a generic cls (internal helper). + + This gives a nice error message in case of count mismatch. + """ + if not elen: + raise TypeError(f"{cls} is not a generic class") + alen = len(parameters) + if alen != elen: + expect_val = elen + if hasattr(cls, "__parameters__"): + parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] + + # deal with TypeVarLike defaults + # required TypeVarLikes cannot appear after a defaulted one. + if alen < elen: + # since we validate TypeVarLike default in _collect_type_vars + # or _collect_parameters we can safely check parameters[alen] + if ( + getattr(parameters[alen], '__default__', NoDefault) + is not NoDefault + ): + return + + num_default_tv = sum(getattr(p, '__default__', NoDefault) + is not NoDefault for p in parameters) + + elen -= num_default_tv + + expect_val = f"at least {elen}" + + raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments" + f" for {cls}; actual {alen}, expected {expect_val}") + +if not _PEP_696_IMPLEMENTED: + typing._check_generic = _check_generic + + +def _has_generic_or_protocol_as_origin() -> bool: + try: + frame = sys._getframe(2) + # - Catch AttributeError: not all Python implementations have sys._getframe() + # - Catch ValueError: maybe we're called from an unexpected module + # and the call stack isn't deep enough + except (AttributeError, ValueError): + return False # err on the side of leniency + else: + # If we somehow get invoked from outside typing.py, + # also err on the side of leniency + if frame.f_globals.get("__name__") != "typing": + return False + origin = frame.f_locals.get("origin") + # Cannot use "in" because origin may be an object with a buggy __eq__ that + # throws an error. + return origin is typing.Generic or origin is Protocol or origin is typing.Protocol + + +_TYPEVARTUPLE_TYPES = {TypeVarTuple, getattr(typing, "TypeVarTuple", None)} + + +def _is_unpacked_typevartuple(x) -> bool: + if get_origin(x) is not Unpack: + return False + args = get_args(x) + return ( + bool(args) + and len(args) == 1 + and type(args[0]) in _TYPEVARTUPLE_TYPES + ) + + +# Python 3.11+ _collect_type_vars was renamed to _collect_parameters +if hasattr(typing, '_collect_type_vars'): + def _collect_type_vars(types, typevar_types=None): + """Collect all type variable contained in types in order of + first appearance (lexicographic order). For example:: + + _collect_type_vars((T, List[S, T])) == (T, S) + """ + if typevar_types is None: + typevar_types = typing.TypeVar + tvars = [] + + # A required TypeVarLike cannot appear after a TypeVarLike with a default + # if it was a direct call to `Generic[]` or `Protocol[]` + enforce_default_ordering = _has_generic_or_protocol_as_origin() + default_encountered = False + + # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple + type_var_tuple_encountered = False + + for t in types: + if _is_unpacked_typevartuple(t): + type_var_tuple_encountered = True + elif ( + isinstance(t, typevar_types) and not isinstance(t, _UnpackAlias) + and t not in tvars + ): + if enforce_default_ordering: + has_default = getattr(t, '__default__', NoDefault) is not NoDefault + if has_default: + if type_var_tuple_encountered: + raise TypeError('Type parameter with a default' + ' follows TypeVarTuple') + default_encountered = True + elif default_encountered: + raise TypeError(f'Type parameter {t!r} without a default' + ' follows type parameter with a default') + + tvars.append(t) + if _should_collect_from_parameters(t): + tvars.extend([t for t in t.__parameters__ if t not in tvars]) + elif isinstance(t, tuple): + # Collect nested type_vars + # tuple wrapped by _prepare_paramspec_params(cls, params) + for x in t: + for collected in _collect_type_vars([x]): + if collected not in tvars: + tvars.append(collected) + return tuple(tvars) + + typing._collect_type_vars = _collect_type_vars +else: + def _collect_parameters(args): + """Collect all type variables and parameter specifications in args + in order of first appearance (lexicographic order). + + For example:: + + assert _collect_parameters((T, Callable[P, T])) == (T, P) + """ + parameters = [] + + # A required TypeVarLike cannot appear after a TypeVarLike with default + # if it was a direct call to `Generic[]` or `Protocol[]` + enforce_default_ordering = _has_generic_or_protocol_as_origin() + default_encountered = False + + # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple + type_var_tuple_encountered = False + + for t in args: + if isinstance(t, type): + # We don't want __parameters__ descriptor of a bare Python class. + pass + elif isinstance(t, tuple): + # `t` might be a tuple, when `ParamSpec` is substituted with + # `[T, int]`, or `[int, *Ts]`, etc. + for x in t: + for collected in _collect_parameters([x]): + if collected not in parameters: + parameters.append(collected) + elif hasattr(t, '__typing_subst__'): + if t not in parameters: + if enforce_default_ordering: + has_default = ( + getattr(t, '__default__', NoDefault) is not NoDefault + ) + + if type_var_tuple_encountered and has_default: + raise TypeError('Type parameter with a default' + ' follows TypeVarTuple') + + if has_default: + default_encountered = True + elif default_encountered: + raise TypeError(f'Type parameter {t!r} without a default' + ' follows type parameter with a default') + + parameters.append(t) + else: + if _is_unpacked_typevartuple(t): + type_var_tuple_encountered = True + for x in getattr(t, '__parameters__', ()): + if x not in parameters: + parameters.append(x) + + return tuple(parameters) + + if not _PEP_696_IMPLEMENTED: + typing._collect_parameters = _collect_parameters + +# Backport typing.NamedTuple as it exists in Python 3.13. +# In 3.11, the ability to define generic `NamedTuple`s was supported. +# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8. +# On 3.12, we added __orig_bases__ to call-based NamedTuples +# On 3.13, we deprecated kwargs-based NamedTuples +# Breakpoint: https://github.com/python/cpython/pull/105609 +if sys.version_info >= (3, 13): + NamedTuple = typing.NamedTuple +else: + def _make_nmtuple(name, types, module, defaults=()): + fields = [n for n, t in types] + annotations = {n: typing._type_check(t, f"field {n} annotation must be a type") + for n, t in types} + nm_tpl = collections.namedtuple(name, fields, + defaults=defaults, module=module) + nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations + return nm_tpl + + _prohibited_namedtuple_fields = typing._prohibited + _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'}) + + class _NamedTupleMeta(type): + def __new__(cls, typename, bases, ns): + assert _NamedTuple in bases + for base in bases: + if base is not _NamedTuple and base is not typing.Generic: + raise TypeError( + 'can only inherit from a NamedTuple type and Generic') + bases = tuple(tuple if base is _NamedTuple else base for base in bases) + if "__annotations__" in ns: + types = ns["__annotations__"] + elif "__annotate__" in ns: + # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated + types = ns["__annotate__"](1) + else: + types = {} + default_names = [] + for field_name in types: + if field_name in ns: + default_names.append(field_name) + elif default_names: + raise TypeError(f"Non-default namedtuple field {field_name} " + f"cannot follow default field" + f"{'s' if len(default_names) > 1 else ''} " + f"{', '.join(default_names)}") + nm_tpl = _make_nmtuple( + typename, types.items(), + defaults=[ns[n] for n in default_names], + module=ns['__module__'] + ) + nm_tpl.__bases__ = bases + if typing.Generic in bases: + if hasattr(typing, '_generic_class_getitem'): # 3.12+ + nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem) + else: + class_getitem = typing.Generic.__class_getitem__.__func__ + nm_tpl.__class_getitem__ = classmethod(class_getitem) + # update from user namespace without overriding special namedtuple attributes + for key, val in ns.items(): + if key in _prohibited_namedtuple_fields: + raise AttributeError("Cannot overwrite NamedTuple attribute " + key) + elif key not in _special_namedtuple_fields: + if key not in nm_tpl._fields: + setattr(nm_tpl, key, ns[key]) + try: + set_name = type(val).__set_name__ + except AttributeError: + pass + else: + try: + set_name(val, nm_tpl, key) + except BaseException as e: + msg = ( + f"Error calling __set_name__ on {type(val).__name__!r} " + f"instance {key!r} in {typename!r}" + ) + # BaseException.add_note() existed on py311, + # but the __set_name__ machinery didn't start + # using add_note() until py312. + # Making sure exceptions are raised in the same way + # as in "normal" classes seems most important here. + # Breakpoint: https://github.com/python/cpython/pull/95915 + if sys.version_info >= (3, 12): + e.add_note(msg) + raise + else: + raise RuntimeError(msg) from e + + if typing.Generic in bases: + nm_tpl.__init_subclass__() + return nm_tpl + + _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {}) + + def _namedtuple_mro_entries(bases): + assert NamedTuple in bases + return (_NamedTuple,) + + def NamedTuple(typename, fields=_marker, /, **kwargs): + """Typed version of namedtuple. + + Usage:: + + class Employee(NamedTuple): + name: str + id: int + + This is equivalent to:: + + Employee = collections.namedtuple('Employee', ['name', 'id']) + + The resulting class has an extra __annotations__ attribute, giving a + dict that maps field names to types. (The field names are also in + the _fields attribute, which is part of the namedtuple API.) + An alternative equivalent functional syntax is also accepted:: + + Employee = NamedTuple('Employee', [('name', str), ('id', int)]) + """ + if fields is _marker: + if kwargs: + deprecated_thing = "Creating NamedTuple classes using keyword arguments" + deprecation_msg = ( + "{name} is deprecated and will be disallowed in Python {remove}. " + "Use the class-based or functional syntax instead." + ) + else: + deprecated_thing = "Failing to pass a value for the 'fields' parameter" + example = f"`{typename} = NamedTuple({typename!r}, [])`" + deprecation_msg = ( + "{name} is deprecated and will be disallowed in Python {remove}. " + "To create a NamedTuple class with 0 fields " + "using the functional syntax, " + "pass an empty list, e.g. " + ) + example + "." + elif fields is None: + if kwargs: + raise TypeError( + "Cannot pass `None` as the 'fields' parameter " + "and also specify fields using keyword arguments" + ) + else: + deprecated_thing = "Passing `None` as the 'fields' parameter" + example = f"`{typename} = NamedTuple({typename!r}, [])`" + deprecation_msg = ( + "{name} is deprecated and will be disallowed in Python {remove}. " + "To create a NamedTuple class with 0 fields " + "using the functional syntax, " + "pass an empty list, e.g. " + ) + example + "." + elif kwargs: + raise TypeError("Either list of fields or keywords" + " can be provided to NamedTuple, not both") + if fields is _marker or fields is None: + warnings.warn( + deprecation_msg.format(name=deprecated_thing, remove="3.15"), + DeprecationWarning, + stacklevel=2, + ) + fields = kwargs.items() + nt = _make_nmtuple(typename, fields, module=_caller()) + nt.__orig_bases__ = (NamedTuple,) + return nt + + NamedTuple.__mro_entries__ = _namedtuple_mro_entries + + +if hasattr(collections.abc, "Buffer"): + Buffer = collections.abc.Buffer +else: + class Buffer(abc.ABC): # noqa: B024 + """Base class for classes that implement the buffer protocol. + + The buffer protocol allows Python objects to expose a low-level + memory buffer interface. Before Python 3.12, it is not possible + to implement the buffer protocol in pure Python code, or even + to check whether a class implements the buffer protocol. In + Python 3.12 and higher, the ``__buffer__`` method allows access + to the buffer protocol from Python code, and the + ``collections.abc.Buffer`` ABC allows checking whether a class + implements the buffer protocol. + + To indicate support for the buffer protocol in earlier versions, + inherit from this ABC, either in a stub file or at runtime, + or use ABC registration. This ABC provides no methods, because + there is no Python-accessible methods shared by pre-3.12 buffer + classes. It is useful primarily for static checks. + + """ + + # As a courtesy, register the most common stdlib buffer classes. + Buffer.register(memoryview) + Buffer.register(bytearray) + Buffer.register(bytes) + + +# Backport of types.get_original_bases, available on 3.12+ in CPython +if hasattr(_types, "get_original_bases"): + get_original_bases = _types.get_original_bases +else: + def get_original_bases(cls, /): + """Return the class's "original" bases prior to modification by `__mro_entries__`. + + Examples:: + + from typing import TypeVar, Generic + from typing_extensions import NamedTuple, TypedDict + + T = TypeVar("T") + class Foo(Generic[T]): ... + class Bar(Foo[int], float): ... + class Baz(list[str]): ... + Eggs = NamedTuple("Eggs", [("a", int), ("b", str)]) + Spam = TypedDict("Spam", {"a": int, "b": str}) + + assert get_original_bases(Bar) == (Foo[int], float) + assert get_original_bases(Baz) == (list[str],) + assert get_original_bases(Eggs) == (NamedTuple,) + assert get_original_bases(Spam) == (TypedDict,) + assert get_original_bases(int) == (object,) + """ + try: + return cls.__dict__.get("__orig_bases__", cls.__bases__) + except AttributeError: + raise TypeError( + f'Expected an instance of type, not {type(cls).__name__!r}' + ) from None + + +# NewType is a class on Python 3.10+, making it pickleable +# The error message for subclassing instances of NewType was improved on 3.11+ +# Breakpoint: https://github.com/python/cpython/pull/30268 +if sys.version_info >= (3, 11): + NewType = typing.NewType +else: + class NewType: + """NewType creates simple unique types with almost zero + runtime overhead. NewType(name, tp) is considered a subtype of tp + by static type checkers. At runtime, NewType(name, tp) returns + a dummy callable that simply returns its argument. Usage:: + UserId = NewType('UserId', int) + def name_by_id(user_id: UserId) -> str: + ... + UserId('user') # Fails type check + name_by_id(42) # Fails type check + name_by_id(UserId(42)) # OK + num = UserId(5) + 1 # type: int + """ + + def __call__(self, obj, /): + return obj + + def __init__(self, name, tp): + self.__qualname__ = name + if '.' in name: + name = name.rpartition('.')[-1] + self.__name__ = name + self.__supertype__ = tp + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + + def __mro_entries__(self, bases): + # We defined __mro_entries__ to get a better error message + # if a user attempts to subclass a NewType instance. bpo-46170 + supercls_name = self.__name__ + + class Dummy: + def __init_subclass__(cls): + subcls_name = cls.__name__ + raise TypeError( + f"Cannot subclass an instance of NewType. " + f"Perhaps you were looking for: " + f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`" + ) + + return (Dummy,) + + def __repr__(self): + return f'{self.__module__}.{self.__qualname__}' + + def __reduce__(self): + return self.__qualname__ + + # Breakpoint: https://github.com/python/cpython/pull/21515 + if sys.version_info >= (3, 10): + # PEP 604 methods + # It doesn't make sense to have these methods on Python <3.10 + + def __or__(self, other): + return typing.Union[self, other] + + def __ror__(self, other): + return typing.Union[other, self] + + +# Breakpoint: https://github.com/python/cpython/pull/149172 +if sys.version_info >= (3, 15): + TypeAliasType = typing.TypeAliasType +# <=3.14 +else: + # Breakpoint: https://github.com/python/cpython/pull/103764 + if sys.version_info >= (3, 12): + # 3.12-3.14 + def _is_unionable(obj): + """Corresponds to is_unionable() in unionobject.c in CPython.""" + return obj is None or isinstance(obj, ( + type, + _types.GenericAlias, + _types.UnionType, + typing.TypeAliasType, + TypeAliasType, + )) + else: + # <=3.11 + def _is_unionable(obj): + """Corresponds to is_unionable() in unionobject.c in CPython.""" + return obj is None or isinstance(obj, ( + type, + _types.GenericAlias, + _types.UnionType, + TypeAliasType, + )) + + if sys.version_info < (3, 10): + # Copied and pasted from https://github.com/python/cpython/blob/986a4e1b6fcae7fe7a1d0a26aea446107dd58dd2/Objects/genericaliasobject.c#L568-L582, + # so that we emulate the behaviour of `types.GenericAlias` + # on the latest versions of CPython + _ATTRIBUTE_DELEGATION_EXCLUSIONS = frozenset({ + "__class__", + "__bases__", + "__origin__", + "__args__", + "__unpacked__", + "__parameters__", + "__typing_unpacked_tuple_args__", + "__mro_entries__", + "__reduce_ex__", + "__reduce__", + "__copy__", + "__deepcopy__", + }) + + class _TypeAliasGenericAlias(typing._GenericAlias, _root=True): + def __getattr__(self, attr): + if attr in _ATTRIBUTE_DELEGATION_EXCLUSIONS: + return object.__getattr__(self, attr) + return getattr(self.__origin__, attr) + + + class TypeAliasType: + """Create named, parameterized type aliases. + + This provides a backport of the new `type` statement in Python 3.12: + + type ListOrSet[T] = list[T] | set[T] + + is equivalent to: + + T = TypeVar("T") + ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,)) + + The name ListOrSet can then be used as an alias for the type it refers to. + + The type_params argument should contain all the type parameters used + in the value of the type alias. If the alias is not generic, this + argument is omitted. + + Static type checkers should only support type aliases declared using + TypeAliasType that follow these rules: + + - The first argument (the name) must be a string literal. + - The TypeAliasType instance must be immediately assigned to a variable + of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid, + as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)'). + + """ + + def __init__(self, name: str, value, *, type_params=()): + if not isinstance(name, str): + raise TypeError("TypeAliasType name must be a string") + if not isinstance(type_params, tuple): + raise TypeError("type_params must be a tuple") + self.__value__ = value + self.__type_params__ = type_params + + default_value_encountered = False + parameters = [] + for type_param in type_params: + if ( + not isinstance(type_param, (TypeVar, TypeVarTuple, ParamSpec)) + # <=3.11 + # Unpack Backport passes isinstance(type_param, TypeVar) + or _is_unpack(type_param) + ): + raise TypeError(f"Expected a type param, got {type_param!r}") + has_default = ( + getattr(type_param, '__default__', NoDefault) is not NoDefault + ) + if default_value_encountered and not has_default: + raise TypeError(f"non-default type parameter '{type_param!r}'" + " follows default type parameter") + if has_default: + default_value_encountered = True + if isinstance(type_param, TypeVarTuple): + parameters.extend(type_param) + else: + parameters.append(type_param) + self.__parameters__ = tuple(parameters) + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + # Setting this attribute closes the TypeAliasType from further modification + self.__name__ = name + + def __setattr__(self, name: str, value: object, /) -> None: + if hasattr(self, "__name__") and name != "__module__": + self._raise_attribute_error(name) + super().__setattr__(name, value) + + def __delattr__(self, name: str, /) -> Never: + self._raise_attribute_error(name) + + def _raise_attribute_error(self, name: str) -> Never: + # Match the Python 3.12 error messages exactly + if name == "__name__": + raise AttributeError("readonly attribute") + elif name in {"__value__", "__type_params__", "__parameters__"}: + raise AttributeError( + f"attribute '{name}' of 'typing.TypeAliasType' objects " + "is not writable" + ) + else: + raise AttributeError( + f"'typing.TypeAliasType' object has no attribute '{name}'" + ) + + def __repr__(self) -> str: + return self.__name__ + + if sys.version_info < (3, 11): + def _check_single_param(self, param, recursion=0): + # Allow [], [int], [int, str], [int, ...], [int, T] + if param is ...: + return ... + if param is None: + return None + # Note in <= 3.9 _ConcatenateGenericAlias inherits from list + if isinstance(param, list) and recursion == 0: + return [self._check_single_param(arg, recursion+1) + for arg in param] + return typing._type_check( + param, f'Subscripting {self.__name__} requires a type.' + ) + + def _check_parameters(self, parameters): + if sys.version_info < (3, 11): + return tuple( + self._check_single_param(item) + for item in parameters + ) + return tuple(typing._type_check( + item, f'Subscripting {self.__name__} requires a type.' + ) + for item in parameters + ) + + def __getitem__(self, parameters): + if not self.__type_params__: + raise TypeError("Only generic type aliases are subscriptable") + if not isinstance(parameters, tuple): + parameters = (parameters,) + # Using 3.9 here will create problems with Concatenate + if sys.version_info >= (3, 10): + return _types.GenericAlias(self, parameters) + type_vars = _collect_type_vars(parameters) + parameters = self._check_parameters(parameters) + alias = _TypeAliasGenericAlias(self, parameters) + # alias.__parameters__ is not complete if Concatenate is present + # as it is converted to a list from which no parameters are extracted. + if alias.__parameters__ != type_vars: + alias.__parameters__ = type_vars + return alias + + def __reduce__(self): + return self.__name__ + + def __init_subclass__(cls, *args, **kwargs): + raise TypeError( + "type 'typing_extensions.TypeAliasType' is not an acceptable base type" + ) + + # The presence of this method convinces typing._type_check + # that TypeAliasTypes are types. + def __call__(self): + raise TypeError("Type alias is not callable") + + # Breakpoint: https://github.com/python/cpython/pull/21515 + if sys.version_info >= (3, 10): + def __or__(self, right): + # For forward compatibility with 3.12, reject Unions + # that are not accepted by the built-in Union. + if not _is_unionable(right): + return NotImplemented + return typing.Union[self, right] + + def __ror__(self, left): + if not _is_unionable(left): + return NotImplemented + return typing.Union[left, self] + + +if hasattr(typing, "is_protocol"): + is_protocol = typing.is_protocol + get_protocol_members = typing.get_protocol_members +else: + def is_protocol(tp: type, /) -> bool: + """Return True if the given type is a Protocol. + + Example:: + + >>> from typing_extensions import Protocol, is_protocol + >>> class P(Protocol): + ... def a(self) -> str: ... + ... b: int + >>> is_protocol(P) + True + >>> is_protocol(int) + False + """ + return ( + isinstance(tp, type) + and getattr(tp, '_is_protocol', False) + and tp is not Protocol + and tp is not typing.Protocol + ) + + def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]: + """Return the set of members defined in a Protocol. + + Example:: + + >>> from typing_extensions import Protocol, get_protocol_members + >>> class P(Protocol): + ... def a(self) -> str: ... + ... b: int + >>> get_protocol_members(P) == frozenset({'a', 'b'}) + True + + Raise a TypeError for arguments that are not Protocols. + """ + if not is_protocol(tp): + raise TypeError(f'{tp!r} is not a Protocol') + if hasattr(tp, '__protocol_attrs__'): + return frozenset(tp.__protocol_attrs__) + return frozenset(_get_protocol_attrs(tp)) + + +if hasattr(typing, "Doc"): + Doc = typing.Doc +else: + class Doc: + """Define the documentation of a type annotation using ``Annotated``, to be + used in class attributes, function and method parameters, return values, + and variables. + + The value should be a positional-only string literal to allow static tools + like editors and documentation generators to use it. + + This complements docstrings. + + The string value passed is available in the attribute ``documentation``. + + Example:: + + >>> from typing_extensions import Annotated, Doc + >>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ... + """ + def __init__(self, documentation: str, /) -> None: + self.documentation = documentation + + def __repr__(self) -> str: + return f"Doc({self.documentation!r})" + + def __hash__(self) -> int: + return hash(self.documentation) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Doc): + return NotImplemented + return self.documentation == other.documentation + + +_CapsuleType = getattr(_types, "CapsuleType", None) + +if _CapsuleType is None: + try: + import _socket + except ImportError: + pass + else: + _CAPI = getattr(_socket, "CAPI", None) + if _CAPI is not None: + _CapsuleType = type(_CAPI) + +if _CapsuleType is not None: + CapsuleType = _CapsuleType + __all__.append("CapsuleType") + + +if sys.version_info >= (3, 14): + from annotationlib import Format, get_annotations +else: + # Available since Python 3.14.0a3 + # PR: https://github.com/python/cpython/pull/124415 + class Format(enum.IntEnum): + VALUE = 1 + VALUE_WITH_FAKE_GLOBALS = 2 + FORWARDREF = 3 + STRING = 4 + + # Available since Python 3.14.0a1 + # PR: https://github.com/python/cpython/pull/119891 + def get_annotations(obj, *, globals=None, locals=None, eval_str=False, + format=Format.VALUE): + """Compute the annotations dict for an object. + + obj may be a callable, class, or module. + Passing in an object of any other type raises TypeError. + + Returns a dict. get_annotations() returns a new dict every time + it's called; calling it twice on the same object will return two + different but equivalent dicts. + + This is a backport of `inspect.get_annotations`, which has been + in the standard library since Python 3.10. See the standard library + documentation for more: + + https://docs.python.org/3/library/inspect.html#inspect.get_annotations + + This backport adds the *format* argument introduced by PEP 649. The + three formats supported are: + * VALUE: the annotations are returned as-is. This is the default and + it is compatible with the behavior on previous Python versions. + * FORWARDREF: return annotations as-is if possible, but replace any + undefined names with ForwardRef objects. The implementation proposed by + PEP 649 relies on language changes that cannot be backported; the + typing-extensions implementation simply returns the same result as VALUE. + * STRING: return annotations as strings, in a format close to the original + source. Again, this behavior cannot be replicated directly in a backport. + As an approximation, typing-extensions retrieves the annotations under + VALUE semantics and then stringifies them. + + The purpose of this backport is to allow users who would like to use + FORWARDREF or STRING semantics once PEP 649 is implemented, but who also + want to support earlier Python versions, to simply write: + + typing_extensions.get_annotations(obj, format=Format.FORWARDREF) + + """ + format = Format(format) + if format is Format.VALUE_WITH_FAKE_GLOBALS: + raise ValueError( + "The VALUE_WITH_FAKE_GLOBALS format is for internal use only" + ) + + if eval_str and format is not Format.VALUE: + raise ValueError("eval_str=True is only supported with format=Format.VALUE") + + if isinstance(obj, type): + # class + obj_dict = getattr(obj, '__dict__', None) + if obj_dict and hasattr(obj_dict, 'get'): + ann = obj_dict.get('__annotations__', None) + if isinstance(ann, _types.GetSetDescriptorType): + ann = None + else: + ann = None + + obj_globals = None + module_name = getattr(obj, '__module__', None) + if module_name: + module = sys.modules.get(module_name, None) + if module: + obj_globals = getattr(module, '__dict__', None) + obj_locals = dict(vars(obj)) + unwrap = obj + elif isinstance(obj, _types.ModuleType): + # module + ann = getattr(obj, '__annotations__', None) + obj_globals = obj.__dict__ + obj_locals = None + unwrap = None + elif callable(obj): + # this includes types.Function, types.BuiltinFunctionType, + # types.BuiltinMethodType, functools.partial, functools.singledispatch, + # "class funclike" from Lib/test/test_inspect... on and on it goes. + ann = getattr(obj, '__annotations__', None) + obj_globals = getattr(obj, '__globals__', None) + obj_locals = None + unwrap = obj + elif hasattr(obj, '__annotations__'): + ann = obj.__annotations__ + obj_globals = obj_locals = unwrap = None + else: + raise TypeError(f"{obj!r} is not a module, class, or callable.") + + if ann is None: + return {} + + if not isinstance(ann, dict): + raise ValueError(f"{obj!r}.__annotations__ is neither a dict nor None") + + if not ann: + return {} + + if not eval_str: + if format is Format.STRING: + return { + key: value if isinstance(value, str) else typing._type_repr(value) + for key, value in ann.items() + } + return dict(ann) + + if unwrap is not None: + while True: + if hasattr(unwrap, '__wrapped__'): + unwrap = unwrap.__wrapped__ + continue + if isinstance(unwrap, functools.partial): + unwrap = unwrap.func + continue + break + if hasattr(unwrap, "__globals__"): + obj_globals = unwrap.__globals__ + + if globals is None: + globals = obj_globals + if locals is None: + locals = obj_locals or {} + + # "Inject" type parameters into the local namespace + # (unless they are shadowed by assignments *in* the local namespace), + # as a way of emulating annotation scopes when calling `eval()` + if type_params := getattr(obj, "__type_params__", ()): + locals = {param.__name__: param for param in type_params} | locals + + return_value = {key: + value if not isinstance(value, str) else eval(value, globals, locals) + for key, value in ann.items() } + return return_value + + +if hasattr(typing, "evaluate_forward_ref"): + evaluate_forward_ref = typing.evaluate_forward_ref +else: + # Implements annotationlib.ForwardRef.evaluate + def _eval_with_owner( + forward_ref, *, owner=None, globals=None, locals=None, type_params=None + ): + if forward_ref.__forward_evaluated__: + return forward_ref.__forward_value__ + if getattr(forward_ref, "__cell__", None) is not None: + try: + value = forward_ref.__cell__.cell_contents + except ValueError: + pass + else: + forward_ref.__forward_evaluated__ = True + forward_ref.__forward_value__ = value + return value + if owner is None: + owner = getattr(forward_ref, "__owner__", None) + + if ( + globals is None + and getattr(forward_ref, "__forward_module__", None) is not None + ): + globals = getattr( + sys.modules.get(forward_ref.__forward_module__, None), "__dict__", None + ) + if globals is None: + globals = getattr(forward_ref, "__globals__", None) + if globals is None: + if isinstance(owner, type): + module_name = getattr(owner, "__module__", None) + if module_name: + module = sys.modules.get(module_name, None) + if module: + globals = getattr(module, "__dict__", None) + elif isinstance(owner, _types.ModuleType): + globals = getattr(owner, "__dict__", None) + elif callable(owner): + globals = getattr(owner, "__globals__", None) + + # If we pass None to eval() below, the globals of this module are used. + if globals is None: + globals = {} + + if locals is None: + locals = {} + if isinstance(owner, type): + locals.update(vars(owner)) + + if type_params is None and owner is not None: + # "Inject" type parameters into the local namespace + # (unless they are shadowed by assignments *in* the local namespace), + # as a way of emulating annotation scopes when calling `eval()` + type_params = getattr(owner, "__type_params__", None) + + # Type parameters exist in their own scope, which is logically + # between the locals and the globals. We simulate this by adding + # them to the globals. + if type_params is not None: + globals = dict(globals) + for param in type_params: + globals[param.__name__] = param + + arg = forward_ref.__forward_arg__ + if arg.isidentifier() and not keyword.iskeyword(arg): + if arg in locals: + value = locals[arg] + elif arg in globals: + value = globals[arg] + elif hasattr(builtins, arg): + return getattr(builtins, arg) + else: + raise NameError(arg) + else: + code = forward_ref.__forward_code__ + value = eval(code, globals, locals) + forward_ref.__forward_evaluated__ = True + forward_ref.__forward_value__ = value + return value + + def evaluate_forward_ref( + forward_ref, + *, + owner=None, + globals=None, + locals=None, + type_params=None, + format=None, + _recursive_guard=frozenset(), + ): + """Evaluate a forward reference as a type hint. + + This is similar to calling the ForwardRef.evaluate() method, + but unlike that method, evaluate_forward_ref() also: + + * Recursively evaluates forward references nested within the type hint. + * Rejects certain objects that are not valid type hints. + * Replaces type hints that evaluate to None with types.NoneType. + * Supports the *FORWARDREF* and *STRING* formats. + + *forward_ref* must be an instance of ForwardRef. *owner*, if given, + should be the object that holds the annotations that the forward reference + derived from, such as a module, class object, or function. It is used to + infer the namespaces to use for looking up names. *globals* and *locals* + can also be explicitly given to provide the global and local namespaces. + *type_params* is a tuple of type parameters that are in scope when + evaluating the forward reference. This parameter must be provided (though + it may be an empty tuple) if *owner* is not given and the forward reference + does not already have an owner set. *format* specifies the format of the + annotation and is a member of the annotationlib.Format enum. + + """ + if format == Format.STRING: + return forward_ref.__forward_arg__ + if forward_ref.__forward_arg__ in _recursive_guard: + return forward_ref + + # Evaluate the forward reference + try: + value = _eval_with_owner( + forward_ref, + owner=owner, + globals=globals, + locals=locals, + type_params=type_params, + ) + except NameError: + if format == Format.FORWARDREF: + return forward_ref + else: + raise + + if isinstance(value, str): + value = ForwardRef(value) + + # Recursively evaluate the type + if isinstance(value, ForwardRef): + if getattr(value, "__forward_module__", True) is not None: + globals = None + return evaluate_forward_ref( + value, + globals=globals, + locals=locals, + type_params=type_params, owner=owner, + _recursive_guard=_recursive_guard, format=format + ) + if sys.version_info < (3, 12, 5) and type_params: + # Make use of type_params + locals = dict(locals) if locals else {} + for tvar in type_params: + if tvar.__name__ not in locals: # lets not overwrite something present + locals[tvar.__name__] = tvar + if sys.version_info < (3, 12, 5): + return typing._eval_type( + value, + globals, + locals, + recursive_guard=_recursive_guard | {forward_ref.__forward_arg__}, + ) + else: + return typing._eval_type( + value, + globals, + locals, + type_params, + recursive_guard=_recursive_guard | {forward_ref.__forward_arg__}, + ) + + +if sys.version_info >= (3, 14, 0, "beta"): + type_repr = annotationlib.type_repr +else: + def type_repr(value): + """Convert a Python value to a format suitable for use with the STRING format. + + This is intended as a helper for tools that support the STRING format but do + not have access to the code that originally produced the annotations. It uses + repr() for most objects. + + """ + if isinstance(value, (type, _types.FunctionType, _types.BuiltinFunctionType)): + if value.__module__ == "builtins": + return value.__qualname__ + return f"{value.__module__}.{value.__qualname__}" + if value is ...: + return "..." + return repr(value) + + +# Aliases for items that are in typing in all supported versions. +# We use hasattr() checks so this library will continue to import on +# future versions of Python that may remove these names. +_typing_names = [ + "AbstractSet", + "AnyStr", + "BinaryIO", + "Callable", + "Collection", + "Container", + "Dict", + "FrozenSet", + "Hashable", + "IO", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "List", + "Mapping", + "MappingView", + "Match", + "MutableMapping", + "MutableSequence", + "MutableSet", + "Optional", + "Pattern", + "Reversible", + "Sequence", + "Set", + "Sized", + "TextIO", + "Tuple", + "Union", + "ValuesView", + "cast", + "no_type_check", + # This is private, but it was defined by typing_extensions for a long time + # and some users rely on it. + "_AnnotatedAlias", +] + +# Breakpoint: https://github.com/python/cpython/pull/133602 +if sys.version_info < (3, 15, 0): + _typing_names.append("no_type_check_decorator") + __all__.append("no_type_check_decorator") + +globals().update( + {name: getattr(typing, name) for name in _typing_names if hasattr(typing, name)} +) +# These are defined unconditionally because they are used in +# typing-extensions itself. +Generic = typing.Generic +ForwardRef = typing.ForwardRef +Annotated = typing.Annotated diff --git a/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/METADATA b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..6b88d5ace0388d1654c7adf6374411644a49ea8f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/METADATA @@ -0,0 +1,432 @@ +Metadata-Version: 2.4 +Name: ultralytics +Version: 8.4.160 +Summary: Ultralytics YOLO 🚀 for SOTA object detection, instance segmentation, semantic segmentation, depth estimation, classification, pose estimation, oriented object detection, and multi-object tracking. +Author-email: Glenn Jocher , Jing Qiu +Maintainer-email: Ultralytics +License: AGPL-3.0 +Project-URL: Homepage, https://ultralytics.com +Project-URL: Source, https://github.com/ultralytics/ultralytics +Project-URL: Documentation, https://docs.ultralytics.com +Project-URL: Bug Reports, https://github.com/ultralytics/ultralytics/issues +Project-URL: Changelog, https://github.com/ultralytics/ultralytics/releases +Keywords: machine-learning,deep-learning,computer-vision,ML,DL,AI,RT-DETR,SAM3,YOLO,YOLOv3,YOLOv5,YOLOv8,YOLO11,YOLO26,Platform,Ultralytics +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+) +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Software Development +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Scientific/Engineering :: Image Recognition +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: MacOS +Classifier: Operating System :: Microsoft :: Windows +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: cloudpickle>=3.1.1 +Requires-Dist: filelock>=3.16.1 +Requires-Dist: numpy>=1.23.0; platform_system != "Darwin" +Requires-Dist: numpy!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.0,!=2.3.1,!=2.3.2,!=2.3.3,!=2.3.4,>=1.23.0; platform_system == "Darwin" +Requires-Dist: matplotlib>=3.3.0 +Requires-Dist: opencv-python!=4.13.0.90,>=4.7.0 +Requires-Dist: pillow>=7.1.2 +Requires-Dist: pyyaml>=5.3.1 +Requires-Dist: requests>=2.23.0 +Requires-Dist: torch>=1.8.0 +Requires-Dist: torch!=2.4.0,>=1.8.0; sys_platform == "win32" +Requires-Dist: torchvision>=0.9.0 +Requires-Dist: psutil>=5.8.0 +Requires-Dist: polars>=0.20.0 +Requires-Dist: nvidia-ml-py>=12.0.0 +Requires-Dist: ultralytics-thop>=2.1.6 +Requires-Dist: ultralytics-platform>=0.1.45; python_version >= "3.11" +Provides-Extra: dev +Requires-Dist: ipython; extra == "dev" +Requires-Dist: pytest; extra == "dev" +Requires-Dist: pytest-cov; extra == "dev" +Requires-Dist: pytest-xdist>=3.0.0; extra == "dev" +Requires-Dist: coverage[toml]; extra == "dev" +Requires-Dist: zensical>=0.0.58; python_version >= "3.10" and extra == "dev" +Requires-Dist: minijinja>=2.0.0; extra == "dev" +Provides-Extra: export-base +Requires-Dist: onnx>=1.12.0; platform_system != "Darwin" and extra == "export-base" +Requires-Dist: onnx<1.18.0,>=1.12.0; (platform_system == "Darwin" and python_version < "3.13") and extra == "export-base" +Requires-Dist: onnx>=1.20.0; (platform_system == "Darwin" and python_version >= "3.13") and extra == "export-base" +Requires-Dist: onnxslim>=0.1.82; extra == "export-base" +Requires-Dist: onnxruntime<1.20.0; (python_version < "3.11" and (platform_machine != "aarch64" or platform_system != "Linux")) and extra == "export-base" +Requires-Dist: onnxruntime>=1.20.0; python_version >= "3.11" and extra == "export-base" +Provides-Extra: export-openvino +Requires-Dist: nncf>=2.14.0; python_version >= "3.9" and extra == "export-openvino" +Requires-Dist: openvino>=2024.0.0; extra == "export-openvino" +Requires-Dist: packaging>=26.0; (platform_machine == "aarch64" and platform_system == "Linux" and python_version >= "3.9") and extra == "export-openvino" +Provides-Extra: export-legacy-torch +Requires-Dist: numpy<2; python_version < "3.13" and extra == "export-legacy-torch" +Requires-Dist: setuptools<81.0.0; python_version >= "3.9" and extra == "export-legacy-torch" +Requires-Dist: nncf<3.0.0; python_version >= "3.9" and extra == "export-legacy-torch" +Provides-Extra: export-tensorflow +Requires-Dist: numpy<2.0.0; python_version < "3.13" and extra == "export-tensorflow" +Requires-Dist: tensorflow<=2.19.0,>=2.0.0; python_version < "3.13" and extra == "export-tensorflow" +Requires-Dist: tensorflow>2.19.0; python_version >= "3.13" and extra == "export-tensorflow" +Requires-Dist: ydf<0.13.0; (platform_machine != "aarch64" and python_version <= "3.12") and extra == "export-tensorflow" +Requires-Dist: googleapis-common-protos<1.74.0; python_version <= "3.12" and extra == "export-tensorflow" +Requires-Dist: tensorstore>=0.1.63; (platform_machine == "aarch64" and python_version >= "3.9") and extra == "export-tensorflow" +Requires-Dist: h5py!=3.11.0; platform_machine == "aarch64" and extra == "export-tensorflow" +Provides-Extra: export-coreai +Requires-Dist: coreai-torch>=0.4.2; (platform_system == "Darwin" and platform_machine == "arm64" and python_version >= "3.11" and python_version < "3.14") and extra == "export-coreai" +Provides-Extra: export-coreml +Requires-Dist: numpy<=2.3.5; (platform_system != "Windows" and python_version <= "3.13") and extra == "export-coreml" +Requires-Dist: coremltools>=9.0; (platform_system != "Windows" and python_version <= "3.13") and extra == "export-coreml" +Requires-Dist: scikit-learn>=1.3.2; (platform_system != "Windows" and python_version <= "3.13") and extra == "export-coreml" +Provides-Extra: export-executorch +Requires-Dist: executorch; extra == "export-executorch" +Requires-Dist: numpy<=2.3.5; extra == "export-executorch" +Provides-Extra: export-deepx +Requires-Dist: dx_com; extra == "export-deepx" +Requires-Dist: numpy<2; python_version < "3.13" and extra == "export-deepx" +Provides-Extra: export-litert +Requires-Dist: litert-torch>=0.9.0; (((platform_system == "Linux" and platform_machine == "x86_64") or platform_system == "Darwin") and python_version >= "3.10") and extra == "export-litert" +Requires-Dist: ai-edge-litert>=2.1.4; (((platform_system == "Linux" and platform_machine == "x86_64") or platform_system == "Darwin") and python_version >= "3.10") and extra == "export-litert" +Requires-Dist: ai-edge-quantizer>=0.6.0; (((platform_system == "Linux" and platform_machine == "x86_64") or platform_system == "Darwin") and python_version >= "3.10") and extra == "export-litert" +Provides-Extra: export +Requires-Dist: ultralytics[export-base]; extra == "export" +Requires-Dist: ultralytics[export-openvino]; extra == "export" +Requires-Dist: ultralytics[export-tensorflow]; extra == "export" +Requires-Dist: ultralytics[export-coreml]; extra == "export" +Requires-Dist: ultralytics[export-litert]; extra == "export" +Requires-Dist: torch<2.13.0,>=2.12.0; (platform_system == "Linux" and platform_machine == "aarch64" and python_version == "3.11") and extra == "export" +Provides-Extra: solutions +Requires-Dist: shapely>=2.0.0; extra == "solutions" +Requires-Dist: lap>=0.5.12; extra == "solutions" +Requires-Dist: streamlit>=1.51.0; python_version >= "3.10" and extra == "solutions" +Requires-Dist: streamlit<1.51.0,>=1.29.0; (python_version < "3.10" and (platform_machine != "aarch64" or platform_system != "Linux")) and extra == "solutions" +Requires-Dist: flask>=3.0.1; extra == "solutions" +Provides-Extra: llm +Requires-Dist: openai>=2.0.0; extra == "llm" +Provides-Extra: logging +Requires-Dist: wandb; extra == "logging" +Requires-Dist: tensorboard; extra == "logging" +Requires-Dist: mlflow; extra == "logging" +Provides-Extra: extra +Requires-Dist: ipython; extra == "extra" +Requires-Dist: albumentations>=1.4.6; extra == "extra" +Requires-Dist: faster-coco-eval>=1.6.7; extra == "extra" +Provides-Extra: typing +Requires-Dist: types-pillow; extra == "typing" +Requires-Dist: types-psutil; extra == "typing" +Requires-Dist: types-pyyaml; extra == "typing" +Requires-Dist: types-requests; extra == "typing" +Requires-Dist: types-shapely; extra == "typing" +Dynamic: license-file + +
+

+ + Ultralytics YOLO banner +

+ +[中文](https://docs.ultralytics.com/zh) | [한국어](https://docs.ultralytics.com/ko) | [日本語](https://docs.ultralytics.com/ja) | [Русский](https://docs.ultralytics.com/ru) | [Deutsch](https://docs.ultralytics.com/de) | [Français](https://docs.ultralytics.com/fr) | [Español](https://docs.ultralytics.com/es) | [Português](https://docs.ultralytics.com/pt) | [Türkçe](https://docs.ultralytics.com/tr) | [Tiếng Việt](https://docs.ultralytics.com/vi) | [العربية](https://docs.ultralytics.com/ar)
+ +
+ Ultralytics CI + Ultralytics Downloads + Ultralytics Discord + Ultralytics Forums + Ultralytics Reddit +
+ Run Ultralytics on Gradient + Open Ultralytics In Colab + Open Ultralytics In Kaggle + Open Ultralytics In Binder +
+
+
+ +
+ ultralytics%2Fultralytics | Trendshift +
+
+ +[Ultralytics](https://www.ultralytics.com) creates cutting-edge, state-of-the-art (SOTA) [YOLO models](https://www.ultralytics.com/yolo) built on years of foundational research in computer vision and AI. Constantly updated for performance and flexibility, our models are **fast**, **accurate**, and **easy to use**. They excel at [object detection](https://docs.ultralytics.com/tasks/detect), [instance segmentation](https://docs.ultralytics.com/tasks/segment), [semantic segmentation](https://docs.ultralytics.com/tasks/semantic), [depth estimation](https://docs.ultralytics.com/tasks/depth), [image classification](https://docs.ultralytics.com/tasks/classify), [pose estimation](https://docs.ultralytics.com/tasks/pose), and [oriented object detection](https://docs.ultralytics.com/tasks/obb) tasks, and can [track](https://docs.ultralytics.com/modes/track) detected objects across video frames. + +Find detailed documentation in the [Ultralytics Docs](https://docs.ultralytics.com). Get support via [GitHub Issues](https://github.com/ultralytics/ultralytics/issues/new/choose). Join discussions on [Discord](https://discord.com/invite/ultralytics), [Reddit](https://www.reddit.com/r/ultralytics/), and the [Ultralytics Community Forums](https://community.ultralytics.com)! + +Request an Enterprise License for commercial use at [Ultralytics Licensing](https://www.ultralytics.com/license). + + + YOLO26 performance plots + + +
+ Ultralytics GitHub + space + Ultralytics LinkedIn + space + Ultralytics Twitter + space + Ultralytics YouTube + space + Ultralytics TikTok + space + Ultralytics BiliBili + space + Ultralytics Discord +
+ +## 📄 Documentation + +See below for quickstart installation and usage examples. For comprehensive guidance on training, validation, prediction, and deployment, refer to our full [Ultralytics Docs](https://docs.ultralytics.com). + +
+Install + +Install the `ultralytics` package, including all [requirements](https://github.com/ultralytics/ultralytics/blob/main/pyproject.toml), in a [**Python>=3.8**](https://www.python.org/) environment with [**PyTorch>=1.8**](https://pytorch.org/get-started/locally/). + +[![PyPI - Version](https://img.shields.io/pypi/v/ultralytics?logo=pypi&logoColor=white)](https://pypi.org/project/ultralytics/) [![Ultralytics Downloads](https://static.pepy.tech/badge/ultralytics)](https://clickpy.clickhouse.com/dashboard/ultralytics) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/ultralytics?logo=python&logoColor=gold)](https://pypi.org/project/ultralytics/) + +```bash +pip install ultralytics +``` + +For alternative installation methods, including [Conda](https://anaconda.org/conda-forge/ultralytics), [Docker](https://hub.docker.com/r/ultralytics/ultralytics), and building from source via Git, please consult the [Quickstart Guide](https://docs.ultralytics.com/quickstart). + +[![Conda Version](https://img.shields.io/conda/vn/conda-forge/ultralytics?logo=condaforge)](https://anaconda.org/conda-forge/ultralytics) [![Docker Image Version](https://img.shields.io/docker/v/ultralytics/ultralytics?sort=semver&logo=docker)](https://hub.docker.com/r/ultralytics/ultralytics) [![Ultralytics Docker Pulls](https://img.shields.io/docker/pulls/ultralytics/ultralytics?logo=docker)](https://hub.docker.com/r/ultralytics/ultralytics) + +
+ +
+Usage + +### CLI + +You can use Ultralytics YOLO directly from the Command Line Interface (CLI) with the `yolo` command: + +```bash +# Predict using a pretrained YOLO model (e.g., YOLO26n) on an image +yolo predict model=yolo26n.pt source='https://ultralytics.com/images/bus.jpg' +``` + +The `yolo` command supports various tasks and modes, accepting additional arguments like `imgsz=640`. Explore the YOLO [CLI Docs](https://docs.ultralytics.com/usage/cli) for more examples. + +### Python + +Ultralytics YOLO can also be integrated directly into your Python projects. It accepts the same [configuration arguments](https://docs.ultralytics.com/usage/cfg) as the CLI: + +```python +from ultralytics import YOLO + +# Load a pretrained YOLO26n model +model = YOLO("yolo26n.pt") + +# Train the model on the COCO8 dataset for 100 epochs +train_results = model.train( + data="coco8.yaml", # Path to dataset configuration file + epochs=100, # Number of training epochs + imgsz=640, # Image size for training + device="cpu", # Device to run on (e.g., 'cpu', 0, [0,1,2,3]) +) + +# Evaluate the model's performance on the validation set +metrics = model.val() + +# Perform object detection on an image +results = model("path/to/image.jpg") # Predict on an image +results[0].show() # Display results + +# Export the model to ONNX format for deployment +path = model.export(format="onnx") # Returns the path to the exported model +``` + +Discover more examples in the YOLO [Python Docs](https://docs.ultralytics.com/usage/python). + +
+ +## ✨ Models + +> **[YOLO27 — Coming Soon](https://docs.ultralytics.com/models/yolo27/):** Preview the upcoming family, currently undergoing final R&D. Models are not yet available, and no launch date is set. + +Ultralytics supports a wide range of YOLO models, from early versions like [YOLOv3](https://docs.ultralytics.com/models/yolov3) to the latest [YOLO26](https://docs.ultralytics.com/models/yolo26). The tables below showcase YOLO26 models pretrained on [COCO](https://docs.ultralytics.com/datasets/detect/coco) for [Detection](https://docs.ultralytics.com/tasks/detect), [Segmentation](https://docs.ultralytics.com/tasks/segment), and [Pose Estimation](https://docs.ultralytics.com/tasks/pose). [Semantic Segmentation](https://docs.ultralytics.com/tasks/semantic) models are pretrained on [Cityscapes](https://docs.ultralytics.com/datasets/semantic/cityscapes), [Depth Estimation](https://docs.ultralytics.com/tasks/depth) models are pretrained on a broad multi-dataset mix and evaluated on [NYU Depth V2](https://cs.nyu.edu/~fergus/datasets/nyu_depth_v2.html), [Classification](https://docs.ultralytics.com/tasks/classify) models are pretrained on [ImageNet](https://docs.ultralytics.com/datasets/classify/imagenet), and [OBB](https://docs.ultralytics.com/tasks/obb) models are pretrained on [DOTAv1](https://docs.ultralytics.com/datasets/obb/dota-v2#dota-v10). [Tracking](https://docs.ultralytics.com/modes/track) mode is compatible with Detection, Segmentation, Pose, and OBB models. The listed [pretrained models](https://docs.ultralytics.com/models) download automatically from the latest Ultralytics [release](https://github.com/ultralytics/assets/releases) on first use. + + + Ultralytics YOLO supported tasks + +
+
+ +
Detection (COCO) + +Explore the [Detection Docs](https://docs.ultralytics.com/tasks/detect) for usage examples. These models are trained on the [COCO dataset](https://cocodataset.org/), featuring 80 object classes. + +| Model | size
(pixels) | mAPval
50-95
| mAPval
50-95(e2e)
| Speed
CPU ONNX
(ms)
| Speed
T4 TensorRT10
(ms)
| params
(M) | FLOPs
(B) | +| ---------------------------------------------------------------------- | --------------------------- | -------------------------- | ------------------------------- | ------------------------------------ | ----------------------------------------- | ------------------------ | ----------------------- | +| [YOLO26n](https://platform.ultralytics.com/ultralytics/yolo26/yolo26n) | 640 | 40.9 | 40.1 | 38.9 ± 0.7 | 1.7 ± 0.0 | 2.4 | 5.5 | +| [YOLO26s](https://platform.ultralytics.com/ultralytics/yolo26/yolo26s) | 640 | 48.6 | 47.8 | 87.2 ± 0.9 | 2.5 ± 0.0 | 9.5 | 20.9 | +| [YOLO26m](https://platform.ultralytics.com/ultralytics/yolo26/yolo26m) | 640 | 53.1 | 52.5 | 220.0 ± 1.4 | 4.7 ± 0.1 | 20.4 | 68.4 | +| [YOLO26l](https://platform.ultralytics.com/ultralytics/yolo26/yolo26l) | 640 | 55.0 | 54.4 | 286.2 ± 2.0 | 6.2 ± 0.2 | 24.8 | 86.8 | +| [YOLO26x](https://platform.ultralytics.com/ultralytics/yolo26/yolo26x) | 640 | 57.5 | 56.9 | 525.8 ± 4.0 | 11.8 ± 0.2 | 55.7 | 194.4 | + +- **mAPval** values refer to single-model single-scale performance on the [COCO val2017](https://cocodataset.org/) dataset. See [YOLO Performance Metrics](https://docs.ultralytics.com/guides/yolo-performance-metrics) for details.
Reproduce with `yolo val detect data=coco.yaml device=0` +- **Speed** metrics are averaged over COCO val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/) instance. CPU speeds measured with [ONNX](https://onnx.ai/) export. GPU speeds measured with [TensorRT](https://developer.nvidia.com/tensorrt) export.
Reproduce with `yolo val detect data=coco.yaml batch=1 device=0|cpu` + +
+ +
Segmentation (COCO) + +Refer to the [Segmentation Docs](https://docs.ultralytics.com/tasks/segment) for usage examples. These models are trained on [COCO-Seg](https://docs.ultralytics.com/datasets/segment/coco), including 80 classes. + +| Model | size
(pixels) | mAPbox
50-95(e2e)
| mAPmask
50-95(e2e)
| Speed
CPU ONNX
(ms)
| Speed
T4 TensorRT10
(ms)
| params
(M) | FLOPs
(B) | +| ------------------------------------------------------------------------------ | --------------------------- | ------------------------------- | -------------------------------- | ------------------------------------ | ----------------------------------------- | ------------------------ | ----------------------- | +| [YOLO26n-seg](https://platform.ultralytics.com/ultralytics/yolo26/yolo26n-seg) | 640 | 39.6 | 33.9 | 53.3 ± 0.5 | 2.1 ± 0.0 | 2.7 | 9.3 | +| [YOLO26s-seg](https://platform.ultralytics.com/ultralytics/yolo26/yolo26s-seg) | 640 | 47.3 | 40.0 | 118.4 ± 0.9 | 3.3 ± 0.0 | 10.4 | 34.5 | +| [YOLO26m-seg](https://platform.ultralytics.com/ultralytics/yolo26/yolo26m-seg) | 640 | 52.5 | 44.1 | 328.2 ± 2.4 | 6.7 ± 0.1 | 23.6 | 121.7 | +| [YOLO26l-seg](https://platform.ultralytics.com/ultralytics/yolo26/yolo26l-seg) | 640 | 54.4 | 45.5 | 387.0 ± 3.7 | 8.0 ± 0.1 | 28.0 | 140.1 | +| [YOLO26x-seg](https://platform.ultralytics.com/ultralytics/yolo26/yolo26x-seg) | 640 | 56.5 | 47.0 | 787.0 ± 6.8 | 16.4 ± 0.1 | 62.8 | 314.0 | + +- **mAPval** values are for single-model single-scale on the [COCO val2017](https://cocodataset.org/) dataset. See [YOLO Performance Metrics](https://docs.ultralytics.com/guides/yolo-performance-metrics) for details.
Reproduce with `yolo val segment data=coco.yaml device=0` +- **Speed** metrics are averaged over COCO val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/) instance. CPU speeds measured with [ONNX](https://onnx.ai/) export. GPU speeds measured with [TensorRT](https://developer.nvidia.com/tensorrt) export.
Reproduce with `yolo val segment data=coco.yaml batch=1 device=0|cpu` + +
+ +
Semantic Segmentation (Cityscapes) + +See the [Semantic Segmentation Docs](https://docs.ultralytics.com/tasks/semantic) for usage examples. These models are trained on [Cityscapes](https://docs.ultralytics.com/datasets/semantic/cityscapes), including 19 classes. + +| Model | size
(pixels) | mIoUval | Speed
RTX3090 PyTorch
(ms)
| params
(M) | FLOPs
(B) | +| ------------------------------------------------------------------------------ | --------------------------- | ------------------ | ------------------------------------------- | ------------------------ | ----------------------- | +| [YOLO26n-sem](https://platform.ultralytics.com/ultralytics/yolo26/yolo26n-sem) | 1024 × 2048 | 78.3 | 4.4 ± 0.0 | 1.6 | 23.8 | +| [YOLO26s-sem](https://platform.ultralytics.com/ultralytics/yolo26/yolo26s-sem) | 1024 × 2048 | 80.8 | 8.4 ± 0.0 | 6.5 | 91.0 | +| [YOLO26m-sem](https://platform.ultralytics.com/ultralytics/yolo26/yolo26m-sem) | 1024 × 2048 | 82.0 | 19.9 ± 0.1 | 14.3 | 305.5 | +| [YOLO26l-sem](https://platform.ultralytics.com/ultralytics/yolo26/yolo26l-sem) | 1024 × 2048 | 82.9 | 26.5 ± 0.1 | 17.8 | 388.2 | +| [YOLO26x-sem](https://platform.ultralytics.com/ultralytics/yolo26/yolo26x-sem) | 1024 × 2048 | 83.6 | 48.9 ± 0.2 | 40.1 | 866.9 | + +- **mIoUval** values are for single-model single-scale on the [Cityscapes](https://www.cityscapes-dataset.com/) validation set.
Reproduce with `yolo semantic val data=cityscapes.yaml device=0 imgsz=2048` +- **Speed** metrics are averaged over Cityscapes validation images using an RTX3090 instance.
Reproduce with `yolo semantic val data=cityscapes.yaml batch=1 device=0|cpu imgsz=2048` + +
+ +
Depth Estimation (NYU Depth V2) + +See the [Depth Estimation Docs](https://docs.ultralytics.com/tasks/depth) for usage examples. These models are pretrained on a broad multi-dataset mix and evaluated on the [NYU Depth V2](https://cs.nyu.edu/~fergus/datasets/nyu_depth_v2.html) Eigen test split, predicting per-pixel depth in meters. + +| Model | size
(pixels) | delta1NYU | abs_relNYU | rmseNYU | Speed
CPU ONNX
(ms)
| Speed
T4 TensorRT10
(ms)
| params
(M) | FLOPs
(B) | +| ---------------------------------------------------------------------------------- | --------------------------- | -------------------- | --------------------- | ------------------ | ------------------------------------ | ----------------------------------------- | ------------------------ | ----------------------- | +| [YOLO26n-depth](https://platform.ultralytics.com/ultralytics/yolo26/yolo26n-depth) | 768 | 0.882 | 0.109 | 0.414 | 272.0 ± 27.2 | 2.7 ± 0.1 | 6.3 | 46.9 | +| [YOLO26s-depth](https://platform.ultralytics.com/ultralytics/yolo26/yolo26s-depth) | 768 | 0.896 | 0.104 | 0.399 | 393.7 ± 13.1 | 3.8 ± 0.0 | 13.2 | 68.0 | +| [YOLO26m-depth](https://platform.ultralytics.com/ultralytics/yolo26/yolo26m-depth) | 768 | 0.921 | 0.089 | 0.364 | 621.5 ± 49.7 | 6.0 ± 0.1 | 23.3 | 130.4 | +| [YOLO26l-depth](https://platform.ultralytics.com/ultralytics/yolo26/yolo26l-depth) | 768 | 0.930 | 0.083 | 0.351 | 821.9 ± 50.7 | 7.7 ± 0.1 | 27.7 | 157.0 | +| [YOLO26x-depth](https://platform.ultralytics.com/ultralytics/yolo26/yolo26x-depth) | 768 | 0.933 | 0.080 | 0.344 | 1240.9 ± 73.3 | 13.6 ± 0.2 | 57.0 | 301.7 | + +- **delta1NYU** is the percentage of pixels where the predicted depth is within a factor of 1.25 of the ground truth, on the NYU Depth V2 Eigen test split (654 images) with multi-scale + horizontal-flip TTA and log-least-squares alignment. +- Single-scale accuracy without TTA is reproducible with `yolo depth val model=yolo26n-depth.pt data=nyu-depth.yaml imgsz=768 device=0` (substitute `model=` for each size), which uses median (scale-only) alignment and scores lower: delta1 0.783 (n), 0.793 (s), 0.840 (m), 0.853 (l), 0.860 (x). +- **abs_rel** is the mean absolute relative error between predicted and ground-truth depth values. +- **rmse** is the root mean squared error in meters. +- **Speed** is inference-only latency (pre/post-processing excluded) at `imgsz=768`, `batch=1`, reported as mean ± std over timed runs after warmup. **CPU ONNX** is ONNX Runtime fp32 on a 32-core Intel Xeon (Skylake); **T4 TensorRT10** is TensorRT fp16 on a Tesla T4. +- **params** and **FLOPs** are measured at 768×768, the training resolution of the released weights. + +
+ +
Classification (ImageNet) + +Consult the [Classification Docs](https://docs.ultralytics.com/tasks/classify) for usage examples. These models are trained on [ImageNet](https://docs.ultralytics.com/datasets/classify/imagenet), covering 1000 classes. + +| Model | size
(pixels) | acc
top1 | acc
top5 | Speed
CPU ONNX
(ms)
| Speed
T4 TensorRT10
(ms)
| params
(M) | FLOPs
(B) at 224 | +| ------------------------------------------------------------------------------ | --------------------------- | ---------------------- | ---------------------- | ------------------------------------ | ----------------------------------------- | ------------------------ | ------------------------------ | +| [YOLO26n-cls](https://platform.ultralytics.com/ultralytics/yolo26/yolo26n-cls) | 224 | 71.4 | 90.1 | 5.0 ± 0.3 | 1.1 ± 0.0 | 2.8 | 0.4 | +| [YOLO26s-cls](https://platform.ultralytics.com/ultralytics/yolo26/yolo26s-cls) | 224 | 76.0 | 92.9 | 7.9 ± 0.2 | 1.3 ± 0.0 | 6.7 | 1.5 | +| [YOLO26m-cls](https://platform.ultralytics.com/ultralytics/yolo26/yolo26m-cls) | 224 | 78.1 | 94.2 | 17.2 ± 0.4 | 2.0 ± 0.0 | 11.6 | 4.8 | +| [YOLO26l-cls](https://platform.ultralytics.com/ultralytics/yolo26/yolo26l-cls) | 224 | 79.0 | 94.6 | 23.2 ± 0.3 | 2.8 ± 0.0 | 14.1 | 6.0 | +| [YOLO26x-cls](https://platform.ultralytics.com/ultralytics/yolo26/yolo26x-cls) | 224 | 79.9 | 95.0 | 41.4 ± 0.9 | 3.8 ± 0.0 | 29.6 | 13.5 | + +- **acc** values represent model accuracy on the [ImageNet](https://www.image-net.org/) dataset validation set.
Reproduce with `yolo val classify data=path/to/ImageNet device=0` +- **Speed** metrics are averaged over ImageNet val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/) instance. CPU speeds measured with [ONNX](https://onnx.ai/) export. GPU speeds measured with [TensorRT](https://developer.nvidia.com/tensorrt) export.
Reproduce with `yolo val classify data=path/to/ImageNet batch=1 device=0|cpu` + +
+ +
Pose (COCO) + +See the [Pose Estimation Docs](https://docs.ultralytics.com/tasks/pose) for usage examples. These models are trained on [COCO-Pose](https://docs.ultralytics.com/datasets/pose/coco), focusing on the 'person' class. + +| Model | size
(pixels) | mAPpose
50-95(e2e)
| mAPpose
50(e2e)
| Speed
CPU ONNX
(ms)
| Speed
T4 TensorRT10
(ms)
| params
(M) | FLOPs
(B) | +| -------------------------------------------------------------------------------- | --------------------------- | -------------------------------- | ----------------------------- | ------------------------------------ | ----------------------------------------- | ------------------------ | ----------------------- | +| [YOLO26n-pose](https://platform.ultralytics.com/ultralytics/yolo26/yolo26n-pose) | 640 | 57.2 | 83.3 | 40.3 ± 0.5 | 1.8 ± 0.0 | 2.9 | 7.6 | +| [YOLO26s-pose](https://platform.ultralytics.com/ultralytics/yolo26/yolo26s-pose) | 640 | 63.0 | 86.6 | 85.3 ± 0.9 | 2.7 ± 0.0 | 10.4 | 24.1 | +| [YOLO26m-pose](https://platform.ultralytics.com/ultralytics/yolo26/yolo26m-pose) | 640 | 68.8 | 89.6 | 218.0 ± 1.5 | 5.0 ± 0.1 | 21.5 | 73.3 | +| [YOLO26l-pose](https://platform.ultralytics.com/ultralytics/yolo26/yolo26l-pose) | 640 | 70.4 | 90.5 | 275.4 ± 2.4 | 6.5 ± 0.1 | 25.9 | 91.7 | +| [YOLO26x-pose](https://platform.ultralytics.com/ultralytics/yolo26/yolo26x-pose) | 640 | 71.6 | 91.6 | 565.4 ± 3.0 | 12.2 ± 0.2 | 57.6 | 202.3 | + +- **mAPval** values are for single-model single-scale on the [COCO Keypoints val2017](https://docs.ultralytics.com/datasets/pose/coco) dataset. See [YOLO Performance Metrics](https://docs.ultralytics.com/guides/yolo-performance-metrics) for details.
Reproduce with `yolo val pose data=coco-pose.yaml device=0` +- **Speed** metrics are averaged over COCO val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/) instance. CPU speeds measured with [ONNX](https://onnx.ai/) export. GPU speeds measured with [TensorRT](https://developer.nvidia.com/tensorrt) export.
Reproduce with `yolo val pose data=coco-pose.yaml batch=1 device=0|cpu` + +
+ +
Oriented Bounding Boxes (DOTAv1) + +Check the [OBB Docs](https://docs.ultralytics.com/tasks/obb) for usage examples. These models are trained on [DOTAv1](https://docs.ultralytics.com/datasets/obb/dota-v2#dota-v10), including 15 classes. + +| Model | size
(pixels) | mAPtest
50-95(e2e)
| mAPtest
50(e2e)
| Speed
CPU ONNX
(ms)
| Speed
T4 TensorRT10
(ms)
| params
(M) | FLOPs
(B) | +| ------------------------------------------------------------------------------ | --------------------------- | -------------------------------- | ----------------------------- | ------------------------------------ | ----------------------------------------- | ------------------------ | ----------------------- | +| [YOLO26n-obb](https://platform.ultralytics.com/ultralytics/yolo26/yolo26n-obb) | 1024 | 52.4 | 78.9 | 97.7 ± 0.9 | 2.8 ± 0.0 | 2.4 | 14.8 | +| [YOLO26s-obb](https://platform.ultralytics.com/ultralytics/yolo26/yolo26s-obb) | 1024 | 54.8 | 80.9 | 218.0 ± 1.4 | 4.9 ± 0.1 | 9.8 | 56.7 | +| [YOLO26m-obb](https://platform.ultralytics.com/ultralytics/yolo26/yolo26m-obb) | 1024 | 55.3 | 81.0 | 579.2 ± 3.8 | 10.2 ± 0.3 | 21.2 | 184.9 | +| [YOLO26l-obb](https://platform.ultralytics.com/ultralytics/yolo26/yolo26l-obb) | 1024 | 56.2 | 81.6 | 735.6 ± 3.1 | 13.0 ± 0.2 | 25.6 | 232.4 | +| [YOLO26x-obb](https://platform.ultralytics.com/ultralytics/yolo26/yolo26x-obb) | 1024 | 56.7 | 81.7 | 1485.7 ± 11.5 | 30.5 ± 0.9 | 57.6 | 520.1 | + +- **mAPtest** values are for single-model multiscale performance on the [DOTAv1 test set](https://captain-whu.github.io/DOTA/dataset.html).
Reproduce by `yolo val obb data=DOTAv1.yaml device=0 split=test` and submit merged results to the [DOTA evaluation server](https://captain-whu.github.io/DOTA/evaluation.html). +- **Speed** metrics are averaged over [DOTAv1 val images](https://docs.ultralytics.com/datasets/obb/dota-v2#dota-v10) using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/) instance. CPU speeds measured with [ONNX](https://onnx.ai/) export. GPU speeds measured with [TensorRT](https://developer.nvidia.com/tensorrt) export.
Reproduce by `yolo val obb data=DOTAv1.yaml batch=1 device=0|cpu` + +
+ +## 🧩 Integrations + +Our key integrations with leading AI platforms extend the functionality of Ultralytics' offerings, enhancing tasks like dataset labeling, training, visualization, and model management. Discover how Ultralytics, in collaboration with partners like [Weights & Biases](https://docs.ultralytics.com/integrations/weights-biases), [Comet ML](https://docs.ultralytics.com/integrations/comet), [Roboflow](https://docs.ultralytics.com/integrations/roboflow), and [Intel OpenVINO](https://docs.ultralytics.com/integrations/openvino), can optimize your AI workflow. Explore more at [Ultralytics Integrations](https://docs.ultralytics.com/integrations). + + + Ultralytics active learning integrations + + +## 🤝 Contribute + +We thrive on community collaboration! Ultralytics YOLO wouldn't be the SOTA framework it is without contributions from developers like you. Please see our [Contributing Guide](https://docs.ultralytics.com/help/contributing) to get started. We also welcome your feedback—share your experience by completing our [Survey](https://www.ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey). A huge **Thank You** 🙏 to everyone who contributes! + + + +[![Ultralytics open-source contributors](https://raw.githubusercontent.com/ultralytics/assets/main/im/image-contributors.png)](https://github.com/ultralytics/ultralytics/graphs/contributors) + +We look forward to your contributions to help make the Ultralytics ecosystem even better! + +## 📜 License + +Ultralytics offers two licensing options to suit different needs: + +- **AGPL-3.0 License**: This [OSI-approved](https://opensource.org/license/agpl-3.0) open-source license is perfect for students, researchers, and enthusiasts. It encourages open collaboration and knowledge sharing. See the [LICENSE](https://github.com/ultralytics/ultralytics/blob/main/LICENSE) file for full details. +- **Ultralytics Enterprise License**: For development and production use, this license enables seamless integration of Ultralytics software and AI models into business products and services, including internal tools, automated workflows, and production deployments, bypassing the open-source requirements of AGPL-3.0. To get started, please contact us via [Ultralytics Licensing](https://www.ultralytics.com/license). + +## 📞 Contact + +For bug reports and feature requests related to Ultralytics software, please visit [GitHub Issues](https://github.com/ultralytics/ultralytics/issues). For questions, discussions, and community support, join our active communities on [Discord](https://discord.com/invite/ultralytics), [Reddit](https://www.reddit.com/r/ultralytics/), and the [Ultralytics Community Forums](https://community.ultralytics.com). We're here to help with all things Ultralytics! + +
+
+ Ultralytics GitHub + space + Ultralytics LinkedIn + space + Ultralytics Twitter + space + Ultralytics YouTube + space + Ultralytics TikTok + space + Ultralytics BiliBili + space + Ultralytics Discord +
diff --git a/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/RECORD b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..ff37c51d305c8904f89dc19927306bd16222bf34 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/RECORD @@ -0,0 +1,624 @@ +../../../bin/ultralytics,sha256=WX-brWL1SUqsbGTwxl5HeW8wn6bhgcWatGMHYarFgyI,258 +../../../bin/yolo,sha256=WX-brWL1SUqsbGTwxl5HeW8wn6bhgcWatGMHYarFgyI,258 +tests/__init__.py,sha256=hgrbjI3dsjk9Ro9oJ5HT0kk4qmTsxGJOijDWKSlBJYk,1512 +tests/__pycache__/__init__.cpython-312.pyc,, +tests/__pycache__/cache_test_assets.cpython-312.pyc,, +tests/__pycache__/conftest.cpython-312.pyc,, +tests/__pycache__/test_cli.cpython-312.pyc,, +tests/__pycache__/test_cuda.cpython-312.pyc,, +tests/__pycache__/test_engine.cpython-312.pyc,, +tests/__pycache__/test_exports.cpython-312.pyc,, +tests/__pycache__/test_integrations.cpython-312.pyc,, +tests/__pycache__/test_ndjson_converter.cpython-312.pyc,, +tests/__pycache__/test_python.cpython-312.pyc,, +tests/__pycache__/test_solutions.cpython-312.pyc,, +tests/cache_test_assets.py,sha256=bKqHTLaOkjwbcmhSw1HXMHi7RzFD9mlYAekthPCDxuY,3912 +tests/conftest.py,sha256=syh3U6IsZ9Ii-ZGBBo1iZUcS5RErfaeNiIGzLmKmLd4,5234 +tests/test_cli.py,sha256=lfuL6l4I-zdH9xU5IkcNwIzhTAlPzuxOKImsUg6Y0A0,8285 +tests/test_cuda.py,sha256=ifFIak6IZno6RxJWsWFGF80qS8_K81gKaiR3WFGsEW8,11601 +tests/test_engine.py,sha256=s00D00A5qAepAHfmPyxBeu-oid0KMsGtIALlKIYQGnI,16576 +tests/test_exports.py,sha256=bXmorX2PO-qDdkchMssStwCJrCGZQ_yN02CiGNe_Gss,31053 +tests/test_integrations.py,sha256=H3ND6namUB8Ajwvb_ul12aRFeemslwwa1f7aMmZdAlg,6481 +tests/test_ndjson_converter.py,sha256=-C8w8isPGR4DZ32GrndT9SGDLACm5BX82sqxCsJ15T4,7744 +tests/test_python.py,sha256=PbwyFSdbZLizSEuLbrlsh1B12bpEAr-7z6PPk52K7jw,106586 +tests/test_solutions.py,sha256=Uo7M8oYOdQbBsrxa8qbhFI72bd3c0reF1XMqFS9MByk,19909 +ultralytics-8.4.160.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +ultralytics-8.4.160.dist-info/METADATA,sha256=m9n71dx1x1AkF1QlPPnk0LNWkSp5ehoUvzWhfHa0rj0,46654 +ultralytics-8.4.160.dist-info/RECORD,, +ultralytics-8.4.160.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +ultralytics-8.4.160.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91 +ultralytics-8.4.160.dist-info/entry_points.txt,sha256=YM_wiKyTe9yRrsEfqvYolNO5ngwfoL4-NwgKzc8_7sI,93 +ultralytics-8.4.160.dist-info/licenses/LICENSE,sha256=DZak_2itbUtvHzD3E7GNUYSRK6jdOJ-GqncQ2weavLA,34523 +ultralytics-8.4.160.dist-info/top_level.txt,sha256=XP49TwiMw4QGsvTLSYiJhz1xF_k7ev5mQ8jJXaXi45Q,12 +ultralytics/__init__.py,sha256=MjcMNFArR4cPYhZDVWNGwcX1GWcq8XGnXntVtGX5BVQ,1855 +ultralytics/__pycache__/__init__.cpython-312.pyc,, +ultralytics/assets/bus.jpg,sha256=wCAZxJecGR63Od3ZRERe9Aja1Weayrb9Ug751DS_vGM,137419 +ultralytics/assets/zidane.jpg,sha256=Ftc4aeMmen1O0A3o6GCDO9FlfBslLpTAw0gnetx7bts,50427 +ultralytics/cfg/__init__.py,sha256=XyCIdsFstVdB82anIc1zyH_4tTnzDz0PBsttzOSEoBU,48520 +ultralytics/cfg/__pycache__/__init__.cpython-312.pyc,, +ultralytics/cfg/datasets/Argoverse.yaml,sha256=VLuhz_gPQZTAaBFHEzSC9PxMOY3z8TUyUBZVBAm_HFE,3353 +ultralytics/cfg/datasets/DOTAv1.5.yaml,sha256=X-u1bHSwFqf5-vgPIWiJfYev3KK9LHhXZz1ShQNkcc0,1212 +ultralytics/cfg/datasets/DOTAv1.yaml,sha256=GOPKL5JUbdFU_B7jWtOPdz27OnX_DJMCm7WIWrZABr8,1182 +ultralytics/cfg/datasets/GlobalWheat2020.yaml,sha256=_GjE5sxGcpLov7r-M06XsjWlolMiy3xLxs4ksw2lZRc,2143 +ultralytics/cfg/datasets/HomeObjects-3K.yaml,sha256=uQ-wWTT9W-Hr7hiuqa4rMS5ATnkQeMuGReaJsqxeP7U,933 +ultralytics/cfg/datasets/ImageNet.yaml,sha256=06smoReuJ9Q0XmzKlK0Y48z----SeaqgC6zdORy3b28,42528 +ultralytics/cfg/datasets/Objects365.yaml,sha256=fKgiwvntM-RpbfJmAgPmfL3k1lyXl0JZZb6e_RE8v14,9648 +ultralytics/cfg/datasets/SKU-110K.yaml,sha256=cVXoMAOHbik-MAOKqtke6TU2QCaEyn9cBlytqQeKh20,2608 +ultralytics/cfg/datasets/TT100K.yaml,sha256=CMb94ZxiADjg1oKZThY2DrSt7VsqxrxIK3zlCotfQHw,6895 +ultralytics/cfg/datasets/VOC.yaml,sha256=bi2uRXcjuXWyCmCVKFL6bLw9KsRpUgKCoO8Inv-qVE0,3816 +ultralytics/cfg/datasets/VisDrone.yaml,sha256=Yn9g92Ats4tqRiMBzth60kvN7ippLqqdTgJEhJK7Kf4,3395 +ultralytics/cfg/datasets/ade20k.yaml,sha256=8--C9ZPN5bjH-R79n3BKeozkw5tTX2anakx5F5jC35I,4323 +ultralytics/cfg/datasets/african-wildlife.yaml,sha256=GH81S5fG5dAibTw_p1c0ivaLnnvXlGF3kzWtbyU3ejo,914 +ultralytics/cfg/datasets/brain-tumor.yaml,sha256=y5Skd-Yy9wmAfF3E40LYvHQkYsgbDlWU5aKg0EhOwJY,799 +ultralytics/cfg/datasets/carparts-seg.yaml,sha256=4bY17UzYD3f5rYRuPnQsUJQoTFl6XX3jt3wX8zYVihQ,1252 +ultralytics/cfg/datasets/cityscapes.yaml,sha256=hvqK65DEjCM0Xjl9xTqlQxUkYyBQjfRQ2zn561GCnEA,2998 +ultralytics/cfg/datasets/cityscapes8.yaml,sha256=MM7KLZW1Jh2duhIaNM5v6PkUtlFgIypzXDrdnhL5kII,1623 +ultralytics/cfg/datasets/coco-pose.yaml,sha256=BqOkq4lg9FVakySnvAveHdrIBgPR0qIBXTkza3PZMl8,1934 +ultralytics/cfg/datasets/coco.yaml,sha256=OO0esSL61u7Y4Y3PjaVqSybbnCBkvkFTBIXiZE-un38,2583 +ultralytics/cfg/datasets/coco12-formats.yaml,sha256=ZzXepkW2h3u9xJpYYZCPNS9E7htGLKfzxGLTq-aioQo,1952 +ultralytics/cfg/datasets/coco128-seg.yaml,sha256=lr8lrEnrsIM4bqG1YI9hYBrAfygf5CMu9opG8FXJf5Y,1992 +ultralytics/cfg/datasets/coco128.yaml,sha256=B6CDxu3TCY1Mm3x-iRXEbM2N1IyOuXC_sU2ViVg5KEQ,1967 +ultralytics/cfg/datasets/coco8-grayscale.yaml,sha256=ZbTr4lQpqVWCHw9d4Pghi9e3fJagrMLqXqX0wtU06G8,1960 +ultralytics/cfg/datasets/coco8-multispectral.yaml,sha256=mDcNFGmSKT-bBk88EDDnIvuy18utSjAXlso1S581Aok,2062 +ultralytics/cfg/datasets/coco8-pose.yaml,sha256=oaFyz668gJUfiL83UleJSch6UNV-biiL2rLTM6RrZPs,1335 +ultralytics/cfg/datasets/coco8-seg.yaml,sha256=iXAMV5GP2xIO2PHl1JDHXvyIob2neo8RlKHkOVDac7Q,1912 +ultralytics/cfg/datasets/coco8.yaml,sha256=Awqv-gj4oWHcNYfSFqqVbAyJR-WUstnYUVo2uaxE-fo,1887 +ultralytics/cfg/datasets/construction-ppe.yaml,sha256=iSa27Cwowv1vycVK_o3hK8UXwHE8EdNTI6NvDVBynck,1007 +ultralytics/cfg/datasets/crack-seg.yaml,sha256=H11kG8GPQhpvl6C5IEzWoySsQy5p0gYC30BrePVeU-Y,836 +ultralytics/cfg/datasets/depth-arkitscenes.yaml,sha256=Ym_kMKmOhVGDaqbzQqsHyokZFRTlwSzWgOkL95MozyM,934 +ultralytics/cfg/datasets/depth-diode.yaml,sha256=IH7X9SfSSK0-yskqzIAjJktTIok9MnEF-1hDOsTeQ9M,2604 +ultralytics/cfg/datasets/depth-hypersim.yaml,sha256=PoUHvMpL-JPOWoQEGExxQZ5dxiTJlDeRdNT5Ybu7I94,919 +ultralytics/cfg/datasets/depth-kitti.yaml,sha256=8BqOxTR85QdMojOQ7I8Alp6M8RSQ3xZNcMy8MjuEPco,6839 +ultralytics/cfg/datasets/depth-sunrgbd.yaml,sha256=AmeZ6TnXXwg-d97I7YfsspFsnpFPCSAu6HWx0O3IpKs,2618 +ultralytics/cfg/datasets/depth-tartanair.yaml,sha256=zFzkeEPCVru96l9LW1WK69HVmfDK78-IVjolxnpBy90,1078 +ultralytics/cfg/datasets/depth-vkitti2.yaml,sha256=QzynjZVemhBA8_msM-ev6BzxjXx998snPwszPoZ08aY,2655 +ultralytics/cfg/datasets/depth8.yaml,sha256=th5DihHacbV6fswmVQugsTZkHRCX_6AkffN1SAsjCqY,1407 +ultralytics/cfg/datasets/dog-pose.yaml,sha256=OboPj_y8QlEGH9ECqLNuT32RY_YapEo3IUn8Walvym0,1407 +ultralytics/cfg/datasets/dota128.yaml,sha256=Kzktc64z93wTZdg3hvHrZyszlhNTZ4oPVsbXkkmtVGg,1079 +ultralytics/cfg/datasets/dota8-multispectral.yaml,sha256=sZzrP1SUMryEJe8syMb6BsAghIbyfMQuqHI0BxiMRS4,1216 +ultralytics/cfg/datasets/dota8.yaml,sha256=W_3Bcp8dRHeOL0VFWsaaNEXq8Kj2PzgYwVEQqeOtNqQ,1058 +ultralytics/cfg/datasets/hand-keypoints.yaml,sha256=wPLYeZmGQ8lWI89oLwRVMDGnBka6H7yPZCtxeg8P878,1362 +ultralytics/cfg/datasets/kitti.yaml,sha256=PRyDF6bkfG3X4aYv6PTUTSGHiCUsVAA2i9i8KO9OElI,894 +ultralytics/cfg/datasets/lvis.yaml,sha256=t1M8pAfMBEDe9qx9D8f9aLhY2n_d-qKapDF5Sf7jSI8,29577 +ultralytics/cfg/datasets/medical-pills.yaml,sha256=5GLYrB0rwkOrDSe1KswZAuly1LWdNyW1GsASRGHaKEM,791 +ultralytics/cfg/datasets/nyu-depth.yaml,sha256=EVIgKsVOItj4247xKGDb622Ees1JAUGorb3Ip25u_SU,1145 +ultralytics/cfg/datasets/open-images-v7.yaml,sha256=SXRor53GRNFJEB78CQcn08b9ZEWR9MwujFresA9K2Eg,12115 +ultralytics/cfg/datasets/package-seg.yaml,sha256=1Fc7f65s8G3ts6ZTOpzwVDC5_1wMUlRiFsYzrZpXyNo,848 +ultralytics/cfg/datasets/signature.yaml,sha256=134eo-EpaK9XxISzTZnUP2bNtn3Hb-5j_-nO4Pt-JJM,773 +ultralytics/cfg/datasets/tiger-pose.yaml,sha256=DQk5S7uH5JbP3pD6Q7I12AAagNRA3AKiZTeubsjhYR4,1195 +ultralytics/cfg/datasets/xView.yaml,sha256=m2pWXw_SheDPwkPdNEVLIlx9uLhTEOTgOxePe7MG2Jo,5405 +ultralytics/cfg/default.yaml,sha256=BpT6a-NlaIi4k6Z6rcSxckCg0ZDPeZsQw0fpYVC3Kbc,10347 +ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml,sha256=1Ycp9qMrwpb8rq7cqht3Q-1gMN0R87U35nm2j_isdro,524 +ultralytics/cfg/models/11/yolo11-cls.yaml,sha256=17l5GdN-Vst4LvafsK2-q6Li9VX9UlUcT5ClCtikweE,1412 +ultralytics/cfg/models/11/yolo11-obb.yaml,sha256=FHo7xWrhKdN2BBn2xdZ099T2NcqcUJiuyQ0a6zdvrqY,2031 +ultralytics/cfg/models/11/yolo11-pose.yaml,sha256=dWOT9VBRxD8h-jmQC0qWEOvFvyx1CUa0tekt1kOdvmk,2131 +ultralytics/cfg/models/11/yolo11-seg.yaml,sha256=xyTWVhFoSszF1LhNEIznIW8QGKU1z0EAIvkp4OwYtls,2046 +ultralytics/cfg/models/11/yolo11.yaml,sha256=Q9inyGrMdygt30lm1lJuCR5bBkwUDtSm5MC2jsvDeEw,2012 +ultralytics/cfg/models/11/yoloe-11-seg.yaml,sha256=j053cYgHMCRFUxJ7MumNkHz7eq6hxvcMMuNOzNsdV1w,2072 +ultralytics/cfg/models/11/yoloe-11.yaml,sha256=qxKDa8Xt-embNVOLOthfQlt1N0kFFHnGFO74R_CQzUw,2038 +ultralytics/cfg/models/12/yolo12-cls.yaml,sha256=yJBuDOXRYLa-LQipGkLBT97ujKSyXx755zts612JVWc,1407 +ultralytics/cfg/models/12/yolo12-obb.yaml,sha256=2cPJKV7kU1thYxnnNsCJPfWNoTk0l29ZD22U4XTX3wQ,1972 +ultralytics/cfg/models/12/yolo12-pose.yaml,sha256=eBo-9b3o_qv3-jftgCaX0FedeJWOfKHDLJPPfCMwu7M,2072 +ultralytics/cfg/models/12/yolo12-seg.yaml,sha256=0JTqSjyhOTLNTIrIFAOuu6F7yQqMkq1soscAkSZtsz8,1985 +ultralytics/cfg/models/12/yolo12.yaml,sha256=ZeA8LuymJXPNjZ5xkxkZHkcktDaKDzUBb2Kc3gCLC1w,1953 +ultralytics/cfg/models/26/yolo26-cls.yaml,sha256=GmaLvnB62X6r9_mZwpx0b2LTRYIXzVYqSqR3Mcy336g,1432 +ultralytics/cfg/models/26/yolo26-depth.yaml,sha256=QaShA165oh8HEGrSPV1EyhEMp2kHFPfw3lzCDHXRq7s,1664 +ultralytics/cfg/models/26/yolo26-obb.yaml,sha256=A9Ng5nZOow74tYkejxoVyGB2wztIi_cuNqxYrqB5T38,2146 +ultralytics/cfg/models/26/yolo26-p2.yaml,sha256=Dbwvo9_t5e3NolZquMfqFQrQZuop155o1sTaK6tHYnk,2405 +ultralytics/cfg/models/26/yolo26-p6.yaml,sha256=eMRZmGxEgjY7X6PAwRV1vVJcEzjAaB3u8nfG2_GTkl0,2467 +ultralytics/cfg/models/26/yolo26-pose.yaml,sha256=B7qC2WNwI_Jh5SbDj6muuKsF2RF2b_2M9PSM0z8nGI0,2245 +ultralytics/cfg/models/26/yolo26-seg.yaml,sha256=U8A0ijaj4Zu8O9T2lfUMu_yXowWfYumyUfJ4rXT918s,2156 +ultralytics/cfg/models/26/yolo26-sem.yaml,sha256=rX3g2vBk7U9T7ejtCjLWqjOaXaPNMEeR2BWq2oe5nYI,1850 +ultralytics/cfg/models/26/yolo26.yaml,sha256=sdH6DGns7WT5k5U2A4vY1pfDLnIgCzQYenZ95DGvfvA,2120 +ultralytics/cfg/models/26/yoloe-26-seg.yaml,sha256=QlyK3awjLOjs9q0raj0we5QCG1tDy-NvQ2uQzKDoBYk,2223 +ultralytics/cfg/models/26/yoloe-26.yaml,sha256=YWsBS4D3f7QhqLQzYT-LVdCOISo0VaTILIaLKmujDdo,2191 +ultralytics/cfg/models/rt-detr/rtdetr-l.yaml,sha256=hXFvYmdpy13fANWfz2yvtYFKrRljKBAL3HyTMG9lDoM,2043 +ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml,sha256=5vCPfihyzXMKCR7kYYIDSHbSHvAzYlWbOZ5Wp9m84Ms,1696 +ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml,sha256=Xm-U_m-_okdspiW7qxb5mgN_NPZPvyjXrS1A1KcoaFo,1692 +ultralytics/cfg/models/rt-detr/rtdetr-x.yaml,sha256=QHa3B5Pwd9TA9B3W5lEwrUl-_bAvwGXVqSlvnLSbKNs,2250 +ultralytics/cfg/models/v10/yolov10b.yaml,sha256=W9K-lqgUEKOCpV0Ae7dk8iBUFpSTTFzDPDL3AHnMKfs,1488 +ultralytics/cfg/models/v10/yolov10l.yaml,sha256=YtdL74ivxWxY2jUsYkkUX_WraWsLJtcOKhRNioCwvJg,1488 +ultralytics/cfg/models/v10/yolov10m.yaml,sha256=YQuxn4KjiGqxwK-3BuRSprt86aWxcxn2VngIlHQKxy4,1479 +ultralytics/cfg/models/v10/yolov10n.yaml,sha256=iL9T4XUrTnf001i6e9qF9wEBCUoral_fF5bjIFxJdMU,1474 +ultralytics/cfg/models/v10/yolov10s.yaml,sha256=dG_z0fSweIzCi7Km9OY-Q9IztEOjX67wFsdP4Eam_to,1483 +ultralytics/cfg/models/v10/yolov10x.yaml,sha256=IFIYR5p46OECsHK3yz5UO5CMxR1JNDWeXKzUQQvxM_M,1491 +ultralytics/cfg/models/v3/yolov3-spp.yaml,sha256=hsM-yhdWv-8XlWuaSOVqFJcHUVZ-FmjH4QjkA9CHJZU,1625 +ultralytics/cfg/models/v3/yolov3-tiny.yaml,sha256=SYrSg0m1A6ErUapdrJDI5E-edLaH0oF-NRb558DZgmQ,1330 +ultralytics/cfg/models/v3/yolov3.yaml,sha256=Fvt4_PTwLBpRw3R4v4VQ-1PIiojpoFZD1uuTZySUYSw,1612 +ultralytics/cfg/models/v5/yolov5-p6.yaml,sha256=VKEWykksykSlzvuy7if4yFo9WlblC3hdqcNxJ9bwHek,1994 +ultralytics/cfg/models/v5/yolov5.yaml,sha256=QD8dRe5e5ys52wXPKvNJn622H_3iX0jPzE_2--2dZx0,1626 +ultralytics/cfg/models/v6/yolov6.yaml,sha256=tl04iHe4dVg_78jgupVul5gbqOn5hBhtLKfP3xYxcWA,1813 +ultralytics/cfg/models/v8/yoloe-v8-seg.yaml,sha256=5cjZ2xCMUF2pV7gv1ZoRFEV6Lo6v4slMQt1lU7_Jqtc,2064 +ultralytics/cfg/models/v8/yoloe-v8.yaml,sha256=dujtgHql2RzqqEEpB4UzsEpAXMRarkltnt8vb1usILc,2015 +ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml,sha256=TAiAkZwUckzjWdY6yn_ulGzM-lnHaY7Yx9v8rI-2WoA,1014 +ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml,sha256=gbIttNMvj02Rk3eKjq45qgjdmdCo5n_mV9R5xt65OdU,1010 +ultralytics/cfg/models/v8/yolov8-cls.yaml,sha256=G50mnw-C0SWrZpZl5wzov1dugdjZMM6zT30t5cQrcJQ,1019 +ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml,sha256=5MX8D3_8lkj9aKVwpAIC1PZAaMoTFs_Wq-XZUTVn9PU,2505 +ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml,sha256=c7YYnEPx2vrwHjbgr4o_Q9f_NI2X1dx2MrLo9xeOvXc,2575 +ultralytics/cfg/models/v8/yolov8-ghost.yaml,sha256=nxzIlvntFajHbu4DN8ujEx65PREgn7o0Dd6cHp8pHSM,2198 +ultralytics/cfg/models/v8/yolov8-obb.yaml,sha256=Owlncx5peKBTNo3xhkbVxz_1qlzVJR4Z2zNeoR_NDxg,2016 +ultralytics/cfg/models/v8/yolov8-p2.yaml,sha256=ulQ2Pp8oPo9gsPoIQ-s3EVCTM41vknPM1PdPYGOXVPQ,1831 +ultralytics/cfg/models/v8/yolov8-p6.yaml,sha256=TqIsa8gNEW04KmdLxxC9rqhd7PCHlUqkzoiDxnMTio0,2363 +ultralytics/cfg/models/v8/yolov8-pose-p6.yaml,sha256=tfgfYrbVu5biWCWmdTZRr7ZRC-zlAzycsRyaJbDtI1g,2047 +ultralytics/cfg/models/v8/yolov8-pose.yaml,sha256=LdzbiIVknZQMLYB2wzCHqul3NilfKp4nx5SdaGQsF6s,1676 +ultralytics/cfg/models/v8/yolov8-rtdetr.yaml,sha256=5cupHKPHD43cuvd3H3zvNijiqpW9-bFLKg-KMeRzOPE,2055 +ultralytics/cfg/models/v8/yolov8-seg-p6.yaml,sha256=7FlNlY-sB8bCcVty2Hf_nYD8fxZpsqaTgGxTfac8DRI,1958 +ultralytics/cfg/models/v8/yolov8-seg.yaml,sha256=hFeiOFVwTV4zv08IrmTIuzJcUZmYkY7SIi2oV322e6U,1587 +ultralytics/cfg/models/v8/yolov8-world.yaml,sha256=2hNQoybITO5FBNnKKz05Pk9ygeAf4qW7XvkMEfBd90A,2174 +ultralytics/cfg/models/v8/yolov8-worldv2.yaml,sha256=UkdRhk7pauLIZto7QdOrWpW8Mb-3J61RdRuxS5lZC24,2124 +ultralytics/cfg/models/v8/yolov8.yaml,sha256=QFo8MC62CWEDqZr02CwdLYsrv_RpoijFWqyUSywZZyo,1977 +ultralytics/cfg/models/v9/yolov9c-seg.yaml,sha256=UBHoQ_cJV2yp6rMzHXRp46uBAUmKIrbgd3jiEBPRvqI,1447 +ultralytics/cfg/models/v9/yolov9c.yaml,sha256=x1kus_2mQdU9V3ZGg0XdE5WTUU3j8fwGe1Ou3x2aX5I,1426 +ultralytics/cfg/models/v9/yolov9e-seg.yaml,sha256=WVpU5jHgoUuCMVirvmn_ScOmH9d1MyVVIX8XAY8787c,2377 +ultralytics/cfg/models/v9/yolov9e.yaml,sha256=Olr2PlADpkD6N1TiVyAJEMzkrA7SbNul1nOaUF8CS38,2355 +ultralytics/cfg/models/v9/yolov9m.yaml,sha256=WcKQ3xRsC1JMgA42Hx4xzr4FZmtE6B3wKvqhlQxkqw8,1411 +ultralytics/cfg/models/v9/yolov9s.yaml,sha256=cWkQtYNWWOckOBXjd8XrJ_q5v6T_C54xGMP1S3qnpZU,1392 +ultralytics/cfg/models/v9/yolov9t.yaml,sha256=Q8GpSXE7fumhuJiQg4a2SkuS_UmnXqp-eoZxW_C0vEo,1375 +ultralytics/cfg/trackers/botsort.yaml,sha256=jNiJMNO-VVe-B3fzhO7P8KNqcBGFD-YT_ApoF4v9WwE,1385 +ultralytics/cfg/trackers/bytetrack.yaml,sha256=OVcB2UenSRed7j4yexGBtzDEypjnysWiqwUoCq5XO4s,856 +ultralytics/cfg/trackers/deepocsort.yaml,sha256=9y-amFdoivTfHcdD-xWruov_iieqjSwsaGq6beMZC9k,1844 +ultralytics/cfg/trackers/fasttrack.yaml,sha256=YAeLULJ9sh54zQ3BCTY5yO53tPhqzNvFZlfTrClEPtc,1584 +ultralytics/cfg/trackers/ocsort.yaml,sha256=VduR8U2z8BRm2Banrw-fqu63T0SF2mMBnH7WmpqvtuM,1267 +ultralytics/cfg/trackers/tracktrack.yaml,sha256=M_zQz0ICP6vBz_k-h2n5SeP5Kjkhmot94Vf8YSod43o,1889 +ultralytics/data/__init__.py,sha256=KsV__8wWRNzjd-iUeIX57Pvtmet28MSxjHqG1ux-YoM,702 +ultralytics/data/__pycache__/__init__.cpython-312.pyc,, +ultralytics/data/__pycache__/annotator.cpython-312.pyc,, +ultralytics/data/__pycache__/augment.cpython-312.pyc,, +ultralytics/data/__pycache__/base.cpython-312.pyc,, +ultralytics/data/__pycache__/build.cpython-312.pyc,, +ultralytics/data/__pycache__/converter.cpython-312.pyc,, +ultralytics/data/__pycache__/dataset.cpython-312.pyc,, +ultralytics/data/__pycache__/loaders.cpython-312.pyc,, +ultralytics/data/__pycache__/split.cpython-312.pyc,, +ultralytics/data/__pycache__/split_dota.cpython-312.pyc,, +ultralytics/data/__pycache__/utils.cpython-312.pyc,, +ultralytics/data/annotator.py,sha256=Xiqm46EBgLjcdJRCHfHsXNNSJGIZINL0-CS-4WeJ8_I,3065 +ultralytics/data/augment.py,sha256=NjGvKZWOF7xELLqkmmvTK2YGFbG7EXGk6OhpK6zh9Cg,144677 +ultralytics/data/base.py,sha256=uX5kc8VRO3E0sYGK_f6I2WFsI6WdS4GJgbn0ZghM1J0,23278 +ultralytics/data/build.py,sha256=w0kDofMHbezIXAD6tCR9SejgiRGYgLWu1zqz_-qGijM,19612 +ultralytics/data/converter.py,sha256=DlW-UJGWHdDuaUC7lNCRCtbj0MXq9Sz2wyLzsSVUL_I,47827 +ultralytics/data/dataset.py,sha256=Kq9g3bzVQOLjRN7mhtZtf7ZlioSgS7PJPJIcJJays9E,59488 +ultralytics/data/loaders.py,sha256=6Run_1xFA1x46C46_7H7kjOyZ6FXM4YA8GBZ4X0Ir1s,34629 +ultralytics/data/scripts/download_weights.sh,sha256=0y8XtZxOru7dVThXDFUXLHBuICgOIqZNUwpyL4Rh6lg,595 +ultralytics/data/scripts/get_coco.sh,sha256=UuJpJeo3qQpTHVINeOpmP0NYmg8PhEFE3A8J3jKrnPw,1768 +ultralytics/data/scripts/get_coco128.sh,sha256=qmRQl_hOKrsdHrTrnyQuFIH01oDz3lfaz138OgGfLt8,650 +ultralytics/data/scripts/get_imagenet.sh,sha256=hr42H16bM47iT27rgS7MpEo-GeOZAYUQXgr0B2cwn48,1705 +ultralytics/data/split.py,sha256=M_fSp011rMWmMqFKpoGsgx3uLWJdPzTDiyXrwwZaOVk,5269 +ultralytics/data/split_dota.py,sha256=oEVbGYYdzKupeI-upeZu8JNwEtSIo0zkaI9dBpbtqeM,12878 +ultralytics/data/utils.py,sha256=hfJNV5vbEy6a9nnrbzRjXs04eoDwmEsGXBy4ia3NZdQ,39335 +ultralytics/engine/__init__.py,sha256=lm6MckFYCPTbqIoX7w0s_daxdjNeBeKW6DXppv1-QUM,70 +ultralytics/engine/__pycache__/__init__.cpython-312.pyc,, +ultralytics/engine/__pycache__/exporter.cpython-312.pyc,, +ultralytics/engine/__pycache__/model.cpython-312.pyc,, +ultralytics/engine/__pycache__/predictor.cpython-312.pyc,, +ultralytics/engine/__pycache__/results.cpython-312.pyc,, +ultralytics/engine/__pycache__/trainer.cpython-312.pyc,, +ultralytics/engine/__pycache__/tuner.cpython-312.pyc,, +ultralytics/engine/__pycache__/validator.cpython-312.pyc,, +ultralytics/engine/exporter.py,sha256=DXjD9Pe6RDy50XxLhLiz7xmk4f-a0V-gBzoYg2CYPYI,95619 +ultralytics/engine/model.py,sha256=blwAAdWJHkIAK9ix1_VQhcaaHo3X_9zF3Vi2PC-GPYg,61738 +ultralytics/engine/predictor.py,sha256=zLfaYMY0_guALjjbJWUiW6fom6WiqJuS-o-TTpA_Se4,26443 +ultralytics/engine/results.py,sha256=I0pSf8QrsqweZ0_GHDkRq7A47UCo87Ji3oMUlEiCzFo,74760 +ultralytics/engine/trainer.py,sha256=7VWT9aIrje--KqhH_h4kkMXMdO0WBMWm99F4T29w-kg,70196 +ultralytics/engine/tuner.py,sha256=Fpp8bMK0YYh0PVxRfQ25yviJL73gO5BImrxqvjxs7l4,29414 +ultralytics/engine/validator.py,sha256=UFq4Io55U6FDtdYbvXdO-jMCwjETQt6mDz5F0OX9350,19931 +ultralytics/models/__init__.py,sha256=TVCojzWJkI4N9TQHfSFFR6syzZTZrJ1IvmzsUhbpXwI,670 +ultralytics/models/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/__pycache__/llm.cpython-312.pyc,, +ultralytics/models/fastsam/__init__.py,sha256=Ku89Fy_X8ok3YPEUajjUZ5i4O08jdJMjJHt-3Z99Frk,231 +ultralytics/models/fastsam/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/fastsam/__pycache__/model.cpython-312.pyc,, +ultralytics/models/fastsam/__pycache__/predict.cpython-312.pyc,, +ultralytics/models/fastsam/__pycache__/utils.cpython-312.pyc,, +ultralytics/models/fastsam/__pycache__/val.cpython-312.pyc,, +ultralytics/models/fastsam/model.py,sha256=AySAHLqcK3Z4NBmVBxaJHJPTturAeyYsgvp5iWESPrA,3434 +ultralytics/models/fastsam/predict.py,sha256=ESwsdrswG3OA6FddxWrJwP8ZIfdreaAg4_v6rCjsdpA,9322 +ultralytics/models/fastsam/utils.py,sha256=de9ieh4pBUuTNh5HTiNdRpWZhXAaSfNo3R1FNMt2GOE,879 +ultralytics/models/fastsam/val.py,sha256=MJUKx_NpFEeuqSq9ynX1FJSK6F5RhUJB-PqhQp2Q0YM,2091 +ultralytics/models/llm.py,sha256=fVhr0preQ0lO-woi3dIlxCd_UUSLICxfnhtWwyoAOVU,7685 +ultralytics/models/nas/__init__.py,sha256=Q4ZQak8xNWtV5YSw_pFu0anbCyDxxEAuMMDfMzu6-0s,207 +ultralytics/models/nas/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/nas/__pycache__/model.cpython-312.pyc,, +ultralytics/models/nas/__pycache__/predict.cpython-312.pyc,, +ultralytics/models/nas/__pycache__/val.cpython-312.pyc,, +ultralytics/models/nas/model.py,sha256=-JF98xlK2tp92uwXhReE9s1eikRNacvcdiRJ6wyx6Ac,3599 +ultralytics/models/nas/predict.py,sha256=4nbuo9nbvnvI3qVH1ylhLCjo-7oW39MumIesm-1eU3Y,2692 +ultralytics/models/nas/val.py,sha256=MIRym3LQNDIRxnYs5xcOiLkKOgv3enZFXh5_g9Pq2hA,1543 +ultralytics/models/rtdetr/__init__.py,sha256=F4NEQqtcVKFxj97Dh7rkn2Vu3JG4Ea_nxqrBB-9P1vc,225 +ultralytics/models/rtdetr/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/rtdetr/__pycache__/model.cpython-312.pyc,, +ultralytics/models/rtdetr/__pycache__/predict.cpython-312.pyc,, +ultralytics/models/rtdetr/__pycache__/train.cpython-312.pyc,, +ultralytics/models/rtdetr/__pycache__/val.cpython-312.pyc,, +ultralytics/models/rtdetr/model.py,sha256=jJzSh_5E__rVQO7_IkmncpC4jIdu9xNiIxlTTIaFJVw,2269 +ultralytics/models/rtdetr/predict.py,sha256=SU5UPoyxLmFCZ2IsSaYb6vux8bsrw90K79FajFDdl80,3969 +ultralytics/models/rtdetr/train.py,sha256=JTRwzn-syHuh6fFfQgDWa2XfKjY26d9NxRwctHbpZ64,3925 +ultralytics/models/rtdetr/val.py,sha256=R1QHGjif93luFtVZaB_UDfwLlJgJdWjd1DeXd_n1ZuU,8062 +ultralytics/models/sam/__init__.py,sha256=hofz9cGGhxEWpZXX8yLp5k_LQUmWL_Shd9kfzK4U6z0,592 +ultralytics/models/sam/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/sam/__pycache__/amg.cpython-312.pyc,, +ultralytics/models/sam/__pycache__/build.cpython-312.pyc,, +ultralytics/models/sam/__pycache__/build_sam3.cpython-312.pyc,, +ultralytics/models/sam/__pycache__/model.cpython-312.pyc,, +ultralytics/models/sam/__pycache__/predict.cpython-312.pyc,, +ultralytics/models/sam/amg.py,sha256=aYvJ7jQMkTR3X9KV7SHi3qP3yNchQggWNUurTRZwxQg,11786 +ultralytics/models/sam/build.py,sha256=NUGwH8hKtYtob9vIBb-FzB8QjL5aJ4HpgrwZMFo1IOI,12865 +ultralytics/models/sam/build_sam3.py,sha256=I4TSSIdjGeo9FWnF9iNFBpUnzSX65rWNdzOxXTN0ajo,12658 +ultralytics/models/sam/model.py,sha256=fV-gMkd7zaqphrRMikIPRHasm7GbSWbL1amgL8ZMF_A,7407 +ultralytics/models/sam/modules/__init__.py,sha256=lm6MckFYCPTbqIoX7w0s_daxdjNeBeKW6DXppv1-QUM,70 +ultralytics/models/sam/modules/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/sam/modules/__pycache__/blocks.cpython-312.pyc,, +ultralytics/models/sam/modules/__pycache__/decoders.cpython-312.pyc,, +ultralytics/models/sam/modules/__pycache__/encoders.cpython-312.pyc,, +ultralytics/models/sam/modules/__pycache__/memory_attention.cpython-312.pyc,, +ultralytics/models/sam/modules/__pycache__/sam.cpython-312.pyc,, +ultralytics/models/sam/modules/__pycache__/tiny_encoder.cpython-312.pyc,, +ultralytics/models/sam/modules/__pycache__/transformer.cpython-312.pyc,, +ultralytics/models/sam/modules/__pycache__/utils.cpython-312.pyc,, +ultralytics/models/sam/modules/blocks.py,sha256=eXfnwhGlKj3kLIr1u9K0iN1aUTxYdbv4bcFSvLbVRe0,44175 +ultralytics/models/sam/modules/decoders.py,sha256=MGUC8zs8FFtSacBwrp4Nva7sgYmCXpULPW-TmVXz4wg,25045 +ultralytics/models/sam/modules/encoders.py,sha256=IDtcpWf2f0OBNUKa81FwRcZFzoG8umIQ7LI8Mm5W2ss,35520 +ultralytics/models/sam/modules/memory_attention.py,sha256=x8AjFkmK7sx4qXDCdJ_yBsxtQBqeldYNBMRe8ntpLHs,13287 +ultralytics/models/sam/modules/sam.py,sha256=qk0pz7QxNX1I4eie3hx-KWxIUn5KLRz5-EcSpS2d_0k,61666 +ultralytics/models/sam/modules/tiny_encoder.py,sha256=w-JWH9NNXCKjyR-9qlfie3xjXHLPPiw6d-fvTIkXxAo,42400 +ultralytics/models/sam/modules/transformer.py,sha256=qGcEt5coPyWeaXjK1nzt-ID5HW2Q30u6tAxSyOkx3Sg,14884 +ultralytics/models/sam/modules/utils.py,sha256=HwHAf_yxMnYc1cs5bAnPIDyOkIbrUMw0qha9TB8olU0,21371 +ultralytics/models/sam/predict.py,sha256=-7sKoSJW43sdWQ1rU6g8InZg7UHygfVdcL-ZQfG4nt8,206505 +ultralytics/models/sam/sam3/__init__.py,sha256=aM4-KimnYgIFe-e5ctLT8e6k9PagvuvKFaHaagDZM7E,144 +ultralytics/models/sam/sam3/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/sam/sam3/__pycache__/decoder.cpython-312.pyc,, +ultralytics/models/sam/sam3/__pycache__/encoder.cpython-312.pyc,, +ultralytics/models/sam/sam3/__pycache__/geometry_encoders.cpython-312.pyc,, +ultralytics/models/sam/sam3/__pycache__/maskformer_segmentation.cpython-312.pyc,, +ultralytics/models/sam/sam3/__pycache__/model_misc.cpython-312.pyc,, +ultralytics/models/sam/sam3/__pycache__/necks.cpython-312.pyc,, +ultralytics/models/sam/sam3/__pycache__/sam3_image.cpython-312.pyc,, +ultralytics/models/sam/sam3/__pycache__/text_encoder_ve.cpython-312.pyc,, +ultralytics/models/sam/sam3/__pycache__/vitdet.cpython-312.pyc,, +ultralytics/models/sam/sam3/__pycache__/vl_combiner.cpython-312.pyc,, +ultralytics/models/sam/sam3/decoder.py,sha256=LLHD8cKvENMnKyjxUtlVTjmGQK4jjxHplMgs5bwh-bc,21593 +ultralytics/models/sam/sam3/encoder.py,sha256=KWAcX8iNgKZINgafFvhmPi_v0xgNelzlu4fQF48owDY,20834 +ultralytics/models/sam/sam3/geometry_encoders.py,sha256=xPI5bkNwTvj8LHBd6QiuSeP7JC42rF2y72Gabl9Uu4w,17666 +ultralytics/models/sam/sam3/maskformer_segmentation.py,sha256=GhAfZ_7MkEHkkanFQCCKMOccH8-tCUp3MKBwc4Q8mrQ,10725 +ultralytics/models/sam/sam3/model_misc.py,sha256=6cn_gjdFkstVnDN8y21JYQeDNOx54k081vrVCE_K5ig,7906 +ultralytics/models/sam/sam3/necks.py,sha256=tyYRPfylf0vkdNm_SjNaAmouA3xq8udsR0pJHPjwYLI,4766 +ultralytics/models/sam/sam3/sam3_image.py,sha256=F4nlCNSF0xVpHAxiPCWyVDH6M8BvajJq3tbNdwHPLPM,14726 +ultralytics/models/sam/sam3/text_encoder_ve.py,sha256=8IAFY1V0CQsKdvNvE-HSKhabxAuL5TJ-a2JP_pK8EXg,12251 +ultralytics/models/sam/sam3/vitdet.py,sha256=fOTtE3_ihvDUKEBbiXzfkloKG0Vow4fOGo4W7QvlAvQ,22103 +ultralytics/models/sam/sam3/vl_combiner.py,sha256=6bCZNuxeBWbRgZJ_-CxOXS3BHoaHBstD8MuZWxFtJys,6997 +ultralytics/models/utils/__init__.py,sha256=lm6MckFYCPTbqIoX7w0s_daxdjNeBeKW6DXppv1-QUM,70 +ultralytics/models/utils/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/utils/__pycache__/loss.cpython-312.pyc,, +ultralytics/models/utils/__pycache__/ops.cpython-312.pyc,, +ultralytics/models/utils/loss.py,sha256=tTRVZvq0Ot0beUdkEBQ2QJACeI4Zm2tkKCdd-kCH3CI,20909 +ultralytics/models/utils/ops.py,sha256=hF3DM_i-BOIcYWRi7NvXKpxx7DxzQE8cAZhQlIYBnQQ,16471 +ultralytics/models/yolo/__init__.py,sha256=8F7fGMtNWr6da0WUpBaxLHIxuZ5nyxZiP3Ro6BuFhgo,398 +ultralytics/models/yolo/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/yolo/__pycache__/model.cpython-312.pyc,, +ultralytics/models/yolo/classify/__init__.py,sha256=9--HVaNOfI1K7rn_rRqclL8FUAnpfeBrRqEQIaQw2xM,383 +ultralytics/models/yolo/classify/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/yolo/classify/__pycache__/predict.cpython-312.pyc,, +ultralytics/models/yolo/classify/__pycache__/train.cpython-312.pyc,, +ultralytics/models/yolo/classify/__pycache__/val.cpython-312.pyc,, +ultralytics/models/yolo/classify/predict.py,sha256=rEUHwxnCX-0Wjx8A84GpoAzSZHAtrcTJEf46SOd0Mpk,5102 +ultralytics/models/yolo/classify/train.py,sha256=kWDo6xFHkP-KwGtzQTAn16tauXbmjPDKwosDNA-_9vU,8709 +ultralytics/models/yolo/classify/val.py,sha256=UVoaUjLlJxq5ACdKPLpEclQARfumjIQywMOXX5WnE94,10742 +ultralytics/models/yolo/depth/__init__.py,sha256=G5M0uC7zkLqkkEjiWXx9qnTC8VaIjPAlMTYPQemtFzM,233 +ultralytics/models/yolo/depth/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/yolo/depth/__pycache__/calibrate.cpython-312.pyc,, +ultralytics/models/yolo/depth/__pycache__/predict.cpython-312.pyc,, +ultralytics/models/yolo/depth/__pycache__/train.cpython-312.pyc,, +ultralytics/models/yolo/depth/__pycache__/val.cpython-312.pyc,, +ultralytics/models/yolo/depth/calibrate.py,sha256=HsQ-0LIT5bqzYRqIavQ2dM6EeSt9YQnopSW5P4pFDsM,15538 +ultralytics/models/yolo/depth/predict.py,sha256=sTx62IM9NPx1GSV6EYJYtQ4nGf3NZxbodxL9i1GCZTw,2162 +ultralytics/models/yolo/depth/train.py,sha256=ilhFyaMoMxA49xr6r1CX5d34gbSM5klumytupoPtbEM,7580 +ultralytics/models/yolo/depth/val.py,sha256=wKZTV9kIqyh6M5C2NkUUS1z7SwVN4Kxl3lK7phXajog,5572 +ultralytics/models/yolo/detect/__init__.py,sha256=GIRsLYR-kT4JJx7lh4ZZAFGBZj0aebokuU0A7JbjDVA,257 +ultralytics/models/yolo/detect/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/yolo/detect/__pycache__/predict.cpython-312.pyc,, +ultralytics/models/yolo/detect/__pycache__/train.cpython-312.pyc,, +ultralytics/models/yolo/detect/__pycache__/val.cpython-312.pyc,, +ultralytics/models/yolo/detect/predict.py,sha256=L01OgXeC2lbZ1oZAhHJ6lXal0nY3DMGBFDViKUGiOF0,5474 +ultralytics/models/yolo/detect/train.py,sha256=dtaxgSWe3AmwP3zqH51ZvU7aL3lkFGu7LnbU9yAdz18,12440 +ultralytics/models/yolo/detect/val.py,sha256=sV_LCExB63HZx2pp8kma_O7s7A8F0a7pjdEkPEz091o,28856 +ultralytics/models/yolo/model.py,sha256=Jo_fDLjuukMm8dm2bjL1Wvw01rl6ueci2KqWyCUC6WI,26868 +ultralytics/models/yolo/obb/__init__.py,sha256=tQmpG8wVHsajWkZdmD6cjGohJ4ki64iSXQT8JY_dydo,221 +ultralytics/models/yolo/obb/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/yolo/obb/__pycache__/predict.cpython-312.pyc,, +ultralytics/models/yolo/obb/__pycache__/train.cpython-312.pyc,, +ultralytics/models/yolo/obb/__pycache__/val.cpython-312.pyc,, +ultralytics/models/yolo/obb/predict.py,sha256=VA5yRo32IVakZ_5nY75KArfaXnZbANzTkxMVGDm-co4,2634 +ultralytics/models/yolo/obb/train.py,sha256=d-xh-NrM0B_WEn70lOj_XIVEg20hyXe4DYvFj1iur64,3381 +ultralytics/models/yolo/obb/val.py,sha256=5Cc61ejAAyWtzM3v_cpkRrP0e360IUtty--iPYf-xU8,14592 +ultralytics/models/yolo/pose/__init__.py,sha256=_9OFLj19XwvJHBRxQtVW5CV7rvJ_3hDPE97miit0sPc,227 +ultralytics/models/yolo/pose/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/yolo/pose/__pycache__/predict.cpython-312.pyc,, +ultralytics/models/yolo/pose/__pycache__/train.cpython-312.pyc,, +ultralytics/models/yolo/pose/__pycache__/val.cpython-312.pyc,, +ultralytics/models/yolo/pose/predict.py,sha256=a_D6-0qCRhTL_ccFe6UTNB1jgaB3Mp1wedLDQpeLPeM,3175 +ultralytics/models/yolo/pose/train.py,sha256=yfN79C7eCrsAp7CJq9i6VRVQxZqfa_SFgGJWtKdhGQ4,4813 +ultralytics/models/yolo/pose/val.py,sha256=EH18gpiwLqMf78-PKN5Xoehd8SyPv_o382OA9pcz5Sc,12489 +ultralytics/models/yolo/segment/__init__.py,sha256=3IThhZ1wlkY9FvmWm9cE-5-ZyE6F1FgzAtQ6jOOFzzw,275 +ultralytics/models/yolo/segment/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/yolo/segment/__pycache__/predict.cpython-312.pyc,, +ultralytics/models/yolo/segment/__pycache__/train.cpython-312.pyc,, +ultralytics/models/yolo/segment/__pycache__/val.cpython-312.pyc,, +ultralytics/models/yolo/segment/predict.py,sha256=L4DCWXgvMwsSs_S16xE0VBa4PpnWr4baO75ZQIm94Bw,5556 +ultralytics/models/yolo/segment/train.py,sha256=fjbdj4BwLa8EGwGHcx9hElAxQTqHrNw3h4bz6p1fvz8,3043 +ultralytics/models/yolo/segment/val.py,sha256=mUoSVokRoxURAkIlfIp4n24GuQZwW3sk6tTzj5DIGqQ,13527 +ultralytics/models/yolo/semantic/__init__.py,sha256=yzL8Q1Ap2etFevc5YPsPv57zDFXldRM0X2vRjArFP7E,323 +ultralytics/models/yolo/semantic/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/yolo/semantic/__pycache__/predict.cpython-312.pyc,, +ultralytics/models/yolo/semantic/__pycache__/train.cpython-312.pyc,, +ultralytics/models/yolo/semantic/__pycache__/val.cpython-312.pyc,, +ultralytics/models/yolo/semantic/predict.py,sha256=vxjPWsF6anQRdMPLUIwGx_nteykOLbpZoQa5zL8suLQ,4340 +ultralytics/models/yolo/semantic/train.py,sha256=-XWy-AARIQSUjeOxGkOj2W2f4fIWCgM9beZsN0LLMQk,6317 +ultralytics/models/yolo/semantic/val.py,sha256=YooJK3dTG-kwmo13cUq9akCdPWXtojelmky89GvOD2k,8478 +ultralytics/models/yolo/world/__init__.py,sha256=MjFKnREHgSY4pZIRzQIVs0nXbSkXPaAn9FHPHGxggWY,181 +ultralytics/models/yolo/world/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/yolo/world/__pycache__/train.cpython-312.pyc,, +ultralytics/models/yolo/world/__pycache__/train_world.cpython-312.pyc,, +ultralytics/models/yolo/world/__pycache__/val.cpython-312.pyc,, +ultralytics/models/yolo/world/train.py,sha256=NxLvKuxAifKTIk9-56tNZDN_oXNbPyGrd_C---ndBxo,8162 +ultralytics/models/yolo/world/train_world.py,sha256=w4kq_lyPmZm2FiC8OA_WtXXxMbR0K4zz-6a72HKwv1c,9436 +ultralytics/models/yolo/world/val.py,sha256=_dXTsd1CbcUJn7hF7BLxYaGBFtfdfTC-ZIRLSeSeByY,2329 +ultralytics/models/yolo/yoloe/__init__.py,sha256=zaZo1_ommaxNv7mD7xpdSomNF4s8mpOcCVTXspg0ncY,760 +ultralytics/models/yolo/yoloe/__pycache__/__init__.cpython-312.pyc,, +ultralytics/models/yolo/yoloe/__pycache__/predict.cpython-312.pyc,, +ultralytics/models/yolo/yoloe/__pycache__/train.cpython-312.pyc,, +ultralytics/models/yolo/yoloe/__pycache__/train_seg.cpython-312.pyc,, +ultralytics/models/yolo/yoloe/__pycache__/val.cpython-312.pyc,, +ultralytics/models/yolo/yoloe/predict.py,sha256=ZzcI0VyRoJbUNtzheW_ag9wtqJx5bzmpsu8Buv7f59c,5854 +ultralytics/models/yolo/yoloe/train.py,sha256=WMUL2UBK6pzp7oo4WcN5uP52Oon7aRombdelYSNgP3w,12939 +ultralytics/models/yolo/yoloe/train_seg.py,sha256=1wHPnq2Oeb-efWf4hUt14BM8Shy4oJNi2ItzyfxgffE,905 +ultralytics/models/yolo/yoloe/val.py,sha256=jdwKHkk0JztBgjtbCrmEzXEN8Wb2bBoX49dGJAjO2qc,9229 +ultralytics/nn/__init__.py,sha256=538LZPUKKvc3JCMgiQ4VLGqRN2ZAaVLFcQbeNNHFkEA,545 +ultralytics/nn/__pycache__/__init__.cpython-312.pyc,, +ultralytics/nn/__pycache__/autobackend.cpython-312.pyc,, +ultralytics/nn/__pycache__/distill_model.cpython-312.pyc,, +ultralytics/nn/__pycache__/tasks.cpython-312.pyc,, +ultralytics/nn/__pycache__/text_model.cpython-312.pyc,, +ultralytics/nn/autobackend.py,sha256=OHLhHVRQTRwrAQmGu3z4liketWwZKOXEWpLqehQgq0A,18376 +ultralytics/nn/backends/__init__.py,sha256=AT3IYM33czoTRKSfifeGhjD-OyHcgttpbqxv0gAgbCc,1606 +ultralytics/nn/backends/__pycache__/__init__.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/ascend.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/axelera.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/base.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/coreai.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/coreml.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/deepx.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/executorch.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/hailo.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/litert.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/mnn.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/ncnn.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/onnx.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/openvino.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/paddle.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/pytorch.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/qnn.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/rknn.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/tensorflow.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/tensorrt.cpython-312.pyc,, +ultralytics/nn/backends/__pycache__/triton.cpython-312.pyc,, +ultralytics/nn/backends/ascend.py,sha256=GeNx8TKDPqeo4-EAgI1__C2bfdBRo1Qn21jkrmheJvU,2315 +ultralytics/nn/backends/axelera.py,sha256=Bj4rh3WImlbL8NpaM0VCXT4PFGhky9pt7xNYFSaNY58,2641 +ultralytics/nn/backends/base.py,sha256=ylVXmaBV29wDWk209x1dtVuxPefompDCiEkyjaxvOOo,10175 +ultralytics/nn/backends/coreai.py,sha256=_7pynrFvW-bnPQ_5G2rCR3ZB__6POB0fCRAjDPM0vDM,2392 +ultralytics/nn/backends/coreml.py,sha256=2tSdWcCOrnbwinumMwBsMtU39J2m_6mWcOCqMxCZanc,3937 +ultralytics/nn/backends/deepx.py,sha256=MBGKxuqPQJQLNAcVnF9RRe519mWkElRukhZnQuT2YZg,2629 +ultralytics/nn/backends/executorch.py,sha256=KaCfKE9H4ngfv73ktY3JrLvLVqjRe1Z45lCg4NZxDHY,1569 +ultralytics/nn/backends/hailo.py,sha256=EwPMzumGaf0CpMLl-Pf-Xi2yr3eAXytvhrCi7JLLl4E,11555 +ultralytics/nn/backends/litert.py,sha256=effsmrTHSP2FxpIu3RNgMyO_EMP6F0K5fj5eV40N-jI,5440 +ultralytics/nn/backends/mnn.py,sha256=UYg_a7GmsO9fWWJUc-HIh5e_dMmdg6D-vnRoob54TbM,2220 +ultralytics/nn/backends/ncnn.py,sha256=y180W614YBm-xxObSR3WcY95QHOiZlQ8oFKbNTdKTWs,2390 +ultralytics/nn/backends/onnx.py,sha256=kNUBF1eA2kzVt5EKXoyKYmImEF0mpuvmUQ01LLzT524,10064 +ultralytics/nn/backends/openvino.py,sha256=LtlvTyyOnQLYdfuzapF97-MXYRqOLs0BWE7njSh2Shw,5896 +ultralytics/nn/backends/paddle.py,sha256=JqvnBOZDq9lFlmZ6WdUMpuPcuvCN6X24zKzt5w27f7Y,2844 +ultralytics/nn/backends/pytorch.py,sha256=mLcsv4nMgRsFTC4g_Czknl6_zC72hEqWb1Hh-rB_1Sw,6207 +ultralytics/nn/backends/qnn.py,sha256=Dbg11h9PrkxMGbuthLNSqnhw7kKFP1lGF-Ha_G7MkhY,3311 +ultralytics/nn/backends/rknn.py,sha256=Wi4VVOdW0PDtsFod0o9rn41coiDlNza40uK9azCy9OY,2863 +ultralytics/nn/backends/tensorflow.py,sha256=iiC_KsQbXv4Y7eXljOBHu-DYSBb2WU6PWesRzGz60oA,7062 +ultralytics/nn/backends/tensorrt.py,sha256=DFoo2IiGHCUph-E5bOIJhOaHFpthANbRbOijNu6cjVo,7646 +ultralytics/nn/backends/triton.py,sha256=tfPmifMNxSlH95BPiqASGQd-6k_9URGHYE9HTlQpYFc,1463 +ultralytics/nn/distill_model.py,sha256=_nf11RnJSGFKAGDlJanFU3rn-Can_luu5ydKFenqp1w,14204 +ultralytics/nn/modules/__init__.py,sha256=GoECx_bcD3NuIquK_NAWisX8ScjAkBOc3M4yqv7r2Lo,3390 +ultralytics/nn/modules/__pycache__/__init__.cpython-312.pyc,, +ultralytics/nn/modules/__pycache__/activation.cpython-312.pyc,, +ultralytics/nn/modules/__pycache__/block.cpython-312.pyc,, +ultralytics/nn/modules/__pycache__/conv.cpython-312.pyc,, +ultralytics/nn/modules/__pycache__/head.cpython-312.pyc,, +ultralytics/nn/modules/__pycache__/transformer.cpython-312.pyc,, +ultralytics/nn/modules/__pycache__/utils.cpython-312.pyc,, +ultralytics/nn/modules/activation.py,sha256=ULZlEWxed-Euw-89XjEBbTTfFWlFtAa78AiH3YeVhdk,2218 +ultralytics/nn/modules/block.py,sha256=-BXGVvxcDW9okyLx7xNlU0nF0BN5L98Ip7kVZ1HiG-M,75557 +ultralytics/nn/modules/conv.py,sha256=VI7h8_ooVCrUa5IOTUJxWU76Cbx2xKswZ6CKlm8wZI0,21132 +ultralytics/nn/modules/head.py,sha256=YXtb3W4tYJxxh-AN8RUA_UCCXz0iMqNJ5tjz8HZW2Xk,83854 +ultralytics/nn/modules/transformer.py,sha256=YIa-EYImoIX0Mp8z9f-QwUXFwpBWQ0Tmgl30-kTspTQ,32625 +ultralytics/nn/modules/utils.py,sha256=GFPEw2DOftXRC0B_M0j03Jp6QRYcezU6tbQDTcsr8_w,4939 +ultralytics/nn/tasks.py,sha256=P0OjD6aRdNGDL7K-BpOiZmukC1oOpLEngbhu8tjD8vA,99504 +ultralytics/nn/text_model.py,sha256=T9oobJQ0tYEMI2jdMEThT6oPf4VESJqf7IhV3s4ruVM,15402 +ultralytics/optim/__init__.py,sha256=7pu_peIqRKkJWdhlQsfhARQnWy19v5baP6jSJK0znYE,116 +ultralytics/optim/__pycache__/__init__.cpython-312.pyc,, +ultralytics/optim/__pycache__/muon.cpython-312.pyc,, +ultralytics/optim/muon.py,sha256=_iZIhUJ_ngkcdLh1eAlYoUAFKVCLD970yOl6NPqyFJs,12200 +ultralytics/py.typed,sha256=la67KBlbjXN-_-DfGNcdOcjYumVpKG_Tkw-8n5dnGB4,8 +ultralytics/solutions/__init__.py,sha256=Jj7OcRiYjHH-e104H4xTgjjR5W6aPB4mBRndbaSPmgU,1209 +ultralytics/solutions/__pycache__/__init__.cpython-312.pyc,, +ultralytics/solutions/__pycache__/ai_gym.cpython-312.pyc,, +ultralytics/solutions/__pycache__/analytics.cpython-312.pyc,, +ultralytics/solutions/__pycache__/config.cpython-312.pyc,, +ultralytics/solutions/__pycache__/distance_calculation.cpython-312.pyc,, +ultralytics/solutions/__pycache__/heatmap.cpython-312.pyc,, +ultralytics/solutions/__pycache__/instance_segmentation.cpython-312.pyc,, +ultralytics/solutions/__pycache__/object_blurrer.cpython-312.pyc,, +ultralytics/solutions/__pycache__/object_counter.cpython-312.pyc,, +ultralytics/solutions/__pycache__/object_cropper.cpython-312.pyc,, +ultralytics/solutions/__pycache__/parking_management.cpython-312.pyc,, +ultralytics/solutions/__pycache__/queue_management.cpython-312.pyc,, +ultralytics/solutions/__pycache__/region_counter.cpython-312.pyc,, +ultralytics/solutions/__pycache__/security_alarm.cpython-312.pyc,, +ultralytics/solutions/__pycache__/similarity_search.cpython-312.pyc,, +ultralytics/solutions/__pycache__/solutions.cpython-312.pyc,, +ultralytics/solutions/__pycache__/speed_estimation.cpython-312.pyc,, +ultralytics/solutions/__pycache__/streamlit_inference.cpython-312.pyc,, +ultralytics/solutions/__pycache__/trackzone.cpython-312.pyc,, +ultralytics/solutions/__pycache__/vision_eye.cpython-312.pyc,, +ultralytics/solutions/ai_gym.py,sha256=PAjZpzDmyIjxIfbOooTrFmNnZAthJkIMNF-cmOH0R3s,6095 +ultralytics/solutions/analytics.py,sha256=q9FEY3ZiaL8xH3hJ1Lhr0X8AA70sK-b4_joqA95NzZ0,12714 +ultralytics/solutions/config.py,sha256=P7KLPNe1qAUnlE_n3HnY98G8Jp4Pak13oMRMh-_BNC4,6007 +ultralytics/solutions/distance_calculation.py,sha256=zLEjU1jk1K_daotwbxNGRIoNJjNnif8LQ_G7Spkh6to,6020 +ultralytics/solutions/heatmap.py,sha256=R4FR5i9E5oCS6nd7m622Ga0E7yEZ9b61YCSVm_xixc0,5719 +ultralytics/solutions/instance_segmentation.py,sha256=uP810WlECIRAbwgX4lXqV5l8vvLp7zvf0FG0RlaYjUE,3786 +ultralytics/solutions/object_blurrer.py,sha256=MPFZ3glegV-LLfUsJ3QtUXbhf06SyNE8Ud749UVPsVs,4200 +ultralytics/solutions/object_counter.py,sha256=OwHvEGetQYNE7t-7_CgSNwUoVSLXGjKhZc1nZyulKL8,10270 +ultralytics/solutions/object_cropper.py,sha256=9NLr4egGJNPX_2wtf4nQtRo1f_wZlpv7fgJt2Xkp0j0,3551 +ultralytics/solutions/parking_management.py,sha256=6RDFoIFW7lkL7Drvo809WMp0jLmX1nVmedmrcRnMcVs,13815 +ultralytics/solutions/queue_management.py,sha256=NtrGJmxKSlu5gsQw2vmj5E9fQWgIvGDE56IQ_PfMZ_Q,4393 +ultralytics/solutions/region_counter.py,sha256=bjXrCClmts5_Vfd9ipvx4WKKbDQUFQlutwVIzhwIv0k,6428 +ultralytics/solutions/security_alarm.py,sha256=c7odhqvxXOSiLVk1W1deAzDyJ5bQukS_shHayVbl8gc,6273 +ultralytics/solutions/similarity_search.py,sha256=ARkqa47WtSRgdcAeOvX64zLIWDcD3sFcec7O-u17CJ4,9907 +ultralytics/solutions/solutions.py,sha256=d6f_jnEbuZODa4Qn6T9qTVuSn0LLJOEk5fRUkOzjhLY,39011 +ultralytics/solutions/speed_estimation.py,sha256=0q0uw8OdvZHKhwsXAacwIvEUSxLTmW7t8kTfQPkMWpc,6276 +ultralytics/solutions/streamlit_inference.py,sha256=OK26OHSKrXsLe00eE2I53a_W3LunqlaY27KAeLkbXXM,13099 +ultralytics/solutions/templates/similarity-search.html,sha256=epX8XDLasOUx8ISPuKP9M0SRUjRcv_FE1r_EG3QpBtw,4177 +ultralytics/solutions/trackzone.py,sha256=An9tNETx_5DY6xy2ZI8mcrNMXRzEezjm3HRseoO7R2A,3910 +ultralytics/solutions/vision_eye.py,sha256=8aScUfkuUGzrHsxB1k6nC5w8Xa_RqW7W7FcAgTdgE7Q,3006 +ultralytics/trackers/__init__.py,sha256=-1tfYXBxpb-y2rYB7H5oD2R0bxbwEfKXIRdz8dzW5JI,482 +ultralytics/trackers/__pycache__/__init__.cpython-312.pyc,, +ultralytics/trackers/__pycache__/basetrack.cpython-312.pyc,, +ultralytics/trackers/__pycache__/bot_sort.cpython-312.pyc,, +ultralytics/trackers/__pycache__/byte_tracker.cpython-312.pyc,, +ultralytics/trackers/__pycache__/deep_oc_sort.cpython-312.pyc,, +ultralytics/trackers/__pycache__/fast_tracker.cpython-312.pyc,, +ultralytics/trackers/__pycache__/oc_sort.cpython-312.pyc,, +ultralytics/trackers/__pycache__/track.cpython-312.pyc,, +ultralytics/trackers/__pycache__/track_tracker.cpython-312.pyc,, +ultralytics/trackers/basetrack.py,sha256=nvCUuaVP8vUskRi1vRovhLozGqVXJ39UGG3hFyjC9-g,3752 +ultralytics/trackers/bot_sort.py,sha256=HXQXKrkd7zlJMc1ssKR4MaYOrXSITpYzTC6CknzwNUk,10020 +ultralytics/trackers/byte_tracker.py,sha256=igEo5FOwXxlpMke2sr3t_jOonpMh88R2cesJKJYnkyw,23745 +ultralytics/trackers/deep_oc_sort.py,sha256=xjlPYML2I-tWzP76LRvhH9tjoemyzB5hMPC_DfSQkfY,11845 +ultralytics/trackers/fast_tracker.py,sha256=v78bti4_qccQExCaLWkT2gfV3PfTN9QIu1kOK2py6Vw,17560 +ultralytics/trackers/oc_sort.py,sha256=1_Kl1JeDDDrj5ObDj_yvfhqezbygXYl-FPT5GhYKl-s,15550 +ultralytics/trackers/track.py,sha256=oL1eAwoaVvLm4YhXrM078uXycgrlgQF42cQXnICnyAI,6468 +ultralytics/trackers/track_tracker.py,sha256=hoHghNLWuAqZwMv8s1yz5LYPYadcYTJedZLsQom1eg0,28088 +ultralytics/trackers/utils/__init__.py,sha256=lm6MckFYCPTbqIoX7w0s_daxdjNeBeKW6DXppv1-QUM,70 +ultralytics/trackers/utils/__pycache__/__init__.cpython-312.pyc,, +ultralytics/trackers/utils/__pycache__/gmc.cpython-312.pyc,, +ultralytics/trackers/utils/__pycache__/kalman_filter.cpython-312.pyc,, +ultralytics/trackers/utils/__pycache__/matching.cpython-312.pyc,, +ultralytics/trackers/utils/__pycache__/reid.cpython-312.pyc,, +ultralytics/trackers/utils/__pycache__/stracks.cpython-312.pyc,, +ultralytics/trackers/utils/gmc.py,sha256=IbALyBxyLns4gaxJjnwUwhzcG9gZBppKkzFYpcmoVW4,14176 +ultralytics/trackers/utils/kalman_filter.py,sha256=kLB4t6oyQYsb9h_o-4lG5JwDeyxlU0lV3J1rNm33Ofg,21785 +ultralytics/trackers/utils/matching.py,sha256=vOfucS9GSriE553SphCH9mIO6e1bN1rnIB7l6JtO_cc,7818 +ultralytics/trackers/utils/reid.py,sha256=F7yPrrkhHy4TcLxozZadDJfQARfBUfU081rAzUGahwU,8107 +ultralytics/trackers/utils/stracks.py,sha256=xM-Dzae-TInuW9jzNCSxSad2TaAOSnBL8Q68-huHBgc,7980 +ultralytics/utils/__init__.py,sha256=alr4okYlIaZ-Q6B_PuxT8haGdq4O157YU7FQ5b5ZK3U,60554 +ultralytics/utils/__pycache__/__init__.cpython-312.pyc,, +ultralytics/utils/__pycache__/autobatch.cpython-312.pyc,, +ultralytics/utils/__pycache__/autodevice.cpython-312.pyc,, +ultralytics/utils/__pycache__/benchmarks.cpython-312.pyc,, +ultralytics/utils/__pycache__/checks.cpython-312.pyc,, +ultralytics/utils/__pycache__/cpu.cpython-312.pyc,, +ultralytics/utils/__pycache__/dist.cpython-312.pyc,, +ultralytics/utils/__pycache__/downloads.cpython-312.pyc,, +ultralytics/utils/__pycache__/events.cpython-312.pyc,, +ultralytics/utils/__pycache__/files.cpython-312.pyc,, +ultralytics/utils/__pycache__/git.cpython-312.pyc,, +ultralytics/utils/__pycache__/instance.cpython-312.pyc,, +ultralytics/utils/__pycache__/logger.cpython-312.pyc,, +ultralytics/utils/__pycache__/loss.cpython-312.pyc,, +ultralytics/utils/__pycache__/metrics.cpython-312.pyc,, +ultralytics/utils/__pycache__/nms.cpython-312.pyc,, +ultralytics/utils/__pycache__/ops.cpython-312.pyc,, +ultralytics/utils/__pycache__/patches.cpython-312.pyc,, +ultralytics/utils/__pycache__/plotting.cpython-312.pyc,, +ultralytics/utils/__pycache__/tal.cpython-312.pyc,, +ultralytics/utils/__pycache__/torch_utils.cpython-312.pyc,, +ultralytics/utils/__pycache__/tqdm.cpython-312.pyc,, +ultralytics/utils/__pycache__/triton.cpython-312.pyc,, +ultralytics/utils/__pycache__/tuner.cpython-312.pyc,, +ultralytics/utils/__pycache__/uploads.cpython-312.pyc,, +ultralytics/utils/autobatch.py,sha256=2vuP5FkBxAi_Y91-kBgqfCvcPLoiP-PV1QTKoHePyew,6274 +ultralytics/utils/autodevice.py,sha256=NjBs39AAi7VggHLDhgSxS9RIySmqWVwd3a-ISfk54-o,9329 +ultralytics/utils/benchmarks.py,sha256=p6gFohI4-ad5ovyBCiL3Va1dpuTqLl9PhK31LJT7OGg,29056 +ultralytics/utils/callbacks/__init__.py,sha256=hzL63Rce6VkZhP4Lcim9LKjadixaQG86nKqPhk7IkS0,242 +ultralytics/utils/callbacks/__pycache__/__init__.cpython-312.pyc,, +ultralytics/utils/callbacks/__pycache__/base.cpython-312.pyc,, +ultralytics/utils/callbacks/__pycache__/clearml.cpython-312.pyc,, +ultralytics/utils/callbacks/__pycache__/comet.cpython-312.pyc,, +ultralytics/utils/callbacks/__pycache__/dvc.cpython-312.pyc,, +ultralytics/utils/callbacks/__pycache__/mlflow.cpython-312.pyc,, +ultralytics/utils/callbacks/__pycache__/platform.cpython-312.pyc,, +ultralytics/utils/callbacks/__pycache__/raytune.cpython-312.pyc,, +ultralytics/utils/callbacks/__pycache__/tensorboard.cpython-312.pyc,, +ultralytics/utils/callbacks/__pycache__/wb.cpython-312.pyc,, +ultralytics/utils/callbacks/base.py,sha256=GO49Xi1uXYB3YO2v7gnNGKeOl7pUo023kiJlhT4mEfw,7022 +ultralytics/utils/callbacks/clearml.py,sha256=AH7JwdZ8qtzlj11Q3MBzoUAzI6fYTb5drqAdpmxpSC8,5902 +ultralytics/utils/callbacks/comet.py,sha256=Rf7H7j2HrKy_b1LUhl80VprwsqRwQem6mp2_eGO5Hzk,25128 +ultralytics/utils/callbacks/dvc.py,sha256=DzT-Q314fap4g7rzXWeTfKw_5aTfnJIkqACAaFGXeg8,7494 +ultralytics/utils/callbacks/mlflow.py,sha256=HiJiPmJgJ82MeCxmPs9Djn1GKLVsp-1N2DeKCMlVEAA,6676 +ultralytics/utils/callbacks/platform.py,sha256=2MyLJd9BqpNs4yvAtGzODnBEGoxQFRhZpYCjxkvukkQ,19001 +ultralytics/utils/callbacks/raytune.py,sha256=ZgPxSq4sdtz9AKeLVp3OQw7C9solTu5UgFckHv13G-8,1296 +ultralytics/utils/callbacks/tensorboard.py,sha256=_RwYg6kqDIgif8v0f08943w7BP-uh-Qi9JCTEkFqqog,5081 +ultralytics/utils/callbacks/wb.py,sha256=AeKl7JTme0J0QpcIUeqxCmARX9R0S0lGUqLY-C-HLuo,8216 +ultralytics/utils/checks.py,sha256=FwP2gznmEmTiHaKTkTKfQs8RZvNurJMmfNa0Ts2YDCw,48113 +ultralytics/utils/cpu.py,sha256=GcCGziGIVqZqa09XZuePE51ccFY4UVr2Zji_Qh0fMVw,4372 +ultralytics/utils/dist.py,sha256=4WbIwjfTwQRDat8uYWnwoWGic1qk1P73hMnHXve_2Q0,5660 +ultralytics/utils/downloads.py,sha256=NEQb1oAhoLrKN0PCu_4rwS6w7HRwp9lOQVY-I71r_hA,32102 +ultralytics/utils/events.py,sha256=pzWYFuzttEdHLqb4BU_Qmo3xaEcnc2MYopnCnZsjL0k,12168 +ultralytics/utils/export/__init__.py,sha256=yRaTZYckdFhj4cm_sRHnGQDWAZ-MuTosQwzdxuabCbg,1022 +ultralytics/utils/export/__pycache__/__init__.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/ascend.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/axelera.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/coreai.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/coreml.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/deepx.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/engine.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/executorch.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/imx.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/litert.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/mnn.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/ncnn.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/onnx.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/openvino.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/paddle.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/qnn.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/rknn.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/tensorflow.cpython-312.pyc,, +ultralytics/utils/export/__pycache__/torchscript.cpython-312.pyc,, +ultralytics/utils/export/ascend.py,sha256=PoFXC8vJ8lyuW0JDdW6zsA_O2iPARFs46sd8bl8p5To,2840 +ultralytics/utils/export/axelera.py,sha256=VEUCAZ28Uq_Lt6MMlrX524pKRUekxjNuZEyvjVuaJU8,5865 +ultralytics/utils/export/coreai.py,sha256=Olko0yW9uAIwH2GKRCOCilIw6UBZqHumbdDtJNU_twc,2920 +ultralytics/utils/export/coreml.py,sha256=JClrrK-fr6cGPZiNgxE5EeyE4TYS_paGpKsgbF51doY,12083 +ultralytics/utils/export/deepx.py,sha256=xWty2N9pQa5Fyj4quHFWpYkTxgMdUg6Ca9I_4ZBMUuE,2824 +ultralytics/utils/export/engine.py,sha256=ZY1S-TQlaJ8gQNBH1zTG_W-CLlHY9nyYLucgRS0cjHc,22574 +ultralytics/utils/export/executorch.py,sha256=AcIAh0kLWLO2EN2DK2jw5lkRNyNBgbK68XMMDg1E-f4,2829 +ultralytics/utils/export/imx.py,sha256=d4deJYjcfF7zx9sfHvxE0EDzwXR269V9yfokdl5o6Ic,15100 +ultralytics/utils/export/litert.py,sha256=hSqYwUshJCVNTgH6AnilDYTXHXLGmB5hWWd11gqRpZk,7243 +ultralytics/utils/export/mnn.py,sha256=bc-OoP3mFBP1L4oD5b1vP9FST0kLkXRMd2FMnWgTfBs,1892 +ultralytics/utils/export/ncnn.py,sha256=990canQVSyT8exIG-10h8Ddx1jw0o_WmC38i7AdWqhs,2587 +ultralytics/utils/export/onnx.py,sha256=-bV_j5v0Q24v7p7TCf8AfE32OLdS4ZxK6Tr4HFxAMIg,2456 +ultralytics/utils/export/openvino.py,sha256=FpPV_Q17z-Ah8tlEegpuQwfpYkeIgsPlHU-HBkCYko8,3654 +ultralytics/utils/export/paddle.py,sha256=YlZrZj6PT-6RwT1VZdKFz6kRUz46hdQgfBjac2xnc_o,2567 +ultralytics/utils/export/qnn.py,sha256=xok-vL_8b4fvgjuRjqkH4qcb_HshCfw_Hpb8mG494o0,8039 +ultralytics/utils/export/rknn.py,sha256=f1E0tzZ_ukFEp-uVPUZP83dC4frQSAml_uEj0DasiDU,3598 +ultralytics/utils/export/tensorflow.py,sha256=n8fITtW6Jz7HSY8q937oKtTOvcWg19j15efq7BCTDPU,13388 +ultralytics/utils/export/torchscript.py,sha256=bXPk5s2ylZGvuq8nD_PVuk8VsyHSzVQuomgBldQLfDY,1228 +ultralytics/utils/files.py,sha256=0NOGyMA6rD7x0GZm8mg05PwbW1p8waJ-_yTHumvpII0,8371 +ultralytics/utils/git.py,sha256=zREX0CV4MRxhOhjKaW5T4E1V-j_2Ah3MlSXkyjtkXjI,6911 +ultralytics/utils/instance.py,sha256=YJ4k3jmUOa_j7rRTM00ecAr6UwR8B3AePyXD6XvdK5g,21382 +ultralytics/utils/logger.py,sha256=Zxfzo8l17tsB6yuduBXmF0NTD0-ULAUK0O4ypnFQlNc,26255 +ultralytics/utils/loss.py,sha256=4smPRmzCyvuKXoSrHnLyx9d-QIdFgwatTe4Jaeajfdk,71908 +ultralytics/utils/metrics.py,sha256=upUFY1Ivw_XWMMySF8IpzjhcEkaLrehH3eUY_L9YfJc,90637 +ultralytics/utils/nms.py,sha256=GrhhaGWaieSioUtedyYLNAUlY9Agd_AcYQ5JPoDOvi0,12998 +ultralytics/utils/ops.py,sha256=GoA0OGyXD7d57xj3EXCD3t5tE41NvF9m7V23ZiTTYVg,34578 +ultralytics/utils/patches.py,sha256=3SX4btn_lZi20ZI9IuyyamrTjfjFDvb08ciXcBqvJQc,10413 +ultralytics/utils/plotting.py,sha256=MJK9JQIsBN3ALBYuXnmtAczhrAl4cXgBM7dA9SV4PNg,68076 +ultralytics/utils/tal.py,sha256=NxCrfV1XQK7D2pePxuopZJnDwTktl8nmFxtu0-YGpgs,25453 +ultralytics/utils/torch_utils.py,sha256=nZ3k9eAWrcaZ_96Kfby5mSRe7mZ1fp1zg4J7EhW6xHI,55868 +ultralytics/utils/tqdm.py,sha256=t7Tugp52Ik56BpkcLuSsd3SeUQNeHulbCmG9M9GIe6o,18189 +ultralytics/utils/triton.py,sha256=qfA4VJvGVUjUj-uuQzHc0eZ989-iZkdMmuqo4WnotU0,5215 +ultralytics/utils/tuner.py,sha256=nW47PW_WM1pZcMVs82d20owbMgeNdjMoYJlLpnNUqso,21297 +ultralytics/utils/uploads.py,sha256=d0L4CPUBwp0ES8DfMpRjvNG3uG9PZOqSorWjEEcs0Ig,3864 diff --git a/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..13013d7b49be5a84c3ee5931b06285b9553cf5d0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (84.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..48edf7be907d0c391c22e4e3a836e170a30b946b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +ultralytics = ultralytics.cfg:entrypoint +yolo = ultralytics.cfg:entrypoint diff --git a/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..be3f7b28e564e7dd05eaf59d64adba1a4065ac0e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/licenses/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e1177227960fd7edd00c10e611224168632b2856 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics-8.4.160.dist-info/top_level.txt @@ -0,0 +1 @@ +ultralytics diff --git a/.venv/lib/python3.12/site-packages/ultralytics/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..06e3c66e034795206adfaab86e1c0a0c139fa980 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/__init__.py @@ -0,0 +1,56 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +__version__ = "8.4.160" + +import importlib +import os +import sys +from typing import TYPE_CHECKING + +# Set ENV variables (place before imports) +if not os.environ.get("OMP_NUM_THREADS"): + os.environ["OMP_NUM_THREADS"] = "1" # default for reduced CPU utilization during training + +from ultralytics.utils import ASSETS, SETTINGS +from ultralytics.utils.checks import check_yolo as checks +from ultralytics.utils.downloads import download + +settings = SETTINGS + +MODELS = ("YOLO", "YOLOWorld", "YOLOE", "NAS", "SAM", "FastSAM", "RTDETR", "LLM") +PLATFORM_EXPORTS = ("Platform", "AsyncPlatform", "APIError", "APIConnectionError") + +__all__ = ( # noqa: PLE0604 + "__version__", + "ASSETS", + *MODELS, + *(PLATFORM_EXPORTS if sys.version_info >= (3, 11) else ()), + "checks", + "download", + "settings", +) + +if TYPE_CHECKING: + # Enable hints for type checkers + from ultralytics.models import LLM, YOLO, YOLOWorld, YOLOE, NAS, SAM, FastSAM, RTDETR # noqa + from ultralytics_platform import APIConnectionError, APIError, AsyncPlatform, Platform # noqa: F401 + + +def __getattr__(name: str): + """Lazy-import public classes on first access.""" + if name in MODELS: + return getattr(importlib.import_module("ultralytics.models"), name) + if name in PLATFORM_EXPORTS: + if sys.version_info < (3, 11): + raise ImportError("Ultralytics Platform requires Python 3.11 or newer.") + return getattr(importlib.import_module("ultralytics_platform"), name) + raise AttributeError(f"module {__name__} has no attribute {name}") + + +def __dir__(): + """Extend dir() to include lazily available public names for IDE autocompletion.""" + return sorted(set(globals()) | set(MODELS) | set(PLATFORM_EXPORTS)) + + +if __name__ == "__main__": + print(__version__) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbd2e8bc25211ccf3adb7ba1905f39cf4e367f9f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/assets/bus.jpg b/.venv/lib/python3.12/site-packages/ultralytics/assets/bus.jpg new file mode 100644 index 0000000000000000000000000000000000000000..41bda57f9b2b3fb2c5ba1163fd738e151f2b81d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/assets/bus.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c02019c4979c191eb739ddd944445ef408dad5679acab6fd520ef9d434bfbc63 +size 137419 diff --git a/.venv/lib/python3.12/site-packages/ultralytics/assets/zidane.jpg b/.venv/lib/python3.12/site-packages/ultralytics/assets/zidane.jpg new file mode 100644 index 0000000000000000000000000000000000000000..637f04ef23a1fe37100e76e07177ad3b8a00ad10 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/assets/zidane.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16d73869e3267a7d4ed00de8e860833bd1657c1b252e94c0c348277adc7b6edb +size 50427 diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/cfg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..461cc30ffc75502ad46d8825ead5c6dc75ca636e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/__init__.py @@ -0,0 +1,1192 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import ast +import os +import shutil +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +from ultralytics import __version__ +from ultralytics.utils import ( + ASSETS, + DEFAULT_CFG, + DEFAULT_CFG_DICT, + DEFAULT_CFG_PATH, + FLOAT_OR_INT, + IS_VSCODE, + LOGGER, + PLATFORM_URL, + RANK, + ROOT, + SETTINGS, + SETTINGS_FILE, + STR_OR_PATH, + TESTS_RUNNING, + YAML, + IterableSimpleNamespace, + checks, + colorstr, + deprecation_warn, + vscode_msg, +) + +# Define valid solutions +SOLUTION_MAP = { + "count": "ObjectCounter", + "crop": "ObjectCropper", + "blur": "ObjectBlurrer", + "workout": "AIGym", + "heatmap": "Heatmap", + "isegment": "InstanceSegmentation", + "visioneye": "VisionEye", + "speed": "SpeedEstimator", + "queue": "QueueManager", + "analytics": "Analytics", + "inference": "Inference", + "trackzone": "TrackZone", + "region": "RegionCounter", + "security": "SecurityAlarm", + "parking": "ParkingManagement", + "help": None, +} + +# Define valid tasks and modes, ordered as they appear across the docs and Ultralytics Platform +MODES = ("train", "val", "predict", "export", "track", "benchmark") +TASKS = ("detect", "segment", "semantic", "depth", "classify", "pose", "obb") +TASK2DATA = { + "detect": "coco8.yaml", + "segment": "coco8-seg.yaml", + "semantic": "cityscapes8.yaml", + "depth": "depth8.yaml", + "classify": "imagenet10", + "pose": "coco8-pose.yaml", + "obb": "dota8.yaml", +} +TASK2CALIBRATIONDATA = { + "detect": "coco128.yaml", + "segment": "coco128-seg.yaml", + "semantic": "cityscapes8.yaml", + "depth": "depth8.yaml", + "classify": "imagenet100", + "pose": "coco8-pose.yaml", + "obb": "dota128.yaml", +} +TASK2MODEL = { + "detect": "yolo26n.pt", + "segment": "yolo26n-seg.pt", + "semantic": "yolo26n-sem.pt", + "depth": "yolo26n-depth.pt", + "classify": "yolo26n-cls.pt", + "pose": "yolo26n-pose.pt", + "obb": "yolo26n-obb.pt", +} +TASK2METRIC = { + "detect": "metrics/mAP50-95(B)", + "segment": "metrics/mAP50-95(M)", + "semantic": "metrics/mIoU", + "depth": "metrics/delta1", + "classify": "metrics/accuracy_top1", + "pose": "metrics/mAP50-95(P)", + "obb": "metrics/mAP50-95(B)", +} + +ARGV = sys.argv or ["", ""] # sometimes sys.argv = [] +_YOLO_CLI_COMMAND = [sys.executable, "-m", "ultralytics.cfg.__init__"] +SOLUTIONS_HELP_MSG = f""" + Arguments received: {["yolo", *ARGV[1:]]!s}. Ultralytics 'yolo solutions' usage overview: + + yolo solutions SOLUTION ARGS + + Where SOLUTION (optional) is one of {list(SOLUTION_MAP.keys())[:-1]} + ARGS (optional) are any number of custom 'arg=value' pairs like 'show_in=True' that override defaults + at https://docs.ultralytics.com/usage/cfg + + 1. Call object counting solution + yolo solutions count source="path/to/video.mp4" region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]" + + 2. Call heatmap solution + yolo solutions heatmap colormap=cv2.COLORMAP_PARULA model=yolo26n.pt + + 3. Call queue management solution + yolo solutions queue region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]" model=yolo26n.pt + + 4. Call workout monitoring solution for push-ups + yolo solutions workout model=yolo26n-pose.pt kpts=[6, 8, 10] + + 5. Generate analytical graphs + yolo solutions analytics analytics_type="pie" + + 6. Track objects within specific zones + yolo solutions trackzone source="path/to/video.mp4" region="[(150, 150), (1130, 150), (1130, 570), (150, 570)]" + + 7. Count objects inside specific regions + yolo solutions region source="path/to/video.mp4" region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]" + + 8. Run security alarm monitoring (email alerts require Python API) + yolo solutions security source="path/to/video.mp4" + + 9. Monitor parking occupancy (create JSON annotations first via Python ParkingPtsSelection) + yolo solutions parking source="path/to/video.mp4" json_file="bounding_boxes.json" + + 10. Streamlit real-time webcam inference GUI + yolo streamlit-predict + """ +CLI_HELP_MSG = f""" + Arguments received: {["yolo", *ARGV[1:]]!s}. Ultralytics 'yolo' commands use the following syntax: + + yolo TASK MODE ARGS + + Where TASK (optional) is one of {list(TASKS)} + MODE (required) is one of {list(MODES)} + ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults. + See all ARGS at https://docs.ultralytics.com/usage/cfg or with 'yolo cfg' + + 1. Train a detection model for 10 epochs with an initial learning_rate of 0.01 + yolo train data=coco8.yaml model=yolo26n.pt epochs=10 lr0=0.01 + + 2. Predict a YouTube video using a pretrained segmentation model at image size 320: + yolo predict model=yolo26n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320 + + 3. Validate a pretrained detection model at batch-size 1 and image size 640: + yolo val model=yolo26n.pt data=coco8.yaml batch=1 imgsz=640 + + 4. Export a YOLO26n classification model to ONNX format at image size 224 by 128 (no TASK required) + yolo export model=yolo26n-cls.pt format=onnx imgsz=224,128 + + 5. Ultralytics solutions usage + yolo solutions count or any of {list(SOLUTION_MAP.keys())[1:-1]} source="path/to/video.mp4" + + 6. Run special commands: + yolo help + yolo checks + yolo version + yolo settings + yolo login API_KEY + yolo logout + yolo copy-cfg + yolo cfg + yolo solutions help + + Docs: https://docs.ultralytics.com + Platform: https://platform.ultralytics.com + Community: https://community.ultralytics.com + GitHub: https://github.com/ultralytics/ultralytics + """ + +# Quantization aliases: maps any accepted `quantize` value to its canonical form. The common case is the integer +# bit-width 8 (INT8) / 16 (FP16) / 32 (FP32); the verbose wa strings are accepted too and +# collapse to the same ints, except the mixed-precision schemes that have no bit-width shorthand: 'w8a16' (INT8 +# weights + FP16 activations) and 'w8a32' (INT8 weights + FP32 activations, i.e. LiteRT dynamic/weight-only INT8). +QUANTIZE_ALIASES = { + "8": 8, + "16": 16, + "32": 32, + "int8": 8, + "fp16": 16, + "fp32": 32, + "w8a8": 8, + "w16a16": 16, + "w32a32": 32, + "w8a16": "w8a16", + "w8a32": "w8a32", +} +QUANTIZE_DOCS_URL = "https://docs.ultralytics.com/modes/export#quantization-options" +QUANTIZE_VALID_VALUES = "8, 16, 32, 'int8', 'fp16', 'fp32', 'w8a8', 'w16a16', 'w8a16', or 'w8a32'" + +# Define keys for arg type checks +CFG_FLOAT_KEYS = frozenset( + { # integer or float arguments, i.e. x=2 and x=2.0 + "warmup_epochs", + "box", + "cls", + "dfl", + "pose", + "kobj", + "rle", + "angle", + "dlog", + "dgrad", + "dis", + "degrees", + "shear", + "time", + "workspace", + "batch", + } +) +CFG_FRACTION_KEYS = frozenset( + { # fractional floats use [0.0, 1.0]; dataset fraction also accepts positive counts and split pairs + "dropout", + "lr0", + "lrf", + "cls_pw", + "momentum", + "weight_decay", + "warmup_momentum", + "warmup_bias_lr", + "hsv_h", + "hsv_s", + "hsv_v", + "translate", + "perspective", + "flipud", + "fliplr", + "bgr", + "mosaic", + "mixup", + "cutmix", + "copy_paste", + "erasing", + "conf", + "iou", + "fraction", + "multi_scale", + "dlam", + } +) +CFG_INT_KEYS = frozenset( + { # integer-only arguments + "epochs", + "patience", + "workers", + "seed", + "close_mosaic", + "mask_ratio", + "max_det", + "vid_stride", + "line_width", + "nbs", + "save_period", + } +) +CFG_INT_MIN = { # minimum valid values for integer arguments used as counts, divisors, sizes or seeds + "epochs": 1, + "patience": 0, # 0 disables early stopping + "nbs": 1, + "max_det": 1, + "mask_ratio": 1, + "vid_stride": 1, + "seed": 0, +} +CFG_BOOL_KEYS = frozenset( + { # boolean-only arguments + "save", + "exist_ok", + "verbose", + "deterministic", + "single_cls", + "rect", + "cos_lr", + "overlap_mask", + "val", + "save_json", + "dnn", + "plots", + "show", + "save_txt", + "save_conf", + "save_crop", + "save_frames", + "show_labels", + "show_conf", + "visualize", + "augment", + "agnostic_nms", + "retina_masks", + "show_boxes", + "keras", + "optimize", + "dynamic", + "simplify", + "nms", + "profile", + "channels_last", + "cls_remap", + } +) +CFG_STR_KEYS = frozenset({"optimizer", "split", "copy_paste_mode", "auto_augment"}) + + +def cfg2dict(cfg: str | Path | dict | SimpleNamespace) -> dict: + """Convert a configuration object to a dictionary. + + Args: + cfg (str | Path | dict | SimpleNamespace): Configuration object to be converted. Can be a file path, a string, a + dictionary, or a SimpleNamespace object. + + Returns: + (dict): Configuration object in dictionary format. + + Examples: + Convert a YAML file path to a dictionary: + >>> config_dict = cfg2dict("config.yaml") + + Convert a SimpleNamespace to a dictionary: + >>> from types import SimpleNamespace + >>> config_sn = SimpleNamespace(param1="value1", param2="value2") + >>> config_dict = cfg2dict(config_sn) + + Pass through an already existing dictionary: + >>> config_dict = cfg2dict({"param1": "value1", "param2": "value2"}) + + Notes: + - If cfg is a path or string, it's loaded as YAML and converted to a dictionary. + - If cfg is a SimpleNamespace object, it's converted to a dictionary using vars(). + - If cfg is already a dictionary, it's returned unchanged. + """ + if isinstance(cfg, STR_OR_PATH): + cfg = YAML.load(cfg) # load dict + elif isinstance(cfg, SimpleNamespace): + cfg = vars(cfg) # convert to dict + return cfg + + +def get_cfg( + cfg: str | Path | dict | SimpleNamespace = DEFAULT_CFG_DICT, overrides: dict | None = None +) -> SimpleNamespace: + """Load and merge configuration data from a file or dictionary, with optional overrides. + + Args: + cfg (str | Path | dict | SimpleNamespace): Configuration data source. Can be a file path, dictionary, or + SimpleNamespace object. + overrides (dict | None): Dictionary containing key-value pairs to override the base configuration. + + Returns: + (SimpleNamespace): Namespace containing the merged configuration arguments. + + Examples: + >>> from ultralytics.cfg import get_cfg + >>> config = get_cfg() # Load default configuration + >>> config_with_overrides = get_cfg("path/to/config.yaml", overrides={"epochs": 50, "batch": 16}) + + Notes: + - If both `cfg` and `overrides` are provided, the values in `overrides` will take precedence. + - Special handling ensures alignment and correctness of the configuration, such as converting numeric + `project` and `name` to strings and validating configuration keys and values. + - The function performs type and value checks on the configuration data. + """ + cfg = _handle_deprecation(cfg2dict(cfg)) + + # Merge overrides + if overrides: + overrides = cfg2dict(overrides) + check_dict_alignment(cfg, overrides) + cfg = {**cfg, **overrides} # merge cfg and overrides dicts (prefer overrides) + + # Special handling for numeric project/name + for k in "project", "name": + if k in cfg and isinstance(cfg[k], FLOAT_OR_INT): + cfg[k] = str(cfg[k]) + if cfg.get("name") == "model": # assign model to 'name' arg + cfg["name"] = Path(str(cfg.get("model") or "")).stem + LOGGER.warning(f"'name=model' automatically updated to 'name={cfg['name']}'.") + + # Type and Value checks + check_cfg(cfg) + + # Return instance + return IterableSimpleNamespace(**cfg) + + +def check_cfg(cfg: dict, hard: bool = True) -> None: + """Check configuration argument types and values for the Ultralytics library. + + This function validates the types and values of configuration arguments, ensuring correctness and converting them if + necessary. It checks for specific key types defined in global variables such as `CFG_FLOAT_KEYS`, + `CFG_FRACTION_KEYS`, `CFG_INT_KEYS`, and `CFG_BOOL_KEYS`. + + Args: + cfg (dict): Configuration dictionary to validate. + hard (bool): If True, raises exceptions for invalid types and values; if False, attempts to convert them. + + Examples: + >>> config = { + ... "epochs": 50, # valid integer + ... "lr0": 0.01, # valid float + ... "momentum": 0.937, # valid float + ... "save": "true", # invalid bool + ... } + >>> check_cfg(config, hard=False) + >>> print(config) + {'epochs': 50, 'lr0': 0.01, 'momentum': 0.937, 'save': True} + + Notes: + - The function modifies the input dictionary in-place. + - None values are ignored as they may be from optional arguments. + - Fraction keys use [0.0, 1.0]; dataset fraction also accepts counts and [train, val, test] lists. + """ + typed_keys = CFG_FLOAT_KEYS | CFG_FRACTION_KEYS | CFG_INT_KEYS | CFG_BOOL_KEYS | CFG_STR_KEYS | {"scale", "compile"} + for k, v in cfg.items(): + if v is None and ( + k == "amp" or (DEFAULT_CFG_DICT.get(k) is not None and k in typed_keys and k != "auto_augment") + ): + raise TypeError(f"'{k}=None' is invalid. '{k}' must not be None.") + if v is not None: # None values may be from optional args + if k in CFG_FLOAT_KEYS and not isinstance(v, FLOAT_OR_INT): + if hard: + raise TypeError( + f"'{k}={v}' is of invalid type {type(v).__name__}. " + f"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')" + ) + cfg[k] = float(v) + elif k == "scale": + if isinstance(v, (list, tuple)): + if len(v) != 2 or not all(isinstance(x, (int, float)) for x in v): + if hard: + raise TypeError( + f"'{k}={v}' is of invalid type {type(v).__name__}. " + f"Valid '{k}' types are int, float, or a tuple/list of two floats (i.e. '{k}=(0.5, 2.0)')" + ) + continue + continue + elif not isinstance(v, FLOAT_OR_INT): + if hard: + raise TypeError( + f"'{k}={v}' is of invalid type {type(v).__name__}. " + f"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')" + ) + cfg[k] = v = float(v) + if not (0.0 <= v <= 1.0): + raise ValueError(f"'{k}={v}' is an invalid value. Valid '{k}' values are between 0.0 and 1.0.") + elif k in CFG_FRACTION_KEYS: + if k == "fraction" and isinstance(v, list): + if ( + len(v) not in {2, 3} + or not all(v[:2]) + or not all((type(x) is int and x >= 0) or (type(x) is float and 0.0 <= x <= 1.0) for x in v) + ): + raise ValueError(f"'{k}={v}' is invalid. Use [train, val] or [train, val, test] counts/ratios.") + cfg[k] = [float(x) if x in {0, 1} else x for x in v] + continue + if k == "fraction" and isinstance(v, bool): + raise TypeError(f"'{k}={v}' is of invalid type bool. Valid '{k}' types are int, float, or list") + if not isinstance(v, FLOAT_OR_INT): + if hard: + raise TypeError( + f"'{k}={v}' is of invalid type {type(v).__name__}. " + f"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')" + ) + cfg[k] = v = float(v) + valid = 0.0 <= v <= 1.0 or (k == "fraction" and isinstance(v, int) and v > 1) + if not valid or (k == "fraction" and v == 0.0): + raise ValueError(f"'{k}={v}' invalid. Use integer count >1 or ratio (0, 1] for fraction.") + if k == "fraction" and v == 1: + cfg[k] = 1.0 + elif k in CFG_INT_KEYS: + if not isinstance(v, int): + if hard: + raise TypeError( + f"'{k}={v}' is of invalid type {type(v).__name__}. '{k}' must be an int (i.e. '{k}=8')" + ) + cfg[k] = v = int(v) + if k in CFG_INT_MIN and v < CFG_INT_MIN[k]: + raise ValueError(f"'{k}={v}' is an invalid value. '{k}' must be >= {CFG_INT_MIN[k]}.") + elif k in CFG_BOOL_KEYS and not isinstance(v, bool): + if hard: + raise TypeError( + f"'{k}={v}' is of invalid type {type(v).__name__}. " + f"'{k}' must be a bool (i.e. '{k}=True' or '{k}=False')" + ) + cfg[k] = bool(v) + elif k in CFG_STR_KEYS and not isinstance(v, str): + if hard: + raise TypeError(f"'{k}={v}' is of invalid type {type(v).__name__}. '{k}' must be a str.") + cfg[k] = str(v) + elif k == "compile" and not isinstance(v, (bool, str)): # False=off, True="default", or a mode string + if hard: + raise TypeError( + f"'{k}={v}' is of invalid type {type(v).__name__}. " + f"'{k}' must be a bool or str (i.e. '{k}=True' or '{k}=max-autotune')" + ) + cfg[k] = bool(v) + elif k == "amp": + if not isinstance(v, bool) and str(v).lower() not in {"fp16", "bf16", "fp32"}: + raise ValueError( + f"'{k}={v}' is invalid. Valid '{k}' values are True, False, 'fp16', 'bf16', or 'fp32'." + ) + cfg[k] = v.lower() if isinstance(v, str) else v + elif k == "quantize": # canonicalize 8/16/32 or w-notation to a scheme (unset stays None for FP32) + scheme = QUANTIZE_ALIASES.get(str(v).lower()) + if scheme is None: + if hard: + raise ValueError( + f"'{k}={v}' is invalid. Valid '{k}' values are {QUANTIZE_VALID_VALUES}. " + f"See {QUANTIZE_DOCS_URL}" + ) + else: + cfg[k] = scheme + + +def get_save_dir(args: SimpleNamespace, name: str | None = None) -> Path: + """Return the directory path for saving outputs, derived from arguments or default settings. + + Args: + args (SimpleNamespace): Namespace object containing configurations such as 'project', 'name', 'task', 'mode', + and 'save_dir'. + name (str | None): Optional name for the output directory. If not provided, it defaults to 'args.name' or the + 'args.mode'. + + Returns: + (Path): Directory path where outputs should be saved. + + Examples: + >>> from types import SimpleNamespace + >>> args = SimpleNamespace(project="my_project", name="exp", task="detect", mode="train", exist_ok=True) + >>> get_save_dir(args).parts[-3:] + ('detect', 'my_project', 'exp') + """ + if getattr(args, "save_dir", None): + save_dir = args.save_dir + else: + from ultralytics.utils.files import increment_path + + project = args.project or "" + if not Path(project).is_absolute(): + base = ROOT.parent / "tests/tmp/runs" if TESTS_RUNNING else Path(SETTINGS["runs_dir"]) + worker = os.environ.get("PYTEST_XDIST_WORKER") + if worker and TESTS_RUNNING: # isolate parallel pytest-xdist workers + base = base / worker + project = base / args.task / project + name = name or args.name or f"{args.mode}" + save_dir = increment_path(Path(project) / name, exist_ok=args.exist_ok if RANK in {-1, 0} else True) + + return Path(save_dir).resolve() # resolve to display full path in console + + +def _handle_deprecation(custom: dict) -> dict: + """Handle deprecated configuration keys by mapping them to current equivalents with deprecation warnings. + + Args: + custom (dict): Configuration dictionary potentially containing deprecated keys. + + Returns: + (dict): Updated configuration dictionary with deprecated keys replaced. + + Examples: + >>> custom_config = {"boxes": True, "hide_labels": "False", "line_thickness": 2} + >>> _handle_deprecation(custom_config) + {'show_boxes': True, 'show_labels': False, 'line_width': 2} + + Notes: + This function modifies the input dictionary in-place, replacing deprecated keys with their current + equivalents. It also handles value conversions where necessary, such as inverting boolean values for + 'hide_labels' and 'hide_conf'. + """ + deprecated_mappings = { + "boxes": ("show_boxes", lambda v: v), + "hide_labels": ("show_labels", lambda v: not bool(v)), + "hide_conf": ("show_conf", lambda v: not bool(v)), + "line_thickness": ("line_width", lambda v: v), + } + removed_keys = {"label_smoothing", "save_hybrid", "crop_fraction"} + + if "end2end" in custom: + end2end = custom.pop("end2end") + if end2end is not None: + if not isinstance(end2end, bool): + raise TypeError("Deprecated 'end2end' must be a bool.") + custom["nms"] = False if end2end else True if custom.get("nms") is True else None + deprecation_warn(f"end2end={end2end}", f"nms={custom.get('nms')}") + + # Forward the deprecated precision flags onto the unified `quantize` scheme (int8 wins over half). The value is read + # as a bool so quoted/string 'False' disables it while a bare CLI flag (empty string) enables it; an explicit false + # flag maps to None to clear any inherited quantize. An explicit `quantize=` always wins over the legacy flags. + int8 = custom.pop("int8", None) + half = custom.pop("half", None) + if (int8 is not None or half is not None) and "quantize" not in custom: + int8_on = int8 is not None and str(int8).strip().lower() not in {"none", "false", "0"} + half_on = half is not None and str(half).strip().lower() not in {"none", "false", "0"} + custom["quantize"] = 8 if int8_on else 16 if half_on else None # False/0 clears precision back to FP32 + deprecation_warn("int8" if int8 is not None else "half", "quantize") + + for old_key, (new_key, transform) in deprecated_mappings.items(): + if old_key not in custom: + continue + deprecation_warn(old_key, new_key) + custom[new_key] = transform(custom.pop(old_key)) + + for key in removed_keys: + if key not in custom: + continue + deprecation_warn(key) + custom.pop(key) + + return custom + + +def check_dict_alignment( + base: dict, custom: dict, e: Exception | None = None, allowed_custom_keys: set | None = None +) -> None: + """Check alignment between custom and base configuration dictionaries, handling deprecated keys and providing error + messages for mismatched keys. + + Args: + base (dict): The base configuration dictionary containing valid keys. + custom (dict): The custom configuration dictionary to be checked for alignment. + e (Exception | None): Optional error instance passed by the calling function. + allowed_custom_keys (set | None): Optional set of additional keys that are allowed in the custom dictionary. + + Raises: + SyntaxError: If mismatched keys are found between the custom and base dictionaries. + + Examples: + >>> base_cfg = {"epochs": 50, "lr0": 0.01, "batch": 16} + >>> custom_cfg = {"epoch": 100, "lr": 0.02, "batch": 32} + >>> try: + ... check_dict_alignment(base_cfg, custom_cfg) + ... except SyntaxError: + ... print("Mismatched keys found") + Mismatched keys found + + Notes: + - Suggests corrections for mismatched keys based on similarity to valid keys. + - Automatically replaces deprecated keys in the custom configuration with updated equivalents. + - Prints detailed error messages for each mismatched key to help users correct their configurations. + """ + custom = _handle_deprecation(custom) + base_keys, custom_keys = (frozenset(x.keys()) for x in (base, custom)) + # Allow 'augmentations' as a valid custom parameter for custom Albumentations transforms + if allowed_custom_keys is None: + allowed_custom_keys = {"augmentations", "save_dir"} + if mismatched := [k for k in custom_keys if k not in base_keys and k not in allowed_custom_keys]: + from difflib import get_close_matches + + string = "" + for x in mismatched: + matches = get_close_matches(x, base_keys) # key list + matches = [f"{k}={base[k]}" if base.get(k) is not None else k for k in matches] + match_str = f"Similar arguments are i.e. {matches}." if matches else "" + string += f"'{colorstr('red', 'bold', x)}' is not a valid YOLO argument. {match_str}\n" + LOGGER.info(CLI_HELP_MSG) + raise SyntaxError(string) from e + + +def merge_equals_args(args: list[str]) -> list[str]: + """Merge arguments around isolated '=' in a list of strings and join fragments with brackets. + + This function handles the following cases: + 1. ['arg', '=', 'val'] becomes ['arg=val'] + 2. ['arg=', 'val'] becomes ['arg=val'] + 3. ['arg', '=val'] becomes ['arg=val'] + 4. Joins fragments with brackets, e.g., ['imgsz=[3,', '640,', '640]'] becomes ['imgsz=[3,640,640]'] + + Args: + args (list[str]): A list of strings where each element represents an argument or fragment. + + Returns: + (list[str]): A list of strings where the arguments around isolated '=' are merged and fragments with brackets + are joined. + + Examples: + >>> args = ["arg1", "=", "value", "arg2=", "value2", "arg3", "=value3", "imgsz=[3,", "640,", "640]"] + >>> merge_equals_args(args) + ['arg1=value', 'arg2=value2', 'arg3=value3', 'imgsz=[3,640,640]'] + """ + new_args = [] + current = "" + depth = 0 + + i = 0 + while i < len(args): + arg = args[i] + + # Handle equals sign merging + if arg == "=" and 0 < i < len(args) - 1: # merge ['arg', '=', 'val'] + new_args[-1] += f"={args[i + 1]}" + i += 2 + continue + elif arg.endswith("=") and i < len(args) - 1 and "=" not in args[i + 1]: # merge ['arg=', 'val'] + new_args.append(f"{arg}{args[i + 1]}") + i += 2 + continue + elif arg.startswith("=") and i > 0: # merge ['arg', '=val'] + new_args[-1] += arg + i += 1 + continue + + # Handle bracket joining + depth += arg.count("[") - arg.count("]") + current += arg + if depth == 0: + new_args.append(current) + current = "" + + i += 1 + + # Append any remaining current string + if current: + new_args.append(current) + + return new_args + + +def handle_yolo_login(args: list[str]) -> None: + """Log in to Ultralytics Platform with an API key or remove the saved key.""" + if args[0] == "logout": + SETTINGS["api_key"] = "" + LOGGER.info("Logged out ✅. To log in again, use 'yolo login API_KEY'.") + return + + api_key_url = f"{PLATFORM_URL}/settings?tab=api-keys" + if len(args) < 2: + LOGGER.info(f"Get an API key from {api_key_url} and then run 'yolo login API_KEY'.") + return + + from ultralytics import APIConnectionError, APIError, Platform + + try: + with Platform(api_key=args[1], base_url=PLATFORM_URL, timeout=30) as client: + client.account.summary() + SETTINGS["api_key"] = args[1] + LOGGER.info("New authentication successful ✅") + except APIError as error: + raise SystemExit( + "Invalid API key" if error.status_code == 401 else f"Authentication failed (HTTP {error.status_code})" + ) from None + except APIConnectionError as error: + raise SystemExit(f"Authentication request failed, check your connection: {error}") from None + + +def handle_yolo_settings(args: list[str]) -> None: + """Handle YOLO settings command-line interface (CLI) commands. + + This function processes YOLO settings CLI commands such as reset and updating individual settings. It should be + called when executing a script with arguments related to YOLO settings management. + + Args: + args (list[str]): A list of command line arguments for YOLO settings management. + + Examples: + >>> handle_yolo_settings(["reset"]) # Reset YOLO settings + >>> handle_yolo_settings(["runs_dir=path/to/dir"]) # Update a specific setting + + Notes: + - If no arguments are provided, the function will display the current settings. + - The 'reset' command will delete the existing settings file and create new default settings. + - Other arguments are treated as key-value pairs to update specific settings. + - The function will check for alignment between the provided settings and the existing ones. + - After processing, the updated settings will be displayed. + - For more information on handling YOLO settings, visit: + https://docs.ultralytics.com/usage/settings + """ + url = "https://docs.ultralytics.com/usage/settings" # help URL + try: + if any(args): + if args[0] == "reset": + SETTINGS_FILE.unlink() # delete the settings file + SETTINGS.reset() # create new settings + LOGGER.info("Settings reset successfully") # inform the user that settings have been reset + else: # save a new setting + new = dict(parse_key_value_pair(a) for a in args) + check_dict_alignment(SETTINGS, new) + SETTINGS.update(new) + for k, v in new.items(): + LOGGER.info(f"✅ Updated '{k}={v}'") + + LOGGER.info(SETTINGS) # print the current settings + LOGGER.info(f"💡 Learn more about Ultralytics Settings at {url}") + except Exception as e: + LOGGER.warning(f"settings error: '{e}'. Please see {url} for help.") + + +def handle_yolo_solutions(args: list[str]) -> None: + """Process YOLO solutions arguments and run the specified computer vision solutions pipeline. + + Args: + args (list[str]): Command-line arguments for configuring and running the Ultralytics YOLO solutions. + + Examples: + Run people counting solution with default settings: + >>> handle_yolo_solutions(["count"]) + + Run analytics with custom configuration: + >>> handle_yolo_solutions(["analytics", "conf=0.25", "source=path/to/video.mp4"]) + + Run inference with custom configuration, requires Streamlit version 1.29.0 or higher. + >>> handle_yolo_solutions(["inference", "model=yolo26n.pt"]) + + Notes: + - Arguments can be provided in the format 'key=value' or as boolean flags + - Available solutions are defined in SOLUTION_MAP with their respective classes and methods + - If an invalid solution is provided, defaults to 'count' solution + - Output videos are saved in 'runs/solutions/exp' directory + - For 'analytics' solution, frame numbers are tracked for generating analytical graphs + - Video processing can be interrupted by pressing 'q' + - Processes video frames sequentially and saves output in .avi format + - If no source is specified, downloads and uses a default sample video + - The inference solution will be launched using the 'streamlit run' command. + - The Streamlit app file is located in the Ultralytics package directory. + """ + from ultralytics.solutions.config import SolutionConfig + + full_args_dict = vars(SolutionConfig()) # arguments dictionary + overrides = {} + + # check dictionary alignment + for arg in merge_equals_args(args): + arg = arg.lstrip("-").rstrip(",") + if "=" in arg: + try: + k, v = parse_key_value_pair(arg) + overrides[k] = v + except (NameError, SyntaxError, ValueError, AssertionError) as e: + check_dict_alignment(full_args_dict, {arg: ""}, e) + elif arg in full_args_dict and isinstance(full_args_dict.get(arg), bool): + overrides[arg] = True + check_dict_alignment(full_args_dict, overrides) # dict alignment + + # Get solution name + if not args: + LOGGER.warning("No solution name provided. i.e `yolo solutions count`. Defaulting to 'count'.") + args = ["count"] + if args[0] == "help": + LOGGER.info(SOLUTIONS_HELP_MSG) + return # Early return for 'help' case + elif args[0] in SOLUTION_MAP: + solution_name = args.pop(0) # Extract the solution name directly + else: + LOGGER.warning( + f"❌ '{args[0]}' is not a valid solution. 💡 Defaulting to 'count'.\n" + f"🚀 Available solutions: {', '.join(list(SOLUTION_MAP.keys())[:-1])}\n" + ) + solution_name = "count" # Default for invalid solution + + if solution_name == "inference": + checks.check_requirements("streamlit>=1.29.0") + LOGGER.info("💡 Loading Ultralytics live inference app...") + subprocess.run( + [ # Run subprocess with Streamlit custom argument + "streamlit", + "run", + str(ROOT / "solutions/streamlit_inference.py"), + "--server.headless", + "true", + overrides.pop("model", "yolo26n.pt"), + ], + check=False, + ) + else: + import cv2 # Only needed for cap and vw functionality + + from ultralytics import solutions + + solution = getattr(solutions, SOLUTION_MAP[solution_name])(is_cli=True, **overrides) # class i.e. ObjectCounter + + cap = cv2.VideoCapture(solution.CFG["source"]) # read the video file + if solution_name != "crop": + # extract width, height and fps of the video file, create save directory and initialize video writer + w, h, fps = ( + int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS) + ) + if solution_name == "analytics": # analytical graphs follow fixed shape for output i.e w=1280, h=720 + w, h = 1280, 720 + save_dir = get_save_dir(SimpleNamespace(task="solutions", name="exp", exist_ok=False, project=None)) + save_dir.mkdir(parents=True, exist_ok=True) # create the output directory i.e. runs/solutions/exp + vw = cv2.VideoWriter(str(save_dir / f"{solution_name}.avi"), cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h)) + + try: # Process video frames + f_n = 0 # frame number, required for analytical graphs + while cap.isOpened(): + success, frame = cap.read() + if not success: + break + results = solution(frame, f_n := f_n + 1) if solution_name == "analytics" else solution(frame) + if solution_name != "crop": + vw.write(results.plot_im) + if solution.CFG["show"] and cv2.waitKey(1) & 0xFF == ord("q"): + break + finally: + cap.release() + + +def parse_key_value_pair(pair: str = "key=value") -> tuple: + """Parse a key-value pair string into separate key and value components. + + Args: + pair (str): A string containing a key-value pair in the format "key=value". + + Returns: + key (str): The parsed key. + value (str): The parsed value. + + Raises: + AssertionError: If the value is missing or empty. + + Examples: + >>> key, value = parse_key_value_pair("model=yolo26n.pt") + >>> print(f"Key: {key}, Value: {value}") + Key: model, Value: yolo26n.pt + + >>> key, value = parse_key_value_pair("epochs=100") + >>> print(f"Key: {key}, Value: {value}") + Key: epochs, Value: 100 + + Notes: + - The function splits the input string on the first '=' character. + - Leading and trailing whitespace is removed from both key and value. + - An assertion error is raised if the value is empty after stripping. + """ + k, v = pair.split("=", 1) # split on first '=' sign + k, v = k.strip(), v.strip() # remove spaces + assert v, f"missing '{k}' value" + return k, smart_value(v) + + +def smart_value(v: str) -> Any: + """Convert a string representation of a value to its appropriate Python type. + + This function attempts to convert a given string into a Python object of the most appropriate type. It handles + conversions to None, bool, int, float, and other types that can be evaluated safely. + + Args: + v (str): The string representation of the value to be converted. + + Returns: + (Any): The converted value. The type can be None, bool, int, float, or the original string if no conversion is + applicable. + + Examples: + >>> smart_value("42") + 42 + >>> smart_value("3.14") + 3.14 + >>> smart_value("True") + True + >>> print(smart_value("None")) + None + >>> smart_value("some_string") + 'some_string' + + Notes: + - The function uses a case-insensitive comparison for boolean and None values. + - For other types, it attempts to use Python's ast.literal_eval() function for safe evaluation. + - If no conversion is possible, the original string is returned. + """ + v_lower = v.lower() + if v_lower == "none": + return None + elif v_lower == "true": + return True + elif v_lower == "false": + return False + else: + try: + return ast.literal_eval(v) + except Exception: + name, _, attr = v.rpartition(".") + if (module := sys.modules.get(name)) and attr.isupper(): + value = getattr(module, attr, None) + if isinstance(value, (int, float)): + return value + return v + + +def entrypoint(debug: str = "") -> None: + """Ultralytics entrypoint function for parsing and executing command-line arguments. + + This function serves as the main entry point for the Ultralytics CLI, parsing command-line arguments and executing + the corresponding tasks such as training, validation, prediction, exporting models, and more. + + Args: + debug (str): Space-separated string of command-line arguments for debugging purposes. + + Examples: + Train a detection model for 10 epochs with an initial learning_rate of 0.01: + >>> entrypoint("train data=coco8.yaml model=yolo26n.pt epochs=10 lr0=0.01") + + Predict a YouTube video using a pretrained segmentation model at image size 320: + >>> entrypoint("predict model=yolo26n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320") + + Validate a pretrained detection model at batch-size 1 and image size 640: + >>> entrypoint("val model=yolo26n.pt data=coco8.yaml batch=1 imgsz=640") + + Notes: + - If no arguments are passed, the function will display the usage help message. + - For a list of all available commands and their arguments, see the provided help messages and the + Ultralytics documentation at https://docs.ultralytics.com. + """ + args = (debug.split(" ") if debug else ARGV)[1:] + if not args: # no arguments passed + LOGGER.info(CLI_HELP_MSG) + return + + special = { + "checks": checks.collect_system_info, + "version": lambda: LOGGER.info(__version__), + "settings": lambda: handle_yolo_settings(args[1:]), + "cfg": lambda: YAML.print(DEFAULT_CFG_PATH), + "login": lambda: handle_yolo_login(args), + "logout": lambda: handle_yolo_login(args), + "copy-cfg": copy_default_cfg, + "solutions": lambda: handle_yolo_solutions(args[1:]), + "help": lambda: LOGGER.info(CLI_HELP_MSG), + } + full_args_dict = {**DEFAULT_CFG_DICT, **{k: None for k in TASKS}, **{k: None for k in MODES}, **special} + + # Define common misuses of special commands, i.e. -h, -help, --help + special.update({k[0]: v for k, v in special.items()}) # singular + special.update({k[:-1]: v for k, v in special.items() if len(k) > 1 and k.endswith("s")}) # singular + special = {**special, **{f"-{k}": v for k, v in special.items()}, **{f"--{k}": v for k, v in special.items()}} + + overrides = {} # basic overrides, i.e. imgsz=320 + for a in merge_equals_args(args): # merge spaces around '=' sign + if a.startswith("--"): + LOGGER.warning(f"argument '{a}' does not require leading dashes '--', updating to '{a[2:]}'.") + a = a[2:] + if a.endswith(","): + LOGGER.warning(f"argument '{a}' does not require trailing comma ',', updating to '{a[:-1]}'.") + a = a[:-1] + if "=" in a: + try: + k, v = parse_key_value_pair(a) + if k == "cfg" and v is not None: # custom.yaml passed + LOGGER.info(f"Overriding {DEFAULT_CFG_PATH} with {v}") + overrides = { + **{k: val for k, val in YAML.load(checks.check_yaml(v)).items() if k != "cfg"}, + **overrides, + } + else: + overrides[k] = v + except (NameError, SyntaxError, ValueError, AssertionError) as e: + check_dict_alignment(full_args_dict, {a: ""}, e) + + elif a in TASKS: + overrides["task"] = a + elif a in MODES: + overrides["mode"] = a + elif a.lower() in special: + special[a.lower()]() + return + elif a in DEFAULT_CFG_DICT and isinstance(DEFAULT_CFG_DICT[a], bool): + overrides[a] = True # auto-True for default bool args, i.e. 'yolo show' sets show=True + elif a in {"half", "int8", "end2end", "nms"}: + overrides[a] = True # bare boolean flags whose defaults are missing or None + elif a in DEFAULT_CFG_DICT: + raise SyntaxError( + f"'{colorstr('red', 'bold', a)}' is a valid YOLO argument but is missing an '=' sign " + f"to set its value, i.e. try '{a}={DEFAULT_CFG_DICT[a]}'\n{CLI_HELP_MSG}" + ) + else: + check_dict_alignment(full_args_dict, {a: ""}) + + # Check keys + check_dict_alignment(full_args_dict, overrides) + + # Mode + mode = overrides.get("mode") + if mode is None: + mode = DEFAULT_CFG.mode or "predict" + LOGGER.warning(f"'mode' argument is missing. Valid modes are {list(MODES)}. Using default 'mode={mode}'.") + elif mode not in MODES: + raise ValueError(f"Invalid 'mode={mode}'. Valid modes are {list(MODES)}.\n{CLI_HELP_MSG}") + + # Task + task = overrides.pop("task", None) + if task: + if task not in TASKS: + if task == "track": + LOGGER.warning( + f"invalid 'task=track', setting 'task=detect' and 'mode=track'. Valid tasks are {list(TASKS)}.\n{CLI_HELP_MSG}." + ) + task, mode = "detect", "track" + else: + raise ValueError(f"Invalid 'task={task}'. Valid tasks are {list(TASKS)}.\n{CLI_HELP_MSG}") + if "model" not in overrides: + overrides["model"] = TASK2MODEL[task] + + # Model + model = overrides.pop("model", DEFAULT_CFG.model) + if model is None: + model = "yolo26n.pt" + LOGGER.warning(f"'model' argument is missing. Using default 'model={model}'.") + overrides["model"] = model + stem = Path(model).stem.lower() + if "rtdetr" in stem: # guess architecture + from ultralytics import RTDETR + + model = RTDETR(model) # no task argument + elif "fastsam" in stem: + from ultralytics import FastSAM + + model = FastSAM(model) + elif "sam_" in stem or "sam2_" in stem or "sam2.1_" in stem: + from ultralytics import SAM + + model = SAM(model) + else: + from ultralytics import YOLO + + model = YOLO(model, task=task) + if "yoloe" in stem or "world" in stem: + cls_list = overrides.get("classes", DEFAULT_CFG.classes) + if isinstance(cls_list, str): # text prompts, i.e. "person, bus" -> ['person', 'bus'] + model.set_classes([c.strip() for c in overrides.pop("classes", cls_list).split(",")]) + # Task Update + if task != model.task: + if task: + LOGGER.warning( + f"conflicting 'task={task}' passed with 'task={model.task}' model. " + f"Ignoring 'task={task}' and updating to 'task={model.task}' to match model." + ) + task = model.task + + # Mode + if mode in {"predict", "track"} and "source" not in overrides: + overrides["source"] = ( + "https://ultralytics.com/images/boats.jpg" if task == "obb" else DEFAULT_CFG.source or ASSETS + ) + LOGGER.warning(f"'source' argument is missing. Using default 'source={overrides['source']}'.") + elif mode == "train": # val resolves a missing 'data' in Model.val() + if overrides.get("data") is None and not overrides.get("resume"): + overrides["data"] = DEFAULT_CFG.data or TASK2DATA.get(task or DEFAULT_CFG.task, DEFAULT_CFG.data) + LOGGER.warning(f"'data' argument is missing. Using default 'data={overrides['data']}'.") + elif mode == "export": + if "format" not in overrides: + overrides["format"] = DEFAULT_CFG.format or "torchscript" + LOGGER.warning(f"'format' argument is missing. Using default 'format={overrides['format']}'.") + + # Run command in python + getattr(model, mode)(**overrides) # default args from model + + # Show help + LOGGER.info(f"💡 Learn more at https://docs.ultralytics.com/modes/{mode}") + + # Recommend VS Code extension + if IS_VSCODE and SETTINGS.get("vscode_msg", True): + LOGGER.info(vscode_msg()) + + +# Special modes -------------------------------------------------------------------------------------------------------- +def copy_default_cfg() -> None: + """Copy the default configuration file and create a new one with '_copy' appended to its name. + + This function duplicates the existing default configuration file (DEFAULT_CFG_PATH) and saves it with '_copy' + appended to its name in the current working directory. It provides a convenient way to create a custom configuration + file based on the default settings. + + Examples: + >>> copy_default_cfg() + + Notes: + - The new configuration file is created in the current working directory. + - After copying, the function prints a message with the new file's location and an example + YOLO command demonstrating how to use the new configuration file. + - This function is useful for users who want to modify the default configuration without + altering the original file. + """ + new_file = Path.cwd() / DEFAULT_CFG_PATH.name.replace(".yaml", "_copy.yaml") + shutil.copy2(DEFAULT_CFG_PATH, new_file) + LOGGER.info( + f"{DEFAULT_CFG_PATH} copied to {new_file}\n" + f"Example YOLO command with this new custom cfg:\n yolo cfg='{new_file}' imgsz=320 batch=8" + ) + + +if __name__ == "__main__": + # Example: entrypoint(debug='yolo predict model=yolo26n.pt') + entrypoint(debug="") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/cfg/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af2305748ed02add097d7a3ac0f8995e1f013428 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/cfg/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/Argoverse.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/Argoverse.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b0cac72a4ab85a5cb4621b1d07246020d1da3686 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/Argoverse.yaml @@ -0,0 +1,78 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Argoverse-HD dataset (ring-front-center camera) by Argo AI: https://www.cs.cmu.edu/~mengtial/proj/streaming/ +# Documentation: https://docs.ultralytics.com/datasets/detect/argoverse +# Example usage: yolo train data=Argoverse.yaml +# parent +# ├── ultralytics +# └── datasets +# └── Argoverse ← downloads here (31.5 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: Argoverse # dataset root dir +train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images +val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images +test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview + +# Classes +names: + 0: person + 1: bicycle + 2: car + 3: motorcycle + 4: bus + 5: truck + 6: traffic_light + 7: stop_sign + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + import json + from pathlib import Path + + from ultralytics.utils import TQDM + from ultralytics.utils.downloads import download + + def argoverse2yolo(annotation_file): + """Convert Argoverse dataset annotations to YOLO format for object detection tasks.""" + labels = {} + with open(annotation_file, encoding="utf-8") as f: + a = json.load(f) + for annot in TQDM(a["annotations"], desc=f"Converting {annotation_file} to YOLO format..."): + img_id = annot["image_id"] + img_name = a["images"][img_id]["name"] + img_label_name = f"{Path(img_name).stem}.txt" + + cls = annot["category_id"] # instance class id + x_center, y_center, width, height = annot["bbox"] + x_center = (x_center + width / 2) / 1920.0 # offset and scale + y_center = (y_center + height / 2) / 1200.0 # offset and scale + width /= 1920.0 # scale + height /= 1200.0 # scale + + img_dir = annotation_file.parents[2] / "Argoverse-1.1" / "labels" / a["seq_dirs"][a["images"][annot["image_id"]]["sid"]] + if not img_dir.exists(): + img_dir.mkdir(parents=True, exist_ok=True) + + k = str(img_dir / img_label_name) + if k not in labels: + labels[k] = [] + labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n") + + for k in labels: + with open(k, "w", encoding="utf-8") as f: + f.writelines(labels[k]) + + + # Download 'https://argoverse-hd.s3.amazonaws.com/Argoverse-HD-Full.zip' (deprecated S3 link) + dir = Path(yaml["path"]) # dataset root dir + urls = ["https://drive.google.com/file/d/1st9qW3BeIwQsnR0t8mRpvbsSWIo16ACi/view?usp=drive_link"] + print("\n\nWARNING: Argoverse dataset MUST be downloaded manually, autodownload will NOT work.") + print(f"WARNING: Manually download Argoverse dataset '{urls[0]}' to '{dir}' and re-run your command.\n\n") + # download(urls, dir=dir) + + # Convert + annotations_dir = "Argoverse-HD/annotations/" + (dir / "Argoverse-1.1" / "tracking").rename(dir / "Argoverse-1.1" / "images") # rename 'tracking' to 'images' + for d in "train.json", "val.json": + argoverse2yolo(dir / annotations_dir / d) # convert Argoverse annotations to YOLO labels diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/DOTAv1.5.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/DOTAv1.5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b22d796f2153b0708504e743d25a48a13e54630f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/DOTAv1.5.yaml @@ -0,0 +1,37 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# DOTA 1.5 dataset https://captain-whu.github.io/DOTA/index.html for object detection in aerial images by Wuhan University +# Documentation: https://docs.ultralytics.com/datasets/obb/dota-v2 +# Example usage: yolo train model=yolov8n-obb.pt data=DOTAv1.5.yaml +# parent +# ├── ultralytics +# └── datasets +# └── DOTAv1.5 ← downloads here (2 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: DOTAv1.5 # dataset root dir +train: images/train # train images (relative to 'path') 1411 images +val: images/val # val images (relative to 'path') 458 images +test: images/test # test images (optional) 937 images + +# Classes for DOTA 1.5 +names: + 0: plane + 1: ship + 2: storage tank + 3: baseball diamond + 4: tennis court + 5: basketball court + 6: ground track field + 7: harbor + 8: bridge + 9: large vehicle + 10: small vehicle + 11: helicopter + 12: roundabout + 13: soccer ball field + 14: swimming pool + 15: container crane + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/DOTAv1.5.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/DOTAv1.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/DOTAv1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dad87436d88a420598c86488944bb88a48302ef9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/DOTAv1.yaml @@ -0,0 +1,36 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# DOTA 1.0 dataset https://captain-whu.github.io/DOTA/index.html for object detection in aerial images by Wuhan University +# Documentation: https://docs.ultralytics.com/datasets/obb/dota-v2 +# Example usage: yolo train model=yolov8n-obb.pt data=DOTAv1.yaml +# parent +# ├── ultralytics +# └── datasets +# └── DOTAv1 ← downloads here (2 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: DOTAv1 # dataset root dir +train: images/train # train images (relative to 'path') 1411 images +val: images/val # val images (relative to 'path') 458 images +test: images/test # test images (optional) 937 images + +# Classes for DOTA 1.0 +names: + 0: plane + 1: ship + 2: storage tank + 3: baseball diamond + 4: tennis court + 5: basketball court + 6: ground track field + 7: harbor + 8: bridge + 9: large vehicle + 10: small vehicle + 11: helicopter + 12: roundabout + 13: soccer ball field + 14: swimming pool + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/DOTAv1.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/GlobalWheat2020.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/GlobalWheat2020.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ab70f1a5952ae13fa47053b30400e79cc01ec163 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/GlobalWheat2020.yaml @@ -0,0 +1,68 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Global Wheat 2020 dataset https://www.global-wheat.com/ by University of Saskatchewan +# Documentation: https://docs.ultralytics.com/datasets/detect/globalwheat2020 +# Example usage: yolo train data=GlobalWheat2020.yaml +# parent +# ├── ultralytics +# └── datasets +# └── GlobalWheat2020 ← downloads here (7.0 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: GlobalWheat2020 # dataset root dir +train: # train images (relative to 'path') 3422 images + - images/arvalis_1 + - images/arvalis_2 + - images/arvalis_3 + - images/ethz_1 + - images/rres_1 + - images/inrae_1 + - images/usask_1 +val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1) + - images/ethz_1 +test: # test images (optional) 1276 images + - images/utokyo_1 + - images/utokyo_2 + - images/nau_1 + - images/uq_1 + +# Classes +names: + 0: wheat_head + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + from pathlib import Path + + from ultralytics.utils.downloads import download + + # Download + dir = Path(yaml["path"]) # dataset root dir + urls = [ + "https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip", + "https://github.com/ultralytics/assets/releases/download/v0.0.0/GlobalWheat2020_labels.zip", + ] + download(urls, dir=dir) + + # Make Directories + for p in "annotations", "images", "labels": + (dir / p).mkdir(parents=True, exist_ok=True) + + # Move + for p in ( + "arvalis_1", + "arvalis_2", + "arvalis_3", + "ethz_1", + "rres_1", + "inrae_1", + "usask_1", + "utokyo_1", + "utokyo_2", + "nau_1", + "uq_1", + ): + (dir / "global-wheat-codalab-official" / p).rename(dir / "images" / p) # move to /images + f = (dir / "global-wheat-codalab-official" / p).with_suffix(".json") # json file + if f.exists(): + f.rename((dir / "annotations" / p).with_suffix(".json")) # move to /annotations diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/HomeObjects-3K.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/HomeObjects-3K.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6e66bfeeb12a25ab72da536d7e41bfdcc61a0baf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/HomeObjects-3K.yaml @@ -0,0 +1,32 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# HomeObjects-3K dataset by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/detect/homeobjects-3k +# Example usage: yolo train data=HomeObjects-3K.yaml +# parent +# ├── ultralytics +# └── datasets +# └── homeobjects-3K ← downloads here (390 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: homeobjects-3K # dataset root dir +train: images/train # train images (relative to 'path') 2285 images +val: images/val # val images (relative to 'path') 404 images + +# Classes +names: + 0: bed + 1: sofa + 2: chair + 3: table + 4: lamp + 5: tv + 6: laptop + 7: wardrobe + 8: window + 9: door + 10: potted plant + 11: photo frame + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/homeobjects-3K.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/ImageNet.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/ImageNet.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e52b063d7ca37225ed3e48e44a24b3b189fc8553 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/ImageNet.yaml @@ -0,0 +1,2025 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# ImageNet-1k dataset https://www.image-net.org/index.php by Stanford University +# Simplified class names from https://github.com/anishathalye/imagenet-simple-labels +# Documentation: https://docs.ultralytics.com/datasets/classify/imagenet +# Example usage: yolo train task=classify data=imagenet +# parent +# ├── ultralytics +# └── datasets +# └── imagenet ← downloads here (144 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: imagenet # dataset root dir +train: train # train images (relative to 'path') 1281167 images +val: val # val images (relative to 'path') 50000 images +test: # test images (optional) + +# Classes +names: + 0: tench + 1: goldfish + 2: great white shark + 3: tiger shark + 4: hammerhead shark + 5: electric ray + 6: stingray + 7: cock + 8: hen + 9: ostrich + 10: brambling + 11: goldfinch + 12: house finch + 13: junco + 14: indigo bunting + 15: American robin + 16: bulbul + 17: jay + 18: magpie + 19: chickadee + 20: American dipper + 21: kite + 22: bald eagle + 23: vulture + 24: great grey owl + 25: fire salamander + 26: smooth newt + 27: newt + 28: spotted salamander + 29: axolotl + 30: American bullfrog + 31: tree frog + 32: tailed frog + 33: loggerhead sea turtle + 34: leatherback sea turtle + 35: mud turtle + 36: terrapin + 37: box turtle + 38: banded gecko + 39: green iguana + 40: Carolina anole + 41: desert grassland whiptail lizard + 42: agama + 43: frilled-necked lizard + 44: alligator lizard + 45: Gila monster + 46: European green lizard + 47: chameleon + 48: Komodo dragon + 49: Nile crocodile + 50: American alligator + 51: triceratops + 52: worm snake + 53: ring-necked snake + 54: eastern hog-nosed snake + 55: smooth green snake + 56: kingsnake + 57: garter snake + 58: water snake + 59: vine snake + 60: night snake + 61: boa constrictor + 62: African rock python + 63: Indian cobra + 64: green mamba + 65: sea snake + 66: Saharan horned viper + 67: eastern diamondback rattlesnake + 68: sidewinder + 69: trilobite + 70: harvestman + 71: scorpion + 72: yellow garden spider + 73: barn spider + 74: European garden spider + 75: southern black widow + 76: tarantula + 77: wolf spider + 78: tick + 79: centipede + 80: black grouse + 81: ptarmigan + 82: ruffed grouse + 83: prairie grouse + 84: peacock + 85: quail + 86: partridge + 87: grey parrot + 88: macaw + 89: sulphur-crested cockatoo + 90: lorikeet + 91: coucal + 92: bee eater + 93: hornbill + 94: hummingbird + 95: jacamar + 96: toucan + 97: duck + 98: red-breasted merganser + 99: goose + 100: black swan + 101: tusker + 102: echidna + 103: platypus + 104: wallaby + 105: koala + 106: wombat + 107: jellyfish + 108: sea anemone + 109: brain coral + 110: flatworm + 111: nematode + 112: conch + 113: snail + 114: slug + 115: sea slug + 116: chiton + 117: chambered nautilus + 118: Dungeness crab + 119: rock crab + 120: fiddler crab + 121: red king crab + 122: American lobster + 123: spiny lobster + 124: crayfish + 125: hermit crab + 126: isopod + 127: white stork + 128: black stork + 129: spoonbill + 130: flamingo + 131: little blue heron + 132: great egret + 133: bittern + 134: crane (bird) + 135: limpkin + 136: common gallinule + 137: American coot + 138: bustard + 139: ruddy turnstone + 140: dunlin + 141: common redshank + 142: dowitcher + 143: oystercatcher + 144: pelican + 145: king penguin + 146: albatross + 147: grey whale + 148: killer whale + 149: dugong + 150: sea lion + 151: Chihuahua + 152: Japanese Chin + 153: Maltese + 154: Pekingese + 155: Shih Tzu + 156: King Charles Spaniel + 157: Papillon + 158: toy terrier + 159: Rhodesian Ridgeback + 160: Afghan Hound + 161: Basset Hound + 162: Beagle + 163: Bloodhound + 164: Bluetick Coonhound + 165: Black and Tan Coonhound + 166: Treeing Walker Coonhound + 167: English foxhound + 168: Redbone Coonhound + 169: borzoi + 170: Irish Wolfhound + 171: Italian Greyhound + 172: Whippet + 173: Ibizan Hound + 174: Norwegian Elkhound + 175: Otterhound + 176: Saluki + 177: Scottish Deerhound + 178: Weimaraner + 179: Staffordshire Bull Terrier + 180: American Staffordshire Terrier + 181: Bedlington Terrier + 182: Border Terrier + 183: Kerry Blue Terrier + 184: Irish Terrier + 185: Norfolk Terrier + 186: Norwich Terrier + 187: Yorkshire Terrier + 188: Wire Fox Terrier + 189: Lakeland Terrier + 190: Sealyham Terrier + 191: Airedale Terrier + 192: Cairn Terrier + 193: Australian Terrier + 194: Dandie Dinmont Terrier + 195: Boston Terrier + 196: Miniature Schnauzer + 197: Giant Schnauzer + 198: Standard Schnauzer + 199: Scottish Terrier + 200: Tibetan Terrier + 201: Australian Silky Terrier + 202: Soft-coated Wheaten Terrier + 203: West Highland White Terrier + 204: Lhasa Apso + 205: Flat-Coated Retriever + 206: Curly-coated Retriever + 207: Golden Retriever + 208: Labrador Retriever + 209: Chesapeake Bay Retriever + 210: German Shorthaired Pointer + 211: Vizsla + 212: English Setter + 213: Irish Setter + 214: Gordon Setter + 215: Brittany + 216: Clumber Spaniel + 217: English Springer Spaniel + 218: Welsh Springer Spaniel + 219: Cocker Spaniels + 220: Sussex Spaniel + 221: Irish Water Spaniel + 222: Kuvasz + 223: Schipperke + 224: Groenendael + 225: Malinois + 226: Briard + 227: Australian Kelpie + 228: Komondor + 229: Old English Sheepdog + 230: Shetland Sheepdog + 231: collie + 232: Border Collie + 233: Bouvier des Flandres + 234: Rottweiler + 235: German Shepherd Dog + 236: Dobermann + 237: Miniature Pinscher + 238: Greater Swiss Mountain Dog + 239: Bernese Mountain Dog + 240: Appenzeller Sennenhund + 241: Entlebucher Sennenhund + 242: Boxer + 243: Bullmastiff + 244: Tibetan Mastiff + 245: French Bulldog + 246: Great Dane + 247: St. Bernard + 248: husky + 249: Alaskan Malamute + 250: Siberian Husky + 251: Dalmatian + 252: Affenpinscher + 253: Basenji + 254: pug + 255: Leonberger + 256: Newfoundland + 257: Pyrenean Mountain Dog + 258: Samoyed + 259: Pomeranian + 260: Chow Chow + 261: Keeshond + 262: Griffon Bruxellois + 263: Pembroke Welsh Corgi + 264: Cardigan Welsh Corgi + 265: Toy Poodle + 266: Miniature Poodle + 267: Standard Poodle + 268: Mexican hairless dog + 269: grey wolf + 270: Alaskan tundra wolf + 271: red wolf + 272: coyote + 273: dingo + 274: dhole + 275: African wild dog + 276: hyena + 277: red fox + 278: kit fox + 279: Arctic fox + 280: grey fox + 281: tabby cat + 282: tiger cat + 283: Persian cat + 284: Siamese cat + 285: Egyptian Mau + 286: cougar + 287: lynx + 288: leopard + 289: snow leopard + 290: jaguar + 291: lion + 292: tiger + 293: cheetah + 294: brown bear + 295: American black bear + 296: polar bear + 297: sloth bear + 298: mongoose + 299: meerkat + 300: tiger beetle + 301: ladybug + 302: ground beetle + 303: longhorn beetle + 304: leaf beetle + 305: dung beetle + 306: rhinoceros beetle + 307: weevil + 308: fly + 309: bee + 310: ant + 311: grasshopper + 312: cricket + 313: stick insect + 314: cockroach + 315: mantis + 316: cicada + 317: leafhopper + 318: lacewing + 319: dragonfly + 320: damselfly + 321: red admiral + 322: ringlet + 323: monarch butterfly + 324: small white + 325: sulfur butterfly + 326: gossamer-winged butterfly + 327: starfish + 328: sea urchin + 329: sea cucumber + 330: cottontail rabbit + 331: hare + 332: Angora rabbit + 333: hamster + 334: porcupine + 335: fox squirrel + 336: marmot + 337: beaver + 338: guinea pig + 339: common sorrel + 340: zebra + 341: pig + 342: wild boar + 343: warthog + 344: hippopotamus + 345: ox + 346: water buffalo + 347: bison + 348: ram + 349: bighorn sheep + 350: Alpine ibex + 351: hartebeest + 352: impala + 353: gazelle + 354: dromedary + 355: llama + 356: weasel + 357: mink + 358: European polecat + 359: black-footed ferret + 360: otter + 361: skunk + 362: badger + 363: armadillo + 364: three-toed sloth + 365: orangutan + 366: gorilla + 367: chimpanzee + 368: gibbon + 369: siamang + 370: guenon + 371: patas monkey + 372: baboon + 373: macaque + 374: langur + 375: black-and-white colobus + 376: proboscis monkey + 377: marmoset + 378: white-headed capuchin + 379: howler monkey + 380: titi + 381: Geoffroy's spider monkey + 382: common squirrel monkey + 383: ring-tailed lemur + 384: indri + 385: Asian elephant + 386: African bush elephant + 387: red panda + 388: giant panda + 389: snoek + 390: eel + 391: coho salmon + 392: rock beauty + 393: clownfish + 394: sturgeon + 395: garfish + 396: lionfish + 397: pufferfish + 398: abacus + 399: abaya + 400: academic gown + 401: accordion + 402: acoustic guitar + 403: aircraft carrier + 404: airliner + 405: airship + 406: altar + 407: ambulance + 408: amphibious vehicle + 409: analog clock + 410: apiary + 411: apron + 412: waste container + 413: assault rifle + 414: backpack + 415: bakery + 416: balance beam + 417: balloon + 418: ballpoint pen + 419: Band-Aid + 420: banjo + 421: baluster + 422: barbell + 423: barber chair + 424: barbershop + 425: barn + 426: barometer + 427: barrel + 428: wheelbarrow + 429: baseball + 430: basketball + 431: bassinet + 432: bassoon + 433: swimming cap + 434: bath towel + 435: bathtub + 436: station wagon + 437: lighthouse + 438: beaker + 439: military cap + 440: beer bottle + 441: beer glass + 442: bell-cot + 443: bib + 444: tandem bicycle + 445: bikini + 446: ring binder + 447: binoculars + 448: birdhouse + 449: boathouse + 450: bobsleigh + 451: bolo tie + 452: poke bonnet + 453: bookcase + 454: bookstore + 455: bottle cap + 456: bow + 457: bow tie + 458: brass + 459: bra + 460: breakwater + 461: breastplate + 462: broom + 463: bucket + 464: buckle + 465: bulletproof vest + 466: high-speed train + 467: butcher shop + 468: taxicab + 469: cauldron + 470: candle + 471: cannon + 472: canoe + 473: can opener + 474: cardigan + 475: car mirror + 476: carousel + 477: tool kit + 478: carton + 479: car wheel + 480: automated teller machine + 481: cassette + 482: cassette player + 483: castle + 484: catamaran + 485: CD player + 486: cello + 487: mobile phone + 488: chain + 489: chain-link fence + 490: chain mail + 491: chainsaw + 492: chest + 493: chiffonier + 494: chime + 495: china cabinet + 496: Christmas stocking + 497: church + 498: movie theater + 499: cleaver + 500: cliff dwelling + 501: cloak + 502: clogs + 503: cocktail shaker + 504: coffee mug + 505: coffeemaker + 506: coil + 507: combination lock + 508: computer keyboard + 509: confectionery store + 510: container ship + 511: convertible + 512: corkscrew + 513: cornet + 514: cowboy boot + 515: cowboy hat + 516: cradle + 517: crane (machine) + 518: crash helmet + 519: crate + 520: infant bed + 521: Crock Pot + 522: croquet ball + 523: crutch + 524: cuirass + 525: dam + 526: desk + 527: desktop computer + 528: rotary dial telephone + 529: diaper + 530: digital clock + 531: digital watch + 532: dining table + 533: dishcloth + 534: dishwasher + 535: disc brake + 536: dock + 537: dog sled + 538: dome + 539: doormat + 540: drilling rig + 541: drum + 542: drumstick + 543: dumbbell + 544: Dutch oven + 545: electric fan + 546: electric guitar + 547: electric locomotive + 548: entertainment center + 549: envelope + 550: espresso machine + 551: face powder + 552: feather boa + 553: filing cabinet + 554: fireboat + 555: fire engine + 556: fire screen sheet + 557: flagpole + 558: flute + 559: folding chair + 560: football helmet + 561: forklift + 562: fountain + 563: fountain pen + 564: four-poster bed + 565: freight car + 566: French horn + 567: frying pan + 568: fur coat + 569: garbage truck + 570: gas mask + 571: gas pump + 572: goblet + 573: go-kart + 574: golf ball + 575: golf cart + 576: gondola + 577: gong + 578: gown + 579: grand piano + 580: greenhouse + 581: grille + 582: grocery store + 583: guillotine + 584: barrette + 585: hair spray + 586: half-track + 587: hammer + 588: hamper + 589: hair dryer + 590: hand-held computer + 591: handkerchief + 592: hard disk drive + 593: harmonica + 594: harp + 595: harvester + 596: hatchet + 597: holster + 598: home theater + 599: honeycomb + 600: hook + 601: hoop skirt + 602: horizontal bar + 603: horse-drawn vehicle + 604: hourglass + 605: iPod + 606: clothes iron + 607: jack-o'-lantern + 608: jeans + 609: jeep + 610: T-shirt + 611: jigsaw puzzle + 612: pulled rickshaw + 613: joystick + 614: kimono + 615: knee pad + 616: knot + 617: lab coat + 618: ladle + 619: lampshade + 620: laptop computer + 621: lawn mower + 622: lens cap + 623: paper knife + 624: library + 625: lifeboat + 626: lighter + 627: limousine + 628: ocean liner + 629: lipstick + 630: slip-on shoe + 631: lotion + 632: speaker + 633: loupe + 634: sawmill + 635: magnetic compass + 636: mail bag + 637: mailbox + 638: tights + 639: tank suit + 640: manhole cover + 641: maraca + 642: marimba + 643: mask + 644: match + 645: maypole + 646: maze + 647: measuring cup + 648: medicine chest + 649: megalith + 650: microphone + 651: microwave oven + 652: military uniform + 653: milk can + 654: minibus + 655: miniskirt + 656: minivan + 657: missile + 658: mitten + 659: mixing bowl + 660: mobile home + 661: Model T + 662: modem + 663: monastery + 664: monitor + 665: moped + 666: mortar + 667: square academic cap + 668: mosque + 669: mosquito net + 670: scooter + 671: mountain bike + 672: tent + 673: computer mouse + 674: mousetrap + 675: moving van + 676: muzzle + 677: nail + 678: neck brace + 679: necklace + 680: nipple + 681: notebook computer + 682: obelisk + 683: oboe + 684: ocarina + 685: odometer + 686: oil filter + 687: organ + 688: oscilloscope + 689: overskirt + 690: bullock cart + 691: oxygen mask + 692: packet + 693: paddle + 694: paddle wheel + 695: padlock + 696: paintbrush + 697: pajamas + 698: palace + 699: pan flute + 700: paper towel + 701: parachute + 702: parallel bars + 703: park bench + 704: parking meter + 705: passenger car + 706: patio + 707: payphone + 708: pedestal + 709: pencil case + 710: pencil sharpener + 711: perfume + 712: Petri dish + 713: photocopier + 714: plectrum + 715: Pickelhaube + 716: picket fence + 717: pickup truck + 718: pier + 719: piggy bank + 720: pill bottle + 721: pillow + 722: ping-pong ball + 723: pinwheel + 724: pirate ship + 725: pitcher + 726: hand plane + 727: planetarium + 728: plastic bag + 729: plate rack + 730: plow + 731: plunger + 732: Polaroid camera + 733: pole + 734: police van + 735: poncho + 736: billiard table + 737: soda bottle + 738: pot + 739: potter's wheel + 740: power drill + 741: prayer rug + 742: printer + 743: prison + 744: projectile + 745: projector + 746: hockey puck + 747: punching bag + 748: purse + 749: quill + 750: quilt + 751: race car + 752: racket + 753: radiator + 754: radio + 755: radio telescope + 756: rain barrel + 757: recreational vehicle + 758: reel + 759: reflex camera + 760: refrigerator + 761: remote control + 762: restaurant + 763: revolver + 764: rifle + 765: rocking chair + 766: rotisserie + 767: eraser + 768: rugby ball + 769: ruler + 770: running shoe + 771: safe + 772: safety pin + 773: salt shaker + 774: sandal + 775: sarong + 776: saxophone + 777: scabbard + 778: weighing scale + 779: school bus + 780: schooner + 781: scoreboard + 782: CRT screen + 783: screw + 784: screwdriver + 785: seat belt + 786: sewing machine + 787: shield + 788: shoe store + 789: shoji + 790: shopping basket + 791: shopping cart + 792: shovel + 793: shower cap + 794: shower curtain + 795: ski + 796: ski mask + 797: sleeping bag + 798: slide rule + 799: sliding door + 800: slot machine + 801: snorkel + 802: snowmobile + 803: snowplow + 804: soap dispenser + 805: soccer ball + 806: sock + 807: solar thermal collector + 808: sombrero + 809: soup bowl + 810: space bar + 811: space heater + 812: space shuttle + 813: spatula + 814: motorboat + 815: spider web + 816: spindle + 817: sports car + 818: spotlight + 819: stage + 820: steam locomotive + 821: through arch bridge + 822: steel drum + 823: stethoscope + 824: scarf + 825: stone wall + 826: stopwatch + 827: stove + 828: strainer + 829: tram + 830: stretcher + 831: couch + 832: stupa + 833: submarine + 834: suit + 835: sundial + 836: sunglass + 837: sunglasses + 838: sunscreen + 839: suspension bridge + 840: mop + 841: sweatshirt + 842: swimsuit + 843: swing + 844: switch + 845: syringe + 846: table lamp + 847: tank + 848: tape player + 849: teapot + 850: teddy bear + 851: television + 852: tennis ball + 853: thatched roof + 854: front curtain + 855: thimble + 856: threshing machine + 857: throne + 858: tile roof + 859: toaster + 860: tobacco shop + 861: toilet seat + 862: torch + 863: totem pole + 864: tow truck + 865: toy store + 866: tractor + 867: semi-trailer truck + 868: tray + 869: trench coat + 870: tricycle + 871: trimaran + 872: tripod + 873: triumphal arch + 874: trolleybus + 875: trombone + 876: tub + 877: turnstile + 878: typewriter keyboard + 879: umbrella + 880: unicycle + 881: upright piano + 882: vacuum cleaner + 883: vase + 884: vault + 885: velvet + 886: vending machine + 887: vestment + 888: viaduct + 889: violin + 890: volleyball + 891: waffle iron + 892: wall clock + 893: wallet + 894: wardrobe + 895: military aircraft + 896: sink + 897: washing machine + 898: water bottle + 899: water jug + 900: water tower + 901: whiskey jug + 902: whistle + 903: wig + 904: window screen + 905: window shade + 906: Windsor tie + 907: wine bottle + 908: wing + 909: wok + 910: wooden spoon + 911: wool + 912: split-rail fence + 913: shipwreck + 914: yawl + 915: yurt + 916: website + 917: comic book + 918: crossword + 919: traffic sign + 920: traffic light + 921: dust jacket + 922: menu + 923: plate + 924: guacamole + 925: consomme + 926: hot pot + 927: trifle + 928: ice cream + 929: ice pop + 930: baguette + 931: bagel + 932: pretzel + 933: cheeseburger + 934: hot dog + 935: mashed potato + 936: cabbage + 937: broccoli + 938: cauliflower + 939: zucchini + 940: spaghetti squash + 941: acorn squash + 942: butternut squash + 943: cucumber + 944: artichoke + 945: bell pepper + 946: cardoon + 947: mushroom + 948: Granny Smith + 949: strawberry + 950: orange + 951: lemon + 952: fig + 953: pineapple + 954: banana + 955: jackfruit + 956: custard apple + 957: pomegranate + 958: hay + 959: carbonara + 960: chocolate syrup + 961: dough + 962: meatloaf + 963: pizza + 964: pot pie + 965: burrito + 966: red wine + 967: espresso + 968: cup + 969: eggnog + 970: alp + 971: bubble + 972: cliff + 973: coral reef + 974: geyser + 975: lakeshore + 976: promontory + 977: shoal + 978: seashore + 979: valley + 980: volcano + 981: baseball player + 982: bridegroom + 983: scuba diver + 984: rapeseed + 985: daisy + 986: yellow lady's slipper + 987: corn + 988: acorn + 989: rose hip + 990: horse chestnut seed + 991: coral fungus + 992: agaric + 993: gyromitra + 994: stinkhorn mushroom + 995: earth star + 996: hen-of-the-woods + 997: bolete + 998: ear + 999: toilet paper + +# Imagenet class codes to human-readable names +map: + n01440764: tench + n01443537: goldfish + n01484850: great_white_shark + n01491361: tiger_shark + n01494475: hammerhead + n01496331: electric_ray + n01498041: stingray + n01514668: cock + n01514859: hen + n01518878: ostrich + n01530575: brambling + n01531178: goldfinch + n01532829: house_finch + n01534433: junco + n01537544: indigo_bunting + n01558993: robin + n01560419: bulbul + n01580077: jay + n01582220: magpie + n01592084: chickadee + n01601694: water_ouzel + n01608432: kite + n01614925: bald_eagle + n01616318: vulture + n01622779: great_grey_owl + n01629819: European_fire_salamander + n01630670: common_newt + n01631663: eft + n01632458: spotted_salamander + n01632777: axolotl + n01641577: bullfrog + n01644373: tree_frog + n01644900: tailed_frog + n01664065: loggerhead + n01665541: leatherback_turtle + n01667114: mud_turtle + n01667778: terrapin + n01669191: box_turtle + n01675722: banded_gecko + n01677366: common_iguana + n01682714: American_chameleon + n01685808: whiptail + n01687978: agama + n01688243: frilled_lizard + n01689811: alligator_lizard + n01692333: Gila_monster + n01693334: green_lizard + n01694178: African_chameleon + n01695060: Komodo_dragon + n01697457: African_crocodile + n01698640: American_alligator + n01704323: triceratops + n01728572: thunder_snake + n01728920: ringneck_snake + n01729322: hognose_snake + n01729977: green_snake + n01734418: king_snake + n01735189: garter_snake + n01737021: water_snake + n01739381: vine_snake + n01740131: night_snake + n01742172: boa_constrictor + n01744401: rock_python + n01748264: Indian_cobra + n01749939: green_mamba + n01751748: sea_snake + n01753488: horned_viper + n01755581: diamondback + n01756291: sidewinder + n01768244: trilobite + n01770081: harvestman + n01770393: scorpion + n01773157: black_and_gold_garden_spider + n01773549: barn_spider + n01773797: garden_spider + n01774384: black_widow + n01774750: tarantula + n01775062: wolf_spider + n01776313: tick + n01784675: centipede + n01795545: black_grouse + n01796340: ptarmigan + n01797886: ruffed_grouse + n01798484: prairie_chicken + n01806143: peacock + n01806567: quail + n01807496: partridge + n01817953: African_grey + n01818515: macaw + n01819313: sulphur-crested_cockatoo + n01820546: lorikeet + n01824575: coucal + n01828970: bee_eater + n01829413: hornbill + n01833805: hummingbird + n01843065: jacamar + n01843383: toucan + n01847000: drake + n01855032: red-breasted_merganser + n01855672: goose + n01860187: black_swan + n01871265: tusker + n01872401: echidna + n01873310: platypus + n01877812: wallaby + n01882714: koala + n01883070: wombat + n01910747: jellyfish + n01914609: sea_anemone + n01917289: brain_coral + n01924916: flatworm + n01930112: nematode + n01943899: conch + n01944390: snail + n01945685: slug + n01950731: sea_slug + n01955084: chiton + n01968897: chambered_nautilus + n01978287: Dungeness_crab + n01978455: rock_crab + n01980166: fiddler_crab + n01981276: king_crab + n01983481: American_lobster + n01984695: spiny_lobster + n01985128: crayfish + n01986214: hermit_crab + n01990800: isopod + n02002556: white_stork + n02002724: black_stork + n02006656: spoonbill + n02007558: flamingo + n02009229: little_blue_heron + n02009912: American_egret + n02011460: bittern + n02012849: crane_(bird) + n02013706: limpkin + n02017213: European_gallinule + n02018207: American_coot + n02018795: bustard + n02025239: ruddy_turnstone + n02027492: red-backed_sandpiper + n02028035: redshank + n02033041: dowitcher + n02037110: oystercatcher + n02051845: pelican + n02056570: king_penguin + n02058221: albatross + n02066245: grey_whale + n02071294: killer_whale + n02074367: dugong + n02077923: sea_lion + n02085620: Chihuahua + n02085782: Japanese_spaniel + n02085936: Maltese_dog + n02086079: Pekinese + n02086240: Shih-Tzu + n02086646: Blenheim_spaniel + n02086910: papillon + n02087046: toy_terrier + n02087394: Rhodesian_ridgeback + n02088094: Afghan_hound + n02088238: basset + n02088364: beagle + n02088466: bloodhound + n02088632: bluetick + n02089078: black-and-tan_coonhound + n02089867: Walker_hound + n02089973: English_foxhound + n02090379: redbone + n02090622: borzoi + n02090721: Irish_wolfhound + n02091032: Italian_greyhound + n02091134: whippet + n02091244: Ibizan_hound + n02091467: Norwegian_elkhound + n02091635: otterhound + n02091831: Saluki + n02092002: Scottish_deerhound + n02092339: Weimaraner + n02093256: Staffordshire_bullterrier + n02093428: American_Staffordshire_terrier + n02093647: Bedlington_terrier + n02093754: Border_terrier + n02093859: Kerry_blue_terrier + n02093991: Irish_terrier + n02094114: Norfolk_terrier + n02094258: Norwich_terrier + n02094433: Yorkshire_terrier + n02095314: wire-haired_fox_terrier + n02095570: Lakeland_terrier + n02095889: Sealyham_terrier + n02096051: Airedale + n02096177: cairn + n02096294: Australian_terrier + n02096437: Dandie_Dinmont + n02096585: Boston_bull + n02097047: miniature_schnauzer + n02097130: giant_schnauzer + n02097209: standard_schnauzer + n02097298: Scotch_terrier + n02097474: Tibetan_terrier + n02097658: silky_terrier + n02098105: soft-coated_wheaten_terrier + n02098286: West_Highland_white_terrier + n02098413: Lhasa + n02099267: flat-coated_retriever + n02099429: curly-coated_retriever + n02099601: golden_retriever + n02099712: Labrador_retriever + n02099849: Chesapeake_Bay_retriever + n02100236: German_short-haired_pointer + n02100583: vizsla + n02100735: English_setter + n02100877: Irish_setter + n02101006: Gordon_setter + n02101388: Brittany_spaniel + n02101556: clumber + n02102040: English_springer + n02102177: Welsh_springer_spaniel + n02102318: cocker_spaniel + n02102480: Sussex_spaniel + n02102973: Irish_water_spaniel + n02104029: kuvasz + n02104365: schipperke + n02105056: groenendael + n02105162: malinois + n02105251: briard + n02105412: kelpie + n02105505: komondor + n02105641: Old_English_sheepdog + n02105855: Shetland_sheepdog + n02106030: collie + n02106166: Border_collie + n02106382: Bouvier_des_Flandres + n02106550: Rottweiler + n02106662: German_shepherd + n02107142: Doberman + n02107312: miniature_pinscher + n02107574: Greater_Swiss_Mountain_dog + n02107683: Bernese_mountain_dog + n02107908: Appenzeller + n02108000: EntleBucher + n02108089: boxer + n02108422: bull_mastiff + n02108551: Tibetan_mastiff + n02108915: French_bulldog + n02109047: Great_Dane + n02109525: Saint_Bernard + n02109961: Eskimo_dog + n02110063: malamute + n02110185: Siberian_husky + n02110341: dalmatian + n02110627: affenpinscher + n02110806: basenji + n02110958: pug + n02111129: Leonberg + n02111277: Newfoundland + n02111500: Great_Pyrenees + n02111889: Samoyed + n02112018: Pomeranian + n02112137: chow + n02112350: keeshond + n02112706: Brabancon_griffon + n02113023: Pembroke + n02113186: Cardigan + n02113624: toy_poodle + n02113712: miniature_poodle + n02113799: standard_poodle + n02113978: Mexican_hairless + n02114367: timber_wolf + n02114548: white_wolf + n02114712: red_wolf + n02114855: coyote + n02115641: dingo + n02115913: dhole + n02116738: African_hunting_dog + n02117135: hyena + n02119022: red_fox + n02119789: kit_fox + n02120079: Arctic_fox + n02120505: grey_fox + n02123045: tabby + n02123159: tiger_cat + n02123394: Persian_cat + n02123597: Siamese_cat + n02124075: Egyptian_cat + n02125311: cougar + n02127052: lynx + n02128385: leopard + n02128757: snow_leopard + n02128925: jaguar + n02129165: lion + n02129604: tiger + n02130308: cheetah + n02132136: brown_bear + n02133161: American_black_bear + n02134084: ice_bear + n02134418: sloth_bear + n02137549: mongoose + n02138441: meerkat + n02165105: tiger_beetle + n02165456: ladybug + n02167151: ground_beetle + n02168699: long-horned_beetle + n02169497: leaf_beetle + n02172182: dung_beetle + n02174001: rhinoceros_beetle + n02177972: weevil + n02190166: fly + n02206856: bee + n02219486: ant + n02226429: grasshopper + n02229544: cricket + n02231487: walking_stick + n02233338: cockroach + n02236044: mantis + n02256656: cicada + n02259212: leafhopper + n02264363: lacewing + n02268443: dragonfly + n02268853: damselfly + n02276258: admiral + n02277742: ringlet + n02279972: monarch + n02280649: cabbage_butterfly + n02281406: sulphur_butterfly + n02281787: lycaenid + n02317335: starfish + n02319095: sea_urchin + n02321529: sea_cucumber + n02325366: wood_rabbit + n02326432: hare + n02328150: Angora + n02342885: hamster + n02346627: porcupine + n02356798: fox_squirrel + n02361337: marmot + n02363005: beaver + n02364673: guinea_pig + n02389026: sorrel + n02391049: zebra + n02395406: hog + n02396427: wild_boar + n02397096: warthog + n02398521: hippopotamus + n02403003: ox + n02408429: water_buffalo + n02410509: bison + n02412080: ram + n02415577: bighorn + n02417914: ibex + n02422106: hartebeest + n02422699: impala + n02423022: gazelle + n02437312: Arabian_camel + n02437616: llama + n02441942: weasel + n02442845: mink + n02443114: polecat + n02443484: black-footed_ferret + n02444819: otter + n02445715: skunk + n02447366: badger + n02454379: armadillo + n02457408: three-toed_sloth + n02480495: orangutan + n02480855: gorilla + n02481823: chimpanzee + n02483362: gibbon + n02483708: siamang + n02484975: guenon + n02486261: patas + n02486410: baboon + n02487347: macaque + n02488291: langur + n02488702: colobus + n02489166: proboscis_monkey + n02490219: marmoset + n02492035: capuchin + n02492660: howler_monkey + n02493509: titi + n02493793: spider_monkey + n02494079: squirrel_monkey + n02497673: Madagascar_cat + n02500267: indri + n02504013: Indian_elephant + n02504458: African_elephant + n02509815: lesser_panda + n02510455: giant_panda + n02514041: barracouta + n02526121: eel + n02536864: coho + n02606052: rock_beauty + n02607072: anemone_fish + n02640242: sturgeon + n02641379: gar + n02643566: lionfish + n02655020: puffer + n02666196: abacus + n02667093: abaya + n02669723: academic_gown + n02672831: accordion + n02676566: acoustic_guitar + n02687172: aircraft_carrier + n02690373: airliner + n02692877: airship + n02699494: altar + n02701002: ambulance + n02704792: amphibian + n02708093: analog_clock + n02727426: apiary + n02730930: apron + n02747177: ashcan + n02749479: assault_rifle + n02769748: backpack + n02776631: bakery + n02777292: balance_beam + n02782093: balloon + n02783161: ballpoint + n02786058: Band_Aid + n02787622: banjo + n02788148: bannister + n02790996: barbell + n02791124: barber_chair + n02791270: barbershop + n02793495: barn + n02794156: barometer + n02795169: barrel + n02797295: barrow + n02799071: baseball + n02802426: basketball + n02804414: bassinet + n02804610: bassoon + n02807133: bathing_cap + n02808304: bath_towel + n02808440: bathtub + n02814533: beach_wagon + n02814860: beacon + n02815834: beaker + n02817516: bearskin + n02823428: beer_bottle + n02823750: beer_glass + n02825657: bell_cote + n02834397: bib + n02835271: bicycle-built-for-two + n02837789: bikini + n02840245: binder + n02841315: binoculars + n02843684: birdhouse + n02859443: boathouse + n02860847: bobsled + n02865351: bolo_tie + n02869837: bonnet + n02870880: bookcase + n02871525: bookshop + n02877765: bottlecap + n02879718: bow + n02883205: bow_tie + n02892201: brass + n02892767: brassiere + n02894605: breakwater + n02895154: breastplate + n02906734: broom + n02909870: bucket + n02910353: buckle + n02916936: bulletproof_vest + n02917067: bullet_train + n02927161: butcher_shop + n02930766: cab + n02939185: caldron + n02948072: candle + n02950826: cannon + n02951358: canoe + n02951585: can_opener + n02963159: cardigan + n02965783: car_mirror + n02966193: carousel + n02966687: carpenter's_kit + n02971356: carton + n02974003: car_wheel + n02977058: cash_machine + n02978881: cassette + n02979186: cassette_player + n02980441: castle + n02981792: catamaran + n02988304: CD_player + n02992211: cello + n02992529: cellular_telephone + n02999410: chain + n03000134: chainlink_fence + n03000247: chain_mail + n03000684: chain_saw + n03014705: chest + n03016953: chiffonier + n03017168: chime + n03018349: china_cabinet + n03026506: Christmas_stocking + n03028079: church + n03032252: cinema + n03041632: cleaver + n03042490: cliff_dwelling + n03045698: cloak + n03047690: clog + n03062245: cocktail_shaker + n03063599: coffee_mug + n03063689: coffeepot + n03065424: coil + n03075370: combination_lock + n03085013: computer_keyboard + n03089624: confectionery + n03095699: container_ship + n03100240: convertible + n03109150: corkscrew + n03110669: cornet + n03124043: cowboy_boot + n03124170: cowboy_hat + n03125729: cradle + n03126707: crane_(machine) + n03127747: crash_helmet + n03127925: crate + n03131574: crib + n03133878: Crock_Pot + n03134739: croquet_ball + n03141823: crutch + n03146219: cuirass + n03160309: dam + n03179701: desk + n03180011: desktop_computer + n03187595: dial_telephone + n03188531: diaper + n03196217: digital_clock + n03197337: digital_watch + n03201208: dining_table + n03207743: dishrag + n03207941: dishwasher + n03208938: disk_brake + n03216828: dock + n03218198: dogsled + n03220513: dome + n03223299: doormat + n03240683: drilling_platform + n03249569: drum + n03250847: drumstick + n03255030: dumbbell + n03259280: Dutch_oven + n03271574: electric_fan + n03272010: electric_guitar + n03272562: electric_locomotive + n03290653: entertainment_center + n03291819: envelope + n03297495: espresso_maker + n03314780: face_powder + n03325584: feather_boa + n03337140: file + n03344393: fireboat + n03345487: fire_engine + n03347037: fire_screen + n03355925: flagpole + n03372029: flute + n03376595: folding_chair + n03379051: football_helmet + n03384352: forklift + n03388043: fountain + n03388183: fountain_pen + n03388549: four-poster + n03393912: freight_car + n03394916: French_horn + n03400231: frying_pan + n03404251: fur_coat + n03417042: garbage_truck + n03424325: gasmask + n03425413: gas_pump + n03443371: goblet + n03444034: go-kart + n03445777: golf_ball + n03445924: golfcart + n03447447: gondola + n03447721: gong + n03450230: gown + n03452741: grand_piano + n03457902: greenhouse + n03459775: grille + n03461385: grocery_store + n03467068: guillotine + n03476684: hair_slide + n03476991: hair_spray + n03478589: half_track + n03481172: hammer + n03482405: hamper + n03483316: hand_blower + n03485407: hand-held_computer + n03485794: handkerchief + n03492542: hard_disc + n03494278: harmonica + n03495258: harp + n03496892: harvester + n03498962: hatchet + n03527444: holster + n03529860: home_theater + n03530642: honeycomb + n03532672: hook + n03534580: hoopskirt + n03535780: horizontal_bar + n03538406: horse_cart + n03544143: hourglass + n03584254: iPod + n03584829: iron + n03590841: jack-o'-lantern + n03594734: jean + n03594945: jeep + n03595614: jersey + n03598930: jigsaw_puzzle + n03599486: jinrikisha + n03602883: joystick + n03617480: kimono + n03623198: knee_pad + n03627232: knot + n03630383: lab_coat + n03633091: ladle + n03637318: lampshade + n03642806: laptop + n03649909: lawn_mower + n03657121: lens_cap + n03658185: letter_opener + n03661043: library + n03662601: lifeboat + n03666591: lighter + n03670208: limousine + n03673027: liner + n03676483: lipstick + n03680355: Loafer + n03690938: lotion + n03691459: loudspeaker + n03692522: loupe + n03697007: lumbermill + n03706229: magnetic_compass + n03709823: mailbag + n03710193: mailbox + n03710637: maillot_(tights) + n03710721: maillot_(tank_suit) + n03717622: manhole_cover + n03720891: maraca + n03721384: marimba + n03724870: mask + n03729826: matchstick + n03733131: maypole + n03733281: maze + n03733805: measuring_cup + n03742115: medicine_chest + n03743016: megalith + n03759954: microphone + n03761084: microwave + n03763968: military_uniform + n03764736: milk_can + n03769881: minibus + n03770439: miniskirt + n03770679: minivan + n03773504: missile + n03775071: mitten + n03775546: mixing_bowl + n03776460: mobile_home + n03777568: Model_T + n03777754: modem + n03781244: monastery + n03782006: monitor + n03785016: moped + n03786901: mortar + n03787032: mortarboard + n03788195: mosque + n03788365: mosquito_net + n03791053: motor_scooter + n03792782: mountain_bike + n03792972: mountain_tent + n03793489: mouse + n03794056: mousetrap + n03796401: moving_van + n03803284: muzzle + n03804744: nail + n03814639: neck_brace + n03814906: necklace + n03825788: nipple + n03832673: notebook + n03837869: obelisk + n03838899: oboe + n03840681: ocarina + n03841143: odometer + n03843555: oil_filter + n03854065: organ + n03857828: oscilloscope + n03866082: overskirt + n03868242: oxcart + n03868863: oxygen_mask + n03871628: packet + n03873416: paddle + n03874293: paddlewheel + n03874599: padlock + n03876231: paintbrush + n03877472: pajama + n03877845: palace + n03884397: panpipe + n03887697: paper_towel + n03888257: parachute + n03888605: parallel_bars + n03891251: park_bench + n03891332: parking_meter + n03895866: passenger_car + n03899768: patio + n03902125: pay-phone + n03903868: pedestal + n03908618: pencil_box + n03908714: pencil_sharpener + n03916031: perfume + n03920288: Petri_dish + n03924679: photocopier + n03929660: pick + n03929855: pickelhaube + n03930313: picket_fence + n03930630: pickup + n03933933: pier + n03935335: piggy_bank + n03937543: pill_bottle + n03938244: pillow + n03942813: ping-pong_ball + n03944341: pinwheel + n03947888: pirate + n03950228: pitcher + n03954731: plane + n03956157: planetarium + n03958227: plastic_bag + n03961711: plate_rack + n03967562: plow + n03970156: plunger + n03976467: Polaroid_camera + n03976657: pole + n03977966: police_van + n03980874: poncho + n03982430: pool_table + n03983396: pop_bottle + n03991062: pot + n03992509: potter's_wheel + n03995372: power_drill + n03998194: prayer_rug + n04004767: printer + n04005630: prison + n04008634: projectile + n04009552: projector + n04019541: puck + n04023962: punching_bag + n04026417: purse + n04033901: quill + n04033995: quilt + n04037443: racer + n04039381: racket + n04040759: radiator + n04041544: radio + n04044716: radio_telescope + n04049303: rain_barrel + n04065272: recreational_vehicle + n04067472: reel + n04069434: reflex_camera + n04070727: refrigerator + n04074963: remote_control + n04081281: restaurant + n04086273: revolver + n04090263: rifle + n04099969: rocking_chair + n04111531: rotisserie + n04116512: rubber_eraser + n04118538: rugby_ball + n04118776: rule + n04120489: running_shoe + n04125021: safe + n04127249: safety_pin + n04131690: saltshaker + n04133789: sandal + n04136333: sarong + n04141076: sax + n04141327: scabbard + n04141975: scale + n04146614: school_bus + n04147183: schooner + n04149813: scoreboard + n04152593: screen + n04153751: screw + n04154565: screwdriver + n04162706: seat_belt + n04179913: sewing_machine + n04192698: shield + n04200800: shoe_shop + n04201297: shoji + n04204238: shopping_basket + n04204347: shopping_cart + n04208210: shovel + n04209133: shower_cap + n04209239: shower_curtain + n04228054: ski + n04229816: ski_mask + n04235860: sleeping_bag + n04238763: slide_rule + n04239074: sliding_door + n04243546: slot + n04251144: snorkel + n04252077: snowmobile + n04252225: snowplow + n04254120: soap_dispenser + n04254680: soccer_ball + n04254777: sock + n04258138: solar_dish + n04259630: sombrero + n04263257: soup_bowl + n04264628: space_bar + n04265275: space_heater + n04266014: space_shuttle + n04270147: spatula + n04273569: speedboat + n04275548: spider_web + n04277352: spindle + n04285008: sports_car + n04286575: spotlight + n04296562: stage + n04310018: steam_locomotive + n04311004: steel_arch_bridge + n04311174: steel_drum + n04317175: stethoscope + n04325704: stole + n04326547: stone_wall + n04328186: stopwatch + n04330267: stove + n04332243: strainer + n04335435: streetcar + n04336792: stretcher + n04344873: studio_couch + n04346328: stupa + n04347754: submarine + n04350905: suit + n04355338: sundial + n04355933: sunglass + n04356056: sunglasses + n04357314: sunscreen + n04366367: suspension_bridge + n04367480: swab + n04370456: sweatshirt + n04371430: swimming_trunks + n04371774: swing + n04372370: switch + n04376876: syringe + n04380533: table_lamp + n04389033: tank + n04392985: tape_player + n04398044: teapot + n04399382: teddy + n04404412: television + n04409515: tennis_ball + n04417672: thatch + n04418357: theater_curtain + n04423845: thimble + n04428191: thresher + n04429376: throne + n04435653: tile_roof + n04442312: toaster + n04443257: tobacco_shop + n04447861: toilet_seat + n04456115: torch + n04458633: totem_pole + n04461696: tow_truck + n04462240: toyshop + n04465501: tractor + n04467665: trailer_truck + n04476259: tray + n04479046: trench_coat + n04482393: tricycle + n04483307: trimaran + n04485082: tripod + n04486054: triumphal_arch + n04487081: trolleybus + n04487394: trombone + n04493381: tub + n04501370: turnstile + n04505470: typewriter_keyboard + n04507155: umbrella + n04509417: unicycle + n04515003: upright + n04517823: vacuum + n04522168: vase + n04523525: vault + n04525038: velvet + n04525305: vending_machine + n04532106: vestment + n04532670: viaduct + n04536866: violin + n04540053: volleyball + n04542943: waffle_iron + n04548280: wall_clock + n04548362: wallet + n04550184: wardrobe + n04552348: warplane + n04553703: washbasin + n04554684: washer + n04557648: water_bottle + n04560804: water_jug + n04562935: water_tower + n04579145: whiskey_jug + n04579432: whistle + n04584207: wig + n04589890: window_screen + n04590129: window_shade + n04591157: Windsor_tie + n04591713: wine_bottle + n04592741: wing + n04596742: wok + n04597913: wooden_spoon + n04599235: wool + n04604644: worm_fence + n04606251: wreck + n04612504: yawl + n04613696: yurt + n06359193: web_site + n06596364: comic_book + n06785654: crossword_puzzle + n06794110: street_sign + n06874185: traffic_light + n07248320: book_jacket + n07565083: menu + n07579787: plate + n07583066: guacamole + n07584110: consomme + n07590611: hot_pot + n07613480: trifle + n07614500: ice_cream + n07615774: ice_lolly + n07684084: French_loaf + n07693725: bagel + n07695742: pretzel + n07697313: cheeseburger + n07697537: hotdog + n07711569: mashed_potato + n07714571: head_cabbage + n07714990: broccoli + n07715103: cauliflower + n07716358: zucchini + n07716906: spaghetti_squash + n07717410: acorn_squash + n07717556: butternut_squash + n07718472: cucumber + n07718747: artichoke + n07720875: bell_pepper + n07730033: cardoon + n07734744: mushroom + n07742313: Granny_Smith + n07745940: strawberry + n07747607: orange + n07749582: lemon + n07753113: fig + n07753275: pineapple + n07753592: banana + n07754684: jackfruit + n07760859: custard_apple + n07768694: pomegranate + n07802026: hay + n07831146: carbonara + n07836838: chocolate_sauce + n07860988: dough + n07871810: meat_loaf + n07873807: pizza + n07875152: potpie + n07880968: burrito + n07892512: red_wine + n07920052: espresso + n07930864: cup + n07932039: eggnog + n09193705: alp + n09229709: bubble + n09246464: cliff + n09256479: coral_reef + n09288635: geyser + n09332890: lakeside + n09399592: promontory + n09421951: sandbar + n09428293: seashore + n09468604: valley + n09472597: volcano + n09835506: ballplayer + n10148035: groom + n10565667: scuba_diver + n11879895: rapeseed + n11939491: daisy + n12057211: yellow_lady's_slipper + n12144580: corn + n12267677: acorn + n12620546: hip + n12768682: buckeye + n12985857: coral_fungus + n12998815: agaric + n13037406: gyromitra + n13040303: stinkhorn + n13044778: earthstar + n13052670: hen-of-the-woods + n13054560: bolete + n13133613: ear + n15075141: toilet_tissue + +# Download script/URL (optional) +download: ultralytics/data/scripts/get_imagenet.sh diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/Objects365.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/Objects365.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9e5d54287593b78a9757969b4ab94b829a4031ce --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/Objects365.yaml @@ -0,0 +1,447 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Objects365 dataset https://www.objects365.org/ by Megvii +# Documentation: https://docs.ultralytics.com/datasets/detect/objects365 +# Example usage: yolo train data=Objects365.yaml +# parent +# ├── ultralytics +# └── datasets +# └── Objects365 ← downloads here (712 GB = 367G data + 345G zips) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: Objects365 # dataset root dir +train: images/train # train images (relative to 'path') 1742289 images +val: images/val # val images (relative to 'path') 80000 images +test: # test images (optional) + +# Classes +names: + 0: Person + 1: Sneakers + 2: Chair + 3: Other Shoes + 4: Hat + 5: Car + 6: Lamp + 7: Glasses + 8: Bottle + 9: Desk + 10: Cup + 11: Street Lights + 12: Cabinet/shelf + 13: Handbag/Satchel + 14: Bracelet + 15: Plate + 16: Picture/Frame + 17: Helmet + 18: Book + 19: Gloves + 20: Storage box + 21: Boat + 22: Leather Shoes + 23: Flower + 24: Bench + 25: Potted Plant + 26: Bowl/Basin + 27: Flag + 28: Pillow + 29: Boots + 30: Vase + 31: Microphone + 32: Necklace + 33: Ring + 34: SUV + 35: Wine Glass + 36: Belt + 37: Monitor/TV + 38: Backpack + 39: Umbrella + 40: Traffic Light + 41: Speaker + 42: Watch + 43: Tie + 44: Trash bin Can + 45: Slippers + 46: Bicycle + 47: Stool + 48: Barrel/bucket + 49: Van + 50: Couch + 51: Sandals + 52: Basket + 53: Drum + 54: Pen/Pencil + 55: Bus + 56: Wild Bird + 57: High Heels + 58: Motorcycle + 59: Guitar + 60: Carpet + 61: Cell Phone + 62: Bread + 63: Camera + 64: Canned + 65: Truck + 66: Traffic cone + 67: Cymbal + 68: Lifesaver + 69: Towel + 70: Stuffed Toy + 71: Candle + 72: Sailboat + 73: Laptop + 74: Awning + 75: Bed + 76: Faucet + 77: Tent + 78: Horse + 79: Mirror + 80: Power outlet + 81: Sink + 82: Apple + 83: Air Conditioner + 84: Knife + 85: Hockey Stick + 86: Paddle + 87: Pickup Truck + 88: Fork + 89: Traffic Sign + 90: Balloon + 91: Tripod + 92: Dog + 93: Spoon + 94: Clock + 95: Pot + 96: Cow + 97: Cake + 98: Dining Table + 99: Sheep + 100: Hanger + 101: Blackboard/Whiteboard + 102: Napkin + 103: Other Fish + 104: Orange/Tangerine + 105: Toiletry + 106: Keyboard + 107: Tomato + 108: Lantern + 109: Machinery Vehicle + 110: Fan + 111: Green Vegetables + 112: Banana + 113: Baseball Glove + 114: Airplane + 115: Mouse + 116: Train + 117: Pumpkin + 118: Soccer + 119: Skiboard + 120: Luggage + 121: Nightstand + 122: Tea pot + 123: Telephone + 124: Trolley + 125: Head Phone + 126: Sports Car + 127: Stop Sign + 128: Dessert + 129: Scooter + 130: Stroller + 131: Crane + 132: Remote + 133: Refrigerator + 134: Oven + 135: Lemon + 136: Duck + 137: Baseball Bat + 138: Surveillance Camera + 139: Cat + 140: Jug + 141: Broccoli + 142: Piano + 143: Pizza + 144: Elephant + 145: Skateboard + 146: Surfboard + 147: Gun + 148: Skating and Skiing shoes + 149: Gas stove + 150: Donut + 151: Bow Tie + 152: Carrot + 153: Toilet + 154: Kite + 155: Strawberry + 156: Other Balls + 157: Shovel + 158: Pepper + 159: Computer Box + 160: Toilet Paper + 161: Cleaning Products + 162: Chopsticks + 163: Microwave + 164: Pigeon + 165: Baseball + 166: Cutting/chopping Board + 167: Coffee Table + 168: Side Table + 169: Scissors + 170: Marker + 171: Pie + 172: Ladder + 173: Snowboard + 174: Cookies + 175: Radiator + 176: Fire Hydrant + 177: Basketball + 178: Zebra + 179: Grape + 180: Giraffe + 181: Potato + 182: Sausage + 183: Tricycle + 184: Violin + 185: Egg + 186: Fire Extinguisher + 187: Candy + 188: Fire Truck + 189: Billiards + 190: Converter + 191: Bathtub + 192: Wheelchair + 193: Golf Club + 194: Briefcase + 195: Cucumber + 196: Cigar/Cigarette + 197: Paint Brush + 198: Pear + 199: Heavy Truck + 200: Hamburger + 201: Extractor + 202: Extension Cord + 203: Tong + 204: Tennis Racket + 205: Folder + 206: American Football + 207: earphone + 208: Mask + 209: Kettle + 210: Tennis + 211: Ship + 212: Swing + 213: Coffee Machine + 214: Slide + 215: Carriage + 216: Onion + 217: Green beans + 218: Projector + 219: Frisbee + 220: Washing Machine/Drying Machine + 221: Chicken + 222: Printer + 223: Watermelon + 224: Saxophone + 225: Tissue + 226: Toothbrush + 227: Ice cream + 228: Hot-air balloon + 229: Cello + 230: French Fries + 231: Scale + 232: Trophy + 233: Cabbage + 234: Hot dog + 235: Blender + 236: Peach + 237: Rice + 238: Wallet/Purse + 239: Volleyball + 240: Deer + 241: Goose + 242: Tape + 243: Tablet + 244: Cosmetics + 245: Trumpet + 246: Pineapple + 247: Golf Ball + 248: Ambulance + 249: Parking meter + 250: Mango + 251: Key + 252: Hurdle + 253: Fishing Rod + 254: Medal + 255: Flute + 256: Brush + 257: Penguin + 258: Megaphone + 259: Corn + 260: Lettuce + 261: Garlic + 262: Swan + 263: Helicopter + 264: Green Onion + 265: Sandwich + 266: Nuts + 267: Speed Limit Sign + 268: Induction Cooker + 269: Broom + 270: Trombone + 271: Plum + 272: Rickshaw + 273: Goldfish + 274: Kiwi fruit + 275: Router/modem + 276: Poker Card + 277: Toaster + 278: Shrimp + 279: Sushi + 280: Cheese + 281: Notepaper + 282: Cherry + 283: Pliers + 284: CD + 285: Pasta + 286: Hammer + 287: Cue + 288: Avocado + 289: Hami melon + 290: Flask + 291: Mushroom + 292: Screwdriver + 293: Soap + 294: Recorder + 295: Bear + 296: Eggplant + 297: Board Eraser + 298: Coconut + 299: Tape Measure/Ruler + 300: Pig + 301: Showerhead + 302: Globe + 303: Chips + 304: Steak + 305: Crosswalk Sign + 306: Stapler + 307: Camel + 308: Formula 1 + 309: Pomegranate + 310: Dishwasher + 311: Crab + 312: Hoverboard + 313: Meatball + 314: Rice Cooker + 315: Tuba + 316: Calculator + 317: Papaya + 318: Antelope + 319: Parrot + 320: Seal + 321: Butterfly + 322: Dumbbell + 323: Donkey + 324: Lion + 325: Urinal + 326: Dolphin + 327: Electric Drill + 328: Hair Dryer + 329: Egg tart + 330: Jellyfish + 331: Treadmill + 332: Lighter + 333: Grapefruit + 334: Game board + 335: Mop + 336: Radish + 337: Baozi + 338: Target + 339: French + 340: Spring Rolls + 341: Monkey + 342: Rabbit + 343: Pencil Case + 344: Yak + 345: Red Cabbage + 346: Binoculars + 347: Asparagus + 348: Barbell + 349: Scallop + 350: Noddles + 351: Comb + 352: Dumpling + 353: Oyster + 354: Table Tennis paddle + 355: Cosmetics Brush/Eyeliner Pencil + 356: Chainsaw + 357: Eraser + 358: Lobster + 359: Durian + 360: Okra + 361: Lipstick + 362: Cosmetics Mirror + 363: Curling + 364: Table Tennis + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + from concurrent.futures import ThreadPoolExecutor + from pathlib import Path + + import numpy as np + + from ultralytics.utils import TQDM + from ultralytics.utils.checks import check_requirements + from ultralytics.utils.downloads import download + from ultralytics.utils.ops import xyxy2xywhn + + check_requirements("faster-coco-eval") + from faster_coco_eval import COCO + + # Train, Val Splits + dir = Path(yaml["path"]) + for split, patches in [("train", 50 + 1), ("val", 43 + 1)]: + print(f"Processing {split} in {patches} patches ...") + images, labels = dir / "images" / split, dir / "labels" / split + images.mkdir(parents=True, exist_ok=True) + labels.mkdir(parents=True, exist_ok=True) + + # Download + url = f"https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/{split}/" + if split == "train": + download([f"{url}zhiyuan_objv2_{split}.tar.gz"], dir=dir) # annotations json + download([f"{url}patch{i}.tar.gz" for i in range(patches)], dir=images, threads=17) # 51 patches / 17 threads = 3 + elif split == "val": + download([f"{url}zhiyuan_objv2_{split}.json"], dir=dir) # annotations json + download([f"{url}images/v1/patch{i}.tar.gz" for i in range(15 + 1)], dir=images, threads=16) + download([f"{url}images/v2/patch{i}.tar.gz" for i in range(16, patches)], dir=images, threads=16) + + # Move + files = list(images.rglob("*.jpg")) + with ThreadPoolExecutor(max_workers=16) as executor: + list(TQDM(executor.map(lambda f: f.rename(images / f.name), files), total=len(files), desc=f"Moving {split} images")) + + # Labels + coco = COCO(dir / f"zhiyuan_objv2_{split}.json") + names = [x["name"] for x in coco.loadCats(coco.getCatIds())] + for cid, cat in enumerate(names): + catIds = coco.getCatIds(catNms=[cat]) + imgIds = coco.getImgIds(catIds=catIds) + + def process_annotation(im): + """Process and write annotations for a single image.""" + try: + width, height = im["width"], im["height"] + path = Path(im["file_name"]) + with open(labels / path.with_suffix(".txt").name, "a", encoding="utf-8") as file: + annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None) + for a in coco.loadAnns(annIds): + x, y, w, h = a["bbox"] # bounding box in xywh (xy top-left corner) + xyxy = np.array([x, y, x + w, y + h])[None] # pixels(1,4) + x, y, w, h = xyxy2xywhn(xyxy, w=width, h=height, clip=True)[0] # normalized and clipped + file.write(f"{cid} {x:.5f} {y:.5f} {w:.5f} {h:.5f}\n") + except Exception as e: + print(e) + + images_list = coco.loadImgs(imgIds) + with ThreadPoolExecutor(max_workers=16) as executor: + list(TQDM(executor.map(process_annotation, images_list), total=len(images_list), desc=f"Class {cid + 1}/{len(names)} {cat}")) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/SKU-110K.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/SKU-110K.yaml new file mode 100644 index 0000000000000000000000000000000000000000..84ec57b769a5b48b4687c890ed92d9306eeb43e3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/SKU-110K.yaml @@ -0,0 +1,58 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 by Trax Retail +# Documentation: https://docs.ultralytics.com/datasets/detect/sku-110k +# Example usage: yolo train data=SKU-110K.yaml +# parent +# ├── ultralytics +# └── datasets +# └── SKU-110K ← downloads here (13.6 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: SKU-110K # dataset root dir +train: train.txt # train images (relative to 'path') 8219 images +val: val.txt # val images (relative to 'path') 588 images +test: test.txt # test images (optional) 2936 images + +# Classes +names: + 0: object + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + import shutil + from pathlib import Path + + import numpy as np + import polars as pl + + from ultralytics.utils import TQDM + from ultralytics.utils.downloads import download + from ultralytics.utils.ops import xyxy2xywh + + # Download + dir = Path(yaml["path"]) # dataset root dir + parent = Path(dir.parent) # download dir + urls = ["http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz"] + download(urls, dir=parent) + + # Rename directories + if dir.exists(): + shutil.rmtree(dir) + (parent / "SKU110K_fixed").rename(dir) # rename dir + (dir / "labels").mkdir(parents=True, exist_ok=True) # create labels dir + + # Convert labels + names = "image", "x1", "y1", "x2", "y2", "class", "image_width", "image_height" # column names + for d in "annotations_train.csv", "annotations_val.csv", "annotations_test.csv": + x = pl.read_csv(dir / "annotations" / d, has_header=False, new_columns=names, infer_schema_length=None).to_numpy() # annotations + images, unique_images = x[:, 0], np.unique(x[:, 0]) + with open((dir / d).with_suffix(".txt").__str__().replace("annotations_", ""), "w", encoding="utf-8") as f: + f.writelines(f"./images/{s}\n" for s in unique_images) + for im in TQDM(unique_images, desc=f"Converting {dir / d}"): + cls = 0 # single-class dataset + with open((dir / "labels" / im).with_suffix(".txt"), "a", encoding="utf-8") as f: + for r in x[images == im]: + w, h = r[6], r[7] # image width, height + xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance + f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/TT100K.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/TT100K.yaml new file mode 100644 index 0000000000000000000000000000000000000000..67b1591f80e606661254a05ccaedf54187df8449 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/TT100K.yaml @@ -0,0 +1,346 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Tsinghua-Tencent 100K (TT100K) dataset https://cg.cs.tsinghua.edu.cn/traffic-sign/ by Tsinghua University +# Documentation: https://cg.cs.tsinghua.edu.cn/traffic-sign/tutorial.html +# Paper: Traffic-Sign Detection and Classification in the Wild (CVPR 2016) +# License: CC BY-NC 2.0 license for non-commercial use only +# Example usage: yolo train data=TT100K.yaml +# parent +# ├── ultralytics +# └── datasets +# └── TT100K ← downloads here (~18 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: TT100K # dataset root dir +train: images/train # train images (relative to 'path') 6105 images +val: images/val # val images (relative to 'path') 7641 images (original 'other' split) +test: images/test # test images (relative to 'path') 3071 images + +# Classes (221 traffic sign categories, 45 with sufficient training instances) +names: + 0: i1 + 1: i10 + 2: i11 + 3: i12 + 4: i13 + 5: i14 + 6: i15 + 7: i2 + 8: i3 + 9: i4 + 10: i5 + 11: il100 + 12: il110 + 13: il50 + 14: il60 + 15: il70 + 16: il80 + 17: il90 + 18: io + 19: ip + 20: p1 + 21: p10 + 22: p11 + 23: p12 + 24: p13 + 25: p14 + 26: p15 + 27: p16 + 28: p17 + 29: p18 + 30: p19 + 31: p2 + 32: p20 + 33: p21 + 34: p22 + 35: p23 + 36: p24 + 37: p25 + 38: p26 + 39: p27 + 40: p28 + 41: p3 + 42: p4 + 43: p5 + 44: p6 + 45: p7 + 46: p8 + 47: p9 + 48: pa10 + 49: pa12 + 50: pa13 + 51: pa14 + 52: pa8 + 53: pb + 54: pc + 55: pg + 56: ph1.5 + 57: ph2 + 58: ph2.1 + 59: ph2.2 + 60: ph2.4 + 61: ph2.5 + 62: ph2.8 + 63: ph2.9 + 64: ph3 + 65: ph3.2 + 66: ph3.5 + 67: ph3.8 + 68: ph4 + 69: ph4.2 + 70: ph4.3 + 71: ph4.5 + 72: ph4.8 + 73: ph5 + 74: ph5.3 + 75: ph5.5 + 76: pl10 + 77: pl100 + 78: pl110 + 79: pl120 + 80: pl15 + 81: pl20 + 82: pl25 + 83: pl30 + 84: pl35 + 85: pl40 + 86: pl5 + 87: pl50 + 88: pl60 + 89: pl65 + 90: pl70 + 91: pl80 + 92: pl90 + 93: pm10 + 94: pm13 + 95: pm15 + 96: pm1.5 + 97: pm2 + 98: pm20 + 99: pm25 + 100: pm30 + 101: pm35 + 102: pm40 + 103: pm46 + 104: pm5 + 105: pm50 + 106: pm55 + 107: pm8 + 108: pn + 109: pne + 110: po + 111: pr10 + 112: pr100 + 113: pr20 + 114: pr30 + 115: pr40 + 116: pr45 + 117: pr50 + 118: pr60 + 119: pr70 + 120: pr80 + 121: ps + 122: pw2 + 123: pw2.5 + 124: pw3 + 125: pw3.2 + 126: pw3.5 + 127: pw4 + 128: pw4.2 + 129: pw4.5 + 130: w1 + 131: w10 + 132: w12 + 133: w13 + 134: w16 + 135: w18 + 136: w20 + 137: w21 + 138: w22 + 139: w24 + 140: w28 + 141: w3 + 142: w30 + 143: w31 + 144: w32 + 145: w34 + 146: w35 + 147: w37 + 148: w38 + 149: w41 + 150: w42 + 151: w43 + 152: w44 + 153: w45 + 154: w46 + 155: w47 + 156: w48 + 157: w49 + 158: w5 + 159: w50 + 160: w55 + 161: w56 + 162: w57 + 163: w58 + 164: w59 + 165: w60 + 166: w62 + 167: w63 + 168: w66 + 169: w8 + 170: wo + 171: i6 + 172: i7 + 173: i8 + 174: i9 + 175: ilx + 176: p29 + 177: w29 + 178: w33 + 179: w36 + 180: w39 + 181: w4 + 182: w40 + 183: w51 + 184: w52 + 185: w53 + 186: w54 + 187: w6 + 188: w61 + 189: w64 + 190: w65 + 191: w67 + 192: w7 + 193: w9 + 194: pax + 195: pd + 196: pe + 197: phx + 198: plx + 199: pmx + 200: pnl + 201: prx + 202: pwx + 203: w11 + 204: w14 + 205: w15 + 206: w17 + 207: w19 + 208: w2 + 209: w23 + 210: w25 + 211: w26 + 212: w27 + 213: pl0 + 214: pl4 + 215: pl3 + 216: pm2.5 + 217: ph4.4 + 218: pn40 + 219: ph3.3 + 220: ph2.6 + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + import json + import shutil + from pathlib import Path + + from PIL import Image + + from ultralytics.utils import TQDM + from ultralytics.utils.downloads import download + + + def tt100k2yolo(dir): + """Convert TT100K annotations to YOLO format with images/{split} and labels/{split} structure.""" + data_dir = dir / "data" + anno_file = data_dir / "annotations.json" + + print("Loading annotations...") + with open(anno_file, encoding="utf-8") as f: + data = json.load(f) + + # Build class name to index mapping from yaml + names = yaml["names"] + class_to_idx = {v: k for k, v in names.items()} + + # Create directories + for split in ["train", "val", "test"]: + (dir / "images" / split).mkdir(parents=True, exist_ok=True) + (dir / "labels" / split).mkdir(parents=True, exist_ok=True) + + print("Converting annotations to YOLO format...") + skipped = 0 + for img_id, img_data in TQDM(data["imgs"].items(), desc="Processing"): + img_path_str = img_data["path"] + if "train" in img_path_str: + split = "train" + elif "test" in img_path_str: + split = "test" + else: + split = "val" + + # Source and destination paths + src_img = data_dir / img_path_str + if not src_img.exists(): + continue + + dst_img = dir / "images" / split / src_img.name + + # Get image dimensions + try: + with Image.open(src_img) as img: + img_width, img_height = img.size + except Exception as e: + print(f"Error reading {src_img}: {e}") + continue + + # Copy image to destination + shutil.copy2(src_img, dst_img) + + # Convert annotations + label_file = dir / "labels" / split / f"{src_img.stem}.txt" + lines = [] + + for obj in img_data.get("objects", []): + category = obj["category"] + if category not in class_to_idx: + skipped += 1 + continue + + bbox = obj["bbox"] + xmin, ymin = bbox["xmin"], bbox["ymin"] + xmax, ymax = bbox["xmax"], bbox["ymax"] + + # Convert to YOLO format (normalized center coordinates and dimensions) + x_center = ((xmin + xmax) / 2.0) / img_width + y_center = ((ymin + ymax) / 2.0) / img_height + width = (xmax - xmin) / img_width + height = (ymax - ymin) / img_height + + # Clip to valid range + x_center = max(0, min(1, x_center)) + y_center = max(0, min(1, y_center)) + width = max(0, min(1, width)) + height = max(0, min(1, height)) + + cls_idx = class_to_idx[category] + lines.append(f"{cls_idx} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n") + + # Write label file + if lines: + label_file.write_text("".join(lines), encoding="utf-8") + + if skipped: + print(f"Skipped {skipped} annotations with unknown categories") + print("Conversion complete!") + + + # Download + dir = Path(yaml["path"]) # dataset root dir + urls = ["https://cg.cs.tsinghua.edu.cn/traffic-sign/data_model_code/data.zip"] + download(urls, dir=dir, curl=True, threads=1) + + # Convert + tt100k2yolo(dir) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/VOC.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/VOC.yaml new file mode 100644 index 0000000000000000000000000000000000000000..29584a4c0462717a816cad4638c33c0061157bdb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/VOC.yaml @@ -0,0 +1,102 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# PASCAL VOC dataset https://www.robots.ox.ac.uk/~vgg/projects/pascal/VOC by University of Oxford +# Documentation: https://docs.ultralytics.com/datasets/detect/voc +# Example usage: yolo train data=VOC.yaml +# parent +# ├── ultralytics +# └── datasets +# └── VOC ← downloads here (2.8 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: VOC +train: # train images (relative to 'path') 16551 images + - images/train2012 + - images/train2007 + - images/val2012 + - images/val2007 +val: # val images (relative to 'path') 4952 images + - images/test2007 +test: # test images (optional) + - images/test2007 + +# Classes +names: + 0: aeroplane + 1: bicycle + 2: bird + 3: boat + 4: bottle + 5: bus + 6: car + 7: cat + 8: chair + 9: cow + 10: diningtable + 11: dog + 12: horse + 13: motorbike + 14: person + 15: pottedplant + 16: sheep + 17: sofa + 18: train + 19: tvmonitor + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + import xml.etree.ElementTree as ET + from pathlib import Path + + from ultralytics.utils.downloads import download + from ultralytics.utils import ASSETS_URL, TQDM + + def convert_label(path, lb_path, year, image_id): + """Converts XML annotations from VOC format to YOLO format by extracting bounding boxes and class IDs.""" + + def convert_box(size, box): + dw, dh = 1.0 / size[0], 1.0 / size[1] + x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2] + return x * dw, y * dh, w * dw, h * dh + + with open(path / f"VOC{year}/Annotations/{image_id}.xml") as in_file, open(lb_path, "w", encoding="utf-8") as out_file: + tree = ET.parse(in_file) + root = tree.getroot() + size = root.find("size") + w = int(size.find("width").text) + h = int(size.find("height").text) + + names = list(yaml["names"].values()) # names list + for obj in root.iter("object"): + cls = obj.find("name").text + if cls in names and int(obj.find("difficult").text) != 1: + xmlbox = obj.find("bndbox") + bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ("xmin", "xmax", "ymin", "ymax")]) + cls_id = names.index(cls) # class id + out_file.write(" ".join(str(a) for a in (cls_id, *bb)) + "\n") + + + # Download + dir = Path(yaml["path"]) # dataset root dir + urls = [ + f"{ASSETS_URL}/VOCtrainval_06-Nov-2007.zip", # 446MB, 5011 images + f"{ASSETS_URL}/VOCtest_06-Nov-2007.zip", # 438MB, 4952 images + f"{ASSETS_URL}/VOCtrainval_11-May-2012.zip", # 1.95GB, 17125 images + ] + download(urls, dir=dir / "images", threads=3, exist_ok=True) # download and unzip over existing (required) + + # Convert + path = dir / "images/VOCdevkit" + for year, image_set in ("2012", "train"), ("2012", "val"), ("2007", "train"), ("2007", "val"), ("2007", "test"): + imgs_path = dir / "images" / f"{image_set}{year}" + lbs_path = dir / "labels" / f"{image_set}{year}" + imgs_path.mkdir(exist_ok=True, parents=True) + lbs_path.mkdir(exist_ok=True, parents=True) + + with open(path / f"VOC{year}/ImageSets/Main/{image_set}.txt") as f: + image_ids = f.read().strip().split() + for id in TQDM(image_ids, desc=f"{image_set}{year}"): + f = path / f"VOC{year}/JPEGImages/{id}.jpg" # old img path + lb_path = (lbs_path / f.name).with_suffix(".txt") # new label path + f.rename(imgs_path / f.name) # move image + convert_label(path, lb_path, year, id) # convert labels to YOLO format diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/VisDrone.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/VisDrone.yaml new file mode 100644 index 0000000000000000000000000000000000000000..60b48d14c155f7975b437eae7e362654c65524eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/VisDrone.yaml @@ -0,0 +1,87 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset by Tianjin University +# Documentation: https://docs.ultralytics.com/datasets/detect/visdrone +# Example usage: yolo train data=VisDrone.yaml +# parent +# ├── ultralytics +# └── datasets +# └── VisDrone ← downloads here (~2 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: VisDrone # dataset root dir +train: images/train # train images (relative to 'path') 6471 images +val: images/val # val images (relative to 'path') 548 images +test: images/test # test-dev images (optional) 1610 images + +# Classes +names: + 0: pedestrian + 1: people + 2: bicycle + 3: car + 4: van + 5: truck + 6: tricycle + 7: awning-tricycle + 8: bus + 9: motor + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + import os + from pathlib import Path + import shutil + + from ultralytics.utils.downloads import download + from ultralytics.utils import ASSETS_URL, TQDM + + + def visdrone2yolo(dir, split, source_name=None): + """Convert VisDrone annotations to YOLO format with images/{split} and labels/{split} structure.""" + from PIL import Image + + source_dir = dir / (source_name or f"VisDrone2019-DET-{split}") + images_dir = dir / "images" / split + labels_dir = dir / "labels" / split + labels_dir.mkdir(parents=True, exist_ok=True) + + # Move images to new structure + if (source_images_dir := source_dir / "images").exists(): + images_dir.mkdir(parents=True, exist_ok=True) + for img in source_images_dir.glob("*.jpg"): + img.rename(images_dir / img.name) + + for f in TQDM((source_dir / "annotations").glob("*.txt"), desc=f"Converting {split}"): + img_size = Image.open(images_dir / f.with_suffix(".jpg").name).size + dw, dh = 1.0 / img_size[0], 1.0 / img_size[1] + lines = [] + + with open(f, encoding="utf-8") as file: + for row in [x.split(",") for x in file.read().strip().splitlines()]: + if row[4] != "0": # Skip ignored regions + x, y, w, h = map(int, row[:4]) + cls = int(row[5]) - 1 + # Convert to YOLO format + x_center, y_center = (x + w / 2) * dw, (y + h / 2) * dh + w_norm, h_norm = w * dw, h * dh + lines.append(f"{cls} {x_center:.6f} {y_center:.6f} {w_norm:.6f} {h_norm:.6f}\n") + + (labels_dir / f.name).write_text("".join(lines), encoding="utf-8") + + + # Download (ignores test-challenge split) + dir = Path(yaml["path"]) # dataset root dir + urls = [ + f"{ASSETS_URL}/VisDrone2019-DET-train.zip", + f"{ASSETS_URL}/VisDrone2019-DET-val.zip", + f"{ASSETS_URL}/VisDrone2019-DET-test-dev.zip", + # f"{ASSETS_URL}/VisDrone2019-DET-test-challenge.zip", + ] + download(urls, dir=dir, threads=4) + + # Convert + splits = {"VisDrone2019-DET-train": "train", "VisDrone2019-DET-val": "val", "VisDrone2019-DET-test-dev": "test"} + for folder, split in splits.items(): + visdrone2yolo(dir, split, folder) # convert VisDrone annotations to YOLO labels + shutil.rmtree(dir / folder) # cleanup original directory diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/ade20k.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/ade20k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2ba75179b92a8d8bceccc88408e7ecb5f7c8cef0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/ade20k.yaml @@ -0,0 +1,326 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# ADE20K semantic segmentation dataset (150 classes) +# Documentation: https://docs.ultralytics.com/datasets/semantic/ade20k +# Example usage: yolo semantic train data=ade20k.yaml model=yolo26n-sem.pt +# parent +# ├── ultralytics +# └── datasets +# └── ADEChallengeData2016 ← downloads here (1 GB) +# └── images +# └── annotations + +# Dataset root directory +path: ADEChallengeData2016 +train: images/training +val: images/validation + +masks_dir: annotations # semantic mask directory + +# ADE20K 150-class labels +names: + 0: wall + 1: building + 2: sky + 3: floor + 4: tree + 5: ceiling + 6: road + 7: bed + 8: windowpane + 9: grass + 10: cabinet + 11: sidewalk + 12: person + 13: earth + 14: door + 15: table + 16: mountain + 17: plant + 18: curtain + 19: chair + 20: car + 21: water + 22: painting + 23: sofa + 24: shelf + 25: house + 26: sea + 27: mirror + 28: rug + 29: field + 30: armchair + 31: seat + 32: fence + 33: desk + 34: rock + 35: wardrobe + 36: lamp + 37: bathtub + 38: railing + 39: cushion + 40: base + 41: box + 42: column + 43: signboard + 44: chest of drawers + 45: counter + 46: sand + 47: sink + 48: skyscraper + 49: fireplace + 50: refrigerator + 51: grandstand + 52: path + 53: stairs + 54: runway + 55: case + 56: pool table + 57: pillow + 58: screen door + 59: stairway + 60: river + 61: bridge + 62: bookcase + 63: blind + 64: coffee table + 65: toilet + 66: flower + 67: book + 68: hill + 69: bench + 70: countertop + 71: stove + 72: palm + 73: kitchen island + 74: computer + 75: swivel chair + 76: boat + 77: bar + 78: arcade machine + 79: hovel + 80: bus + 81: towel + 82: light + 83: truck + 84: tower + 85: chandelier + 86: awning + 87: streetlight + 88: booth + 89: television receiver + 90: airplane + 91: dirt track + 92: apparel + 93: pole + 94: land + 95: bannister + 96: escalator + 97: ottoman + 98: bottle + 99: buffet + 100: poster + 101: stage + 102: van + 103: ship + 104: fountain + 105: conveyor belt + 106: canopy + 107: washer + 108: plaything + 109: swimming pool + 110: stool + 111: barrel + 112: basket + 113: waterfall + 114: tent + 115: bag + 116: minibike + 117: cradle + 118: oven + 119: ball + 120: food + 121: step + 122: tank + 123: trade name + 124: microwave + 125: pot + 126: animal + 127: bicycle + 128: lake + 129: dishwasher + 130: screen + 131: blanket + 132: sculpture + 133: hood + 134: sconce + 135: vase + 136: traffic light + 137: tray + 138: ashcan + 139: fan + 140: pier + 141: crt screen + 142: plate + 143: monitor + 144: bulletin board + 145: shower + 146: radiator + 147: glass + 148: clock + 149: flag + +# Map source label IDs to train IDs; ignore_label is converted to 255. +label_mapping: + 0: ignore_label + 1: 0 + 2: 1 + 3: 2 + 4: 3 + 5: 4 + 6: 5 + 7: 6 + 8: 7 + 9: 8 + 10: 9 + 11: 10 + 12: 11 + 13: 12 + 14: 13 + 15: 14 + 16: 15 + 17: 16 + 18: 17 + 19: 18 + 20: 19 + 21: 20 + 22: 21 + 23: 22 + 24: 23 + 25: 24 + 26: 25 + 27: 26 + 28: 27 + 29: 28 + 30: 29 + 31: 30 + 32: 31 + 33: 32 + 34: 33 + 35: 34 + 36: 35 + 37: 36 + 38: 37 + 39: 38 + 40: 39 + 41: 40 + 42: 41 + 43: 42 + 44: 43 + 45: 44 + 46: 45 + 47: 46 + 48: 47 + 49: 48 + 50: 49 + 51: 50 + 52: 51 + 53: 52 + 54: 53 + 55: 54 + 56: 55 + 57: 56 + 58: 57 + 59: 58 + 60: 59 + 61: 60 + 62: 61 + 63: 62 + 64: 63 + 65: 64 + 66: 65 + 67: 66 + 68: 67 + 69: 68 + 70: 69 + 71: 70 + 72: 71 + 73: 72 + 74: 73 + 75: 74 + 76: 75 + 77: 76 + 78: 77 + 79: 78 + 80: 79 + 81: 80 + 82: 81 + 83: 82 + 84: 83 + 85: 84 + 86: 85 + 87: 86 + 88: 87 + 89: 88 + 90: 89 + 91: 90 + 92: 91 + 93: 92 + 94: 93 + 95: 94 + 96: 95 + 97: 96 + 98: 97 + 99: 98 + 100: 99 + 101: 100 + 102: 101 + 103: 102 + 104: 103 + 105: 104 + 106: 105 + 107: 106 + 108: 107 + 109: 108 + 110: 109 + 111: 110 + 112: 111 + 113: 112 + 114: 113 + 115: 114 + 116: 115 + 117: 116 + 118: 117 + 119: 118 + 120: 119 + 121: 120 + 122: 121 + 123: 122 + 124: 123 + 125: 124 + 126: 125 + 127: 126 + 128: 127 + 129: 128 + 130: 129 + 131: 130 + 132: 131 + 133: 132 + 134: 133 + 135: 134 + 136: 135 + 137: 136 + 138: 137 + 139: 138 + 140: 139 + 141: 140 + 142: 141 + 143: 142 + 144: 143 + 145: 144 + 146: 145 + 147: 146 + 148: 147 + 149: 148 + 150: 149 +# Download URL (manual): https://data.csail.mit.edu/places/ADEchallenge/ADEChallengeData2016.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/african-wildlife.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/african-wildlife.yaml new file mode 100644 index 0000000000000000000000000000000000000000..53fce53117bdb72390460cf955c20e13ad58ee14 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/african-wildlife.yaml @@ -0,0 +1,25 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# African Wildlife dataset by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/detect/african-wildlife +# Example usage: yolo train data=african-wildlife.yaml +# parent +# ├── ultralytics +# └── datasets +# └── african-wildlife ← downloads here (100 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: african-wildlife # dataset root dir +train: images/train # train images (relative to 'path') 1052 images +val: images/val # val images (relative to 'path') 225 images +test: images/test # test images (relative to 'path') 227 images + +# Classes +names: + 0: buffalo + 1: elephant + 2: rhino + 3: zebra + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/african-wildlife.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/brain-tumor.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/brain-tumor.yaml new file mode 100644 index 0000000000000000000000000000000000000000..daaf5503845dee6c6e0dd6b8315094dbe77cb4b6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/brain-tumor.yaml @@ -0,0 +1,22 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Brain-tumor dataset by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/detect/brain-tumor +# Example usage: yolo train data=brain-tumor.yaml +# parent +# ├── ultralytics +# └── datasets +# └── brain-tumor ← downloads here (4.21 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: brain-tumor # dataset root dir +train: images/train # train images (relative to 'path') 893 images +val: images/val # val images (relative to 'path') 223 images + +# Classes +names: + 0: negative + 1: positive + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/brain-tumor.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/carparts-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/carparts-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c76d7a6b1c3f952017e20a7856168bf60d1e3321 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/carparts-seg.yaml @@ -0,0 +1,44 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Carparts-seg dataset by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/segment/carparts-seg +# Example usage: yolo train data=carparts-seg.yaml +# parent +# ├── ultralytics +# └── datasets +# └── carparts-seg ← downloads here (133 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: carparts-seg # dataset root dir +train: images/train # train images (relative to 'path') 3156 images +val: images/val # val images (relative to 'path') 401 images +test: images/test # test images (relative to 'path') 276 images + +# Classes +names: + 0: back_bumper + 1: back_door + 2: back_glass + 3: back_left_door + 4: back_left_light + 5: back_light + 6: back_right_door + 7: back_right_light + 8: front_bumper + 9: front_door + 10: front_glass + 11: front_left_door + 12: front_left_light + 13: front_light + 14: front_right_door + 15: front_right_light + 16: hood + 17: left_mirror + 18: object + 19: right_mirror + 20: tailgate + 21: trunk + 22: wheel + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/carparts-seg.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/cityscapes.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/cityscapes.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2c4df696f90af47e3c6b11ad664ab995f667b723 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/cityscapes.yaml @@ -0,0 +1,111 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Cityscapes semantic segmentation dataset (19 classes) +# Documentation: https://docs.ultralytics.com/datasets/semantic/cityscapes +# Example usage: yolo semantic train data=cityscapes.yaml model=yolo26n-sem.pt +# parent +# ├── ultralytics +# └── datasets +# └── cityscapes ← downloads here (11 GB) +# └── images +# └── masks + +# Dataset root directory +path: cityscapes # dataset root dir +train: images/train # train images (relative to 'path') 2975 images +val: images/val # val images (relative to 'path') 500 images +test: images/test # test images (relative to 'path') 1525 images + +masks_dir: masks # semantic mask directory + +# Cityscapes 19-class labels +names: + 0: road + 1: sidewalk + 2: building + 3: wall + 4: fence + 5: pole + 6: traffic light + 7: traffic sign + 8: vegetation + 9: terrain + 10: sky + 11: person + 12: rider + 13: car + 14: truck + 15: bus + 16: train + 17: motorcycle + 18: bicycle + +# Map source label IDs to train IDs; ignore_label is converted to 255. +label_mapping: + -1: ignore_label + 0: ignore_label + 1: ignore_label + 2: ignore_label + 3: ignore_label + 4: ignore_label + 5: ignore_label + 6: ignore_label + 7: 0 + 8: 1 + 9: ignore_label + 10: ignore_label + 11: 2 + 12: 3 + 13: 4 + 14: ignore_label + 15: ignore_label + 16: ignore_label + 17: 5 + 18: ignore_label + 19: 6 + 20: 7 + 21: 8 + 22: 9 + 23: 10 + 24: 11 + 25: 12 + 26: 13 + 27: 14 + 28: 15 + 29: ignore_label + 30: ignore_label + 31: 16 + 32: 17 + 33: 18 + +# Preparation script (requires manual Cityscapes download) +download: | + from pathlib import Path + from shutil import copy2 + + cityscapes_dir = Path(yaml["path"]) # dataset root dir + # Download and extract the official Cityscapes leftImg8bit and gtFine archives into cityscapes_dir first. + leftimg8bit_dir = cityscapes_dir / "leftImg8bit" + gtfine_dir = cityscapes_dir / "gtFine" + + for split in ("train", "val", "test"): + print(f"Processing {split} set") + src_image_dir = leftimg8bit_dir / split + dst_image_dir = cityscapes_dir / "images" / split + dst_mask_dir = cityscapes_dir / "masks" / split + dst_image_dir.mkdir(parents=True, exist_ok=True) + dst_mask_dir.mkdir(parents=True, exist_ok=True) + + image_paths = sorted(src_image_dir.rglob("*_leftImg8bit.png")) + for image_path in image_paths: + relative_path = image_path.relative_to(src_image_dir) + mask_path = gtfine_dir / split / relative_path.parent / image_path.name.replace( + "_leftImg8bit.png", "_gtFine_labelIds.png" + ) + if not mask_path.exists(): + raise FileNotFoundError(f"Mask not found for {image_path}: {mask_path}") + + image_name = image_path.name.replace("_leftImg8bit", "") + mask_name = mask_path.name.replace("_gtFine_labelIds", "") + copy2(image_path, dst_image_dir / image_name) + copy2(mask_path, dst_mask_dir / mask_name) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/cityscapes8.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/cityscapes8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c11da58dc69439c1ba92e95a60627234d7d8e326 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/cityscapes8.yaml @@ -0,0 +1,81 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Cityscapes semantic segmentation dataset (19 classes) +# Documentation: https://docs.ultralytics.com/datasets/semantic/cityscapes8 +# Example usage: yolo semantic train data=cityscapes8.yaml model=yolo26n-sem.pt +# parent +# ├── ultralytics +# └── datasets +# └── cityscapes8 ← downloads here (small subset) +# └── images +# └── masks + +# Dataset root directory +path: cityscapes8 # dataset root dir +train: images/train # train images (relative to 'path') 4 images +val: images/val # val images (relative to 'path') 4 images + +masks_dir: masks # semantic mask directory + +# Cityscapes 19-class labels +names: + 0: road + 1: sidewalk + 2: building + 3: wall + 4: fence + 5: pole + 6: traffic light + 7: traffic sign + 8: vegetation + 9: terrain + 10: sky + 11: person + 12: rider + 13: car + 14: truck + 15: bus + 16: train + 17: motorcycle + 18: bicycle + +# Map source label IDs to train IDs; ignore_label is converted to 255. +label_mapping: + -1: ignore_label + 0: ignore_label + 1: ignore_label + 2: ignore_label + 3: ignore_label + 4: ignore_label + 5: ignore_label + 6: ignore_label + 7: 0 + 8: 1 + 9: ignore_label + 10: ignore_label + 11: 2 + 12: 3 + 13: 4 + 14: ignore_label + 15: ignore_label + 16: ignore_label + 17: 5 + 18: ignore_label + 19: 6 + 20: 7 + 21: 8 + 22: 9 + 23: 10 + 24: 11 + 25: 12 + 26: 13 + 27: 14 + 28: 15 + 29: ignore_label + 30: ignore_label + 31: 16 + 32: 17 + 33: 18 + +# Download URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/cityscapes8.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco-pose.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco-pose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3ae9bf7e460d216b010b92fa37a6243ffb82b9d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco-pose.yaml @@ -0,0 +1,64 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# COCO 2017 Keypoints dataset https://cocodataset.org by Microsoft +# Documentation: https://docs.ultralytics.com/datasets/pose/coco +# Example usage: yolo train data=coco-pose.yaml +# parent +# ├── ultralytics +# └── datasets +# └── coco-pose ← downloads here (20.2 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: coco-pose # dataset root dir +train: train2017.txt # train images (relative to 'path') 56599 images +val: val2017.txt # val images (relative to 'path') 2346 images +test: test-dev2017.txt # 20288 of 40670 images, submit to https://codalab.lisn.upsaclay.fr/competitions/7403 + +# Keypoints +kpt_shape: [17, 3] # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible) +flip_idx: [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15] + +# Classes +names: + 0: person + +# Keypoint names per class +kpt_names: + 0: + - nose + - left_eye + - right_eye + - left_ear + - right_ear + - left_shoulder + - right_shoulder + - left_elbow + - right_elbow + - left_wrist + - right_wrist + - left_hip + - right_hip + - left_knee + - right_knee + - left_ankle + - right_ankle + +# Download script/URL (optional) +download: | + from pathlib import Path + + from ultralytics.utils import ASSETS_URL + from ultralytics.utils.downloads import download + + # Download labels + dir = Path(yaml["path"]) # dataset root dir + + urls = [f"{ASSETS_URL}/coco2017labels-pose.zip"] + download(urls, dir=dir.parent) + + # Download data (test2017.zip excluded: ground truth is withheld, only used for the CodaLab test-dev split) + urls = [ + "http://images.cocodataset.org/zips/train2017.zip", # 19G, 118k images + "http://images.cocodataset.org/zips/val2017.zip", # 1G, 5k images + ] + download(urls, dir=dir / "images", threads=3) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco.yaml new file mode 100644 index 0000000000000000000000000000000000000000..62fb625322597418c4e38a05375808e3cc94d95b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco.yaml @@ -0,0 +1,118 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# COCO 2017 dataset https://cocodataset.org by Microsoft +# Documentation: https://docs.ultralytics.com/datasets/detect/coco +# Example usage: yolo train data=coco.yaml +# parent +# ├── ultralytics +# └── datasets +# └── coco ← downloads here (20.3 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: coco # dataset root dir +train: train2017.txt # train images (relative to 'path') 118287 images +val: val2017.txt # val images (relative to 'path') 5000 images +test: test-dev2017.txt # 20288 of 40670 images, submit via https://cocodataset.org/#detection-eval + +# Classes +names: + 0: person + 1: bicycle + 2: car + 3: motorcycle + 4: airplane + 5: bus + 6: train + 7: truck + 8: boat + 9: traffic light + 10: fire hydrant + 11: stop sign + 12: parking meter + 13: bench + 14: bird + 15: cat + 16: dog + 17: horse + 18: sheep + 19: cow + 20: elephant + 21: bear + 22: zebra + 23: giraffe + 24: backpack + 25: umbrella + 26: handbag + 27: tie + 28: suitcase + 29: frisbee + 30: skis + 31: snowboard + 32: sports ball + 33: kite + 34: baseball bat + 35: baseball glove + 36: skateboard + 37: surfboard + 38: tennis racket + 39: bottle + 40: wine glass + 41: cup + 42: fork + 43: knife + 44: spoon + 45: bowl + 46: banana + 47: apple + 48: sandwich + 49: orange + 50: broccoli + 51: carrot + 52: hot dog + 53: pizza + 54: donut + 55: cake + 56: chair + 57: couch + 58: potted plant + 59: bed + 60: dining table + 61: toilet + 62: tv + 63: laptop + 64: mouse + 65: remote + 66: keyboard + 67: cell phone + 68: microwave + 69: oven + 70: toaster + 71: sink + 72: refrigerator + 73: book + 74: clock + 75: vase + 76: scissors + 77: teddy bear + 78: hair drier + 79: toothbrush + +# Download script/URL (optional) +download: | + from pathlib import Path + + from ultralytics.utils import ASSETS_URL + from ultralytics.utils.downloads import download + + # Download labels + segments = True # segment or box labels + dir = Path(yaml["path"]) # dataset root dir + urls = [ASSETS_URL + ("/coco2017labels-segments.zip" if segments else "/coco2017labels.zip")] # labels + download(urls, dir=dir.parent) + + # Download data (test2017.zip excluded: ground truth is withheld, only used for the eval-server test-dev split) + urls = [ + "http://images.cocodataset.org/zips/train2017.zip", # 19G, 118k images + "http://images.cocodataset.org/zips/val2017.zip", # 1G, 5k images + ] + download(urls, dir=dir / "images", threads=3) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco12-formats.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco12-formats.yaml new file mode 100644 index 0000000000000000000000000000000000000000..de2be17d145174916b88af1d25d698740a80bab9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco12-formats.yaml @@ -0,0 +1,101 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# COCO12-Formats dataset (12 images testing all supported image formats) by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/detect/coco12-formats +# Example usage: yolo train data=coco12-formats.yaml +# parent +# ├── ultralytics +# └── datasets +# └── coco12-formats ← downloads here (1 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: coco12-formats # dataset root dir +train: images/train # train images (relative to 'path') 6 images +val: images/val # val images (relative to 'path') 6 images +test: # test images (optional) + +# Classes +names: + 0: person + 1: bicycle + 2: car + 3: motorcycle + 4: airplane + 5: bus + 6: train + 7: truck + 8: boat + 9: traffic light + 10: fire hydrant + 11: stop sign + 12: parking meter + 13: bench + 14: bird + 15: cat + 16: dog + 17: horse + 18: sheep + 19: cow + 20: elephant + 21: bear + 22: zebra + 23: giraffe + 24: backpack + 25: umbrella + 26: handbag + 27: tie + 28: suitcase + 29: frisbee + 30: skis + 31: snowboard + 32: sports ball + 33: kite + 34: baseball bat + 35: baseball glove + 36: skateboard + 37: surfboard + 38: tennis racket + 39: bottle + 40: wine glass + 41: cup + 42: fork + 43: knife + 44: spoon + 45: bowl + 46: banana + 47: apple + 48: sandwich + 49: orange + 50: broccoli + 51: carrot + 52: hot dog + 53: pizza + 54: donut + 55: cake + 56: chair + 57: couch + 58: potted plant + 59: bed + 60: dining table + 61: toilet + 62: tv + 63: laptop + 64: mouse + 65: remote + 66: keyboard + 67: cell phone + 68: microwave + 69: oven + 70: toaster + 71: sink + 72: refrigerator + 73: book + 74: clock + 75: vase + 76: scissors + 77: teddy bear + 78: hair drier + 79: toothbrush + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/coco12-formats.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco128-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco128-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3657c3077d554cec4d943649e73eb5ad997f7ca6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco128-seg.yaml @@ -0,0 +1,101 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# COCO128-seg dataset https://www.kaggle.com/datasets/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/segment/coco128-seg +# Example usage: yolo train data=coco128-seg.yaml +# parent +# ├── ultralytics +# └── datasets +# └── coco128-seg ← downloads here (7 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: coco128-seg # dataset root dir +train: images/train2017 # train images (relative to 'path') 128 images +val: images/train2017 # val images (relative to 'path') 128 images +test: # test images (optional) + +# Classes +names: + 0: person + 1: bicycle + 2: car + 3: motorcycle + 4: airplane + 5: bus + 6: train + 7: truck + 8: boat + 9: traffic light + 10: fire hydrant + 11: stop sign + 12: parking meter + 13: bench + 14: bird + 15: cat + 16: dog + 17: horse + 18: sheep + 19: cow + 20: elephant + 21: bear + 22: zebra + 23: giraffe + 24: backpack + 25: umbrella + 26: handbag + 27: tie + 28: suitcase + 29: frisbee + 30: skis + 31: snowboard + 32: sports ball + 33: kite + 34: baseball bat + 35: baseball glove + 36: skateboard + 37: surfboard + 38: tennis racket + 39: bottle + 40: wine glass + 41: cup + 42: fork + 43: knife + 44: spoon + 45: bowl + 46: banana + 47: apple + 48: sandwich + 49: orange + 50: broccoli + 51: carrot + 52: hot dog + 53: pizza + 54: donut + 55: cake + 56: chair + 57: couch + 58: potted plant + 59: bed + 60: dining table + 61: toilet + 62: tv + 63: laptop + 64: mouse + 65: remote + 66: keyboard + 67: cell phone + 68: microwave + 69: oven + 70: toaster + 71: sink + 72: refrigerator + 73: book + 74: clock + 75: vase + 76: scissors + 77: teddy bear + 78: hair drier + 79: toothbrush + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/coco128-seg.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco128.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco128.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6a93deafc400766486a0b58460ecca65239285c6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco128.yaml @@ -0,0 +1,101 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# COCO128 dataset https://www.kaggle.com/datasets/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/detect/coco128 +# Example usage: yolo train data=coco128.yaml +# parent +# ├── ultralytics +# └── datasets +# └── coco128 ← downloads here (7 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: coco128 # dataset root dir +train: images/train2017 # train images (relative to 'path') 128 images +val: images/train2017 # val images (relative to 'path') 128 images +test: # test images (optional) + +# Classes +names: + 0: person + 1: bicycle + 2: car + 3: motorcycle + 4: airplane + 5: bus + 6: train + 7: truck + 8: boat + 9: traffic light + 10: fire hydrant + 11: stop sign + 12: parking meter + 13: bench + 14: bird + 15: cat + 16: dog + 17: horse + 18: sheep + 19: cow + 20: elephant + 21: bear + 22: zebra + 23: giraffe + 24: backpack + 25: umbrella + 26: handbag + 27: tie + 28: suitcase + 29: frisbee + 30: skis + 31: snowboard + 32: sports ball + 33: kite + 34: baseball bat + 35: baseball glove + 36: skateboard + 37: surfboard + 38: tennis racket + 39: bottle + 40: wine glass + 41: cup + 42: fork + 43: knife + 44: spoon + 45: bowl + 46: banana + 47: apple + 48: sandwich + 49: orange + 50: broccoli + 51: carrot + 52: hot dog + 53: pizza + 54: donut + 55: cake + 56: chair + 57: couch + 58: potted plant + 59: bed + 60: dining table + 61: toilet + 62: tv + 63: laptop + 64: mouse + 65: remote + 66: keyboard + 67: cell phone + 68: microwave + 69: oven + 70: toaster + 71: sink + 72: refrigerator + 73: book + 74: clock + 75: vase + 76: scissors + 77: teddy bear + 78: hair drier + 79: toothbrush + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/coco128.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8-grayscale.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8-grayscale.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4923e1260a8c941510b4749b40a0fd6b31667ea6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8-grayscale.yaml @@ -0,0 +1,103 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# COCO8-Grayscale dataset (first 8 images from COCO train2017) by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/detect/coco8-grayscale +# Example usage: yolo train data=coco8-grayscale.yaml +# parent +# ├── ultralytics +# └── datasets +# └── coco8-grayscale ← downloads here (1 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: coco8-grayscale # dataset root dir +train: images/train # train images (relative to 'path') 4 images +val: images/val # val images (relative to 'path') 4 images +test: # test images (optional) + +channels: 1 + +# Classes +names: + 0: person + 1: bicycle + 2: car + 3: motorcycle + 4: airplane + 5: bus + 6: train + 7: truck + 8: boat + 9: traffic light + 10: fire hydrant + 11: stop sign + 12: parking meter + 13: bench + 14: bird + 15: cat + 16: dog + 17: horse + 18: sheep + 19: cow + 20: elephant + 21: bear + 22: zebra + 23: giraffe + 24: backpack + 25: umbrella + 26: handbag + 27: tie + 28: suitcase + 29: frisbee + 30: skis + 31: snowboard + 32: sports ball + 33: kite + 34: baseball bat + 35: baseball glove + 36: skateboard + 37: surfboard + 38: tennis racket + 39: bottle + 40: wine glass + 41: cup + 42: fork + 43: knife + 44: spoon + 45: bowl + 46: banana + 47: apple + 48: sandwich + 49: orange + 50: broccoli + 51: carrot + 52: hot dog + 53: pizza + 54: donut + 55: cake + 56: chair + 57: couch + 58: potted plant + 59: bed + 60: dining table + 61: toilet + 62: tv + 63: laptop + 64: mouse + 65: remote + 66: keyboard + 67: cell phone + 68: microwave + 69: oven + 70: toaster + 71: sink + 72: refrigerator + 73: book + 74: clock + 75: vase + 76: scissors + 77: teddy bear + 78: hair drier + 79: toothbrush + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/coco8-grayscale.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8-multispectral.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8-multispectral.yaml new file mode 100644 index 0000000000000000000000000000000000000000..76c021020de4c1a87e27516f2f10bb45e5bcd9bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8-multispectral.yaml @@ -0,0 +1,104 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# COCO8-Multispectral dataset (COCO8 images interpolated across 10 channels in the visual spectrum) by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/detect/coco8-multispectral +# Example usage: yolo train data=coco8-multispectral.yaml +# parent +# ├── ultralytics +# └── datasets +# └── coco8-multispectral ← downloads here (20.2 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: coco8-multispectral # dataset root dir +train: images/train # train images (relative to 'path') 4 images +val: images/val # val images (relative to 'path') 4 images +test: # test images (optional) + +# Number of multispectral image channels +channels: 10 + +# Classes +names: + 0: person + 1: bicycle + 2: car + 3: motorcycle + 4: airplane + 5: bus + 6: train + 7: truck + 8: boat + 9: traffic light + 10: fire hydrant + 11: stop sign + 12: parking meter + 13: bench + 14: bird + 15: cat + 16: dog + 17: horse + 18: sheep + 19: cow + 20: elephant + 21: bear + 22: zebra + 23: giraffe + 24: backpack + 25: umbrella + 26: handbag + 27: tie + 28: suitcase + 29: frisbee + 30: skis + 31: snowboard + 32: sports ball + 33: kite + 34: baseball bat + 35: baseball glove + 36: skateboard + 37: surfboard + 38: tennis racket + 39: bottle + 40: wine glass + 41: cup + 42: fork + 43: knife + 44: spoon + 45: bowl + 46: banana + 47: apple + 48: sandwich + 49: orange + 50: broccoli + 51: carrot + 52: hot dog + 53: pizza + 54: donut + 55: cake + 56: chair + 57: couch + 58: potted plant + 59: bed + 60: dining table + 61: toilet + 62: tv + 63: laptop + 64: mouse + 65: remote + 66: keyboard + 67: cell phone + 68: microwave + 69: oven + 70: toaster + 71: sink + 72: refrigerator + 73: book + 74: clock + 75: vase + 76: scissors + 77: teddy bear + 78: hair drier + 79: toothbrush + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/coco8-multispectral.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8-pose.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8-pose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bbcc2e3cc52bc0c43d27a0dddc985a87cb8959f7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8-pose.yaml @@ -0,0 +1,47 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# COCO8-pose dataset (first 8 images from COCO train2017) by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/pose/coco8-pose +# Example usage: yolo train data=coco8-pose.yaml +# parent +# ├── ultralytics +# └── datasets +# └── coco8-pose ← downloads here (1 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: coco8-pose # dataset root dir +train: images/train # train images (relative to 'path') 4 images +val: images/val # val images (relative to 'path') 4 images +test: # test images (optional) + +# Keypoints +kpt_shape: [17, 3] # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible) +flip_idx: [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15] + +# Classes +names: + 0: person + +# Keypoint names per class +kpt_names: + 0: + - nose + - left_eye + - right_eye + - left_ear + - right_ear + - left_shoulder + - right_shoulder + - left_elbow + - right_elbow + - left_wrist + - right_wrist + - left_hip + - right_hip + - left_knee + - right_knee + - left_ankle + - right_ankle + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/coco8-pose.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d476a78be3ff4b10ef459ecd083f89c369b278d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8-seg.yaml @@ -0,0 +1,101 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# COCO8-seg dataset (first 8 images from COCO train2017) by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/segment/coco8-seg +# Example usage: yolo train data=coco8-seg.yaml +# parent +# ├── ultralytics +# └── datasets +# └── coco8-seg ← downloads here (1 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: coco8-seg # dataset root dir +train: images/train # train images (relative to 'path') 4 images +val: images/val # val images (relative to 'path') 4 images +test: # test images (optional) + +# Classes +names: + 0: person + 1: bicycle + 2: car + 3: motorcycle + 4: airplane + 5: bus + 6: train + 7: truck + 8: boat + 9: traffic light + 10: fire hydrant + 11: stop sign + 12: parking meter + 13: bench + 14: bird + 15: cat + 16: dog + 17: horse + 18: sheep + 19: cow + 20: elephant + 21: bear + 22: zebra + 23: giraffe + 24: backpack + 25: umbrella + 26: handbag + 27: tie + 28: suitcase + 29: frisbee + 30: skis + 31: snowboard + 32: sports ball + 33: kite + 34: baseball bat + 35: baseball glove + 36: skateboard + 37: surfboard + 38: tennis racket + 39: bottle + 40: wine glass + 41: cup + 42: fork + 43: knife + 44: spoon + 45: bowl + 46: banana + 47: apple + 48: sandwich + 49: orange + 50: broccoli + 51: carrot + 52: hot dog + 53: pizza + 54: donut + 55: cake + 56: chair + 57: couch + 58: potted plant + 59: bed + 60: dining table + 61: toilet + 62: tv + 63: laptop + 64: mouse + 65: remote + 66: keyboard + 67: cell phone + 68: microwave + 69: oven + 70: toaster + 71: sink + 72: refrigerator + 73: book + 74: clock + 75: vase + 76: scissors + 77: teddy bear + 78: hair drier + 79: toothbrush + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/coco8-seg.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c325f7aa53ff036c0bf0b143be5bf682b767dac4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/coco8.yaml @@ -0,0 +1,101 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# COCO8 dataset (first 8 images from COCO train2017) by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/detect/coco8 +# Example usage: yolo train data=coco8.yaml +# parent +# ├── ultralytics +# └── datasets +# └── coco8 ← downloads here (1 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: coco8 # dataset root dir +train: images/train # train images (relative to 'path') 4 images +val: images/val # val images (relative to 'path') 4 images +test: # test images (optional) + +# Classes +names: + 0: person + 1: bicycle + 2: car + 3: motorcycle + 4: airplane + 5: bus + 6: train + 7: truck + 8: boat + 9: traffic light + 10: fire hydrant + 11: stop sign + 12: parking meter + 13: bench + 14: bird + 15: cat + 16: dog + 17: horse + 18: sheep + 19: cow + 20: elephant + 21: bear + 22: zebra + 23: giraffe + 24: backpack + 25: umbrella + 26: handbag + 27: tie + 28: suitcase + 29: frisbee + 30: skis + 31: snowboard + 32: sports ball + 33: kite + 34: baseball bat + 35: baseball glove + 36: skateboard + 37: surfboard + 38: tennis racket + 39: bottle + 40: wine glass + 41: cup + 42: fork + 43: knife + 44: spoon + 45: bowl + 46: banana + 47: apple + 48: sandwich + 49: orange + 50: broccoli + 51: carrot + 52: hot dog + 53: pizza + 54: donut + 55: cake + 56: chair + 57: couch + 58: potted plant + 59: bed + 60: dining table + 61: toilet + 62: tv + 63: laptop + 64: mouse + 65: remote + 66: keyboard + 67: cell phone + 68: microwave + 69: oven + 70: toaster + 71: sink + 72: refrigerator + 73: book + 74: clock + 75: vase + 76: scissors + 77: teddy bear + 78: hair drier + 79: toothbrush + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/coco8.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/construction-ppe.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/construction-ppe.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cedce9afedf0fc53f99583ec631f1e4fdc223077 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/construction-ppe.yaml @@ -0,0 +1,32 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Construction-PPE dataset by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/detect/construction-ppe +# Example usage: yolo train data=construction-ppe.yaml +# parent +# ├── ultralytics +# └── datasets +# └── construction-ppe ← downloads here (178.4 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: construction-ppe # dataset root dir +train: images/train # train images (relative to 'path') 1132 images +val: images/val # val images (relative to 'path') 143 images +test: images/test # test images (relative to 'path') 141 images + +# Classes +names: + 0: helmet + 1: gloves + 2: vest + 3: boots + 4: goggles + 5: none + 6: Person + 7: no_helmet + 8: no_goggle + 9: no_gloves + 10: no_boots + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/construction-ppe.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/crack-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/crack-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5e9c0c20a052af9bd3cd98098a53ed0cb8638bd0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/crack-seg.yaml @@ -0,0 +1,22 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Crack-seg dataset by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/segment/crack-seg +# Example usage: yolo train data=crack-seg.yaml +# parent +# ├── ultralytics +# └── datasets +# └── crack-seg ← downloads here (91.6 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: crack-seg # dataset root dir +train: images/train # train images (relative to 'path') 3717 images +val: images/val # val images (relative to 'path') 200 images +test: images/test # test images (relative to 'path') 112 images + +# Classes +names: + 0: crack + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/crack-seg.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-arkitscenes.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-arkitscenes.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4e109fb7f841eb4d3ac2c1bfbcd96e59ff58c2f2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-arkitscenes.yaml @@ -0,0 +1,22 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# ARKitScenes dataset for monocular depth estimation — real indoor RGB-D from Apple ARKit (iPad Pro LiDAR), depth ~0.5-6 m +# Documentation: https://docs.ultralytics.com/datasets/depth/arkitscenes +# Example usage: yolo depth train data=depth-arkitscenes.yaml model=yolo26n-depth.pt +# No autodownload — obtain the source data (see docs) and arrange it as below. +# parent +# ├── ultralytics +# └── datasets +# └── depth-arkitscenes +# ├── images/{train,val} # RGB images +# └── depth/{train,val} # paired 16-bit *.png depth maps (images/ -> depth/) + +path: depth-arkitscenes # dataset root dir (relative to Ultralytics settings 'datasets_dir') +train: images/train # train images (relative to 'path') 676080 images +val: images/val # val images (relative to 'path') 21559 images + +nc: 1 +names: + 0: depth + +channels: 3 diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-diode.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-diode.yaml new file mode 100644 index 0000000000000000000000000000000000000000..08ad9f27f3dac873dc0daef541cc573e2979763c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-diode.yaml @@ -0,0 +1,51 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# DIODE dataset for monocular depth estimation — real indoor + outdoor, FARO Focus survey-grade laser, depth up to ~80 m +# Documentation: https://docs.ultralytics.com/datasets/depth/diode +# Example usage: yolo depth train data=depth-diode.yaml model=yolo26n-depth.pt +# parent +# ├── ultralytics +# └── datasets +# └── depth-diode ← downloads here (84 GB archives, ~90 GB converted) +# ├── images/{train,val} # RGB images +# └── depth/{train,val} # paired 16-bit *.png depth maps (images/ -> depth/) +# If an interrupted download leaves a partial dataset, delete the depth-diode dir and re-run to rebuild it. + +path: depth-diode # dataset root dir (relative to Ultralytics settings 'datasets_dir') +train: images/train # train images (relative to 'path') 25458 images +val: images/val # val images (relative to 'path') 771 images +max_depth: 80 # (m) maximum valid depth; GT beyond this is excluded from val metrics + +nc: 1 +names: + 0: depth + +channels: 3 +depth_scale: 256 # PNG value 256 = 1 meter; represents the 80 m outdoor range + +# Download script/URL (optional) +download: | + import shutil + from pathlib import Path + + import numpy as np + + from ultralytics.data.utils import save_depth_png + from ultralytics.utils import TQDM + from ultralytics.utils.downloads import download + + # Download and extract the official archives (train ~81 GB, val ~2.6 GB), then convert: + # flatten ///*.png into images// and save the paired *_depth.npy + # (masked invalid -> 0, clipped at 80 m) as depth//*.png + dir = Path(yaml["path"]) # dataset root dir + download([f"https://diode-dataset.s3.amazonaws.com/{s}.tar.gz" for s in ("train", "val")], dir=dir / "source", delete=True) + for split in ("train", "val"): + (dir / "images" / split).mkdir(parents=True, exist_ok=True) + (dir / "depth" / split).mkdir(parents=True, exist_ok=True) + for im in TQDM(sorted((dir / "source" / split).rglob("*.png")), desc=f"Converting {split}"): + name = "_".join(im.relative_to(dir / "source").parts) # train/indoors/scene/scan/x.png -> train_indoors_scene_scan_x.png + depth = np.load(im.with_name(f"{im.stem}_depth.npy")).squeeze().astype(np.float32) + depth[np.load(im.with_name(f"{im.stem}_depth_mask.npy")) == 0] = 0.0 # zero out invalid pixels + save_depth_png(dir / "depth" / split / f"{name[:-4]}.png", depth.clip(max=80), scale=256) + im.replace(dir / "images" / split / name) + shutil.rmtree(dir / "source") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-hypersim.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-hypersim.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d17e09547c3b4d5c9a11b19d97459b05214e0c0d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-hypersim.yaml @@ -0,0 +1,22 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Hypersim dataset for monocular depth estimation — photorealistic synthetic indoor (ray-traced), dense depth up to ~10 m +# Documentation: https://docs.ultralytics.com/datasets/depth/hypersim +# Example usage: yolo depth train data=depth-hypersim.yaml model=yolo26n-depth.pt +# No autodownload — obtain the source data (see docs) and arrange it as below. +# parent +# ├── ultralytics +# └── datasets +# └── depth-hypersim +# ├── images/{train,val} # RGB images +# └── depth/{train,val} # paired 16-bit *.png depth maps (images/ -> depth/) + +path: depth-hypersim # dataset root dir (relative to Ultralytics settings 'datasets_dir') +train: images/train # train images (relative to 'path') 68242 images +val: images/val # val images (relative to 'path') 6377 images + +nc: 1 +names: + 0: depth + +channels: 3 diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-kitti.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-kitti.yaml new file mode 100644 index 0000000000000000000000000000000000000000..265f7ba1148162e46a89f6a16b460b3f1c784840 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-kitti.yaml @@ -0,0 +1,95 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# KITTI dataset for monocular depth estimation — real outdoor driving, Velodyne HDL-64 LiDAR (densified), sparse, up to ~80 m +# Documentation: https://docs.ultralytics.com/datasets/depth/kitti +# Example usage: yolo depth train data=depth-kitti.yaml model=yolo26n-depth.pt +# parent +# ├── ultralytics +# └── datasets +# └── depth-kitti ← downloads here (~190 GB archives, ~140 GB converted) +# ├── images/{train,val} # RGB images +# └── depth/{train,val} # paired 16-bit *.png depth maps (images/ -> depth/) +# If an interrupted download leaves a partial dataset, delete the depth-kitti dir and re-run to rebuild it. +# The download only runs when the val images are missing (train is never checked), so a depth-kitti dir +# built before this split fix keeps the old split until it is deleted and rebuilt. + +path: depth-kitti # dataset root dir (relative to Ultralytics settings 'datasets_dir') +train: images/train # train images (relative to 'path') 55198 images +val: images/val # val images (relative to 'path') 652 images (KITTI Eigen test split, left camera) +max_depth: 80 # (m) maximum valid depth; GT beyond this is excluded from val metrics + +nc: 1 +names: + 0: depth + +channels: 3 +depth_scale: 256 # KITTI PNG value 256 = 1 meter + +# Download script/URL (optional) +download: | + import shutil + from pathlib import Path + + from ultralytics.utils import TQDM + from ultralytics.utils.downloads import download + + # The 28 KITTI Eigen test scenes as " " -> val; every other annotated drive -> train. val is + # the 697-frame Eigen et al. (NeurIPS 2014) test split restricted to frames with improved GT here: 652 left-camera. + EIGEN_TEST = """ + 2011_09_26_drive_0002 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 69 + 2011_09_26_drive_0009 16 32 48 64 80 96 112 128 144 160 176 196 212 228 244 260 276 292 308 324 340 356 372 388 + 2011_09_26_drive_0013 5 10 20 30 35 40 45 50 60 65 70 80 85 90 95 100 105 110 115 120 125 130 135 + 2011_09_26_drive_0020 6 9 12 15 18 21 27 33 36 42 45 48 51 54 57 60 63 66 69 72 75 78 + 2011_09_26_drive_0023 18 36 54 72 90 108 126 144 162 180 198 216 252 270 288 306 324 342 360 378 396 414 432 450 468 + 2011_09_26_drive_0027 7 14 21 28 35 42 49 56 63 70 77 84 91 98 112 119 126 133 140 147 161 168 175 182 + 2011_09_26_drive_0029 14 28 42 56 70 84 98 112 126 140 154 168 182 196 268 296 310 324 338 352 366 380 394 408 + 2011_09_26_drive_0036 32 64 96 128 160 192 224 256 288 320 352 384 416 448 480 512 544 576 608 640 672 704 768 + 2011_09_26_drive_0046 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 + 2011_09_26_drive_0048 5 6 7 8 9 10 11 12 13 14 15 16 + 2011_09_26_drive_0052 6 8 10 12 14 16 18 20 22 26 28 30 32 36 38 40 42 44 46 48 50 52 + 2011_09_26_drive_0056 11 22 33 44 55 66 77 88 99 110 121 143 154 165 176 187 198 209 220 231 242 253 264 275 286 + 2011_09_26_drive_0059 14 28 42 56 70 84 98 112 126 140 154 182 196 210 224 238 274 288 302 316 330 344 358 + 2011_09_26_drive_0064 22 44 66 88 110 154 176 198 220 242 264 286 308 330 352 374 396 418 440 462 484 506 528 550 + 2011_09_26_drive_0084 49 62 75 88 101 114 127 140 153 179 192 205 218 231 244 257 270 283 296 309 322 335 348 361 374 + 2011_09_26_drive_0086 7 34 61 88 115 142 169 196 223 250 277 304 331 358 385 412 439 466 493 520 574 601 628 655 682 + 2011_09_26_drive_0093 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256 305 321 337 353 369 385 401 417 + 2011_09_26_drive_0096 19 38 57 76 95 114 133 152 171 190 209 228 247 266 285 304 323 342 361 380 399 418 437 456 + 2011_09_26_drive_0101 80 114 148 182 216 284 318 352 386 420 454 488 522 556 590 624 658 692 726 760 794 828 862 896 930 + 2011_09_26_drive_0106 15 35 43 51 59 67 75 83 91 99 107 115 123 131 139 147 155 163 171 179 187 195 203 211 219 + 2011_09_26_drive_0117 26 52 78 104 130 156 182 208 234 260 286 312 338 364 390 416 442 468 494 546 572 598 624 650 + 2011_09_28_drive_0002 6 9 12 18 21 24 30 33 36 39 45 48 51 54 57 60 63 72 78 81 84 87 90 + 2011_09_29_drive_0071 36 72 108 144 180 216 252 288 324 360 396 432 468 504 540 576 612 735 771 807 879 915 951 + 2011_09_30_drive_0016 11 22 33 44 55 66 77 88 110 121 132 143 154 165 176 187 198 209 220 231 242 253 264 + 2011_09_30_drive_0018 107 214 428 535 642 749 856 963 1070 1177 1284 1391 1498 1605 1712 1819 1926 2033 2140 2247 2419 2526 2633 2740 + 2011_09_30_drive_0027 41 82 123 164 205 246 287 328 369 410 451 492 533 574 615 656 753 794 835 876 917 958 1040 1081 + 2011_10_03_drive_0027 181 362 543 734 915 1096 1277 1458 1639 1820 2001 2363 2544 2725 2906 3087 3268 3449 3630 3811 3992 4173 4354 4535 + 2011_10_03_drive_0047 32 64 96 128 160 192 224 288 320 352 384 416 448 480 512 544 576 608 640 672 704 736 768 800""" + EIGEN_TEST = {ln.split()[0]: {int(i) for i in ln.split()[1:]} for ln in EIGEN_TEST.strip().splitlines()} + # Annotated drives excluded from the release training set (raw data was unavailable at build time) + SKIP_DRIVES = {"2011_09_28_drive_0104", "2011_09_28_drive_0135", "2011_09_28_drive_0177", "2011_09_28_drive_0214"} + + # Download the improved sparse GT (~14 GB) and the raw recordings it covers (~175 GB) + dir = Path(yaml["path"]) # dataset root dir + base = "https://s3.eu-central-1.amazonaws.com/avg-kitti" + download([f"{base}/data_depth_annotated.zip"], dir=dir / "source", delete=True, exist_ok=True) + gt_drives = sorted(p for p in (dir / "source" / "data_depth_annotated").glob("*/*_sync") if p.name[:-5] not in SKIP_DRIVES) + urls = [f"{base}/raw_data/{p.name[:-5]}/{p.name}.zip" for p in gt_drives] + download(urls, dir=dir / "source" / "raw", delete=True, exist_ok=True, threads=4) + + # Convert: GT PNGs are uint16 meters*256; RGB frames come from the matching raw drive + for split in ("train", "val"): + (dir / "images" / split).mkdir(parents=True, exist_ok=True) + (dir / "depth" / split).mkdir(parents=True, exist_ok=True) + for gt in TQDM(gt_drives, desc="Converting"): + drive = gt.name[:-5] # 2011_09_26_drive_0002 + split = "val" if drive in EIGEN_TEST else "train" + # val is the canonical Eigen test split: left camera only, and only its 652 listed frames + for cam in ("image_02",) if split == "val" else ("image_02", "image_03"): + for png in sorted((gt / "proj_depth" / "groundtruth" / cam).glob("*.png")): + if split == "val" and int(png.stem) not in EIGEN_TEST[drive]: + continue + name = f"{drive}_{cam[-2:]}_{png.stem}" + png.replace(dir / "depth" / split / f"{name}.png") + raw = dir / "source" / "raw" / drive[:10] / gt.name / cam / "data" / png.name + raw.replace(dir / "images" / split / f"{name}.png") + shutil.rmtree(dir / "source") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-sunrgbd.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-sunrgbd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..33fe854be83c5598e8cc4f26ebd967db5840f935 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-sunrgbd.yaml @@ -0,0 +1,54 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# SUN RGB-D dataset for monocular depth estimation — real indoor, multi-sensor RGB-D (RealSense/Xtion/Kinect), up to ~10 m +# Documentation: https://docs.ultralytics.com/datasets/depth/sunrgbd +# Example usage: yolo depth train data=depth-sunrgbd.yaml model=yolo26n-depth.pt +# parent +# ├── ultralytics +# └── datasets +# └── depth-sunrgbd ← downloads here (6.5 GB archive, ~14 GB converted) +# ├── images/{train,val} # RGB images +# └── depth/{train,val} # paired 16-bit *.png depth maps (images/ -> depth/) +# If an interrupted download leaves a partial dataset, delete the depth-sunrgbd dir and re-run to rebuild it. + +path: depth-sunrgbd # dataset root dir (relative to Ultralytics settings 'datasets_dir') +train: images/train # train images (relative to 'path') 9245 images +val: images/val # val images (relative to 'path') 1090 images + +nc: 1 +names: + 0: depth + +channels: 3 + +# Download script/URL (optional) +download: | + import random + import shutil + from pathlib import Path + + import cv2 + import numpy as np + + from ultralytics.data.utils import save_depth_png + from ultralytics.utils import TQDM + from ultralytics.utils.downloads import download + + # Download and extract the official archive (~6.5 GB), then convert each of the 10335 scenes: + # refined depth_bfx PNGs decode via the SUN RGB-D bit-rotation (d>>3 | d<<13) to millimeters, + # clipped at 10 m; a deterministic random 1090-scene subset (seed 0) forms the val split + dir = Path(yaml["path"]) # dataset root dir + download(["https://rgbd.cs.princeton.edu/data/SUNRGBD.zip"], dir=dir / "source", delete=True, exist_ok=True) + for split in ("train", "val"): + (dir / "images" / split).mkdir(parents=True, exist_ok=True) + (dir / "depth" / split).mkdir(parents=True, exist_ok=True) + scenes = sorted(p.parent for p in (dir / "source" / "SUNRGBD").rglob("depth_bfx")) + names = ["_".join(s.relative_to(dir / "source" / "SUNRGBD").parts) for s in scenes] + val = set(random.Random(0).sample(names, k=1090)) + for scene, name in TQDM(zip(scenes, names), total=len(scenes), desc="Converting"): + split = "val" if name in val else "train" + d = cv2.imread(str(next((scene / "depth_bfx").glob("*.png"))), cv2.IMREAD_ANYDEPTH) + d = (((d >> 3) | (d << 13)) / 1000.0).clip(max=10).astype(np.float32) # bit-rotated mm -> m + save_depth_png(dir / "depth" / split / f"{name}.png", d) + next((scene / "image").glob("*.jpg")).replace(dir / "images" / split / f"{name}.jpg") + shutil.rmtree(dir / "source") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-tartanair.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-tartanair.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f666b421a686a192fda6f31b92f6a1fadd0b7822 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-tartanair.yaml @@ -0,0 +1,24 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# TartanAir dataset for monocular depth estimation — synthetic indoor + outdoor (AirSim), dense depth up to ~80 m +# Documentation: https://docs.ultralytics.com/datasets/depth/tartanair +# Example usage: yolo depth train data=depth-tartanair.yaml model=yolo26n-depth.pt +# No autodownload — obtain the source data (see docs) and arrange it as below. +# parent +# ├── ultralytics +# └── datasets +# └── depth-tartanair +# ├── images/{train,val} # RGB images +# └── depth/{train,val} # paired 16-bit *.png depth maps (images/ -> depth/) + +path: depth-tartanair # dataset root dir (relative to Ultralytics settings 'datasets_dir') +train: images/train # train images (relative to 'path') 55660 images +val: images/val # val images (relative to 'path') 5810 images +max_depth: 80 # (m) maximum valid depth; GT beyond this is excluded from val metrics + +nc: 1 +names: + 0: depth + +channels: 3 +depth_scale: 256 # PNG value 256 = 1 meter; represents the 80 m outdoor range diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-vkitti2.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-vkitti2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dcea926b5d6dd5d7561019742a9cea036bf2c945 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth-vkitti2.yaml @@ -0,0 +1,53 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Virtual KITTI 2 dataset for monocular depth estimation — photorealistic synthetic outdoor driving, dense per-pixel depth +# Documentation: https://docs.ultralytics.com/datasets/depth/vkitti2 +# Example usage: yolo depth train data=depth-vkitti2.yaml model=yolo26n-depth.pt +# parent +# ├── ultralytics +# └── datasets +# └── depth-vkitti2 ← downloads here (15 GB archives, ~85 GB converted) +# ├── images/{train,val} # RGB images +# └── depth/{train,val} # paired 16-bit *.png depth maps (images/ -> depth/) +# If an interrupted download leaves a partial dataset, delete the depth-vkitti2 dir and re-run to rebuild it. + +path: depth-vkitti2 # dataset root dir (relative to Ultralytics settings 'datasets_dir') +train: images/train # train images (relative to 'path') 25780 images +val: images/val # val images (relative to 'path') 16740 images +max_depth: 80 # (m) maximum valid depth; GT beyond this is excluded from val metrics + +nc: 1 +names: + 0: depth + +channels: 3 +depth_scale: 100 # source PNG value 100 = 1 meter (centimeters) + +# Download script/URL (optional) +download: | + import shutil + from pathlib import Path + + import cv2 + import numpy as np + + from ultralytics.data.utils import save_depth_png + from ultralytics.utils import TQDM + from ultralytics.utils.downloads import download + + # Download and extract the official RGB + depth tars (~15 GB), then convert: Scene20 -> val, all + # other scenes -> train; depth PNGs are uint16 centimeters (sky = 655.35 m), clipped at 80 m + dir = Path(yaml["path"]) # dataset root dir + urls = [f"https://download.europe.naverlabs.com/virtual_kitti_2.0.3/vkitti_2.0.3_{s}.tar" for s in ("rgb", "depth")] + download(urls, dir=dir / "source", delete=True) + for split in ("train", "val"): + (dir / "images" / split).mkdir(parents=True, exist_ok=True) + (dir / "depth" / split).mkdir(parents=True, exist_ok=True) + for im in TQDM(sorted((dir / "source").rglob("rgb_*.jpg")), desc="Converting"): + scene, variation, camera = im.parts[-6], im.parts[-5], im.parts[-2] # Scene01/clone/frames/rgb/Camera_0/rgb_00000.jpg + split = "val" if scene == "Scene20" else "train" + name = f"{scene}_{variation}_{camera}_{im.stem[4:]}" + depth = cv2.imread(str(im.parents[2] / "depth" / camera / f"depth_{im.stem[4:]}.png"), cv2.IMREAD_ANYDEPTH) + save_depth_png(dir / "depth" / split / f"{name}.png", (depth.astype(np.float32) / 100.0).clip(max=80), scale=100) # cm -> m -> cm PNG + im.replace(dir / "images" / split / f"{name}.jpg") + shutil.rmtree(dir / "source") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth8.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1f722b21ea03133efffb91fb530797749afaea83 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/depth8.yaml @@ -0,0 +1,31 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Depth8 dataset (8 clean-label indoor images from SUN RGB-D Kinect v1/v2, 4 train / 4 val) by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/depth/depth8 +# Format: https://docs.ultralytics.com/datasets/depth#depth-map-format +# uint16 PNG values are divided by depth_scale to produce meters. The default 1000 gives 65,535 +# one-millimeter depth values from 0.001 to 65.535 m; code 0 is invalid. +# Common values (resolution, uint16 maximum): +# ARKitScenes and NYU Depth V2: 1000 (1 mm, 65.535 m) +# KITTI: 256 (3.90625 mm, 255.996 m); Virtual KITTI 2: 100 (1 cm, 655.35 m) +# Example usage: yolo depth train data=depth8.yaml model=yolo26n-depth.pt +# parent +# ├── ultralytics +# └── datasets +# └── depth8-png ← downloads here (1.3 MB) +# ├── images/{train,val} # RGB images +# └── depth/{train,val} # paired 16-bit *.png depth maps (images/ -> depth/) + +path: depth8-png # dataset root dir (relative to Ultralytics settings 'datasets_dir') +train: images/train # train images (relative to 'path') 4 images +val: images/val # val images (relative to 'path') 4 images + +nc: 1 +names: + 0: depth + +channels: 3 +depth_scale: 1000 # PNG value 1000 = 1 meter + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/depth8-png.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/dog-pose.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/dog-pose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cade144a25fd173ce881cc8d8faaa8d4f71ac130 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/dog-pose.yaml @@ -0,0 +1,52 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Dogs dataset http://vision.stanford.edu/aditya86/ImageNetDogs/ by Stanford +# Documentation: https://docs.ultralytics.com/datasets/pose/dog-pose +# Example usage: yolo train data=dog-pose.yaml +# parent +# ├── ultralytics +# └── datasets +# └── dog-pose ← downloads here (337 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: dog-pose # dataset root dir +train: images/train # train images (relative to 'path') 6773 images +val: images/val # val images (relative to 'path') 1703 images + +# Keypoints +kpt_shape: [24, 3] # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible) + +# Classes +names: + 0: dog + +# Keypoint names per class +kpt_names: + 0: + - front_left_paw + - front_left_knee + - front_left_elbow + - rear_left_paw + - rear_left_knee + - rear_left_elbow + - front_right_paw + - front_right_knee + - front_right_elbow + - rear_right_paw + - rear_right_knee + - rear_right_elbow + - tail_start + - tail_end + - left_ear_base + - right_ear_base + - nose + - chin + - left_ear_tip + - right_ear_tip + - left_eye + - right_eye + - withers + - throat + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/dog-pose.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/dota128.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/dota128.yaml new file mode 100644 index 0000000000000000000000000000000000000000..49129bf70fc686eba8b6d2d13591971e7c985324 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/dota128.yaml @@ -0,0 +1,35 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# DOTA128 dataset (128 images from the DOTAv1 split) by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/obb/dota128 +# Example usage: yolo train model=yolo26n-obb.pt data=dota128.yaml +# parent +# ├── ultralytics +# └── datasets +# └── dota128 ← downloads here (34 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: dota128 # dataset root dir +train: images/train # train images (relative to 'path') 128 images +val: images/train # val images (relative to 'path') 128 images + +# Classes for DOTA 1.0 +names: + 0: plane + 1: ship + 2: storage tank + 3: baseball diamond + 4: tennis court + 5: basketball court + 6: ground track field + 7: harbor + 8: bridge + 9: large vehicle + 10: small vehicle + 11: helicopter + 12: roundabout + 13: soccer ball field + 14: swimming pool + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/dota128.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/dota8-multispectral.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/dota8-multispectral.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1e9b86dfc4b09079e59bb57e580fe6a9a413333b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/dota8-multispectral.yaml @@ -0,0 +1,38 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# DOTA8-Multispectral dataset (DOTA8 interpolated across 10 channels in the visual spectrum) by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/obb/dota8 +# Example usage: yolo train model=yolov8n-obb.pt data=dota8-multispectral.yaml +# parent +# ├── ultralytics +# └── datasets +# └── dota8-multispectral ← downloads here (37.3 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: dota8-multispectral # dataset root dir +train: images/train # train images (relative to 'path') 4 images +val: images/val # val images (relative to 'path') 4 images + +# Number of multispectral image channels +channels: 10 + +# Classes for DOTA 1.0 +names: + 0: plane + 1: ship + 2: storage tank + 3: baseball diamond + 4: tennis court + 5: basketball court + 6: ground track field + 7: harbor + 8: bridge + 9: large vehicle + 10: small vehicle + 11: helicopter + 12: roundabout + 13: soccer ball field + 14: swimming pool + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/dota8-multispectral.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/dota8.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/dota8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0778e5e7566a997553794565e576d16dc43b900a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/dota8.yaml @@ -0,0 +1,35 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# DOTA8 dataset (8 images from the DOTAv1 split) by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/obb/dota8 +# Example usage: yolo train model=yolov8n-obb.pt data=dota8.yaml +# parent +# ├── ultralytics +# └── datasets +# └── dota8 ← downloads here (1 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: dota8 # dataset root dir +train: images/train # train images (relative to 'path') 4 images +val: images/val # val images (relative to 'path') 4 images + +# Classes for DOTA 1.0 +names: + 0: plane + 1: ship + 2: storage tank + 3: baseball diamond + 4: tennis court + 5: basketball court + 6: ground track field + 7: harbor + 8: bridge + 9: large vehicle + 10: small vehicle + 11: helicopter + 12: roundabout + 13: soccer ball field + 14: swimming pool + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/dota8.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/hand-keypoints.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/hand-keypoints.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b9a8f6307dc9ac5e19aece92ee9a832813536208 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/hand-keypoints.yaml @@ -0,0 +1,50 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Hand Keypoints dataset by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/pose/hand-keypoints +# Example usage: yolo train data=hand-keypoints.yaml +# parent +# ├── ultralytics +# └── datasets +# └── hand-keypoints ← downloads here (369 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: hand-keypoints # dataset root dir +train: images/train # train images (relative to 'path') 18776 images +val: images/val # val images (relative to 'path') 7992 images + +# Keypoints +kpt_shape: [21, 3] # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible) +flip_idx: [0, 1, 2, 4, 3, 10, 11, 12, 13, 14, 5, 6, 7, 8, 9, 15, 16, 17, 18, 19, 20] + +# Classes +names: + 0: hand + +# Keypoint names per class +kpt_names: + 0: + - wrist + - thumb_cmc + - thumb_mcp + - thumb_ip + - thumb_tip + - index_mcp + - index_pip + - index_dip + - index_tip + - middle_mcp + - middle_pip + - middle_dip + - middle_tip + - ring_mcp + - ring_pip + - ring_dip + - ring_tip + - pinky_mcp + - pinky_pip + - pinky_dip + - pinky_tip + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/hand-keypoints.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/kitti.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/kitti.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f8ba698b177800ce74759f407e978a8bba34d14a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/kitti.yaml @@ -0,0 +1,27 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# KITTI dataset by Karlsruhe Institute of Technology and Toyota Technological Institute at Chicago +# Documentation: https://docs.ultralytics.com/datasets/detect/kitti +# Example usage: yolo train data=kitti.yaml +# parent +# ├── ultralytics +# └── datasets +# └── kitti ← downloads here (390.5 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: kitti # dataset root dir +train: images/train # train images (relative to 'path') 5985 images +val: images/val # val images (relative to 'path') 1496 images + +names: + 0: car + 1: van + 2: truck + 3: pedestrian + 4: person_sitting + 5: cyclist + 6: tram + 7: misc + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/kitti.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/lvis.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/lvis.yaml new file mode 100644 index 0000000000000000000000000000000000000000..533a73cde0d1265dc3f4e1366e8ea8939353c697 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/lvis.yaml @@ -0,0 +1,1239 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# LVIS dataset http://www.lvisdataset.org by Facebook AI Research. +# Documentation: https://docs.ultralytics.com/datasets/detect/lvis +# Example usage: yolo train data=lvis.yaml +# parent +# ├── ultralytics +# └── datasets +# └── lvis ← downloads here (20.7 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: lvis # dataset root dir +train: train.txt # train images (relative to 'path') 100170 images +val: val.txt # val images (relative to 'path') 19809 images +minival: minival.txt # minival images (relative to 'path') 5000 images + +names: + 0: aerosol can/spray can + 1: air conditioner + 2: airplane/aeroplane + 3: alarm clock + 4: alcohol/alcoholic beverage + 5: alligator/gator + 6: almond + 7: ambulance + 8: amplifier + 9: anklet/ankle bracelet + 10: antenna/aerial/transmitting aerial + 11: apple + 12: applesauce + 13: apricot + 14: apron + 15: aquarium/fish tank + 16: arctic/arctic type of shoe/galosh/golosh/rubber/rubber type of shoe/gumshoe + 17: armband + 18: armchair + 19: armoire + 20: armor + 21: artichoke + 22: trash can/garbage can/wastebin/dustbin/trash barrel/trash bin + 23: ashtray + 24: asparagus + 25: atomizer/atomiser/spray/sprayer/nebulizer/nebuliser + 26: avocado + 27: award/accolade + 28: awning + 29: ax/axe + 30: baboon + 31: baby buggy/baby carriage/perambulator/pram/stroller + 32: basketball backboard + 33: backpack/knapsack/packsack/rucksack/haversack + 34: handbag/purse/pocketbook + 35: suitcase/baggage/luggage + 36: bagel/beigel + 37: bagpipe + 38: baguet/baguette + 39: bait/lure + 40: ball + 41: ballet skirt/tutu + 42: balloon + 43: bamboo + 44: banana + 45: Band Aid + 46: bandage + 47: bandanna/bandana + 48: banjo + 49: banner/streamer + 50: barbell + 51: barge + 52: barrel/cask + 53: barrette + 54: barrow/garden cart/lawn cart/wheelbarrow + 55: baseball base + 56: baseball + 57: baseball bat + 58: baseball cap/jockey cap/golf cap + 59: baseball glove/baseball mitt + 60: basket/handbasket + 61: basketball + 62: bass horn/sousaphone/tuba + 63: bat/bat animal + 64: bath mat + 65: bath towel + 66: bathrobe + 67: bathtub/bathing tub + 68: batter/batter food + 69: battery + 70: beachball + 71: bead + 72: bean curd/tofu + 73: beanbag + 74: beanie/beany + 75: bear + 76: bed + 77: bedpan + 78: bedspread/bedcover/bed covering/counterpane/spread + 79: cow + 80: beef/beef food/boeuf/boeuf food + 81: beeper/pager + 82: beer bottle + 83: beer can + 84: beetle + 85: bell + 86: bell pepper/capsicum + 87: belt + 88: belt buckle + 89: bench + 90: beret + 91: bib + 92: Bible + 93: bicycle/bike/bike bicycle + 94: visor/vizor + 95: billboard + 96: binder/ring-binder + 97: binoculars/field glasses/opera glasses + 98: bird + 99: birdfeeder + 100: birdbath + 101: birdcage + 102: birdhouse + 103: birthday cake + 104: birthday card + 105: pirate flag + 106: black sheep + 107: blackberry + 108: blackboard/chalkboard + 109: blanket + 110: blazer/sport jacket/sport coat/sports jacket/sports coat + 111: blender/liquidizer/liquidiser + 112: blimp + 113: blinker/flasher + 114: blouse + 115: blueberry + 116: gameboard + 117: boat/ship/ship boat + 118: bob/bobber/bobfloat + 119: bobbin/spool/reel + 120: bobby pin/hairgrip + 121: boiled egg/coddled egg + 122: bolo tie/bolo/bola tie/bola + 123: deadbolt + 124: bolt + 125: bonnet + 126: book + 127: bookcase + 128: booklet/brochure/leaflet/pamphlet + 129: bookmark/bookmarker + 130: boom microphone/microphone boom + 131: boot + 132: bottle + 133: bottle opener + 134: bouquet + 135: bow/bow weapon + 136: bow/bow decorative ribbons + 137: bow-tie/bowtie + 138: bowl + 139: pipe bowl + 140: bowler hat/bowler/derby hat/derby/plug hat + 141: bowling ball + 142: box + 143: boxing glove + 144: suspenders + 145: bracelet/bangle + 146: brass plaque + 147: brassiere/bra/bandeau + 148: bread-bin/breadbox + 149: bread + 150: breechcloth/breechclout/loincloth + 151: bridal gown/wedding gown/wedding dress + 152: briefcase + 153: broccoli + 154: broach + 155: broom + 156: brownie + 157: brussels sprouts + 158: bubble gum + 159: bucket/pail + 160: horse buggy + 161: horned cow + 162: bulldog + 163: bulldozer/dozer + 164: bullet train + 165: bulletin board/notice board + 166: bulletproof vest + 167: bullhorn/megaphone + 168: bun/roll + 169: bunk bed + 170: buoy + 171: burrito + 172: bus/bus vehicle/autobus/charabanc/double-decker/motorbus/motorcoach + 173: business card + 174: butter + 175: butterfly + 176: button + 177: cab/cab taxi/taxi/taxicab + 178: cabana + 179: cabin car/caboose + 180: cabinet + 181: locker/storage locker + 182: cake + 183: calculator + 184: calendar + 185: calf + 186: camcorder + 187: camel + 188: camera + 189: camera lens + 190: camper/camper vehicle/camping bus/motor home + 191: can/tin can + 192: can opener/tin opener + 193: candle/candlestick + 194: candle holder + 195: candy bar + 196: candy cane + 197: walking cane + 198: canister/canister + 199: canoe + 200: cantaloup/cantaloupe + 201: canteen + 202: cap/cap headwear + 203: bottle cap/cap/cap container lid + 204: cape + 205: cappuccino/coffee cappuccino + 206: car/car automobile/auto/auto automobile/automobile + 207: railcar/railcar part of a train/railway car/railway car part of a train/railroad car/railroad car part of a train + 208: elevator car + 209: car battery/automobile battery + 210: identity card + 211: card + 212: cardigan + 213: cargo ship/cargo vessel + 214: carnation + 215: horse carriage + 216: carrot + 217: tote bag + 218: cart + 219: carton + 220: cash register/register/register for cash transactions + 221: casserole + 222: cassette + 223: cast/plaster cast/plaster bandage + 224: cat + 225: cauliflower + 226: cayenne/cayenne spice/cayenne pepper/cayenne pepper spice/red pepper/red pepper spice + 227: CD player + 228: celery + 229: cellular telephone/cellular phone/cellphone/mobile phone/smart phone + 230: chain mail/ring mail/chain armor/ring armor + 231: chair + 232: chaise longue/chaise/daybed + 233: chalice + 234: chandelier + 235: chap + 236: checkbook/chequebook + 237: checkerboard + 238: cherry + 239: chessboard + 240: chicken/chicken animal + 241: chickpea/garbanzo + 242: chili/chili vegetable/chili pepper/chili pepper vegetable/chilli/chilli vegetable/chilly/chilly vegetable/chile/chile vegetable + 243: chime/gong + 244: chinaware + 245: crisp/crisp potato chip/potato chip + 246: poker chip + 247: chocolate bar + 248: chocolate cake + 249: chocolate milk + 250: chocolate mousse + 251: choker/collar/neckband + 252: chopping board/cutting board/chopping block + 253: chopstick + 254: Christmas tree + 255: slide + 256: cider/cyder + 257: cigar box + 258: cigarette + 259: cigarette case/cigarette pack + 260: cistern/water tank + 261: clarinet + 262: clasp + 263: cleansing agent/cleanser/cleaner + 264: cleat/cleat for securing rope + 265: clementine + 266: clip + 267: clipboard + 268: clippers/clippers for plants + 269: cloak + 270: clock/timepiece/timekeeper + 271: clock tower + 272: clothes hamper/laundry basket/clothes basket + 273: clothespin/clothes peg + 274: clutch bag + 275: coaster + 276: coat + 277: coat hanger/clothes hanger/dress hanger + 278: coatrack/hatrack + 279: cock/rooster + 280: cockroach + 281: cocoa/cocoa beverage/hot chocolate/hot chocolate beverage/drinking chocolate + 282: coconut/cocoanut + 283: coffee maker/coffee machine + 284: coffee table/cocktail table + 285: coffeepot + 286: coil + 287: coin + 288: colander/cullender + 289: coleslaw/slaw + 290: coloring material + 291: combination lock + 292: pacifier/teething ring + 293: comic book + 294: compass + 295: computer keyboard/keyboard/keyboard computer + 296: condiment + 297: cone/traffic cone + 298: control/controller + 299: convertible/convertible automobile + 300: sofa bed + 301: cooker + 302: cookie/cooky/biscuit/biscuit cookie + 303: cooking utensil + 304: cooler/cooler for food/ice chest + 305: cork/cork bottle plug/bottle cork + 306: corkboard + 307: corkscrew/bottle screw + 308: edible corn/corn/maize + 309: cornbread + 310: cornet/horn/trumpet + 311: cornice/valance/valance board/pelmet + 312: cornmeal + 313: corset/girdle + 314: costume + 315: cougar/puma/catamount/mountain lion/panther + 316: coverall + 317: cowbell + 318: cowboy hat/ten-gallon hat + 319: crab/crab animal + 320: crabmeat + 321: cracker + 322: crape/crepe/French pancake + 323: crate + 324: crayon/wax crayon + 325: cream pitcher + 326: crescent roll/croissant + 327: crib/cot + 328: crock pot/earthenware jar + 329: crossbar + 330: crouton + 331: crow + 332: crowbar/wrecking bar/pry bar + 333: crown + 334: crucifix + 335: cruise ship/cruise liner + 336: police cruiser/patrol car/police car/squad car + 337: crumb + 338: crutch + 339: cub/cub animal + 340: cube/square block + 341: cucumber/cuke + 342: cufflink + 343: cup + 344: trophy cup + 345: cupboard/closet + 346: cupcake + 347: hair curler/hair roller/hair crimper + 348: curling iron + 349: curtain/drapery + 350: cushion + 351: cylinder + 352: cymbal + 353: dagger + 354: dalmatian + 355: dartboard + 356: date/date fruit + 357: deck chair/beach chair + 358: deer/cervid + 359: dental floss/floss + 360: desk + 361: detergent + 362: diaper + 363: diary/journal + 364: die/dice + 365: dinghy/dory/rowboat + 366: dining table + 367: tux/tuxedo + 368: dish + 369: dish antenna + 370: dishrag/dishcloth + 371: dishtowel/tea towel + 372: dishwasher/dishwashing machine + 373: dishwasher detergent/dishwashing detergent/dishwashing liquid/dishsoap + 374: dispenser + 375: diving board + 376: Dixie cup/paper cup + 377: dog + 378: dog collar + 379: doll + 380: dollar/dollar bill/one dollar bill + 381: dollhouse/doll's house + 382: dolphin + 383: domestic ass/donkey + 384: doorknob/doorhandle + 385: doormat/welcome mat + 386: donut + 387: dove + 388: dragonfly + 389: drawer + 390: underdrawers/boxers/boxershorts + 391: dress/frock + 392: dress hat/high hat/opera hat/silk hat/top hat + 393: dress suit + 394: dresser + 395: drill + 396: drone + 397: dropper/eye dropper + 398: drum/drum musical instrument + 399: drumstick + 400: duck + 401: duckling + 402: duct tape + 403: duffel bag/duffle bag/duffel/duffle + 404: dumbbell + 405: dumpster + 406: dustpan + 407: eagle + 408: earphone/earpiece/headphone + 409: earplug + 410: earring + 411: easel + 412: eclair + 413: eel + 414: egg/eggs + 415: egg roll/spring roll + 416: egg yolk/yolk/yolk egg + 417: eggbeater/eggwhisk + 418: eggplant/aubergine + 419: electric chair + 420: refrigerator + 421: elephant + 422: elk/moose + 423: envelope + 424: eraser + 425: escargot + 426: eyepatch + 427: falcon + 428: fan + 429: faucet/spigot/tap + 430: fedora + 431: ferret + 432: Ferris wheel + 433: ferry/ferryboat + 434: fig/fig fruit + 435: fighter jet/fighter aircraft/attack aircraft + 436: figurine + 437: file cabinet/filing cabinet + 438: file/file tool + 439: fire alarm/smoke alarm + 440: fire engine/fire truck + 441: fire extinguisher/extinguisher + 442: fire hose + 443: fireplace + 444: fireplug/fire hydrant/hydrant + 445: first-aid kit + 446: fish + 447: fish/fish food + 448: fishbowl/goldfish bowl + 449: fishing rod/fishing pole + 450: flag + 451: flagpole/flagstaff + 452: flamingo + 453: flannel + 454: flap + 455: flash/flashbulb + 456: flashlight/torch + 457: fleece + 458: flip-flop/flip-flop sandal + 459: flipper/flipper footwear/fin/fin footwear + 460: flower arrangement/floral arrangement + 461: flute glass/champagne flute + 462: foal + 463: folding chair + 464: food processor + 465: football/football American + 466: football helmet + 467: footstool/footrest + 468: fork + 469: forklift + 470: freight car + 471: French toast + 472: freshener/air freshener + 473: frisbee + 474: frog/toad/toad frog + 475: fruit juice + 476: frying pan/frypan/skillet + 477: fudge + 478: funnel + 479: futon + 480: gag/muzzle + 481: garbage + 482: garbage truck + 483: garden hose + 484: gargle/mouthwash + 485: gargoyle + 486: garlic/ail + 487: gasmask/respirator/gas helmet + 488: gazelle + 489: gelatin/jelly + 490: gemstone + 491: generator + 492: giant panda/panda/panda bear + 493: gift wrap + 494: ginger/gingerroot + 495: giraffe + 496: cincture/sash/waistband/waistcloth + 497: glass/glass drink container/drinking glass + 498: globe + 499: glove + 500: goat + 501: goggles + 502: goldfish + 503: golf club/golf-club + 504: golfcart + 505: gondola/gondola boat + 506: goose + 507: gorilla + 508: gourd + 509: grape + 510: grater + 511: gravestone/headstone/tombstone + 512: gravy boat/gravy holder + 513: green bean + 514: green onion/spring onion/scallion + 515: griddle + 516: grill/grille/grillwork/radiator grille + 517: grits/hominy grits + 518: grizzly/grizzly bear + 519: grocery bag + 520: guitar + 521: gull/seagull + 522: gun + 523: hairbrush + 524: hairnet + 525: hairpin + 526: halter top + 527: ham/jambon/gammon + 528: hamburger/beefburger/burger + 529: hammer + 530: hammock + 531: hamper + 532: hamster + 533: hair dryer + 534: hand glass/hand mirror + 535: hand towel/face towel + 536: handcart/pushcart/hand truck + 537: handcuff + 538: handkerchief + 539: handle/grip/handgrip + 540: handsaw/carpenter's saw + 541: hardback book/hardcover book + 542: harmonium/organ/organ musical instrument/reed organ/reed organ musical instrument + 543: hat + 544: hatbox + 545: veil + 546: headband + 547: headboard + 548: headlight/headlamp + 549: headscarf + 550: headset + 551: headstall/headstall for horses/headpiece/headpiece for horses + 552: heart + 553: heater/warmer + 554: helicopter + 555: helmet + 556: heron + 557: highchair/feeding chair + 558: hinge + 559: hippopotamus + 560: hockey stick + 561: hog/pig + 562: home plate/home plate baseball/home base/home base baseball + 563: honey + 564: fume hood/exhaust hood + 565: hook + 566: hookah/narghile/nargileh/sheesha/shisha/water pipe + 567: hornet + 568: horse + 569: hose/hosepipe + 570: hot-air balloon + 571: hotplate + 572: hot sauce + 573: hourglass + 574: houseboat + 575: hummingbird + 576: hummus/humus/hommos/hoummos/humous + 577: polar bear + 578: icecream + 579: popsicle + 580: ice maker + 581: ice pack/ice bag + 582: ice skate + 583: igniter/ignitor/lighter + 584: inhaler/inhalator + 585: iPod + 586: iron/iron for clothing/smoothing iron/smoothing iron for clothing + 587: ironing board + 588: jacket + 589: jam + 590: jar + 591: jean/blue jean/denim + 592: jeep/landrover + 593: jelly bean/jelly egg + 594: jersey/T-shirt/tee shirt + 595: jet plane/jet-propelled plane + 596: jewel/gem/precious stone + 597: jewelry/jewellery + 598: joystick + 599: jumpsuit + 600: kayak + 601: keg + 602: kennel/doghouse + 603: kettle/boiler + 604: key + 605: keycard + 606: kilt + 607: kimono + 608: kitchen sink + 609: kitchen table + 610: kite + 611: kitten/kitty + 612: kiwi fruit + 613: knee pad + 614: knife + 615: knitting needle + 616: knob + 617: knocker/knocker on a door/doorknocker + 618: koala/koala bear + 619: lab coat/laboratory coat + 620: ladder + 621: ladle + 622: ladybug/ladybeetle/ladybird beetle + 623: lamb/lamb animal + 624: lamb-chop/lambchop + 625: lamp + 626: lamppost + 627: lampshade + 628: lantern + 629: lanyard/laniard + 630: laptop computer/notebook computer + 631: lasagna/lasagne + 632: latch + 633: lawn mower + 634: leather + 635: legging/legging clothing/leging/leging clothing/leg covering + 636: Lego/Lego set + 637: legume + 638: lemon + 639: lemonade + 640: lettuce + 641: license plate/numberplate + 642: life buoy/lifesaver/life belt/life ring + 643: life jacket/life vest + 644: lightbulb + 645: lightning rod/lightning conductor + 646: lime + 647: limousine + 648: lion + 649: lip balm + 650: liquor/spirits/hard liquor/liqueur/cordial + 651: lizard + 652: log + 653: lollipop + 654: speaker/speaker stereo equipment + 655: loveseat + 656: machine gun + 657: magazine + 658: magnet + 659: mail slot + 660: mailbox/mailbox at home/letter box/letter box at home + 661: mallard + 662: mallet + 663: mammoth + 664: manatee + 665: mandarin orange + 666: manger/trough + 667: manhole + 668: map + 669: marker + 670: martini + 671: mascot + 672: mashed potato + 673: masher + 674: mask/facemask + 675: mast + 676: mat/mat gym equipment/gym mat + 677: matchbox + 678: mattress + 679: measuring cup + 680: measuring stick/ruler/ruler measuring stick/measuring rod + 681: meatball + 682: medicine + 683: melon + 684: microphone + 685: microscope + 686: microwave oven + 687: milestone/milepost + 688: milk + 689: milk can + 690: milkshake + 691: minivan + 692: mint candy + 693: mirror + 694: mitten + 695: mixer/mixer kitchen tool/stand mixer + 696: money + 697: monitor/monitor computer equipment + 698: monkey + 699: motor + 700: motor scooter/scooter + 701: motor vehicle/automotive vehicle + 702: motorcycle + 703: mound/mound baseball/pitcher's mound + 704: mouse/mouse computer equipment/computer mouse + 705: mousepad + 706: muffin + 707: mug + 708: mushroom + 709: music stool/piano stool + 710: musical instrument/instrument/instrument musical + 711: nailfile + 712: napkin/table napkin/serviette + 713: neckerchief + 714: necklace + 715: necktie/tie/tie necktie + 716: needle + 717: nest + 718: newspaper/paper/paper newspaper + 719: newsstand + 720: nightshirt/nightwear/sleepwear/nightclothes + 721: nosebag/nosebag for animals/feedbag + 722: noseband/noseband for animals/nosepiece/nosepiece for animals + 723: notebook + 724: notepad + 725: nut + 726: nutcracker + 727: oar + 728: octopus/octopus food + 729: octopus/octopus animal + 730: oil lamp/kerosene lamp/kerosine lamp + 731: olive oil + 732: omelet/omelette + 733: onion + 734: orange/orange fruit + 735: orange juice + 736: ostrich + 737: ottoman/pouf/pouffe/hassock + 738: oven + 739: overalls/overalls clothing + 740: owl + 741: packet + 742: inkpad/inking pad/stamp pad + 743: pad + 744: paddle/boat paddle + 745: padlock + 746: paintbrush + 747: painting + 748: pajamas/pyjamas + 749: palette/pallet + 750: pan/pan for cooking/cooking pan + 751: pan/pan metal container + 752: pancake + 753: pantyhose + 754: papaya + 755: paper plate + 756: paper towel + 757: paperback book/paper-back book/softback book/soft-cover book + 758: paperweight + 759: parachute + 760: parakeet/parrakeet/parroket/paraquet/paroquet/parroquet + 761: parasail/parasail sports + 762: parasol/sunshade + 763: parchment + 764: parka/anorak + 765: parking meter + 766: parrot + 767: passenger car/passenger car part of a train/coach/coach part of a train + 768: passenger ship + 769: passport + 770: pastry + 771: patty/patty food + 772: pea/pea food + 773: peach + 774: peanut butter + 775: pear + 776: peeler/peeler tool for fruit and vegetables + 777: wooden leg/pegleg + 778: pegboard + 779: pelican + 780: pen + 781: pencil + 782: pencil box/pencil case + 783: pencil sharpener + 784: pendulum + 785: penguin + 786: pennant + 787: penny/penny coin + 788: pepper/peppercorn + 789: pepper mill/pepper grinder + 790: perfume + 791: persimmon + 792: person/baby/child/boy/girl/man/woman/human + 793: pet + 794: pew/pew church bench/church bench + 795: phonebook/telephone book/telephone directory + 796: phonograph record/phonograph recording/record/record phonograph recording + 797: piano + 798: pickle + 799: pickup truck + 800: pie + 801: pigeon + 802: piggy bank/penny bank + 803: pillow + 804: pin/pin non jewelry + 805: pineapple + 806: pinecone + 807: ping-pong ball + 808: pinwheel + 809: tobacco pipe + 810: pipe/piping + 811: pistol/handgun + 812: pita/pita bread/pocket bread + 813: pitcher/pitcher vessel for liquid/ewer + 814: pitchfork + 815: pizza + 816: place mat + 817: plate + 818: platter + 819: playpen + 820: pliers/plyers + 821: plow/plow farm equipment/plough/plough farm equipment + 822: plume + 823: pocket watch + 824: pocketknife + 825: poker/poker fire stirring tool/stove poker/fire hook + 826: pole/post + 827: polo shirt/sport shirt + 828: poncho + 829: pony + 830: pool table/billiard table/snooker table + 831: pop/pop soda/soda/soda pop/tonic/soft drink + 832: postbox/postbox public/mailbox/mailbox public + 833: postcard/postal card/mailing-card + 834: poster/placard + 835: pot + 836: flowerpot + 837: potato + 838: potholder + 839: pottery/clayware + 840: pouch + 841: power shovel/excavator/digger + 842: prawn/shrimp + 843: pretzel + 844: printer/printing machine + 845: projectile/projectile weapon/missile + 846: projector + 847: propeller/propellor + 848: prune + 849: pudding + 850: puffer/puffer fish/pufferfish/blowfish/globefish + 851: puffin + 852: pug-dog + 853: pumpkin + 854: puncher + 855: puppet/marionette + 856: puppy + 857: quesadilla + 858: quiche + 859: quilt/comforter + 860: rabbit + 861: race car/racing car + 862: racket/racquet + 863: radar + 864: radiator + 865: radio receiver/radio set/radio/tuner/tuner radio + 866: radish/daikon + 867: raft + 868: rag doll + 869: raincoat/waterproof jacket + 870: ram/ram animal + 871: raspberry + 872: rat + 873: razorblade + 874: reamer/reamer juicer/juicer/juice reamer + 875: rearview mirror + 876: receipt + 877: recliner/reclining chair/lounger/lounger chair + 878: record player/phonograph/phonograph record player/turntable + 879: reflector + 880: remote control + 881: rhinoceros + 882: rib/rib food + 883: rifle + 884: ring + 885: river boat + 886: road map + 887: robe + 888: rocking chair + 889: rodent + 890: roller skate + 891: Rollerblade + 892: rolling pin + 893: root beer + 894: router/router computer equipment + 895: rubber band/elastic band + 896: runner/runner carpet + 897: plastic bag/paper bag + 898: saddle/saddle on an animal + 899: saddle blanket/saddlecloth/horse blanket + 900: saddlebag + 901: safety pin + 902: sail + 903: salad + 904: salad plate/salad bowl + 905: salami + 906: salmon/salmon fish + 907: salmon/salmon food + 908: salsa + 909: saltshaker + 910: sandal/sandal type of shoe + 911: sandwich + 912: satchel + 913: saucepan + 914: saucer + 915: sausage + 916: sawhorse/sawbuck + 917: saxophone + 918: scale/scale measuring instrument + 919: scarecrow/strawman + 920: scarf + 921: school bus + 922: scissors + 923: scoreboard + 924: scraper + 925: screwdriver + 926: scrubbing brush + 927: sculpture + 928: seabird/seafowl + 929: seahorse + 930: seaplane/hydroplane + 931: seashell + 932: sewing machine + 933: shaker + 934: shampoo + 935: shark + 936: sharpener + 937: Sharpie + 938: shaver/shaver electric/electric shaver/electric razor + 939: shaving cream/shaving soap + 940: shawl + 941: shears + 942: sheep + 943: shepherd dog/sheepdog + 944: sherbert/sherbet + 945: shield + 946: shirt + 947: shoe/sneaker/sneaker type of shoe/tennis shoe + 948: shopping bag + 949: shopping cart + 950: short pants/shorts/shorts clothing/trunks/trunks clothing + 951: shot glass + 952: shoulder bag + 953: shovel + 954: shower head + 955: shower cap + 956: shower curtain + 957: shredder/shredder for paper + 958: signboard + 959: silo + 960: sink + 961: skateboard + 962: skewer + 963: ski + 964: ski boot + 965: ski parka/ski jacket + 966: ski pole + 967: skirt + 968: skullcap + 969: sled/sledge/sleigh + 970: sleeping bag + 971: sling/sling bandage/triangular bandage + 972: slipper/slipper footwear/carpet slipper/carpet slipper footwear + 973: smoothie + 974: snake/serpent + 975: snowboard + 976: snowman + 977: snowmobile + 978: soap + 979: soccer ball + 980: sock + 981: sofa/couch/lounge + 982: softball + 983: solar array/solar battery/solar panel + 984: sombrero + 985: soup + 986: soup bowl + 987: soupspoon + 988: sour cream/soured cream + 989: soya milk/soybean milk/soymilk + 990: space shuttle + 991: sparkler/sparkler fireworks + 992: spatula + 993: spear/lance + 994: spectacles/specs/eyeglasses/glasses + 995: spice rack + 996: spider + 997: crawfish/crayfish + 998: sponge + 999: spoon + 1000: sportswear/athletic wear/activewear + 1001: spotlight + 1002: squid/squid food/calamari/calamary + 1003: squirrel + 1004: stagecoach + 1005: stapler/stapler stapling machine + 1006: starfish/sea star + 1007: statue/statue sculpture + 1008: steak/steak food + 1009: steak knife + 1010: steering wheel + 1011: stepladder + 1012: step stool + 1013: stereo/stereo sound system + 1014: stew + 1015: stirrer + 1016: stirrup + 1017: stool + 1018: stop sign + 1019: brake light + 1020: stove/kitchen stove/range/range kitchen appliance/kitchen range/cooking stove + 1021: strainer + 1022: strap + 1023: straw/straw for drinking/drinking straw + 1024: strawberry + 1025: street sign + 1026: streetlight/street lamp + 1027: string cheese + 1028: stylus + 1029: subwoofer + 1030: sugar bowl + 1031: sugarcane/sugarcane plant + 1032: suit/suit clothing + 1033: sunflower + 1034: sunglasses + 1035: sunhat + 1036: surfboard + 1037: sushi + 1038: mop + 1039: sweat pants + 1040: sweatband + 1041: sweater + 1042: sweatshirt + 1043: sweet potato + 1044: swimsuit/swimwear/bathing suit/swimming costume/bathing costume/swimming trunks/bathing trunks + 1045: sword + 1046: syringe + 1047: Tabasco sauce + 1048: table-tennis table/ping-pong table + 1049: table + 1050: table lamp + 1051: tablecloth + 1052: tachometer + 1053: taco + 1054: tag + 1055: taillight/rear light + 1056: tambourine + 1057: army tank/armored combat vehicle + 1058: tank/tank storage vessel/storage tank + 1059: tank top/tank top clothing + 1060: tape/tape sticky cloth or paper + 1061: tape measure/measuring tape + 1062: tapestry + 1063: tarp + 1064: tartan/plaid + 1065: tassel + 1066: tea bag + 1067: teacup + 1068: teakettle + 1069: teapot + 1070: teddy bear + 1071: telephone/phone/telephone set + 1072: telephone booth/phone booth/call box/telephone box/telephone kiosk + 1073: telephone pole/telegraph pole/telegraph post + 1074: telephoto lens/zoom lens + 1075: television camera/tv camera + 1076: television set/tv/tv set + 1077: tennis ball + 1078: tennis racket + 1079: tequila + 1080: thermometer + 1081: thermos bottle + 1082: thermostat + 1083: thimble + 1084: thread/yarn + 1085: thumbtack/drawing pin/pushpin + 1086: tiara + 1087: tiger + 1088: tights/tights clothing/leotards + 1089: timer/stopwatch + 1090: tinfoil + 1091: tinsel + 1092: tissue paper + 1093: toast/toast food + 1094: toaster + 1095: toaster oven + 1096: toilet + 1097: toilet tissue/toilet paper/bathroom tissue + 1098: tomato + 1099: tongs + 1100: toolbox + 1101: toothbrush + 1102: toothpaste + 1103: toothpick + 1104: cover + 1105: tortilla + 1106: tow truck + 1107: towel + 1108: towel rack/towel rail/towel bar + 1109: toy + 1110: tractor/tractor farm equipment + 1111: traffic light + 1112: dirt bike + 1113: trailer truck/tractor trailer/trucking rig/articulated lorry/semi truck + 1114: train/train railroad vehicle/railroad train + 1115: trampoline + 1116: tray + 1117: trench coat + 1118: triangle/triangle musical instrument + 1119: tricycle + 1120: tripod + 1121: trousers/pants/pants clothing + 1122: truck + 1123: truffle/truffle chocolate/chocolate truffle + 1124: trunk + 1125: vat + 1126: turban + 1127: turkey/turkey food + 1128: turnip + 1129: turtle + 1130: turtleneck/turtleneck clothing/polo-neck + 1131: typewriter + 1132: umbrella + 1133: underwear/underclothes/underclothing/underpants + 1134: unicycle + 1135: urinal + 1136: urn + 1137: vacuum cleaner + 1138: vase + 1139: vending machine + 1140: vent/blowhole/air vent + 1141: vest/waistcoat + 1142: videotape + 1143: vinegar + 1144: violin/fiddle + 1145: vodka + 1146: volleyball + 1147: vulture + 1148: waffle + 1149: waffle iron + 1150: wagon + 1151: wagon wheel + 1152: walking stick + 1153: wall clock + 1154: wall socket/wall plug/electric outlet/electrical outlet/outlet/electric receptacle + 1155: wallet/billfold + 1156: walrus + 1157: wardrobe + 1158: washbasin/basin/basin for washing/washbowl/washstand/handbasin + 1159: automatic washer/washing machine + 1160: watch/wristwatch + 1161: water bottle + 1162: water cooler + 1163: water faucet/water tap/tap/tap water faucet + 1164: water heater/hot-water heater + 1165: water jug + 1166: water gun/squirt gun + 1167: water scooter/sea scooter/jet ski + 1168: water ski + 1169: water tower + 1170: watering can + 1171: watermelon + 1172: weathervane/vane/vane weathervane/wind vane + 1173: webcam + 1174: wedding cake/bridecake + 1175: wedding ring/wedding band + 1176: wet suit + 1177: wheel + 1178: wheelchair + 1179: whipped cream + 1180: whistle + 1181: wig + 1182: wind chime + 1183: windmill + 1184: window box/window box for plants + 1185: windshield wiper/windscreen wiper/wiper/wiper for windshield or screen + 1186: windsock/air sock/air-sleeve/wind sleeve/wind cone + 1187: wine bottle + 1188: wine bucket/wine cooler + 1189: wineglass + 1190: blinder/blinder for horses + 1191: wok + 1192: wolf + 1193: wooden spoon + 1194: wreath + 1195: wrench/spanner + 1196: wristband + 1197: wristlet/wrist band + 1198: yacht + 1199: yogurt/yoghurt/yoghourt + 1200: yoke/yoke animal equipment + 1201: zebra + 1202: zucchini/courgette + +# Download script/URL (optional) +download: | + from pathlib import Path + + from ultralytics.utils import ASSETS_URL + from ultralytics.utils.downloads import download + + # Download labels + dir = Path(yaml["path"]) # dataset root dir + urls = [f"{ASSETS_URL}/lvis-labels-segments.zip"] + download(urls, dir=dir.parent) + + # Download data (test2017.zip excluded: LVIS has no 'test:' split and never reads it) + urls = [ + "http://images.cocodataset.org/zips/train2017.zip", # 19G, 118k images + "http://images.cocodataset.org/zips/val2017.zip", # 1G, 5k images + ] + download(urls, dir=dir / "images", threads=3) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/medical-pills.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/medical-pills.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a763bb61a3cbdfc03ed4915fdc15326f94f2b167 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/medical-pills.yaml @@ -0,0 +1,21 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Medical-pills dataset by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/detect/medical-pills +# Example usage: yolo train data=medical-pills.yaml +# parent +# ├── ultralytics +# └── datasets +# └── medical-pills ← downloads here (8.19 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: medical-pills # dataset root dir +train: images/train # train images (relative to 'path') 92 images +val: images/val # val images (relative to 'path') 23 images + +# Classes +names: + 0: pill + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/medical-pills.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/nyu-depth.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/nyu-depth.yaml new file mode 100644 index 0000000000000000000000000000000000000000..85cc5c26373052a34e8d0d96e087839b86cf48f3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/nyu-depth.yaml @@ -0,0 +1,29 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# NYU Depth V2 dataset for monocular depth estimation +# Documentation: https://cs.nyu.edu/~fergus/datasets/nyu_depth_v2.html +# 795 train + 654 val (Eigen test split) images, 480x640, indoor scenes, depth in meters +# Example usage: yolo depth train data=nyu-depth.yaml model=yolo26n-depth.pt +# parent +# ├── ultralytics +# └── datasets +# └── nyu-depth-png ← downloads here (≈1.5 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: nyu-depth-png # dataset root dir (relative to Ultralytics settings 'datasets_dir') +train: images/train # train images (relative to 'path') 795 images +val: images/val # val images (relative to 'path') 654 images + +# Depth maps are paired uint16 millimeter PNGs under depth//, resolved by +# swapping '/images/' -> '/depth/' on each image path. + +# Classes +nc: 1 +names: + 0: depth + +channels: 3 +depth_scale: 1000 + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/nyu-depth-png.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/open-images-v7.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/open-images-v7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b0f2051fed882298a65ca61c9c4317eb62426b85 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/open-images-v7.yaml @@ -0,0 +1,663 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Open Images v7 dataset https://storage.googleapis.com/openimages/web/index.html by Google +# Documentation: https://docs.ultralytics.com/datasets/detect/open-images-v7 +# Example usage: yolo train data=open-images-v7.yaml +# parent +# ├── ultralytics +# └── datasets +# └── open-images-v7 ← downloads here (561 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: open-images-v7 # dataset root dir +train: images/train # train images (relative to 'path') 1743042 images +val: images/val # val images (relative to 'path') 41620 images +test: # test images (optional) + +# Classes +names: + 0: Accordion + 1: Adhesive tape + 2: Aircraft + 3: Airplane + 4: Alarm clock + 5: Alpaca + 6: Ambulance + 7: Animal + 8: Ant + 9: Antelope + 10: Apple + 11: Armadillo + 12: Artichoke + 13: Auto part + 14: Axe + 15: Backpack + 16: Bagel + 17: Baked goods + 18: Balance beam + 19: Ball + 20: Balloon + 21: Banana + 22: Band-aid + 23: Banjo + 24: Barge + 25: Barrel + 26: Baseball bat + 27: Baseball glove + 28: Bat (Animal) + 29: Bathroom accessory + 30: Bathroom cabinet + 31: Bathtub + 32: Beaker + 33: Bear + 34: Bed + 35: Bee + 36: Beehive + 37: Beer + 38: Beetle + 39: Bell pepper + 40: Belt + 41: Bench + 42: Bicycle + 43: Bicycle helmet + 44: Bicycle wheel + 45: Bidet + 46: Billboard + 47: Billiard table + 48: Binoculars + 49: Bird + 50: Blender + 51: Blue jay + 52: Boat + 53: Bomb + 54: Book + 55: Bookcase + 56: Boot + 57: Bottle + 58: Bottle opener + 59: Bow and arrow + 60: Bowl + 61: Bowling equipment + 62: Box + 63: Boy + 64: Brassiere + 65: Bread + 66: Briefcase + 67: Broccoli + 68: Bronze sculpture + 69: Brown bear + 70: Building + 71: Bull + 72: Burrito + 73: Bus + 74: Bust + 75: Butterfly + 76: Cabbage + 77: Cabinetry + 78: Cake + 79: Cake stand + 80: Calculator + 81: Camel + 82: Camera + 83: Can opener + 84: Canary + 85: Candle + 86: Candy + 87: Cannon + 88: Canoe + 89: Cantaloupe + 90: Car + 91: Carnivore + 92: Carrot + 93: Cart + 94: Cassette deck + 95: Castle + 96: Cat + 97: Cat furniture + 98: Caterpillar + 99: Cattle + 100: Ceiling fan + 101: Cello + 102: Centipede + 103: Chainsaw + 104: Chair + 105: Cheese + 106: Cheetah + 107: Chest of drawers + 108: Chicken + 109: Chime + 110: Chisel + 111: Chopsticks + 112: Christmas tree + 113: Clock + 114: Closet + 115: Clothing + 116: Coat + 117: Cocktail + 118: Cocktail shaker + 119: Coconut + 120: Coffee + 121: Coffee cup + 122: Coffee table + 123: Coffeemaker + 124: Coin + 125: Common fig + 126: Common sunflower + 127: Computer keyboard + 128: Computer monitor + 129: Computer mouse + 130: Container + 131: Convenience store + 132: Cookie + 133: Cooking spray + 134: Corded phone + 135: Cosmetics + 136: Couch + 137: Countertop + 138: Cowboy hat + 139: Crab + 140: Cream + 141: Cricket ball + 142: Crocodile + 143: Croissant + 144: Crown + 145: Crutch + 146: Cucumber + 147: Cupboard + 148: Curtain + 149: Cutting board + 150: Dagger + 151: Dairy Product + 152: Deer + 153: Desk + 154: Dessert + 155: Diaper + 156: Dice + 157: Digital clock + 158: Dinosaur + 159: Dishwasher + 160: Dog + 161: Dog bed + 162: Doll + 163: Dolphin + 164: Door + 165: Door handle + 166: Donut + 167: Dragonfly + 168: Drawer + 169: Dress + 170: Drill (Tool) + 171: Drink + 172: Drinking straw + 173: Drum + 174: Duck + 175: Dumbbell + 176: Eagle + 177: Earrings + 178: Egg (Food) + 179: Elephant + 180: Envelope + 181: Eraser + 182: Face powder + 183: Facial tissue holder + 184: Falcon + 185: Fashion accessory + 186: Fast food + 187: Fax + 188: Fedora + 189: Filing cabinet + 190: Fire hydrant + 191: Fireplace + 192: Fish + 193: Flag + 194: Flashlight + 195: Flower + 196: Flowerpot + 197: Flute + 198: Flying disc + 199: Food + 200: Food processor + 201: Football + 202: Football helmet + 203: Footwear + 204: Fork + 205: Fountain + 206: Fox + 207: French fries + 208: French horn + 209: Frog + 210: Fruit + 211: Frying pan + 212: Furniture + 213: Garden Asparagus + 214: Gas stove + 215: Giraffe + 216: Girl + 217: Glasses + 218: Glove + 219: Goat + 220: Goggles + 221: Goldfish + 222: Golf ball + 223: Golf cart + 224: Gondola + 225: Goose + 226: Grape + 227: Grapefruit + 228: Grinder + 229: Guacamole + 230: Guitar + 231: Hair dryer + 232: Hair spray + 233: Hamburger + 234: Hammer + 235: Hamster + 236: Hand dryer + 237: Handbag + 238: Handgun + 239: Harbor seal + 240: Harmonica + 241: Harp + 242: Harpsichord + 243: Hat + 244: Headphones + 245: Heater + 246: Hedgehog + 247: Helicopter + 248: Helmet + 249: High heels + 250: Hiking equipment + 251: Hippopotamus + 252: Home appliance + 253: Honeycomb + 254: Horizontal bar + 255: Horse + 256: Hot dog + 257: House + 258: Houseplant + 259: Human arm + 260: Human beard + 261: Human body + 262: Human ear + 263: Human eye + 264: Human face + 265: Human foot + 266: Human hair + 267: Human hand + 268: Human head + 269: Human leg + 270: Human mouth + 271: Human nose + 272: Humidifier + 273: Ice cream + 274: Indoor rower + 275: Infant bed + 276: Insect + 277: Invertebrate + 278: Ipod + 279: Isopod + 280: Jacket + 281: Jacuzzi + 282: Jaguar (Animal) + 283: Jeans + 284: Jellyfish + 285: Jet ski + 286: Jug + 287: Juice + 288: Kangaroo + 289: Kettle + 290: Kitchen & dining room table + 291: Kitchen appliance + 292: Kitchen knife + 293: Kitchen utensil + 294: Kitchenware + 295: Kite + 296: Knife + 297: Koala + 298: Ladder + 299: Ladle + 300: Ladybug + 301: Lamp + 302: Land vehicle + 303: Lantern + 304: Laptop + 305: Lavender (Plant) + 306: Lemon + 307: Leopard + 308: Light bulb + 309: Light switch + 310: Lighthouse + 311: Lily + 312: Limousine + 313: Lion + 314: Lipstick + 315: Lizard + 316: Lobster + 317: Loveseat + 318: Luggage and bags + 319: Lynx + 320: Magpie + 321: Mammal + 322: Man + 323: Mango + 324: Maple + 325: Maracas + 326: Marine invertebrates + 327: Marine mammal + 328: Measuring cup + 329: Mechanical fan + 330: Medical equipment + 331: Microphone + 332: Microwave oven + 333: Milk + 334: Miniskirt + 335: Mirror + 336: Missile + 337: Mixer + 338: Mixing bowl + 339: Mobile phone + 340: Monkey + 341: Moths and butterflies + 342: Motorcycle + 343: Mouse + 344: Muffin + 345: Mug + 346: Mule + 347: Mushroom + 348: Musical instrument + 349: Musical keyboard + 350: Nail (Construction) + 351: Necklace + 352: Nightstand + 353: Oboe + 354: Office building + 355: Office supplies + 356: Orange + 357: Organ (Musical Instrument) + 358: Ostrich + 359: Otter + 360: Oven + 361: Owl + 362: Oyster + 363: Paddle + 364: Palm tree + 365: Pancake + 366: Panda + 367: Paper cutter + 368: Paper towel + 369: Parachute + 370: Parking meter + 371: Parrot + 372: Pasta + 373: Pastry + 374: Peach + 375: Pear + 376: Pen + 377: Pencil case + 378: Pencil sharpener + 379: Penguin + 380: Perfume + 381: Person + 382: Personal care + 383: Personal flotation device + 384: Piano + 385: Picnic basket + 386: Picture frame + 387: Pig + 388: Pillow + 389: Pineapple + 390: Pitcher (Container) + 391: Pizza + 392: Pizza cutter + 393: Plant + 394: Plastic bag + 395: Plate + 396: Platter + 397: Plumbing fixture + 398: Polar bear + 399: Pomegranate + 400: Popcorn + 401: Porch + 402: Porcupine + 403: Poster + 404: Potato + 405: Power plugs and sockets + 406: Pressure cooker + 407: Pretzel + 408: Printer + 409: Pumpkin + 410: Punching bag + 411: Rabbit + 412: Raccoon + 413: Racket + 414: Radish + 415: Ratchet (Device) + 416: Raven + 417: Rays and skates + 418: Red panda + 419: Refrigerator + 420: Remote control + 421: Reptile + 422: Rhinoceros + 423: Rifle + 424: Ring binder + 425: Rocket + 426: Roller skates + 427: Rose + 428: Rugby ball + 429: Ruler + 430: Salad + 431: Salt and pepper shakers + 432: Sandal + 433: Sandwich + 434: Saucer + 435: Saxophone + 436: Scale + 437: Scarf + 438: Scissors + 439: Scoreboard + 440: Scorpion + 441: Screwdriver + 442: Sculpture + 443: Sea lion + 444: Sea turtle + 445: Seafood + 446: Seahorse + 447: Seat belt + 448: Segway + 449: Serving tray + 450: Sewing machine + 451: Shark + 452: Sheep + 453: Shelf + 454: Shellfish + 455: Shirt + 456: Shorts + 457: Shotgun + 458: Shower + 459: Shrimp + 460: Sink + 461: Skateboard + 462: Ski + 463: Skirt + 464: Skull + 465: Skunk + 466: Skyscraper + 467: Slow cooker + 468: Snack + 469: Snail + 470: Snake + 471: Snowboard + 472: Snowman + 473: Snowmobile + 474: Snowplow + 475: Soap dispenser + 476: Sock + 477: Sofa bed + 478: Sombrero + 479: Sparrow + 480: Spatula + 481: Spice rack + 482: Spider + 483: Spoon + 484: Sports equipment + 485: Sports uniform + 486: Squash (Plant) + 487: Squid + 488: Squirrel + 489: Stairs + 490: Stapler + 491: Starfish + 492: Stationary bicycle + 493: Stethoscope + 494: Stool + 495: Stop sign + 496: Strawberry + 497: Street light + 498: Stretcher + 499: Studio couch + 500: Submarine + 501: Submarine sandwich + 502: Suit + 503: Suitcase + 504: Sun hat + 505: Sunglasses + 506: Surfboard + 507: Sushi + 508: Swan + 509: Swim cap + 510: Swimming pool + 511: Swimwear + 512: Sword + 513: Syringe + 514: Table + 515: Table tennis racket + 516: Tablet computer + 517: Tableware + 518: Taco + 519: Tank + 520: Tap + 521: Tart + 522: Taxi + 523: Tea + 524: Teapot + 525: Teddy bear + 526: Telephone + 527: Television + 528: Tennis ball + 529: Tennis racket + 530: Tent + 531: Tiara + 532: Tick + 533: Tie + 534: Tiger + 535: Tin can + 536: Tire + 537: Toaster + 538: Toilet + 539: Toilet paper + 540: Tomato + 541: Tool + 542: Toothbrush + 543: Torch + 544: Tortoise + 545: Towel + 546: Tower + 547: Toy + 548: Traffic light + 549: Traffic sign + 550: Train + 551: Training bench + 552: Treadmill + 553: Tree + 554: Tree house + 555: Tripod + 556: Trombone + 557: Trousers + 558: Truck + 559: Trumpet + 560: Turkey + 561: Turtle + 562: Umbrella + 563: Unicycle + 564: Van + 565: Vase + 566: Vegetable + 567: Vehicle + 568: Vehicle registration plate + 569: Violin + 570: Volleyball (Ball) + 571: Waffle + 572: Waffle iron + 573: Wall clock + 574: Wardrobe + 575: Washing machine + 576: Waste container + 577: Watch + 578: Watercraft + 579: Watermelon + 580: Weapon + 581: Whale + 582: Wheel + 583: Wheelchair + 584: Whisk + 585: Whiteboard + 586: Willow + 587: Window + 588: Window blind + 589: Wine + 590: Wine glass + 591: Wine rack + 592: Winter melon + 593: Wok + 594: Woman + 595: Wood-burning stove + 596: Woodpecker + 597: Worm + 598: Wrench + 599: Zebra + 600: Zucchini + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + import warnings + + from ultralytics.utils import LOGGER, SETTINGS, Path + from ultralytics.utils.checks import check_requirements + + check_requirements("fiftyone") + + import fiftyone as fo + import fiftyone.zoo as foz + + name = "open-images-v7" + fo.config.dataset_zoo_dir = Path(SETTINGS["datasets_dir"]) / "fiftyone" / name + fraction = 1.0 # fraction of full dataset to use + LOGGER.warning("Open Images V7 dataset requires at least **561 GB of free space. Starting download...") + for split in "train", "validation": # 1743042 train, 41620 val images + train = split == "train" + + # Load Open Images dataset + dataset = foz.load_zoo_dataset( + name, + split=split, + label_types=["detections"], + max_samples=round((1743042 if train else 41620) * fraction), + ) + + # Define classes + if train: + classes = dataset.default_classes # all classes + # classes = dataset.distinct('ground_truth.detections.label') # only observed classes + + # Export to YOLO format + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=UserWarning, module="fiftyone.utils.yolo") + dataset.export( + export_dir=str(Path(SETTINGS["datasets_dir"]) / name), + dataset_type=fo.types.YOLOv5Dataset, + label_field="ground_truth", + split="val" if split == "validation" else split, + classes=classes, + overwrite=train, + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/package-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/package-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5058d9dbb50d15c59a43ca83480454df3086b2da --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/package-seg.yaml @@ -0,0 +1,22 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Package-seg dataset by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/segment/package-seg +# Example usage: yolo train data=package-seg.yaml +# parent +# ├── ultralytics +# └── datasets +# └── package-seg ← downloads here (103 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: package-seg # dataset root dir +train: images/train # train images (relative to 'path') 1920 images +val: images/val # val images (relative to 'path') 188 images +test: images/test # test images (relative to 'path') 89 images + +# Classes +names: + 0: package + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/package-seg.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/signature.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/signature.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e9e8553a13b23c590c51fe29e0f86ddc451d5ab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/signature.yaml @@ -0,0 +1,21 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Signature dataset by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/detect/signature +# Example usage: yolo train data=signature.yaml +# parent +# ├── ultralytics +# └── datasets +# └── signature ← downloads here (11.3 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: signature # dataset root dir +train: images/train # train images (relative to 'path') 143 images +val: images/val # val images (relative to 'path') 35 images + +# Classes +names: + 0: signature + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/signature.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/tiger-pose.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/tiger-pose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c3f98eaf6a561c8f396b32371bb8dc2a34c3d530 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/tiger-pose.yaml @@ -0,0 +1,41 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Tiger Pose dataset by Ultralytics +# Documentation: https://docs.ultralytics.com/datasets/pose/tiger-pose +# Example usage: yolo train data=tiger-pose.yaml +# parent +# ├── ultralytics +# └── datasets +# └── tiger-pose ← downloads here (49.8 MB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: tiger-pose # dataset root dir +train: images/train # train images (relative to 'path') 210 images +val: images/val # val images (relative to 'path') 53 images + +# Keypoints +kpt_shape: [12, 2] # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible) +flip_idx: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + +# Classes +names: + 0: tiger + +# Keypoint names per class +kpt_names: + 0: + - nose + - head + - withers + - tail_base + - right_hind_hock + - right_hind_paw + - left_hind_paw + - left_hind_hock + - right_front_wrist + - right_front_paw + - left_front_wrist + - left_front_paw + +# Download script/URL (optional) +download: https://github.com/ultralytics/assets/releases/download/v0.0.0/tiger-pose.zip diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/xView.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/xView.yaml new file mode 100644 index 0000000000000000000000000000000000000000..50e7767dae0e7f10abd8332a2a84d3c152b9ef7f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/datasets/xView.yaml @@ -0,0 +1,155 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# DIUx xView 2018 Challenge dataset https://challenge.xviewdataset.org by U.S. National Geospatial-Intelligence Agency (NGA) +# -------- Download and extract data manually to `datasets/xView` before running the train command. -------- +# Documentation: https://docs.ultralytics.com/datasets/detect/xview +# Example usage: yolo train data=xView.yaml +# parent +# ├── ultralytics +# └── datasets +# └── xView ← downloads here (20.7 GB) + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: xView # dataset root dir +train: images/autosplit_train.txt # train images (relative to 'path') 90% of 847 train images +val: images/autosplit_val.txt # val images (relative to 'path') 10% of 847 train images + +# Classes +names: + 0: Fixed-wing Aircraft + 1: Small Aircraft + 2: Cargo Plane + 3: Helicopter + 4: Passenger Vehicle + 5: Small Car + 6: Bus + 7: Pickup Truck + 8: Utility Truck + 9: Truck + 10: Cargo Truck + 11: Truck w/Box + 12: Truck Tractor + 13: Trailer + 14: Truck w/Flatbed + 15: Truck w/Liquid + 16: Crane Truck + 17: Railway Vehicle + 18: Passenger Car + 19: Cargo Car + 20: Flat Car + 21: Tank car + 22: Locomotive + 23: Maritime Vessel + 24: Motorboat + 25: Sailboat + 26: Tugboat + 27: Barge + 28: Fishing Vessel + 29: Ferry + 30: Yacht + 31: Container Ship + 32: Oil Tanker + 33: Engineering Vehicle + 34: Tower crane + 35: Container Crane + 36: Reach Stacker + 37: Straddle Carrier + 38: Mobile Crane + 39: Dump Truck + 40: Haul Truck + 41: Scraper/Tractor + 42: Front loader/Bulldozer + 43: Excavator + 44: Cement Mixer + 45: Ground Grader + 46: Hut/Tent + 47: Shed + 48: Building + 49: Aircraft Hangar + 50: Damaged Building + 51: Facility + 52: Construction Site + 53: Vehicle Lot + 54: Helipad + 55: Storage Tank + 56: Shipping container lot + 57: Shipping Container + 58: Pylon + 59: Tower + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + import json + from pathlib import Path + import shutil + + import numpy as np + from PIL import Image + + from ultralytics.utils import TQDM + from ultralytics.data.split import autosplit + from ultralytics.utils.ops import xyxy2xywhn + + + def convert_labels(fname=Path("xView/xView_train.geojson")): + """Convert xView GeoJSON labels to YOLO format (classes 0-59) and save them as text files.""" + path = fname.parent + with open(fname, encoding="utf-8") as f: + print(f"Loading {fname}...") + data = json.load(f) + + # Make dirs + labels = path / "labels" / "train" + shutil.rmtree(labels, ignore_errors=True) + labels.mkdir(parents=True, exist_ok=True) + + # xView classes 11-94 to 0-59 + xview_class2index = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, -1, 9, 10, 11, + 12, 13, 14, 15, -1, -1, 16, 17, 18, 19, 20, 21, 22, -1, 23, 24, 25, -1, 26, 27, -1, 28, -1, + 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, 38, 39, 40, 41, 42, 43, 44, 45, -1, -1, -1, -1, 46, + 47, 48, 49, -1, 50, 51, -1, 52, -1, -1, -1, 53, 54, -1, 55, -1, -1, 56, -1, 57, -1, 58, 59] + + shapes = {} + for feature in TQDM(data["features"], desc=f"Converting {fname}"): + p = feature["properties"] + if p["bounds_imcoords"]: + image_id = p["image_id"] + image_file = path / "train_images" / image_id + if image_file.exists(): # 1395.tif missing + try: + box = np.array([int(num) for num in p["bounds_imcoords"].split(",")]) + assert box.shape[0] == 4, f"incorrect box shape {box.shape[0]}" + cls = p["type_id"] + cls = xview_class2index[int(cls)] # xView class to 0-59 + assert 59 >= cls >= 0, f"incorrect class index {cls}" + + # Write YOLO label + if image_id not in shapes: + shapes[image_id] = Image.open(image_file).size + box = xyxy2xywhn(box[None].astype(float), w=shapes[image_id][0], h=shapes[image_id][1], clip=True) + with open((labels / image_id).with_suffix(".txt"), "a", encoding="utf-8") as f: + f.write(f"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\n") # write label.txt + except Exception as e: + print(f"WARNING: skipping one label for {image_file}: {e}") + + + # Download manually from https://challenge.xviewdataset.org + dir = Path(yaml["path"]) # dataset root dir + # urls = [ + # "https://d307kc0mrhucc3.cloudfront.net/train_labels.zip", # train labels + # "https://d307kc0mrhucc3.cloudfront.net/train_images.zip", # 15G, 847 train images + # "https://d307kc0mrhucc3.cloudfront.net/val_images.zip", # 5G, 282 val images (no labels) + # ] + # download(urls, dir=dir) + + # Convert labels + convert_labels(dir / "xView_train.geojson") + + # Move images + images = Path(dir / "images") + images.mkdir(parents=True, exist_ok=True) + Path(dir / "train_images").rename(dir / "images" / "train") + Path(dir / "val_images").rename(dir / "images" / "val") + + # Split + autosplit(dir / "images" / "train") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/default.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/default.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1152226f95e63cc6a89a642579aedb0bd1577c53 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/default.yaml @@ -0,0 +1,139 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Global configuration YAML with settings and hyperparameters for YOLO training, validation, prediction and export +# For documentation see https://docs.ultralytics.com/usage/cfg + +task: detect # (str) YOLO task, i.e. detect, segment, semantic, depth, classify, pose, obb +mode: train # (str) YOLO mode, i.e. train, val, predict, export, track, benchmark + +# Train settings ------------------------------------------------------------------------------------------------------- +model: # (str, optional) path to model file, i.e. yolo26n.pt or yolo26n.yaml +data: # (str, optional) path to dataset file or classification directory/name +epochs: 100 # (int) number of epochs to train for +time: # (float, optional) max hours to train; overrides epochs if set +patience: 100 # (int) early stop after N epochs without val improvement +batch: 16 # (int | float) batch size as int (e.g. 16), -1 for AutoBatch, or float in (0.0, 1.0) for GPU memory fraction +imgsz: 640 # (int | list) train/val use int (square); predict/export may use [h,w] +save: True # (bool) save train checkpoints and predict results +save_period: -1 # (int) save checkpoint every N epochs; disabled if < 1 +cache: False # (bool | str) cache images in RAM (True/'ram') or on 'disk' to speed dataloading; False disables +device: # (int | str | list) device: 0/[0,1] CUDA, 'npu:0' Ascend, 'xpu:0' Intel, 'cpu'/'mps', -1/[-1,-1] auto GPUs +workers: 8 # (int) dataloader workers (per RANK if DDP) +project: # (str, optional) project name for results root +name: # (str, optional) experiment name or export hardware target +exist_ok: False # (bool) overwrite existing 'project/name' if True +pretrained: True # (bool | str) use pretrained weights (bool) or load weights from path (str) +cls_remap: True # (bool) when fine-tuning across datasets, remap pretrained cls head rows by class-name match +optimizer: auto # (str) optimizer: SGD, MuSGD, Adam, Adamax, AdamW, NAdam, RAdam, RMSProp, or auto +verbose: True # (bool) print verbose logs +seed: 0 # (int) random seed for reproducibility +deterministic: True # (bool) enable deterministic ops; reproducible but may be slower +single_cls: False # (bool) treat all classes as a single class +rect: False # (bool) rectangular batches for train; rectangular batching for val when mode='val' +cos_lr: False # (bool) cosine learning rate scheduler +close_mosaic: 10 # (int) disable mosaic augmentation for final N epochs (0 to keep enabled) +resume: False # (bool) resume training from last checkpoint in the run dir +amp: True # (bool | str) train precision: True/'fp16' (AMP check), 'bf16', or False/'fp32'; AMP uses FP16 train validation +fraction: 1.0 # (float | int | list) train ratio/count or split values; 1 = all, integer >1 = count, test 0 = none +profile: False # (bool) profile ONNX/TensorRT speeds during training for loggers +freeze: # (int | list, optional) freeze first N layers (int), or specific layer indices or module names like "23.cv2" (list) +multi_scale: 0.0 # (float) multi-scale range as a fraction of imgsz; sizes are rounded to stride multiples +compile: False # (bool | str) enable torch.compile() backend='inductor'; True="default", False=off, or "default|reduce-overhead|max-autotune-no-cudagraphs" +channels_last: # (bool, optional) auto-enable for non-Windows CUDA training on PyTorch 1.11+ and supported x86 CPU inference + +# Segmentation +overlap_mask: True # (bool) merge instance masks into one mask during training (segment only) +mask_ratio: 4 # (int) mask downsample ratio (segment only) + +# Classification +dropout: 0.0 # (float) dropout for classification head (classify only) + +# Val/Test settings ---------------------------------------------------------------------------------------------------- +val: True # (bool) run validation/testing during training +split: val # (str) dataset split to evaluate: 'val', 'test' or 'train' +save_json: False # (bool) save COCO JSON (detect/segment/pose), compute detect size metrics, or save semantic PNG masks +conf: # (float, optional) confidence threshold; defaults: predict=0.25, val=0.001 +iou: 0.7 # (float) IoU threshold used for NMS +max_det: 300 # (int) maximum number of detections per image +quantize: # (int|str, optional) precision: predict/val 16/fp16 or 32/fp32/None sets pt/torchscript compute; elsewhere the artifact/runtime decides, though 16 rounds openvino inputs; export also supports 8/int8 and w8a8|w16a16|w8a16|w8a32; train uses 8/int8 for quantization-aware training (QAT); replaces deprecated half/int8 args +dnn: False # (bool) use OpenCV DNN for ONNX inference +plots: True # (bool) save plots and images during train/val +nms: # (bool, optional) None: external NMS (default); True: embed NMS on export; False: NMS-free head if available + +# Predict settings ----------------------------------------------------------------------------------------------------- +source: # (str, optional) path/dir/URL/stream for images or videos; e.g. 'ultralytics/assets' or '0' for webcam +vid_stride: 1 # (int) read every Nth frame for video sources +stream_buffer: False # (bool) True buffers all frames; False keeps the most recent frame for low-latency streams +visualize: False # (bool) save class activation heatmaps (predict) or visualize TP/FP/FN confusion (val) +augment: False # (bool) apply test-time augmentation during prediction +agnostic_nms: False # (bool) class-agnostic NMS +classes: # (int | list[int], optional) filter by class id(s), e.g. 0 or [0,2,3] +retina_masks: False # (bool) use high-resolution segmentation masks (segment) +embed: # (list[int], optional) return feature embeddings from given layer indices + +# Visualize settings --------------------------------------------------------------------------------------------------- +show: False # (bool) show images/videos in a window if supported +save_frames: False # (bool) save individual frames from video predictions +save_txt: False # (bool) save results as .txt files (xywh format) +save_conf: False # (bool) save confidence scores with results +save_crop: False # (bool) save cropped prediction regions to files +show_labels: True # (bool) draw class labels on images, e.g. 'person' +show_conf: True # (bool) draw confidence values on images, e.g. '0.99' +show_boxes: True # (bool) draw bounding boxes on images +line_width: # (int, optional) line width of boxes; auto-scales with image size if not set + +# Export settings ------------------------------------------------------------------------------------------------------ +format: torchscript # (str) target format, e.g. torchscript|onnx|openvino|engine|coreml|saved_model|pb|edgetpu|paddle|mnn|ncnn|imx|rknn|executorch|axelera|deepx|qnn|litert|hailo|ascend +keras: False # (bool) TF SavedModel only (format=saved_model); enable Keras layers during export +optimize: False # (bool) DEEPX only; higher compiler optimization (slower compile, faster inference) +dynamic: False # (bool) dynamic shapes for torchscript, onnx, openvino, engine, coreml; enable variable image sizes +simplify: True # (bool) supported ONNX-based exports (see export table); simplify intermediate ONNX graph +opset: # (int, optional) supported ONNX-based exports (see export table); intermediate ONNX opset version +workspace: # (float, optional) engine (TensorRT) only; workspace size in GiB, e.g. 4 + +# Hyperparameters ------------------------------------------------------------------------------------------------------ +lr0: 0.01 # (float) initial learning rate (SGD=1e-2, Adam/AdamW=1e-3) +lrf: 0.01 # (float) final LR fraction; final LR = lr0 * lrf +momentum: 0.937 # (float) SGD momentum or Adam beta1 +weight_decay: 0.0005 # (float) weight decay (L2 regularization) +warmup_epochs: 3.0 # (float) warmup epochs (fractions allowed) +warmup_momentum: 0.8 # (float) initial momentum during warmup +warmup_bias_lr: 0.1 # (float) bias learning rate during warmup +distill_model: # (str, optional) path to teacher model for knowledge distillation +dis: 6.0 # (float) distillation loss weight +box: 7.5 # (float) box loss gain +cls: 0.5 # (float) classification loss gain +cls_pw: 0.0 # (float) class weights power for handling class imbalance (0.0=disable, 1.0=full inverse frequency) +dfl: 1.5 # (float) box distance loss gain (DFL when reg_max > 1, L1 on DFL-free YOLO26) +pose: 12.0 # (float) pose loss gain (pose tasks) +kobj: 1.0 # (float) keypoint objectness loss gain (pose tasks) +rle: 1.0 # (float) rle loss gain (pose tasks) +angle: 1.0 # (float) oriented angle loss gain (obb tasks) +dlog: 1.0 # (float) depth log (SILog) loss gain (depth tasks) +dgrad: 0.5 # (float) depth gradient loss gain (depth tasks) +dlam: 1.0 # (float) depth SILog variance focus: 1.0=scale-invariant, 0.0=log-RMSE (depth tasks) +nbs: 64 # (int) nominal batch size used for loss normalization +hsv_h: 0.015 # (float) HSV hue augmentation fraction +hsv_s: 0.7 # (float) HSV saturation augmentation fraction +hsv_v: 0.4 # (float) HSV value (brightness) augmentation fraction +degrees: 0.0 # (float) rotation degrees (+/-) +translate: 0.1 # (float) translation fraction (+/-) +scale: 0.5 # (float | tuple) scale gain (+/-) as float, or explicit (min, max) tuple +shear: 0.0 # (float) shear degrees (+/-) +perspective: 0.0 # (float) perspective fraction (0–0.001 typical) +flipud: 0.0 # (float) vertical flip probability +fliplr: 0.5 # (float) horizontal flip probability +bgr: 0.0 # (float) RGB↔BGR channel swap probability +mosaic: 1.0 # (float) mosaic augmentation probability +mixup: 0.0 # (float) MixUp augmentation probability +cutmix: 0.0 # (float) CutMix augmentation probability +copy_paste: 0.0 # (float) segment/obb copy-paste fraction of eligible objects +copy_paste_mode: flip # (str) copy-paste strategy for segment/obb: flip or mixup +auto_augment: randaugment # (str) classification auto augmentation policy: randaugment, autoaugment, augmix +erasing: 0.4 # (float) random erasing probability for classification (0.0–1.0) + +# Custom config.yaml --------------------------------------------------------------------------------------------------- +cfg: # (str, optional) path to a config.yaml that overrides defaults + +# Tracker settings ------------------------------------------------------------------------------------------------------ +tracker: tracktrack.yaml # (str) tracker config: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c427f855b006bd91314e0a5dfe1a9ec9357cb6de --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml @@ -0,0 +1,17 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO11-cls image classification model with ResNet18 backbone +# Model docs: https://docs.ultralytics.com/models/yolo11 +# Task docs: https://docs.ultralytics.com/tasks/classify + +# Parameters +nc: 1000 # number of classes + +# ResNet18 backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, TorchVision, [512, resnet18, DEFAULT, True, 2]] # truncate two layers from the end + +# YOLO11n head +head: + - [-1, 1, Classify, [nc]] # Classify diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-cls.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-cls.yaml new file mode 100644 index 0000000000000000000000000000000000000000..753e27b6ddf2e1e93a22c6bf1bf2e8c1b062cfb9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-cls.yaml @@ -0,0 +1,33 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO11-cls image classification model +# Model docs: https://docs.ultralytics.com/models/yolo11 +# Task docs: https://docs.ultralytics.com/tasks/classify + +# Parameters +nc: 1000 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolo11n-cls.yaml' will call yolo11-cls.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 86 layers, 1633584 parameters, 1633584 gradients, 0.5 GFLOPs + s: [0.50, 0.50, 1024] # summary: 86 layers, 5545488 parameters, 5545488 gradients, 1.6 GFLOPs + m: [0.50, 1.00, 512] # summary: 106 layers, 10455696 parameters, 10455696 gradients, 5.0 GFLOPs + l: [1.00, 1.00, 512] # summary: 176 layers, 12937104 parameters, 12937104 gradients, 6.2 GFLOPs + x: [1.00, 1.50, 512] # summary: 176 layers, 28458544 parameters, 28458544 gradients, 13.7 GFLOPs + +# YOLO11n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 2, C2PSA, [1024]] # 9 + +# YOLO11n head +head: + - [-1, 1, Classify, [nc]] # Classify diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-obb.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-obb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ef63a728ed5b7d6fd3fd1aedf78e67ea905ee86c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-obb.yaml @@ -0,0 +1,50 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO11-obb Oriented Bounding Boxes (OBB) model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo11 +# Task docs: https://docs.ultralytics.com/tasks/obb + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolo11n-obb.yaml' will call yolo11-obb.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 196 layers, 2695747 parameters, 2695731 gradients, 6.9 GFLOPs + s: [0.50, 0.50, 1024] # summary: 196 layers, 9744931 parameters, 9744915 gradients, 22.7 GFLOPs + m: [0.50, 1.00, 512] # summary: 246 layers, 20963523 parameters, 20963507 gradients, 72.2 GFLOPs + l: [1.00, 1.00, 512] # summary: 372 layers, 26220995 parameters, 26220979 gradients, 91.3 GFLOPs + x: [1.00, 1.50, 512] # summary: 372 layers, 58875331 parameters, 58875315 gradients, 204.3 GFLOPs + +# YOLO11n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLO11n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, False]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, False]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, False]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 2, C3k2, [1024, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, OBB, [nc, 1]] # OBB(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-pose.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-pose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fb3dd7a119981acd8e0c90f6c9fdd299caf6d9b3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-pose.yaml @@ -0,0 +1,51 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO11-pose keypoints/pose estimation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo11 +# Task docs: https://docs.ultralytics.com/tasks/pose + +# Parameters +nc: 80 # number of classes +kpt_shape: [17, 3] # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible) +scales: # model compound scaling constants, i.e. 'model=yolo11n-pose.yaml' will call yolo11-pose.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 196 layers, 2908507 parameters, 2908491 gradients, 7.7 GFLOPs + s: [0.50, 0.50, 1024] # summary: 196 layers, 9948811 parameters, 9948795 gradients, 23.5 GFLOPs + m: [0.50, 1.00, 512] # summary: 246 layers, 20973273 parameters, 20973257 gradients, 72.3 GFLOPs + l: [1.00, 1.00, 512] # summary: 372 layers, 26230745 parameters, 26230729 gradients, 91.4 GFLOPs + x: [1.00, 1.50, 512] # summary: 372 layers, 58889881 parameters, 58889865 gradients, 204.3 GFLOPs + +# YOLO11n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLO11n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, False]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, False]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, False]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 2, C3k2, [1024, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, Pose, [nc, kpt_shape]] # Pose(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d4afee00611ba1105426147ae7c8bb36dd8d3112 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11-seg.yaml @@ -0,0 +1,50 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO11-seg instance segmentation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo11 +# Task docs: https://docs.ultralytics.com/tasks/segment + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolo11n-seg.yaml' will call yolo11-seg.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 203 layers, 2876848 parameters, 2876832 gradients, 10.5 GFLOPs + s: [0.50, 0.50, 1024] # summary: 203 layers, 10113248 parameters, 10113232 gradients, 35.8 GFLOPs + m: [0.50, 1.00, 512] # summary: 253 layers, 22420896 parameters, 22420880 gradients, 123.9 GFLOPs + l: [1.00, 1.00, 512] # summary: 379 layers, 27678368 parameters, 27678352 gradients, 143.0 GFLOPs + x: [1.00, 1.50, 512] # summary: 379 layers, 62142656 parameters, 62142640 gradients, 320.2 GFLOPs + +# YOLO11n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLO11n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, False]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, False]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, False]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 2, C3k2, [1024, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, Segment, [nc, 32, 256]] # Segment(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c90c444859b460a870d97235e0bbc74fc45e599d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yolo11.yaml @@ -0,0 +1,50 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO11 object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo11 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolo11n.yaml' will call yolo11.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 181 layers, 2624080 parameters, 2624064 gradients, 6.6 GFLOPs + s: [0.50, 0.50, 1024] # summary: 181 layers, 9458752 parameters, 9458736 gradients, 21.7 GFLOPs + m: [0.50, 1.00, 512] # summary: 231 layers, 20114688 parameters, 20114672 gradients, 68.5 GFLOPs + l: [1.00, 1.00, 512] # summary: 357 layers, 25372160 parameters, 25372144 gradients, 87.6 GFLOPs + x: [1.00, 1.50, 512] # summary: 357 layers, 56966176 parameters, 56966160 gradients, 196.0 GFLOPs + +# YOLO11n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLO11n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, False]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, False]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, False]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 2, C3k2, [1024, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yoloe-11-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yoloe-11-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e3400d7774dc705e03da0f87ea98c61dada2eaec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yoloe-11-seg.yaml @@ -0,0 +1,50 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOE-11-seg instance segmentation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yoloe +# Task docs: https://docs.ultralytics.com/tasks/segment + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yoloe-11n-seg.yaml' will call yoloe-11-seg.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 355 layers, 2876848 parameters, 2876832 gradients, 10.5 GFLOPs + s: [0.50, 0.50, 1024] # summary: 355 layers, 10113248 parameters, 10113232 gradients, 35.8 GFLOPs + m: [0.50, 1.00, 512] # summary: 445 layers, 22420896 parameters, 22420880 gradients, 123.9 GFLOPs + l: [1.00, 1.00, 512] # summary: 667 layers, 27678368 parameters, 27678352 gradients, 143.0 GFLOPs + x: [1.00, 1.50, 512] # summary: 667 layers, 62142656 parameters, 62142640 gradients, 320.2 GFLOPs + +# YOLO11n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLO11n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, False]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, False]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, False]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 2, C3k2, [1024, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, YOLOESegment, [nc, 32, 256, 512, True]] # YOLOESegment(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yoloe-11.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yoloe-11.yaml new file mode 100644 index 0000000000000000000000000000000000000000..67da307c51467dd9bdc75e446568dc3c4b0f566c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/11/yoloe-11.yaml @@ -0,0 +1,50 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOE-11 object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yoloe +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yoloe-11n.yaml' will call yoloe-11.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 319 layers, 2624080 parameters, 2624064 gradients, 6.6 GFLOPs + s: [0.50, 0.50, 1024] # summary: 319 layers, 9458752 parameters, 9458736 gradients, 21.7 GFLOPs + m: [0.50, 1.00, 512] # summary: 409 layers, 20114688 parameters, 20114672 gradients, 68.5 GFLOPs + l: [1.00, 1.00, 512] # summary: 631 layers, 25372160 parameters, 25372144 gradients, 87.6 GFLOPs + x: [1.00, 1.50, 512] # summary: 631 layers, 56966176 parameters, 56966160 gradients, 196.0 GFLOPs + +# YOLO11n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLO11n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, False]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, False]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, False]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 2, C3k2, [1024, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, YOLOEDetect, [nc, 512, True]] # YOLOEDetect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12-cls.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12-cls.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fb5d190345d887b64869f4860f1756064eb8d119 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12-cls.yaml @@ -0,0 +1,32 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLO12-cls image classification model +# Model docs: https://docs.ultralytics.com/models/yolo12 +# Task docs: https://docs.ultralytics.com/tasks/classify + +# Parameters +nc: 1000 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolo12n-cls.yaml' will call yolo12-cls.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 152 layers, 1,820,976 parameters, 1,820,976 gradients, 3.7 GFLOPs + s: [0.50, 0.50, 1024] # summary: 152 layers, 6,206,992 parameters, 6,206,992 gradients, 13.6 GFLOPs + m: [0.50, 1.00, 512] # summary: 172 layers, 12,083,088 parameters, 12,083,088 gradients, 44.2 GFLOPs + l: [1.00, 1.00, 512] # summary: 312 layers, 15,558,640 parameters, 15,558,640 gradients, 56.9 GFLOPs + x: [1.00, 1.50, 512] # summary: 312 layers, 34,172,592 parameters, 34,172,592 gradients, 126.5 GFLOPs + +# YOLO12n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 4, A2C2f, [512, True, 4]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 4, A2C2f, [1024, True, 1]] # 8 + +# YOLO12n head +head: + - [-1, 1, Classify, [nc]] # Classify diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12-obb.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12-obb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9351c75d1c83c276039adee52bba58cb0a1097c5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12-obb.yaml @@ -0,0 +1,48 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLO12-obb Oriented Bounding Boxes (OBB) model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo12 +# Task docs: https://docs.ultralytics.com/tasks/obb + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolo12n-obb.yaml' will call yolo12-obb.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 287 layers, 2,673,955 parameters, 2,673,939 gradients, 6.9 GFLOPs + s: [0.50, 0.50, 1024] # summary: 287 layers, 9,570,275 parameters, 9,570,259 gradients, 22.7 GFLOPs + m: [0.50, 1.00, 512] # summary: 307 layers, 21,048,003 parameters, 21,047,987 gradients, 71.8 GFLOPs + l: [1.00, 1.00, 512] # summary: 503 layers, 27,299,619 parameters, 27,299,603 gradients, 93.4 GFLOPs + x: [1.00, 1.50, 512] # summary: 503 layers, 61,119,939 parameters, 61,119,923 gradients, 208.6 GFLOPs + +# YOLO12n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 4, A2C2f, [512, True, 4]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 4, A2C2f, [1024, True, 1]] # 8 + +# YOLO12n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, A2C2f, [512, False, -1]] # 11 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, A2C2f, [256, False, -1]] # 14 + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 11], 1, Concat, [1]] # cat head P4 + - [-1, 2, A2C2f, [512, False, -1]] # 17 + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 8], 1, Concat, [1]] # cat head P5 + - [-1, 2, C3k2, [1024, True]] # 20 (P5/32-large) + + - [[14, 17, 20], 1, OBB, [nc, 1]] # OBB(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12-pose.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12-pose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1ecf1a4cd15ba3e11c934539033814b94c9b5e1d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12-pose.yaml @@ -0,0 +1,49 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLO12-pose keypoints/pose estimation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo12 +# Task docs: https://docs.ultralytics.com/tasks/pose + +# Parameters +nc: 80 # number of classes +kpt_shape: [17, 3] # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible) +scales: # model compound scaling constants, i.e. 'model=yolo12n-pose.yaml' will call yolo12-pose.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 287 layers, 2,886,715 parameters, 2,886,699 gradients, 7.8 GFLOPs + s: [0.50, 0.50, 1024] # summary: 287 layers, 9,774,155 parameters, 9,774,139 gradients, 23.5 GFLOPs + m: [0.50, 1.00, 512] # summary: 307 layers, 21,057,753 parameters, 21,057,737 gradients, 71.8 GFLOPs + l: [1.00, 1.00, 512] # summary: 503 layers, 27,309,369 parameters, 27,309,353 gradients, 93.5 GFLOPs + x: [1.00, 1.50, 512] # summary: 503 layers, 61,134,489 parameters, 61,134,473 gradients, 208.7 GFLOPs + +# YOLO12n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 4, A2C2f, [512, True, 4]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 4, A2C2f, [1024, True, 1]] # 8 + +# YOLO12n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, A2C2f, [512, False, -1]] # 11 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, A2C2f, [256, False, -1]] # 14 + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 11], 1, Concat, [1]] # cat head P4 + - [-1, 2, A2C2f, [512, False, -1]] # 17 + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 8], 1, Concat, [1]] # cat head P5 + - [-1, 2, C3k2, [1024, True]] # 20 (P5/32-large) + + - [[14, 17, 20], 1, Pose, [nc, kpt_shape]] # Pose(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ec775a0d17544d3abbeaa380ea3174354ba0d8c9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12-seg.yaml @@ -0,0 +1,48 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLO12-seg instance segmentation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo12 +# Task docs: https://docs.ultralytics.com/tasks/segment + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolo12n-seg.yaml' will call yolo12-seg.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 294 layers, 2,855,056 parameters, 2,855,040 gradients, 10.6 GFLOPs + s: [0.50, 0.50, 1024] # summary: 294 layers, 9,938,592 parameters, 9,938,576 gradients, 35.7 GFLOPs + m: [0.50, 1.00, 512] # summary: 314 layers, 22,505,376 parameters, 22,505,360 gradients, 123.5 GFLOPs + l: [1.00, 1.00, 512] # summary: 510 layers, 28,756,992 parameters, 28,756,976 gradients, 145.1 GFLOPs + x: [1.00, 1.50, 512] # summary: 510 layers, 64,387,264 parameters, 64,387,248 gradients, 324.6 GFLOPs + +# YOLO12n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 4, A2C2f, [512, True, 4]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 4, A2C2f, [1024, True, 1]] # 8 + +# YOLO12n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, A2C2f, [512, False, -1]] # 11 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, A2C2f, [256, False, -1]] # 14 + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 11], 1, Concat, [1]] # cat head P4 + - [-1, 2, A2C2f, [512, False, -1]] # 17 + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 8], 1, Concat, [1]] # cat head P5 + - [-1, 2, C3k2, [1024, True]] # 20 (P5/32-large) + + - [[14, 17, 20], 1, Segment, [nc, 32, 256]] # Segment(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12.yaml new file mode 100644 index 0000000000000000000000000000000000000000..737c03339b7ef54abb1db151f7d7fa4c60c3a923 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/12/yolo12.yaml @@ -0,0 +1,48 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLO12 object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo12 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolo12n.yaml' will call yolo12.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 272 layers, 2,602,288 parameters, 2,602,272 gradients, 6.7 GFLOPs + s: [0.50, 0.50, 1024] # summary: 272 layers, 9,284,096 parameters, 9,284,080 gradients, 21.7 GFLOPs + m: [0.50, 1.00, 512] # summary: 292 layers, 20,199,168 parameters, 20,199,152 gradients, 68.1 GFLOPs + l: [1.00, 1.00, 512] # summary: 488 layers, 26,450,784 parameters, 26,450,768 gradients, 89.7 GFLOPs + x: [1.00, 1.50, 512] # summary: 488 layers, 59,210,784 parameters, 59,210,768 gradients, 200.3 GFLOPs + +# YOLO12n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 4, A2C2f, [512, True, 4]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 4, A2C2f, [1024, True, 1]] # 8 + +# YOLO12n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, A2C2f, [512, False, -1]] # 11 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, A2C2f, [256, False, -1]] # 14 + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 11], 1, Concat, [1]] # cat head P4 + - [-1, 2, A2C2f, [512, False, -1]] # 17 + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 8], 1, Concat, [1]] # cat head P5 + - [-1, 2, C3k2, [1024, True]] # 20 (P5/32-large) + + - [[14, 17, 20], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-cls.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-cls.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1253499e76646225bf7eb73b3d96448b7c8a5355 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-cls.yaml @@ -0,0 +1,33 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO26-cls image classification model +# Model docs: https://docs.ultralytics.com/models/yolo26 +# Task docs: https://docs.ultralytics.com/tasks/classify + +# Parameters +nc: 1000 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolo26n-cls.yaml' will call yolo26-cls.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 86 layers, 2,812,104 parameters, 2,812,104 gradients, 0.5 GFLOPs + s: [0.50, 0.50, 1024] # summary: 86 layers, 6,724,008 parameters, 6,724,008 gradients, 1.6 GFLOPs + m: [0.50, 1.00, 512] # summary: 106 layers, 11,634,216 parameters, 11,634,216 gradients, 5.0 GFLOPs + l: [1.00, 1.00, 512] # summary: 176 layers, 14,115,624 parameters, 14,115,624 gradients, 6.2 GFLOPs + x: [1.00, 1.50, 512] # summary: 176 layers, 29,637,064 parameters, 29,637,064 gradients, 13.7 GFLOPs + +# YOLO26n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 2, C2PSA, [1024]] # 9 + +# YOLO26n head +head: + - [-1, 1, Classify, [nc]] # Classify diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-depth.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-depth.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b43a4b3640309f5f38437c7f9f2888eb6985637a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-depth.yaml @@ -0,0 +1,50 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO26-depth monocular depth estimation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo26 +# Task docs: https://docs.ultralytics.com/tasks/depth + +# Parameters +nc: 1 # not used for depth but required by parser +scales: # model compound scaling constants + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] + s: [0.50, 0.50, 1024] + m: [0.50, 1.00, 512] + l: [1.00, 1.00, 512] + x: [1.00, 1.50, 512] + +# YOLO26n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5, 3, True]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLO26n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, True]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, True]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, True]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 1, C3k2, [1024, True, 0.5, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, Depth, [256]] # Depth(P3, P4, P5) c_mid=256; unbounded log-depth output diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-obb.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-obb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ddee0404e93502ac1dc36effe47dec8fcca82a7d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-obb.yaml @@ -0,0 +1,52 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO26-obb Oriented Bounding Boxes (OBB) model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo26 +# Task docs: https://docs.ultralytics.com/tasks/obb + +# Parameters +nc: 80 # number of classes +end2end: True # whether to use end-to-end mode +reg_max: 1 # DFL bins +scales: # model compound scaling constants, i.e. 'model=yolo26n-obb.yaml' will call yolo26-obb.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 291 layers, 2,715,614 parameters, 2,715,614 gradients, 16.9 GFLOPs + s: [0.50, 0.50, 1024] # summary: 291 layers, 10,582,142 parameters, 10,582,142 gradients, 63.5 GFLOPs + m: [0.50, 1.00, 512] # summary: 311 layers, 23,593,918 parameters, 23,593,918 gradients, 211.9 GFLOPs + l: [1.00, 1.00, 512] # summary: 423 layers, 27,997,374 parameters, 27,997,374 gradients, 259.0 GFLOPs + x: [1.00, 1.50, 512] # summary: 423 layers, 62,811,678 parameters, 62,811,678 gradients, 578.9 GFLOPs + +# YOLO26n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5, 3, True]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLO26n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, True]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, True]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, True]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 1, C3k2, [1024, True, 0.5, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, OBB26, [nc, 1]] # OBB26(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-p2.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-p2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..29520f2bbddb6ae28cfb72592f10a3b4235d6b71 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-p2.yaml @@ -0,0 +1,60 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO26 object detection model with P2/4 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo26 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +end2end: True # whether to use end-to-end mode +reg_max: 1 # DFL bins +scales: # model compound scaling constants, i.e. 'model=yolo26n-p2.yaml' will call yolo26-p2.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 329 layers, 2,662,400 parameters, 2,662,400 gradients, 9.5 GFLOPs + s: [0.50, 0.50, 1024] # summary: 329 layers, 9,765,856 parameters, 9,765,856 gradients, 27.8 GFLOPs + m: [0.50, 1.00, 512] # summary: 349 layers, 21,144,288 parameters, 21,144,288 gradients, 91.4 GFLOPs + l: [1.00, 1.00, 512] # summary: 489 layers, 25,815,520 parameters, 25,815,520 gradients, 115.3 GFLOPs + x: [1.00, 1.50, 512] # summary: 489 layers, 57,935,232 parameters, 57,935,232 gradients, 256.9 GFLOPs + +# YOLO26n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5, 3, True]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLO26n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, True]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, True]] # 16 (P3/8-small) + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 2], 1, Concat, [1]] # cat backbone P2 + - [-1, 2, C3k2, [128, True]] # 19 (P2/4-xsmall) + + - [-1, 1, Conv, [128, 3, 2]] + - [[-1, 16], 1, Concat, [1]] # cat head P3 + - [-1, 2, C3k2, [256, True]] # 22 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, True]] # 25 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 1, C3k2, [1024, True, 0.5, True]] # 28 (P5/32-large) + + - [[19, 22, 25, 28], 1, Detect, [nc]] # Detect(P2, P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-p6.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-p6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a0fead51111f54ea7e2cb1459c8acbf8e329fa56 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-p6.yaml @@ -0,0 +1,62 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO26 object detection model with P3/8 - P6/64 outputs +# Model docs: https://docs.ultralytics.com/models/yolo26 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +end2end: True # whether to use end-to-end mode +reg_max: 1 # DFL bins +scales: # model compound scaling constants, i.e. 'model=yolo26n-p6.yaml' will call yolo26-p6.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 349 layers, 4,063,872 parameters, 4,063,872 gradients, 6.0 GFLOPs + s: [0.50, 0.50, 1024] # summary: 349 layers, 15,876,448 parameters, 15,876,448 gradients, 22.3 GFLOPs + m: [0.50, 1.00, 512] # summary: 369 layers, 32,400,096 parameters, 32,400,096 gradients, 77.3 GFLOPs + l: [1.00, 1.00, 512] # summary: 523 layers, 39,365,600 parameters, 39,365,600 gradients, 97.0 GFLOPs + x: [1.00, 1.50, 512] # summary: 523 layers, 88,330,368 parameters, 88,330,368 gradients, 216.6 GFLOPs + +# YOLO26n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [768, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [768, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 9-P6/64 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5, 3, False]] # 11 + - [-1, 2, C2PSA, [1024]] # 12 + +# YOLO26n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 8], 1, Concat, [1]] # cat backbone P5 + - [-1, 2, C3k2, [768, True]] # 15 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, True]] # 18 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, True]] # 21 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 18], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, True]] # 24 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 15], 1, Concat, [1]] # cat head P5 + - [-1, 2, C3k2, [768, True]] # 27 (P5/32-large) + + - [-1, 1, Conv, [768, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P6 + - [-1, 1, C3k2, [1024, True, 0.5, True]] # 30 (P6/64-large) + + - [[21, 24, 27, 30], 1, Detect, [nc]] # Detect(P3, P4, P5, P6) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-pose.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-pose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9be3382f7d13f0881585ed6c4218d1ce9bea1008 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-pose.yaml @@ -0,0 +1,53 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO26-pose keypoints/pose estimation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo26 +# Task docs: https://docs.ultralytics.com/tasks/pose + +# Parameters +nc: 80 # number of classes +end2end: True # whether to use end-to-end mode +reg_max: 1 # DFL bins +kpt_shape: [17, 3] # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible) +scales: # model compound scaling constants, i.e. 'model=yolo26n-pose.yaml' will call yolo26-pose.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 363 layers, 3,747,554 parameters, 3,747,554 gradients, 10.7 GFLOPs + s: [0.50, 0.50, 1024] # summary: 363 layers, 11,870,498 parameters, 11,870,498 gradients, 29.6 GFLOPs + m: [0.50, 1.00, 512] # summary: 383 layers, 24,344,482 parameters, 24,344,482 gradients, 85.9 GFLOPs + l: [1.00, 1.00, 512] # summary: 495 layers, 28,747,938 parameters, 28,747,938 gradients, 104.3 GFLOPs + x: [1.00, 1.50, 512] # summary: 495 layers, 62,914,350 parameters, 62,914,350 gradients, 226.3 GFLOPs + +# YOLO26n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5, 3, True]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLO26n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, True]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, True]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, True]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 1, C3k2, [1024, True, 0.5, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, Pose26, [nc, kpt_shape]] # Pose26(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c6ab4879e73568f84503f27ba477cd17b77daac7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-seg.yaml @@ -0,0 +1,52 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO26-seg instance segmentation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo26 +# Task docs: https://docs.ultralytics.com/tasks/segment + +# Parameters +nc: 80 # number of classes +end2end: True # whether to use end-to-end mode +reg_max: 1 # DFL bins +scales: # model compound scaling constants, i.e. 'model=yolo26n-seg.yaml' will call yolo26-seg.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 309 layers, 3,126,280 parameters, 3,126,280 gradients, 10.5 GFLOPs + s: [0.50, 0.50, 1024] # summary: 309 layers, 11,505,800 parameters, 11,505,800 gradients, 37.4 GFLOPs + m: [0.50, 1.00, 512] # summary: 329 layers, 27,112,072 parameters, 27,112,072 gradients, 132.5 GFLOPs + l: [1.00, 1.00, 512] # summary: 441 layers, 31,515,528 parameters, 31,515,528 gradients, 150.9 GFLOPs + x: [1.00, 1.50, 512] # summary: 441 layers, 70,693,800 parameters, 70,693,800 gradients, 337.7 GFLOPs + +# YOLO26n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5, 3, True]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLO26n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, True]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, True]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, True]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 1, C3k2, [1024, True, 0.5, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, Segment26, [nc, 32, 256]] # Segment26(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-sem.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-sem.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8a3811becb7804405db429227d48bf23a4ae7c4c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26-sem.yaml @@ -0,0 +1,42 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO26 semantic segmentation model with P3/8 and P4/16 head inputs +# Model docs: https://docs.ultralytics.com/models/yolo26 +# Task docs: https://docs.ultralytics.com/tasks/semantic + +# Parameters +nc: 19 # number of classes (Cityscapes default) +scales: # model compound scaling constants, i.e. 'model=yolo26n-sem.yaml' will call yolo26-sem.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 260 layers, 2,572,280 parameters, 2,572,280 gradients, 6.1 GFLOPs + s: [0.50, 0.50, 1024] # summary: 260 layers, 10,009,784 parameters, 10,009,784 gradients, 22.8 GFLOPs + m: [0.50, 1.00, 512] # summary: 280 layers, 21,896,248 parameters, 21,896,248 gradients, 75.4 GFLOPs + l: [1.00, 1.00, 512] # summary: 392 layers, 26,299,704 parameters, 26,299,704 gradients, 93.8 GFLOPs + x: [1.00, 1.50, 512] # summary: 392 layers, 58,993,368 parameters, 58,993,368 gradients, 209.5 GFLOPs + +# YOLO26n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5, 3, True]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLO26n semantic segmentation head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, True]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, True]] # 16 (P3/8-small) + + - [[16, 13], 1, SemanticSegment, [nc]] # SemanticSegment diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4fc9eb29bad151741c39c958f1dfba17bdc4c25c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yolo26.yaml @@ -0,0 +1,52 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLO26 object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo26 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +end2end: True # whether to use end-to-end mode +reg_max: 1 # DFL bins +scales: # model compound scaling constants, i.e. 'model=yolo26n.yaml' will call yolo26.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 260 layers, 2,572,280 parameters, 2,572,280 gradients, 6.1 GFLOPs + s: [0.50, 0.50, 1024] # summary: 260 layers, 10,009,784 parameters, 10,009,784 gradients, 22.8 GFLOPs + m: [0.50, 1.00, 512] # summary: 280 layers, 21,896,248 parameters, 21,896,248 gradients, 75.4 GFLOPs + l: [1.00, 1.00, 512] # summary: 392 layers, 26,299,704 parameters, 26,299,704 gradients, 93.8 GFLOPs + x: [1.00, 1.50, 512] # summary: 392 layers, 58,993,368 parameters, 58,993,368 gradients, 209.5 GFLOPs + +# YOLO26n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5, 3, True]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLO26n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, True]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, True]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, True]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 1, C3k2, [1024, True, 0.5, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yoloe-26-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yoloe-26-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c698d107af227b1da887d6562626df5142cc33c8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yoloe-26-seg.yaml @@ -0,0 +1,53 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOE-26 open-vocabulary instance segmentation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo26 +# Task docs: https://docs.ultralytics.com/tasks/segment + +# Parameters +nc: 80 # number of classes +end2end: True # whether to use end-to-end mode +reg_max: 1 # DFL bins +text_model: mobileclip2:b +scales: # model compound scaling constants, i.e. 'model=yoloe-26n-seg.yaml' will call yoloe-26-seg.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 347 layers, 5,615,540 parameters, 5,615,540 gradients, 11.7 GFLOPs + s: [0.50, 0.50, 1024] # summary: 347 layers, 15,272,852 parameters, 15,272,852 gradients, 39.3 GFLOPs + m: [0.50, 1.00, 512] # summary: 367 layers, 34,922,132 parameters, 34,922,132 gradients, 136.3 GFLOPs + l: [1.00, 1.00, 512] # summary: 479 layers, 39,325,588 parameters, 39,325,588 gradients, 154.7 GFLOPs + x: [1.00, 1.50, 512] # summary: 479 layers, 85,397,684 parameters, 85,397,684 gradients, 343.3 GFLOPs + +# YOLOE26n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5, 3, True]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLOE26n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, True]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, True]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, True]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 1, C3k2, [1024, True, 0.5, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, YOLOESegment26, [nc, 32, 256, 512, True]] # YOLOESegment26(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yoloe-26.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yoloe-26.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0b5f2e8104bc8fb0abd0a8c4556ef86e24b4fffa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/26/yoloe-26.yaml @@ -0,0 +1,53 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOE-26 open-vocabulary object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo26 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +end2end: True # whether to use end-to-end mode +reg_max: 1 # DFL bins +text_model: mobileclip2:b +scales: # model compound scaling constants, i.e. 'model=yoloe-26n.yaml' will call yoloe-26.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.50, 0.25, 1024] # summary: 298 layers, 5,061,540 parameters, 5,061,540 gradients, 7.3 GFLOPs + s: [0.50, 0.50, 1024] # summary: 298 layers, 13,776,836 parameters, 13,776,836 gradients, 24.8 GFLOPs + m: [0.50, 1.00, 512] # summary: 318 layers, 29,706,308 parameters, 29,706,308 gradients, 79.2 GFLOPs + l: [1.00, 1.00, 512] # summary: 430 layers, 34,109,764 parameters, 34,109,764 gradients, 97.6 GFLOPs + x: [1.00, 1.50, 512] # summary: 430 layers, 73,697,252 parameters, 73,697,252 gradients, 215.2 GFLOPs + +# YOLOE26n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 2, C3k2, [256, False, 0.25]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 2, C3k2, [512, False, 0.25]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 2, C3k2, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 2, C3k2, [1024, True]] + - [-1, 1, SPPF, [1024, 5, 3, True]] # 9 + - [-1, 2, C2PSA, [1024]] # 10 + +# YOLOE26n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 2, C3k2, [512, True]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 2, C3k2, [256, True]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 2, C3k2, [512, True]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 1, C3k2, [1024, True, 0.5, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, YOLOEDetect, [nc, 512, True]] # YOLOEDetect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/rt-detr/rtdetr-l.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/rt-detr/rtdetr-l.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3593b48e695cb9fbe36c3ac9d546ac2b0c736b74 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/rt-detr/rtdetr-l.yaml @@ -0,0 +1,53 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics RT-DETR-l hybrid object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/rtdetr +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=rtdetr-l.yaml' will call rtdetr-l.yaml with scale 'l' + # [depth, width, max_channels] + l: [1.00, 1.00, 1024] + +backbone: + # [from, repeats, module, args] + - [-1, 1, HGStem, [32, 48]] # 0-P2/4 + - [-1, 6, HGBlock, [48, 128, 3]] # stage 1 + + - [-1, 1, DWConv, [128, 3, 2, 1, False]] # 2-P3/8 + - [-1, 6, HGBlock, [96, 512, 3]] # stage 2 + + - [-1, 1, DWConv, [512, 3, 2, 1, False]] # 4-P4/16 + - [-1, 6, HGBlock, [192, 1024, 5, True, False]] # cm, c2, k, light, shortcut + - [-1, 6, HGBlock, [192, 1024, 5, True, True]] + - [-1, 6, HGBlock, [192, 1024, 5, True, True]] # stage 3 + + - [-1, 1, DWConv, [1024, 3, 2, 1, False]] # 8-P5/32 + - [-1, 6, HGBlock, [384, 2048, 5, True, False]] # stage 4 + +head: + - [-1, 1, Conv, [256, 1, 1, None, 1, 1, False]] # 10 input_proj.2 + - [-1, 1, AIFI, [1024, 8]] + - [-1, 1, Conv, [256, 1, 1]] # 12, Y5, lateral_convs.0 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [7, 1, Conv, [256, 1, 1, None, 1, 1, False]] # 14 input_proj.1 + - [[-2, -1], 1, Concat, [1]] + - [-1, 3, RepC3, [256]] # 16, fpn_blocks.0 + - [-1, 1, Conv, [256, 1, 1]] # 17, Y4, lateral_convs.1 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [3, 1, Conv, [256, 1, 1, None, 1, 1, False]] # 19 input_proj.0 + - [[-2, -1], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, RepC3, [256]] # X3 (21), fpn_blocks.1 + + - [-1, 1, Conv, [256, 3, 2]] # 22, downsample_convs.0 + - [[-1, 17], 1, Concat, [1]] # cat Y4 + - [-1, 3, RepC3, [256]] # F4 (24), pan_blocks.0 + + - [-1, 1, Conv, [256, 3, 2]] # 25, downsample_convs.1 + - [[-1, 12], 1, Concat, [1]] # cat Y5 + - [-1, 3, RepC3, [256]] # F5 (27), pan_blocks.1 + + - [[21, 24, 27], 1, RTDETRDecoder, [nc]] # RTDETRDecoder(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e05b592a7c7c4b8962984e74bfbcde83f3d4fb55 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml @@ -0,0 +1,45 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics RT-DETR-ResNet101 hybrid object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/rtdetr +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=rtdetr-resnet101.yaml' will call rtdetr-resnet101.yaml with scale 'l' + # [depth, width, max_channels] + l: [1.00, 1.00, 1024] + +backbone: + # [from, repeats, module, args] + - [-1, 1, ResNetLayer, [3, 64, 1, True, 1]] # 0 + - [-1, 1, ResNetLayer, [64, 64, 1, False, 3]] # 1 + - [-1, 1, ResNetLayer, [256, 128, 2, False, 4]] # 2 + - [-1, 1, ResNetLayer, [512, 256, 2, False, 23]] # 3 + - [-1, 1, ResNetLayer, [1024, 512, 2, False, 3]] # 4 + +head: + - [-1, 1, Conv, [256, 1, 1, None, 1, 1, False]] # 5 + - [-1, 1, AIFI, [1024, 8]] + - [-1, 1, Conv, [256, 1, 1]] # 7 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [3, 1, Conv, [256, 1, 1, None, 1, 1, False]] # 9 + - [[-2, -1], 1, Concat, [1]] + - [-1, 3, RepC3, [256]] # 11 + - [-1, 1, Conv, [256, 1, 1]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [2, 1, Conv, [256, 1, 1, None, 1, 1, False]] # 14 + - [[-2, -1], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, RepC3, [256]] # X3 (16), fpn_blocks.1 + + - [-1, 1, Conv, [256, 3, 2]] # 17, downsample_convs.0 + - [[-1, 12], 1, Concat, [1]] # cat Y4 + - [-1, 3, RepC3, [256]] # F4 (19), pan_blocks.0 + + - [-1, 1, Conv, [256, 3, 2]] # 20, downsample_convs.1 + - [[-1, 7], 1, Concat, [1]] # cat Y5 + - [-1, 3, RepC3, [256]] # F5 (22), pan_blocks.1 + + - [[16, 19, 22], 1, RTDETRDecoder, [nc]] # RTDETRDecoder(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml new file mode 100644 index 0000000000000000000000000000000000000000..68a9406c6ff035df7de39bdc279b9446e5061ced --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml @@ -0,0 +1,45 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics RT-DETR-ResNet50 hybrid object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/rtdetr +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=rtdetr-resnet50.yaml' will call rtdetr-resnet50.yaml with scale 'l' + # [depth, width, max_channels] + l: [1.00, 1.00, 1024] + +backbone: + # [from, repeats, module, args] + - [-1, 1, ResNetLayer, [3, 64, 1, True, 1]] # 0 + - [-1, 1, ResNetLayer, [64, 64, 1, False, 3]] # 1 + - [-1, 1, ResNetLayer, [256, 128, 2, False, 4]] # 2 + - [-1, 1, ResNetLayer, [512, 256, 2, False, 6]] # 3 + - [-1, 1, ResNetLayer, [1024, 512, 2, False, 3]] # 4 + +head: + - [-1, 1, Conv, [256, 1, 1, None, 1, 1, False]] # 5 + - [-1, 1, AIFI, [1024, 8]] + - [-1, 1, Conv, [256, 1, 1]] # 7 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [3, 1, Conv, [256, 1, 1, None, 1, 1, False]] # 9 + - [[-2, -1], 1, Concat, [1]] + - [-1, 3, RepC3, [256]] # 11 + - [-1, 1, Conv, [256, 1, 1]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [2, 1, Conv, [256, 1, 1, None, 1, 1, False]] # 14 + - [[-2, -1], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, RepC3, [256]] # X3 (16), fpn_blocks.1 + + - [-1, 1, Conv, [256, 3, 2]] # 17, downsample_convs.0 + - [[-1, 12], 1, Concat, [1]] # cat Y4 + - [-1, 3, RepC3, [256]] # F4 (19), pan_blocks.0 + + - [-1, 1, Conv, [256, 3, 2]] # 20, downsample_convs.1 + - [[-1, 7], 1, Concat, [1]] # cat Y5 + - [-1, 3, RepC3, [256]] # F5 (22), pan_blocks.1 + + - [[16, 19, 22], 1, RTDETRDecoder, [nc]] # RTDETRDecoder(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/rt-detr/rtdetr-x.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/rt-detr/rtdetr-x.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7a7a0cdb8a9b6589f6ecc35bb18e29cadfba5c04 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/rt-detr/rtdetr-x.yaml @@ -0,0 +1,57 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics RT-DETR-x hybrid object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/rtdetr +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=rtdetr-x.yaml' will call rtdetr-x.yaml with scale 'x' + # [depth, width, max_channels] + x: [1.00, 1.00, 2048] + +backbone: + # [from, repeats, module, args] + - [-1, 1, HGStem, [32, 64]] # 0-P2/4 + - [-1, 6, HGBlock, [64, 128, 3]] # stage 1 + + - [-1, 1, DWConv, [128, 3, 2, 1, False]] # 2-P3/8 + - [-1, 6, HGBlock, [128, 512, 3]] + - [-1, 6, HGBlock, [128, 512, 3, False, True]] # 4-stage 2 + + - [-1, 1, DWConv, [512, 3, 2, 1, False]] # 5-P4/16 + - [-1, 6, HGBlock, [256, 1024, 5, True, False]] # cm, c2, k, light, shortcut + - [-1, 6, HGBlock, [256, 1024, 5, True, True]] + - [-1, 6, HGBlock, [256, 1024, 5, True, True]] + - [-1, 6, HGBlock, [256, 1024, 5, True, True]] + - [-1, 6, HGBlock, [256, 1024, 5, True, True]] # 10-stage 3 + + - [-1, 1, DWConv, [1024, 3, 2, 1, False]] # 11-P5/32 + - [-1, 6, HGBlock, [512, 2048, 5, True, False]] + - [-1, 6, HGBlock, [512, 2048, 5, True, True]] # 13-stage 4 + +head: + - [-1, 1, Conv, [384, 1, 1, None, 1, 1, False]] # 14 input_proj.2 + - [-1, 1, AIFI, [2048, 8]] + - [-1, 1, Conv, [384, 1, 1]] # 16, Y5, lateral_convs.0 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [10, 1, Conv, [384, 1, 1, None, 1, 1, False]] # 18 input_proj.1 + - [[-2, -1], 1, Concat, [1]] + - [-1, 3, RepC3, [384]] # 20, fpn_blocks.0 + - [-1, 1, Conv, [384, 1, 1]] # 21, Y4, lateral_convs.1 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [4, 1, Conv, [384, 1, 1, None, 1, 1, False]] # 23 input_proj.0 + - [[-2, -1], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, RepC3, [384]] # X3 (25), fpn_blocks.1 + + - [-1, 1, Conv, [384, 3, 2]] # 26, downsample_convs.0 + - [[-1, 21], 1, Concat, [1]] # cat Y4 + - [-1, 3, RepC3, [384]] # F4 (28), pan_blocks.0 + + - [-1, 1, Conv, [384, 3, 2]] # 29, downsample_convs.1 + - [[-1, 16], 1, Concat, [1]] # cat Y5 + - [-1, 3, RepC3, [384]] # F5 (31), pan_blocks.1 + + - [[25, 28, 31], 1, RTDETRDecoder, [nc]] # RTDETRDecoder(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10b.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8b801dfc64a61f8f475deebc3f150571503a6e96 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10b.yaml @@ -0,0 +1,45 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLOv10b object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov10 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov10n.yaml' uses the 'n' scale + # [depth, width, max_channels] + b: [0.67, 1.00, 512] + +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, SCDown, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, SCDown, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2fCIB, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + - [-1, 1, PSA, [1024]] # 10 + +# YOLOv10 head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2fCIB, [512, True]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2fCIB, [512, True]] # 19 (P4/16-medium) + + - [-1, 1, SCDown, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2fCIB, [1024, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, v10Detect, [nc]] # v10Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10l.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10l.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ab73c304ce26e49028014c9ae3b25fddd16109df --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10l.yaml @@ -0,0 +1,45 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLOv10l object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov10 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov10n.yaml' uses the 'n' scale + # [depth, width, max_channels] + l: [1.00, 1.00, 512] + +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, SCDown, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, SCDown, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2fCIB, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + - [-1, 1, PSA, [1024]] # 10 + +# YOLOv10 head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2fCIB, [512, True]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2fCIB, [512, True]] # 19 (P4/16-medium) + + - [-1, 1, SCDown, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2fCIB, [1024, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, v10Detect, [nc]] # v10Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10m.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10m.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6d11875f952fa0411336136113591689bd216ca7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10m.yaml @@ -0,0 +1,45 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLOv10m object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov10 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov10n.yaml' uses the 'n' scale + # [depth, width, max_channels] + m: [0.67, 0.75, 768] + +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, SCDown, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, SCDown, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2fCIB, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + - [-1, 1, PSA, [1024]] # 10 + +# YOLOv10 head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2f, [512]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2fCIB, [512, True]] # 19 (P4/16-medium) + + - [-1, 1, SCDown, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2fCIB, [1024, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, v10Detect, [nc]] # v10Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10n.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fa10d756b45b2e60293389440d2b2a4ce6603172 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10n.yaml @@ -0,0 +1,45 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLOv10n object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov10 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov10n.yaml' uses the 'n' scale + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] + +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, SCDown, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, SCDown, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + - [-1, 1, PSA, [1024]] # 10 + +# YOLOv10 head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2f, [512]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2f, [512]] # 19 (P4/16-medium) + + - [-1, 1, SCDown, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2fCIB, [1024, True, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, v10Detect, [nc]] # v10Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10s.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10s.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b33ab573903bd2da318f5f0c28e34f7de178c0a3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10s.yaml @@ -0,0 +1,45 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLOv10s object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov10 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov10n.yaml' uses the 'n' scale + # [depth, width, max_channels] + s: [0.33, 0.50, 1024] + +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, SCDown, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, SCDown, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2fCIB, [1024, True, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + - [-1, 1, PSA, [1024]] # 10 + +# YOLOv10 head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2f, [512]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2f, [512]] # 19 (P4/16-medium) + + - [-1, 1, SCDown, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2fCIB, [1024, True, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, v10Detect, [nc]] # v10Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10x.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10x.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b339f972cc40cce01b47075b25bd1c4455bd3275 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v10/yolov10x.yaml @@ -0,0 +1,45 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLOv10x object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov10 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov10n.yaml' uses the 'n' scale + # [depth, width, max_channels] + x: [1.00, 1.25, 512] + +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, SCDown, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2fCIB, [512, True]] + - [-1, 1, SCDown, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2fCIB, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + - [-1, 1, PSA, [1024]] # 10 + +# YOLOv10 head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2fCIB, [512, True]] # 13 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 16 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 13], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2fCIB, [512, True]] # 19 (P4/16-medium) + + - [-1, 1, SCDown, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2fCIB, [1024, True]] # 22 (P5/32-large) + + - [[16, 19, 22], 1, v10Detect, [nc]] # v10Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v3/yolov3-spp.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v3/yolov3-spp.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6aef25ab748bc84ee6ad054057029de97e7e1b14 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v3/yolov3-spp.yaml @@ -0,0 +1,49 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv3-SPP object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov3 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple + +# darknet53 backbone +backbone: + # [from, number, module, args] + - [-1, 1, Conv, [32, 3, 1]] # 0 + - [-1, 1, Conv, [64, 3, 2]] # 1-P1/2 + - [-1, 1, Bottleneck, [64]] + - [-1, 1, Conv, [128, 3, 2]] # 3-P2/4 + - [-1, 2, Bottleneck, [128]] + - [-1, 1, Conv, [256, 3, 2]] # 5-P3/8 + - [-1, 8, Bottleneck, [256]] + - [-1, 1, Conv, [512, 3, 2]] # 7-P4/16 + - [-1, 8, Bottleneck, [512]] + - [-1, 1, Conv, [1024, 3, 2]] # 9-P5/32 + - [-1, 4, Bottleneck, [1024]] # 10 + +# YOLOv3-SPP head +head: + - [-1, 1, Bottleneck, [1024, False]] + - [-1, 1, SPP, [512, [5, 9, 13]]] + - [-1, 1, Conv, [1024, 3, 1]] + - [-1, 1, Conv, [512, 1, 1]] + - [-1, 1, Conv, [1024, 3, 1]] # 15 (P5/32-large) + + - [-2, 1, Conv, [256, 1, 1]] + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 8], 1, Concat, [1]] # cat backbone P4 + - [-1, 1, Bottleneck, [512, False]] + - [-1, 1, Bottleneck, [512, False]] + - [-1, 1, Conv, [256, 1, 1]] + - [-1, 1, Conv, [512, 3, 1]] # 22 (P4/16-medium) + + - [-2, 1, Conv, [128, 1, 1]] + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P3 + - [-1, 1, Bottleneck, [256, False]] + - [-1, 2, Bottleneck, [256, False]] # 27 (P3/8-small) + + - [[27, 22, 15], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v3/yolov3-tiny.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v3/yolov3-tiny.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2959fbda7f4b6c256528b76d3a36989a7c053fc2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v3/yolov3-tiny.yaml @@ -0,0 +1,40 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv3-tiny object detection model with P4/16 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov3 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple + +# YOLOv3-tiny backbone +backbone: + # [from, number, module, args] + - [-1, 1, Conv, [16, 3, 1]] # 0 + - [-1, 1, nn.MaxPool2d, [2, 2, 0]] # 1-P1/2 + - [-1, 1, Conv, [32, 3, 1]] + - [-1, 1, nn.MaxPool2d, [2, 2, 0]] # 3-P2/4 + - [-1, 1, Conv, [64, 3, 1]] + - [-1, 1, nn.MaxPool2d, [2, 2, 0]] # 5-P3/8 + - [-1, 1, Conv, [128, 3, 1]] + - [-1, 1, nn.MaxPool2d, [2, 2, 0]] # 7-P4/16 + - [-1, 1, Conv, [256, 3, 1]] + - [-1, 1, nn.MaxPool2d, [2, 2, 0]] # 9-P5/32 + - [-1, 1, Conv, [512, 3, 1]] + - [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]] # 11 + - [-1, 1, nn.MaxPool2d, [2, 1, 0]] # 12 + +# YOLOv3-tiny head +head: + - [-1, 1, Conv, [1024, 3, 1]] + - [-1, 1, Conv, [256, 1, 1]] + - [-1, 1, Conv, [512, 3, 1]] # 15 (P5/32-large) + + - [-2, 1, Conv, [128, 1, 1]] + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 8], 1, Concat, [1]] # cat backbone P4 + - [-1, 1, Conv, [256, 3, 1]] # 19 (P4/16-medium) + + - [[19, 15], 1, Detect, [nc]] # Detect(P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v3/yolov3.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v3/yolov3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..95c99de52be649df826589f73da346d4a75dd05f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v3/yolov3.yaml @@ -0,0 +1,49 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv3 object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov3 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple + +# darknet53 backbone +backbone: + # [from, number, module, args] + - [-1, 1, Conv, [32, 3, 1]] # 0 + - [-1, 1, Conv, [64, 3, 2]] # 1-P1/2 + - [-1, 1, Bottleneck, [64]] + - [-1, 1, Conv, [128, 3, 2]] # 3-P2/4 + - [-1, 2, Bottleneck, [128]] + - [-1, 1, Conv, [256, 3, 2]] # 5-P3/8 + - [-1, 8, Bottleneck, [256]] + - [-1, 1, Conv, [512, 3, 2]] # 7-P4/16 + - [-1, 8, Bottleneck, [512]] + - [-1, 1, Conv, [1024, 3, 2]] # 9-P5/32 + - [-1, 4, Bottleneck, [1024]] # 10 + +# YOLOv3 head +head: + - [-1, 1, Bottleneck, [1024, False]] + - [-1, 1, Conv, [512, 1, 1]] + - [-1, 1, Conv, [1024, 3, 1]] + - [-1, 1, Conv, [512, 1, 1]] + - [-1, 1, Conv, [1024, 3, 1]] # 15 (P5/32-large) + + - [-2, 1, Conv, [256, 1, 1]] + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 8], 1, Concat, [1]] # cat backbone P4 + - [-1, 1, Bottleneck, [512, False]] + - [-1, 1, Bottleneck, [512, False]] + - [-1, 1, Conv, [256, 1, 1]] + - [-1, 1, Conv, [512, 3, 1]] # 22 (P4/16-medium) + + - [-2, 1, Conv, [128, 1, 1]] + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P3 + - [-1, 1, Bottleneck, [256, False]] + - [-1, 2, Bottleneck, [256, False]] # 27 (P3/8-small) + + - [[27, 22, 15], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v5/yolov5-p6.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v5/yolov5-p6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..376d1aba90c24c0df93c14af4a45f5b98b6dbf02 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v5/yolov5-p6.yaml @@ -0,0 +1,62 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv5 object detection model with P3/8 - P6/64 outputs +# Model docs: https://docs.ultralytics.com/models/yolov5 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov5n-p6.yaml' will call yolov5-p6.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] + s: [0.33, 0.50, 1024] + m: [0.67, 0.75, 1024] + l: [1.00, 1.00, 1024] + x: [1.33, 1.25, 1024] + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + - [-1, 1, Conv, [64, 6, 2, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C3, [128]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C3, [256]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 9, C3, [512]] + - [-1, 1, Conv, [768, 3, 2]] # 7-P5/32 + - [-1, 3, C3, [768]] + - [-1, 1, Conv, [1024, 3, 2]] # 9-P6/64 + - [-1, 3, C3, [1024]] + - [-1, 1, SPPF, [1024, 5]] # 11 + +# YOLOv5 v6.0 head +head: + - [-1, 1, Conv, [768, 1, 1]] + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 8], 1, Concat, [1]] # cat backbone P5 + - [-1, 3, C3, [768, False]] # 15 + + - [-1, 1, Conv, [512, 1, 1]] + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C3, [512, False]] # 19 + + - [-1, 1, Conv, [256, 1, 1]] + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C3, [256, False]] # 23 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 20], 1, Concat, [1]] # cat head P4 + - [-1, 3, C3, [512, False]] # 26 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 16], 1, Concat, [1]] # cat head P5 + - [-1, 3, C3, [768, False]] # 29 (P5/32-large) + + - [-1, 1, Conv, [768, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P6 + - [-1, 3, C3, [1024, False]] # 32 (P6/64-xlarge) + + - [[23, 26, 29, 32], 1, Detect, [nc]] # Detect(P3, P4, P5, P6) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v5/yolov5.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v5/yolov5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..76a4749ae4f102cdee4db2a14dae4912476736c4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v5/yolov5.yaml @@ -0,0 +1,51 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv5 object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov5 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov5n.yaml' will call yolov5.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] + s: [0.33, 0.50, 1024] + m: [0.67, 0.75, 1024] + l: [1.00, 1.00, 1024] + x: [1.33, 1.25, 1024] + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + - [-1, 1, Conv, [64, 6, 2, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C3, [128]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C3, [256]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 9, C3, [512]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C3, [1024]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv5 v6.0 head +head: + - [-1, 1, Conv, [512, 1, 1]] + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C3, [512, False]] # 13 + + - [-1, 1, Conv, [256, 1, 1]] + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C3, [256, False]] # 17 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 14], 1, Concat, [1]] # cat head P4 + - [-1, 3, C3, [512, False]] # 20 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 3, C3, [1024, False]] # 23 (P5/32-large) + + - [[17, 20, 23], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v6/yolov6.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v6/yolov6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8359675a00bc8c78cdaca2f46bc520a9b105ec58 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v6/yolov6.yaml @@ -0,0 +1,56 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Meituan YOLOv6 object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov6 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +activation: torch.nn.ReLU() # (optional) model default activation function +scales: # model compound scaling constants, i.e. 'model=yolov6n.yaml' will call yolov6.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] + s: [0.33, 0.50, 1024] + m: [0.67, 0.75, 768] + l: [1.00, 1.00, 512] + x: [1.00, 1.25, 512] + +# YOLOv6-3.0s backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 6, Conv, [128, 3, 1]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 12, Conv, [256, 3, 1]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 18, Conv, [512, 3, 1]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 6, Conv, [1024, 3, 1]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv6-3.0s head +head: + - [-1, 1, Conv, [256, 1, 1]] + - [-1, 1, nn.ConvTranspose2d, [256, 2, 2, 0]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 1, Conv, [256, 3, 1]] + - [-1, 9, Conv, [256, 3, 1]] # 14 + + - [-1, 1, Conv, [128, 1, 1]] + - [-1, 1, nn.ConvTranspose2d, [128, 2, 2, 0]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 1, Conv, [128, 3, 1]] + - [-1, 9, Conv, [128, 3, 1]] # 19 + + - [-1, 1, Conv, [128, 3, 2]] + - [[-1, 15], 1, Concat, [1]] # cat head P4 + - [-1, 1, Conv, [256, 3, 1]] + - [-1, 9, Conv, [256, 3, 1]] # 23 + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 10], 1, Concat, [1]] # cat head P5 + - [-1, 1, Conv, [512, 3, 1]] + - [-1, 9, Conv, [512, 3, 1]] # 27 + + - [[19, 23, 27], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yoloe-v8-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yoloe-v8-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..59f07465383c17a44932988b3fc964c2dc973332 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yoloe-v8-seg.yaml @@ -0,0 +1,49 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOE-v8-seg instance segmentation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yoloe +# Task docs: https://docs.ultralytics.com/tasks/segment + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yoloe-v8n-seg.yaml' will call yoloe-v8-seg.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] # YOLOE-v8n-seg summary: 161 layers, 4204111 parameters, 4204095 gradients, 39.6 GFLOPs + s: [0.33, 0.50, 1024] # YOLOE-v8s-seg summary: 161 layers, 13383496 parameters, 13383480 gradients, 71.5 GFLOPs + m: [0.67, 0.75, 768] # YOLOE-v8m-seg summary: 201 layers, 29065310 parameters, 29065294 gradients, 131.4 GFLOPs + l: [1.00, 1.00, 512] # YOLOE-v8l-seg summary: 241 layers, 47553970 parameters, 47553954 gradients, 225.6 GFLOPs + x: [1.00, 1.25, 512] # YOLOE-v8x-seg summary: 241 layers, 73690217 parameters, 73690201 gradients, 330.8 GFLOPs + +# YOLOv8.0n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv8.0n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2f, [512]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 15 (P3/8-small) + + - [15, 1, Conv, [256, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2f, [512]] # 18 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2f, [1024]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, YOLOESegment, [nc, 32, 256, 512, True]] # YOLOESegment(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yoloe-v8.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yoloe-v8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ed023d37cdd92bafd59a3aff555225bd1bbcd47d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yoloe-v8.yaml @@ -0,0 +1,49 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOE-v8 object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yoloe +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yoloe-v8n.yaml' will call yoloe-v8.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] # YOLOE-v8n summary: 148 layers, 3695183 parameters, 3695167 gradients, 19.5 GFLOPs + s: [0.33, 0.50, 1024] # YOLOE-v8s summary: 148 layers, 12759880 parameters, 12759864 gradients, 51.0 GFLOPs + m: [0.67, 0.75, 768] # YOLOE-v8m summary: 188 layers, 28376158 parameters, 28376142 gradients, 110.5 GFLOPs + l: [1.00, 1.00, 512] # YOLOE-v8l summary: 228 layers, 46832050 parameters, 46832034 gradients, 204.5 GFLOPs + x: [1.00, 1.25, 512] # YOLOE-v8x summary: 228 layers, 72886377 parameters, 72886361 gradients, 309.3 GFLOPs + +# YOLOv8.0n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv8.0n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2f, [512]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 15 (P3/8-small) + + - [15, 1, Conv, [256, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2f, [512]] # 18 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2f, [1024]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, YOLOEDetect, [nc, 512, True]] # YOLOEDetect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml new file mode 100644 index 0000000000000000000000000000000000000000..11a05756a041a07920c7ef3d0f415227aab48986 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml @@ -0,0 +1,28 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-cls image classification model with ResNet101 backbone +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/classify + +# Parameters +nc: 1000 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-cls-resnet101.yaml' will call yolov8-cls-resnet101.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] + s: [0.33, 0.50, 1024] + m: [0.67, 0.75, 1024] + l: [1.00, 1.00, 1024] + x: [1.00, 1.25, 1024] + +# YOLOv8.0n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, ResNetLayer, [3, 64, 1, True, 1]] # 0-P1/2 + - [-1, 1, ResNetLayer, [64, 64, 1, False, 3]] # 1-P2/4 + - [-1, 1, ResNetLayer, [256, 128, 2, False, 4]] # 2-P3/8 + - [-1, 1, ResNetLayer, [512, 256, 2, False, 23]] # 3-P4/16 + - [-1, 1, ResNetLayer, [1024, 512, 2, False, 3]] # 4-P5/32 + +# YOLOv8.0n head +head: + - [-1, 1, Classify, [nc]] # Classify diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d54d970379ec2626b3bf4f3da370513b996a786 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml @@ -0,0 +1,28 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-cls image classification model with ResNet50 backbone +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/classify + +# Parameters +nc: 1000 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-cls-resnet50.yaml' will call yolov8-cls-resnet50.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] + s: [0.33, 0.50, 1024] + m: [0.67, 0.75, 1024] + l: [1.00, 1.00, 1024] + x: [1.00, 1.25, 1024] + +# YOLOv8.0n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, ResNetLayer, [3, 64, 1, True, 1]] # 0-P1/2 + - [-1, 1, ResNetLayer, [64, 64, 1, False, 3]] # 1-P2/4 + - [-1, 1, ResNetLayer, [256, 128, 2, False, 4]] # 2-P3/8 + - [-1, 1, ResNetLayer, [512, 256, 2, False, 6]] # 3-P4/16 + - [-1, 1, ResNetLayer, [1024, 512, 2, False, 3]] # 4-P5/32 + +# YOLOv8.0n head +head: + - [-1, 1, Classify, [nc]] # Classify diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-cls.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-cls.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e346e5e1b76164894a01f0640d30145d4161ce53 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-cls.yaml @@ -0,0 +1,32 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-cls image classification model with YOLO backbone +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/classify + +# Parameters +nc: 1000 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-cls.yaml' will call yolov8-cls.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] + s: [0.33, 0.50, 1024] + m: [0.67, 0.75, 1024] + l: [1.00, 1.00, 1024] + x: [1.00, 1.25, 1024] + +# YOLOv8.0n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [1024, True]] + +# YOLOv8.0n head +head: + - [-1, 1, Classify, [nc]] # Classify diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f66a8dce37837de183054e0503343f41faf20c6e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml @@ -0,0 +1,58 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-ghost object detection model with P2/4 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/detect +# Employs Ghost convolutions and modules proposed in Huawei's GhostNet in https://arxiv.org/abs/1911.11907v2 + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-ghost-p2.yaml' will call yolov8-ghost-p2.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] # YOLOv8n-ghost-p2 summary: 290 layers, 2033944 parameters, 2033928 gradients, 13.8 GFLOPs + s: [0.33, 0.50, 1024] # YOLOv8s-ghost-p2 summary: 290 layers, 5562080 parameters, 5562064 gradients, 25.1 GFLOPs + m: [0.67, 0.75, 768] # YOLOv8m-ghost-p2 summary: 434 layers, 9031728 parameters, 9031712 gradients, 42.8 GFLOPs + l: [1.00, 1.00, 512] # YOLOv8l-ghost-p2 summary: 578 layers, 12214448 parameters, 12214432 gradients, 69.1 GFLOPs + x: [1.00, 1.25, 512] # YOLOv8x-ghost-p2 summary: 578 layers, 18664776 parameters, 18664760 gradients, 103.3 GFLOPs + +# YOLOv8.0-ghost backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, GhostConv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C3Ghost, [128, True]] + - [-1, 1, GhostConv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C3Ghost, [256, True]] + - [-1, 1, GhostConv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C3Ghost, [512, True]] + - [-1, 1, GhostConv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C3Ghost, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv8.0-ghost-p2 head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C3Ghost, [512]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C3Ghost, [256]] # 15 (P3/8-small) + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 2], 1, Concat, [1]] # cat backbone P2 + - [-1, 3, C3Ghost, [128]] # 18 (P2/4-xsmall) + + - [-1, 1, GhostConv, [128, 3, 2]] + - [[-1, 15], 1, Concat, [1]] # cat head P3 + - [-1, 3, C3Ghost, [256]] # 21 (P3/8-small) + + - [-1, 1, GhostConv, [256, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 3, C3Ghost, [512]] # 24 (P4/16-medium) + + - [-1, 1, GhostConv, [512, 3, 2]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 3, C3Ghost, [1024]] # 27 (P5/32-large) + + - [[18, 21, 24, 27], 1, Detect, [nc]] # Detect(P2, P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7e2680397d99e57ef4c8dda8f950b245f5516d6e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml @@ -0,0 +1,60 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-ghost object detection model with P3/8 - P6/64 outputs +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/detect +# Employs Ghost convolutions and modules proposed in Huawei's GhostNet in https://arxiv.org/abs/1911.11907v2 + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-ghost-p6.yaml' will call yolov8-ghost-p6.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] # YOLOv8n-ghost-p6 summary: 312 layers, 2901100 parameters, 2901084 gradients, 5.8 GFLOPs + s: [0.33, 0.50, 1024] # YOLOv8s-ghost-p6 summary: 312 layers, 9520008 parameters, 9519992 gradients, 16.4 GFLOPs + m: [0.67, 0.75, 768] # YOLOv8m-ghost-p6 summary: 468 layers, 18002904 parameters, 18002888 gradients, 34.4 GFLOPs + l: [1.00, 1.00, 512] # YOLOv8l-ghost-p6 summary: 624 layers, 21227584 parameters, 21227568 gradients, 55.3 GFLOPs + x: [1.00, 1.25, 512] # YOLOv8x-ghost-p6 summary: 624 layers, 33057852 parameters, 33057836 gradients, 85.7 GFLOPs + +# YOLOv8.0-ghost backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, GhostConv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C3Ghost, [128, True]] + - [-1, 1, GhostConv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C3Ghost, [256, True]] + - [-1, 1, GhostConv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C3Ghost, [512, True]] + - [-1, 1, GhostConv, [768, 3, 2]] # 7-P5/32 + - [-1, 3, C3Ghost, [768, True]] + - [-1, 1, GhostConv, [1024, 3, 2]] # 9-P6/64 + - [-1, 3, C3Ghost, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 11 + +# YOLOv8.0-ghost-p6 head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 8], 1, Concat, [1]] # cat backbone P5 + - [-1, 3, C3Ghost, [768]] # 14 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C3Ghost, [512]] # 17 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C3Ghost, [256]] # 20 (P3/8-small) + + - [-1, 1, GhostConv, [256, 3, 2]] + - [[-1, 17], 1, Concat, [1]] # cat head P4 + - [-1, 3, C3Ghost, [512]] # 23 (P4/16-medium) + + - [-1, 1, GhostConv, [512, 3, 2]] + - [[-1, 14], 1, Concat, [1]] # cat head P5 + - [-1, 3, C3Ghost, [768]] # 26 (P5/32-large) + + - [-1, 1, GhostConv, [768, 3, 2]] + - [[-1, 11], 1, Concat, [1]] # cat head P6 + - [-1, 3, C3Ghost, [1024]] # 29 (P6/64-xlarge) + + - [[20, 23, 26, 29], 1, Detect, [nc]] # Detect(P3, P4, P5, P6) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-ghost.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-ghost.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5390133411884e97a6af2fa684c93a4fb0fb61b0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-ghost.yaml @@ -0,0 +1,50 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-ghost object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/detect +# Employs Ghost convolutions and modules proposed in Huawei's GhostNet in https://arxiv.org/abs/1911.11907v2 + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-ghost.yaml' will call yolov8-ghost.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] # YOLOv8n-ghost summary: 237 layers, 1865316 parameters, 1865300 gradients, 5.8 GFLOPs + s: [0.33, 0.50, 1024] # YOLOv8s-ghost summary: 237 layers, 5960072 parameters, 5960056 gradients, 16.4 GFLOPs + m: [0.67, 0.75, 768] # YOLOv8m-ghost summary: 357 layers, 10336312 parameters, 10336296 gradients, 32.7 GFLOPs + l: [1.00, 1.00, 512] # YOLOv8l-ghost summary: 477 layers, 14277872 parameters, 14277856 gradients, 53.7 GFLOPs + x: [1.00, 1.25, 512] # YOLOv8x-ghost summary: 477 layers, 22229308 parameters, 22229292 gradients, 83.3 GFLOPs + +# YOLOv8.0n-ghost backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, GhostConv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C3Ghost, [128, True]] + - [-1, 1, GhostConv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C3Ghost, [256, True]] + - [-1, 1, GhostConv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C3Ghost, [512, True]] + - [-1, 1, GhostConv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C3Ghost, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv8.0n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C3Ghost, [512]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C3Ghost, [256]] # 15 (P3/8-small) + + - [-1, 1, GhostConv, [256, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 3, C3Ghost, [512]] # 18 (P4/16-medium) + + - [-1, 1, GhostConv, [512, 3, 2]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 3, C3Ghost, [1024]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-obb.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-obb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b114e971749de167f17a0e3a512ad78111f7c8bd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-obb.yaml @@ -0,0 +1,49 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-obb Oriented Bounding Boxes (OBB) model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/obb + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-obb.yaml' will call yolov8-obb.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] # YOLOv8n-obb summary: 144 layers, 3228867 parameters, 3228851 gradients, 9.1 GFLOPs + s: [0.33, 0.50, 1024] # YOLOv8s-obb summary: 144 layers, 11452739 parameters, 11452723 gradients, 29.8 GFLOPs + m: [0.67, 0.75, 768] # YOLOv8m-obb summary: 184 layers, 26463235 parameters, 26463219 gradients, 81.5 GFLOPs + l: [1.00, 1.00, 512] # YOLOv8l-obb summary: 224 layers, 44540355 parameters, 44540339 gradients, 169.4 GFLOPs + x: [1.00, 1.25, 512] # YOLOv8x-obb summary: 224 layers, 69555651 parameters, 69555635 gradients, 264.3 GFLOPs + +# YOLOv8.0n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv8.0n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2f, [512]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 15 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2f, [512]] # 18 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2f, [1024]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, OBB, [nc, 1]] # OBB(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-p2.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-p2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2da8311476ce5d11d8daab329d87fb11e892b752 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-p2.yaml @@ -0,0 +1,57 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8 object detection model with P2/4 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-p2.yaml' will call yolov8-p2.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] + s: [0.33, 0.50, 1024] + m: [0.67, 0.75, 768] + l: [1.00, 1.00, 512] + x: [1.00, 1.25, 512] + +# YOLOv8.0 backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv8.0-p2 head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2f, [512]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 15 (P3/8-small) + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 2], 1, Concat, [1]] # cat backbone P2 + - [-1, 3, C2f, [128]] # 18 (P2/4-xsmall) + + - [-1, 1, Conv, [128, 3, 2]] + - [[-1, 15], 1, Concat, [1]] # cat head P3 + - [-1, 3, C2f, [256]] # 21 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2f, [512]] # 24 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2f, [1024]] # 27 (P5/32-large) + + - [[18, 21, 24, 27], 1, Detect, [nc]] # Detect(P2, P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-p6.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-p6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7fb243fbe36433ffbec4c4ea286ec23956f7ead0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-p6.yaml @@ -0,0 +1,59 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8 object detection model with P3/8 - P6/64 outputs +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-p6.yaml' will call yolov8-p6.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] # YOLOv8n-p6 summary: 170 layers, 4984352 parameters, 4984336 gradients, 8.8 GFLOPs + s: [0.33, 0.50, 1024] # YOLOv8s-p6 summary: 170 layers, 17911792 parameters, 17911776 gradients, 28.7 GFLOPs + m: [0.67, 0.75, 768] # YOLOv8m-p6 summary: 222 layers, 44887488 parameters, 44887472 gradients, 83.5 GFLOPs + l: [1.00, 1.00, 512] # YOLOv8l-p6 summary: 274 layers, 62384016 parameters, 62384000 gradients, 167.9 GFLOPs + x: [1.00, 1.25, 512] # YOLOv8x-p6 summary: 274 layers, 97423072 parameters, 97423056 gradients, 261.8 GFLOPs + +# YOLOv8.0x6 backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [768, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [768, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 9-P6/64 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 11 + +# YOLOv8.0x6 head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 8], 1, Concat, [1]] # cat backbone P5 + - [-1, 3, C2, [768, False]] # 14 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2, [512, False]] # 17 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2, [256, False]] # 20 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 17], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2, [512, False]] # 23 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 14], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2, [768, False]] # 26 (P5/32-large) + + - [-1, 1, Conv, [768, 3, 2]] + - [[-1, 11], 1, Concat, [1]] # cat head P6 + - [-1, 3, C2, [1024, False]] # 29 (P6/64-xlarge) + + - [[20, 23, 26, 29], 1, Detect, [nc]] # Detect(P3, P4, P5, P6) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-pose-p6.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-pose-p6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c2e6f6949f6a8f68398a4021f3ecbd09be5b03e7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-pose-p6.yaml @@ -0,0 +1,60 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-pose keypoints/pose estimation model with P3/8 - P6/64 outputs +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/pose + +# Parameters +nc: 1 # number of classes +kpt_shape: [17, 3] # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible) +scales: # model compound scaling constants, i.e. 'model=yolov8n-pose-p6.yaml' will call yolov8-pose-p6.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] + s: [0.33, 0.50, 1024] + m: [0.67, 0.75, 768] + l: [1.00, 1.00, 512] + x: [1.00, 1.25, 512] + +# YOLOv8.0x6 backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [768, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [768, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 9-P6/64 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 11 + +# YOLOv8.0x6 head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 8], 1, Concat, [1]] # cat backbone P5 + - [-1, 3, C2, [768, False]] # 14 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2, [512, False]] # 17 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2, [256, False]] # 20 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 17], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2, [512, False]] # 23 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 14], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2, [768, False]] # 26 (P5/32-large) + + - [-1, 1, Conv, [768, 3, 2]] + - [[-1, 11], 1, Concat, [1]] # cat head P6 + - [-1, 3, C2, [1024, False]] # 29 (P6/64-xlarge) + + - [[20, 23, 26, 29], 1, Pose, [nc, kpt_shape]] # Pose(P3, P4, P5, P6) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-pose.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-pose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c22bc435b578d58b1a432e1ee0f203562e73f076 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-pose.yaml @@ -0,0 +1,50 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-pose keypoints/pose estimation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/pose + +# Parameters +nc: 1 # number of classes +kpt_shape: [17, 3] # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible) +scales: # model compound scaling constants, i.e. 'model=yolov8n-pose.yaml' will call yolov8-pose.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] + s: [0.33, 0.50, 1024] + m: [0.67, 0.75, 768] + l: [1.00, 1.00, 512] + x: [1.00, 1.25, 512] + +# YOLOv8.0n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv8.0n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2f, [512]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 15 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2f, [512]] # 18 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2f, [1024]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, Pose, [nc, kpt_shape]] # Pose(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-rtdetr.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-rtdetr.yaml new file mode 100644 index 0000000000000000000000000000000000000000..32f241bd39f974c7ef5777c1c2af8464ec5935e3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-rtdetr.yaml @@ -0,0 +1,49 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-RTDETR hybrid object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/rtdetr +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-rtdetr.yaml' will call yolov8-rtdetr.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] # YOLOv8n-rtdetr summary: 235 layers, 9643868 parameters, 9643868 gradients, 17.1 GFLOPs + s: [0.33, 0.50, 1024] # YOLOv8s-rtdetr summary: 235 layers, 16518572 parameters, 16518572 gradients, 32.8 GFLOPs + m: [0.67, 0.75, 768] # YOLOv8m-rtdetr summary: 275 layers, 29645180 parameters, 29645180 gradients, 75.8 GFLOPs + l: [1.00, 1.00, 512] # YOLOv8l-rtdetr summary: 315 layers, 45644364 parameters, 45644364 gradients, 152.3 GFLOPs + x: [1.00, 1.25, 512] # YOLOv8x-rtdetr summary: 315 layers, 67113884 parameters, 67113884 gradients, 230.8 GFLOPs + +# YOLOv8.0n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv8.0n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2f, [512]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 15 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2f, [512]] # 18 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2f, [1024]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, RTDETRDecoder, [nc]] # RTDETRDecoder(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-seg-p6.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-seg-p6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8112d48afd58494a7e63f1024ec196e44b8fd5e9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-seg-p6.yaml @@ -0,0 +1,59 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-seg instance segmentation model with P3/8 - P6/64 outputs +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/segment + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-seg-p6.yaml' will call yolov8-seg-p6.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] + s: [0.33, 0.50, 1024] + m: [0.67, 0.75, 768] + l: [1.00, 1.00, 512] + x: [1.00, 1.25, 512] + +# YOLOv8.0x6 backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [768, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [768, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 9-P6/64 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 11 + +# YOLOv8.0x6 head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 8], 1, Concat, [1]] # cat backbone P5 + - [-1, 3, C2, [768, False]] # 14 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2, [512, False]] # 17 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2, [256, False]] # 20 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 17], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2, [512, False]] # 23 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 14], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2, [768, False]] # 26 (P5/32-large) + + - [-1, 1, Conv, [768, 3, 2]] + - [[-1, 11], 1, Concat, [1]] # cat head P6 + - [-1, 3, C2, [1024, False]] # 29 (P6/64-xlarge) + + - [[20, 23, 26, 29], 1, Segment, [nc, 32, 256]] # Segment(P3, P4, P5, P6) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..52b1c7e9aedc4fbc04d5c4f48f4ad214ad6a51e2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-seg.yaml @@ -0,0 +1,49 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-seg instance segmentation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/segment + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-seg.yaml' will call yolov8-seg.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] + s: [0.33, 0.50, 1024] + m: [0.67, 0.75, 768] + l: [1.00, 1.00, 512] + x: [1.00, 1.25, 512] + +# YOLOv8.0n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv8.0n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2f, [512]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 15 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2f, [512]] # 18 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2f, [1024]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, Segment, [nc, 32, 256]] # Segment(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-world.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-world.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b86d3353d34fcc8134e7a1e17eb9555cd8a0d4b3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-world.yaml @@ -0,0 +1,51 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-World hybrid object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo-world +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-world.yaml' will call yolov8-world.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] # YOLOv8n-world summary: 161 layers, 4204111 parameters, 4204095 gradients, 39.6 GFLOPs + s: [0.33, 0.50, 1024] # YOLOv8s-world summary: 161 layers, 13383496 parameters, 13383480 gradients, 71.5 GFLOPs + m: [0.67, 0.75, 768] # YOLOv8m-world summary: 201 layers, 29065310 parameters, 29065294 gradients, 131.4 GFLOPs + l: [1.00, 1.00, 512] # YOLOv8l-world summary: 241 layers, 47553970 parameters, 47553954 gradients, 225.6 GFLOPs + x: [1.00, 1.25, 512] # YOLOv8x-world summary: 241 layers, 73690217 parameters, 73690201 gradients, 330.8 GFLOPs + +# YOLOv8.0n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv8.0n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2fAttn, [512, 256, 8]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2fAttn, [256, 128, 4]] # 15 (P3/8-small) + + - [[15, 12, 9], 1, ImagePoolingAttn, [256]] # 16 (P3/8-small) + + - [15, 1, Conv, [256, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2fAttn, [512, 256, 8]] # 19 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2fAttn, [1024, 512, 16]] # 22 (P5/32-large) + + - [[15, 19, 22], 1, WorldDetect, [nc, 512, False]] # WorldDetect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-worldv2.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-worldv2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..482710b02a6b8c5994e06c6832ddaf7542b86bbf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8-worldv2.yaml @@ -0,0 +1,49 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8-Worldv2 hybrid object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolo-world +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n-worldv2.yaml' will call yolov8-worldv2.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] # YOLOv8n-worldv2 summary: 148 layers, 3695183 parameters, 3695167 gradients, 19.5 GFLOPs + s: [0.33, 0.50, 1024] # YOLOv8s-worldv2 summary: 148 layers, 12759880 parameters, 12759864 gradients, 51.0 GFLOPs + m: [0.67, 0.75, 768] # YOLOv8m-worldv2 summary: 188 layers, 28376158 parameters, 28376142 gradients, 110.5 GFLOPs + l: [1.00, 1.00, 512] # YOLOv8l-worldv2 summary: 228 layers, 46832050 parameters, 46832034 gradients, 204.5 GFLOPs + x: [1.00, 1.25, 512] # YOLOv8x-worldv2 summary: 228 layers, 72886377 parameters, 72886361 gradients, 309.3 GFLOPs + +# YOLOv8.0n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv8.0n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2fAttn, [512, 256, 8]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2fAttn, [256, 128, 4]] # 15 (P3/8-small) + + - [15, 1, Conv, [256, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2fAttn, [512, 256, 8]] # 18 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2fAttn, [1024, 512, 16]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, WorldDetect, [nc, 512, True]] # WorldDetect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..189b89c10b5369b1d8a6b88b731b39ac7040ae56 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v8/yolov8.yaml @@ -0,0 +1,49 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Ultralytics YOLOv8 object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov8 +# Task docs: https://docs.ultralytics.com/tasks/detect + +# Parameters +nc: 80 # number of classes +scales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n' + # [depth, width, max_channels] + n: [0.33, 0.25, 1024] # YOLOv8n summary: 129 layers, 3157200 parameters, 3157184 gradients, 8.9 GFLOPS + s: [0.33, 0.50, 1024] # YOLOv8s summary: 129 layers, 11166560 parameters, 11166544 gradients, 28.8 GFLOPS + m: [0.67, 0.75, 768] # YOLOv8m summary: 169 layers, 25902640 parameters, 25902624 gradients, 79.3 GFLOPS + l: [1.00, 1.00, 512] # YOLOv8l summary: 209 layers, 43691520 parameters, 43691504 gradients, 165.7 GFLOPS + x: [1.00, 1.25, 512] # YOLOv8x summary: 209 layers, 68229648 parameters, 68229632 gradients, 258.5 GFLOPS + +# YOLOv8.0n backbone +backbone: + # [from, repeats, module, args] + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 3, C2f, [128, True]] + - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8 + - [-1, 6, C2f, [256, True]] + - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16 + - [-1, 6, C2f, [512, True]] + - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32 + - [-1, 3, C2f, [1024, True]] + - [-1, 1, SPPF, [1024, 5]] # 9 + +# YOLOv8.0n head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 3, C2f, [512]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 3, C2f, [256]] # 15 (P3/8-small) + + - [-1, 1, Conv, [256, 3, 2]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 3, C2f, [512]] # 18 (P4/16-medium) + + - [-1, 1, Conv, [512, 3, 2]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 3, C2f, [1024]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9c-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9c-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..94940fe4a3083da9b04518d48425ec7f1d177dd1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9c-seg.yaml @@ -0,0 +1,41 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLOv9c-seg instance segmentation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov9 +# Task docs: https://docs.ultralytics.com/tasks/segment +# 380 layers, 27897120 parameters, 159.4 GFLOPs + +# Parameters +nc: 80 # number of classes + +# GELAN backbone +backbone: + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 1, RepNCSPELAN4, [256, 128, 64, 1]] # 2 + - [-1, 1, ADown, [256]] # 3-P3/8 + - [-1, 1, RepNCSPELAN4, [512, 256, 128, 1]] # 4 + - [-1, 1, ADown, [512]] # 5-P4/16 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 1]] # 6 + - [-1, 1, ADown, [512]] # 7-P5/32 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 1]] # 8 + - [-1, 1, SPPELAN, [512, 256]] # 9 + +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 1]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 1, RepNCSPELAN4, [256, 256, 128, 1]] # 15 (P3/8-small) + + - [-1, 1, ADown, [256]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 1]] # 18 (P4/16-medium) + + - [-1, 1, ADown, [512]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 1]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, Segment, [nc, 32, 256]] # Segment(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9c.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2808d8160a0a316f199a11de53d1887697150b5c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9c.yaml @@ -0,0 +1,41 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLOv9c object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov9 +# Task docs: https://docs.ultralytics.com/tasks/detect +# 358 layers, 25590912 parameters, 104.0 GFLOPs + +# Parameters +nc: 80 # number of classes + +# GELAN backbone +backbone: + - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4 + - [-1, 1, RepNCSPELAN4, [256, 128, 64, 1]] # 2 + - [-1, 1, ADown, [256]] # 3-P3/8 + - [-1, 1, RepNCSPELAN4, [512, 256, 128, 1]] # 4 + - [-1, 1, ADown, [512]] # 5-P4/16 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 1]] # 6 + - [-1, 1, ADown, [512]] # 7-P5/32 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 1]] # 8 + - [-1, 1, SPPELAN, [512, 256]] # 9 + +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 1]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 1, RepNCSPELAN4, [256, 256, 128, 1]] # 15 (P3/8-small) + + - [-1, 1, ADown, [256]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 1]] # 18 (P4/16-medium) + + - [-1, 1, ADown, [512]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 1]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9e-seg.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9e-seg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..056ec842e0335e9f5c058ddea819c11a4d038285 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9e-seg.yaml @@ -0,0 +1,64 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLOv9e-seg instance segmentation model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov9 +# Task docs: https://docs.ultralytics.com/tasks/segment +# 743 layers, 60512800 parameters, 248.4 GFLOPs + +# Parameters +nc: 80 # number of classes + +# GELAN backbone +backbone: + - [-1, 1, nn.Identity, []] + - [-1, 1, Conv, [64, 3, 2]] # 1-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 2-P2/4 + - [-1, 1, RepNCSPELAN4, [256, 128, 64, 2]] # 3 + - [-1, 1, ADown, [256]] # 4-P3/8 + - [-1, 1, RepNCSPELAN4, [512, 256, 128, 2]] # 5 + - [-1, 1, ADown, [512]] # 6-P4/16 + - [-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]] # 7 + - [-1, 1, ADown, [1024]] # 8-P5/32 + - [-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]] # 9 + + - [1, 1, CBLinear, [[64]]] # 10 + - [3, 1, CBLinear, [[64, 128]]] # 11 + - [5, 1, CBLinear, [[64, 128, 256]]] # 12 + - [7, 1, CBLinear, [[64, 128, 256, 512]]] # 13 + - [9, 1, CBLinear, [[64, 128, 256, 512, 1024]]] # 14 + + - [0, 1, Conv, [64, 3, 2]] # 15-P1/2 + - [[10, 11, 12, 13, 14, -1], 1, CBFuse, [[0, 0, 0, 0, 0]]] # 16 + - [-1, 1, Conv, [128, 3, 2]] # 17-P2/4 + - [[11, 12, 13, 14, -1], 1, CBFuse, [[1, 1, 1, 1]]] # 18 + - [-1, 1, RepNCSPELAN4, [256, 128, 64, 2]] # 19 + - [-1, 1, ADown, [256]] # 20-P3/8 + - [[12, 13, 14, -1], 1, CBFuse, [[2, 2, 2]]] # 21 + - [-1, 1, RepNCSPELAN4, [512, 256, 128, 2]] # 22 + - [-1, 1, ADown, [512]] # 23-P4/16 + - [[13, 14, -1], 1, CBFuse, [[3, 3]]] # 24 + - [-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]] # 25 + - [-1, 1, ADown, [1024]] # 26-P5/32 + - [[14, -1], 1, CBFuse, [[4]]] # 27 + - [-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]] # 28 + - [-1, 1, SPPELAN, [512, 256]] # 29 + +# GELAN head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 25], 1, Concat, [1]] # cat backbone P4 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 2]] # 32 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 22], 1, Concat, [1]] # cat backbone P3 + - [-1, 1, RepNCSPELAN4, [256, 256, 128, 2]] # 35 (P3/8-small) + + - [-1, 1, ADown, [256]] + - [[-1, 32], 1, Concat, [1]] # cat head P4 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 2]] # 38 (P4/16-medium) + + - [-1, 1, ADown, [512]] + - [[-1, 29], 1, Concat, [1]] # cat head P5 + - [-1, 1, RepNCSPELAN4, [512, 1024, 512, 2]] # 41 (P5/32-large) + + - [[35, 38, 41], 1, Segment, [nc, 32, 256]] # Segment (P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9e.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..29a61e5cbb2f0d85c86331e5d08241b46e06f8e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9e.yaml @@ -0,0 +1,64 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLOv9e object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov9 +# Task docs: https://docs.ultralytics.com/tasks/detect +# 721 layers, 58206592 parameters, 193.0 GFLOPs + +# Parameters +nc: 80 # number of classes + +# GELAN backbone +backbone: + - [-1, 1, nn.Identity, []] + - [-1, 1, Conv, [64, 3, 2]] # 1-P1/2 + - [-1, 1, Conv, [128, 3, 2]] # 2-P2/4 + - [-1, 1, RepNCSPELAN4, [256, 128, 64, 2]] # 3 + - [-1, 1, ADown, [256]] # 4-P3/8 + - [-1, 1, RepNCSPELAN4, [512, 256, 128, 2]] # 5 + - [-1, 1, ADown, [512]] # 6-P4/16 + - [-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]] # 7 + - [-1, 1, ADown, [1024]] # 8-P5/32 + - [-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]] # 9 + + - [1, 1, CBLinear, [[64]]] # 10 + - [3, 1, CBLinear, [[64, 128]]] # 11 + - [5, 1, CBLinear, [[64, 128, 256]]] # 12 + - [7, 1, CBLinear, [[64, 128, 256, 512]]] # 13 + - [9, 1, CBLinear, [[64, 128, 256, 512, 1024]]] # 14 + + - [0, 1, Conv, [64, 3, 2]] # 15-P1/2 + - [[10, 11, 12, 13, 14, -1], 1, CBFuse, [[0, 0, 0, 0, 0]]] # 16 + - [-1, 1, Conv, [128, 3, 2]] # 17-P2/4 + - [[11, 12, 13, 14, -1], 1, CBFuse, [[1, 1, 1, 1]]] # 18 + - [-1, 1, RepNCSPELAN4, [256, 128, 64, 2]] # 19 + - [-1, 1, ADown, [256]] # 20-P3/8 + - [[12, 13, 14, -1], 1, CBFuse, [[2, 2, 2]]] # 21 + - [-1, 1, RepNCSPELAN4, [512, 256, 128, 2]] # 22 + - [-1, 1, ADown, [512]] # 23-P4/16 + - [[13, 14, -1], 1, CBFuse, [[3, 3]]] # 24 + - [-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]] # 25 + - [-1, 1, ADown, [1024]] # 26-P5/32 + - [[14, -1], 1, CBFuse, [[4]]] # 27 + - [-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]] # 28 + - [-1, 1, SPPELAN, [512, 256]] # 29 + +# GELAN head +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 25], 1, Concat, [1]] # cat backbone P4 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 2]] # 32 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 22], 1, Concat, [1]] # cat backbone P3 + - [-1, 1, RepNCSPELAN4, [256, 256, 128, 2]] # 35 (P3/8-small) + + - [-1, 1, ADown, [256]] + - [[-1, 32], 1, Concat, [1]] # cat head P4 + - [-1, 1, RepNCSPELAN4, [512, 512, 256, 2]] # 38 (P4/16-medium) + + - [-1, 1, ADown, [512]] + - [[-1, 29], 1, Concat, [1]] # cat head P5 + - [-1, 1, RepNCSPELAN4, [512, 1024, 512, 2]] # 41 (P5/32-large) + + - [[35, 38, 41], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9m.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9m.yaml new file mode 100644 index 0000000000000000000000000000000000000000..683f90dac8b505caf2bd808d4c7c3f0424e74379 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9m.yaml @@ -0,0 +1,41 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLOv9m object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov9 +# Task docs: https://docs.ultralytics.com/tasks/detect +# 348 layers, 20216160 parameters, 77.9 GFLOPs + +# Parameters +nc: 80 # number of classes + +# GELAN backbone +backbone: + - [-1, 1, Conv, [32, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [64, 3, 2]] # 1-P2/4 + - [-1, 1, RepNCSPELAN4, [128, 128, 64, 1]] # 2 + - [-1, 1, AConv, [240]] # 3-P3/8 + - [-1, 1, RepNCSPELAN4, [240, 240, 120, 1]] # 4 + - [-1, 1, AConv, [360]] # 5-P4/16 + - [-1, 1, RepNCSPELAN4, [360, 360, 180, 1]] # 6 + - [-1, 1, AConv, [480]] # 7-P5/32 + - [-1, 1, RepNCSPELAN4, [480, 480, 240, 1]] # 8 + - [-1, 1, SPPELAN, [480, 240]] # 9 + +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 1, RepNCSPELAN4, [360, 360, 180, 1]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 1, RepNCSPELAN4, [240, 240, 120, 1]] # 15 + + - [-1, 1, AConv, [180]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 1, RepNCSPELAN4, [360, 360, 180, 1]] # 18 (P4/16-medium) + + - [-1, 1, AConv, [240]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 1, RepNCSPELAN4, [480, 480, 240, 1]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9s.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9s.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ea4c5c2559956e7f8f88c79bdd6a4371e5ca9bef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9s.yaml @@ -0,0 +1,41 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLOv9s object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov9 +# Task docs: https://docs.ultralytics.com/tasks/detect +# 544 layers, 7318368 parameters, 27.6 GFLOPs + +# Parameters +nc: 80 # number of classes + +# GELAN backbone +backbone: + - [-1, 1, Conv, [32, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [64, 3, 2]] # 1-P2/4 + - [-1, 1, ELAN1, [64, 64, 32]] # 2 + - [-1, 1, AConv, [128]] # 3-P3/8 + - [-1, 1, RepNCSPELAN4, [128, 128, 64, 3]] # 4 + - [-1, 1, AConv, [192]] # 5-P4/16 + - [-1, 1, RepNCSPELAN4, [192, 192, 96, 3]] # 6 + - [-1, 1, AConv, [256]] # 7-P5/32 + - [-1, 1, RepNCSPELAN4, [256, 256, 128, 3]] # 8 + - [-1, 1, SPPELAN, [256, 128]] # 9 + +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 1, RepNCSPELAN4, [192, 192, 96, 3]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 1, RepNCSPELAN4, [128, 128, 64, 3]] # 15 + + - [-1, 1, AConv, [96]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 1, RepNCSPELAN4, [192, 192, 96, 3]] # 18 (P4/16-medium) + + - [-1, 1, AConv, [128]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 1, RepNCSPELAN4, [256, 256, 128, 3]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9t.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9t.yaml new file mode 100644 index 0000000000000000000000000000000000000000..950d28f499de8320a296c00cf391666993b0253b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/models/v9/yolov9t.yaml @@ -0,0 +1,41 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# YOLOv9t object detection model with P3/8 - P5/32 outputs +# Model docs: https://docs.ultralytics.com/models/yolov9 +# Task docs: https://docs.ultralytics.com/tasks/detect +# 544 layers, 2128720 parameters, 8.5 GFLOPs + +# Parameters +nc: 80 # number of classes + +# GELAN backbone +backbone: + - [-1, 1, Conv, [16, 3, 2]] # 0-P1/2 + - [-1, 1, Conv, [32, 3, 2]] # 1-P2/4 + - [-1, 1, ELAN1, [32, 32, 16]] # 2 + - [-1, 1, AConv, [64]] # 3-P3/8 + - [-1, 1, RepNCSPELAN4, [64, 64, 32, 3]] # 4 + - [-1, 1, AConv, [96]] # 5-P4/16 + - [-1, 1, RepNCSPELAN4, [96, 96, 48, 3]] # 6 + - [-1, 1, AConv, [128]] # 7-P5/32 + - [-1, 1, RepNCSPELAN4, [128, 128, 64, 3]] # 8 + - [-1, 1, SPPELAN, [128, 64]] # 9 + +head: + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 6], 1, Concat, [1]] # cat backbone P4 + - [-1, 1, RepNCSPELAN4, [96, 96, 48, 3]] # 12 + + - [-1, 1, nn.Upsample, [None, 2, "nearest"]] + - [[-1, 4], 1, Concat, [1]] # cat backbone P3 + - [-1, 1, RepNCSPELAN4, [64, 64, 32, 3]] # 15 + + - [-1, 1, AConv, [48]] + - [[-1, 12], 1, Concat, [1]] # cat head P4 + - [-1, 1, RepNCSPELAN4, [96, 96, 48, 3]] # 18 (P4/16-medium) + + - [-1, 1, AConv, [64]] + - [[-1, 9], 1, Concat, [1]] # cat head P5 + - [-1, 1, RepNCSPELAN4, [128, 128, 64, 3]] # 21 (P5/32-large) + + - [[15, 18, 21], 1, Detect, [nc]] # Detect(P3, P4, P5) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/botsort.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/botsort.yaml new file mode 100644 index 0000000000000000000000000000000000000000..667b51d618709d018db7de09d3d31f066c08529d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/botsort.yaml @@ -0,0 +1,21 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# BoT-SORT tracker defaults for mode="track" +# Docs: https://docs.ultralytics.com/modes/track + +tracker_type: botsort # (str) Tracker backend: botsort +track_high_thresh: 0.25 # (float) First-stage match threshold; raise for cleaner tracks, lower to keep more +track_low_thresh: 0.1 # (float) Second-stage threshold for low-score matches; balances recovery vs drift +new_track_thresh: 0.25 # (float) Start a new track if no match ≥ this; higher reduces false tracks +track_buffer: 30 # (int) Frames to keep lost tracks alive; higher handles occlusion, increases ID switches risk +match_thresh: 0.8 # (float) Association similarity threshold (IoU/cost); tune with detector quality +fuse_score: True # (bool) Fuse detection score with motion/IoU for matching; stabilizes weak detections + +# BoT-SORT specifics +gmc_method: sparseOptFlow # (str) Global motion compensation: sparseOptFlow|orb|sift|ecc|none; helps moving camera scenes + +# ReID model related thresh +proximity_thresh: 0.5 # (float) Min IoU to consider tracks proximate for ReID; higher is stricter +appearance_thresh: 0.8 # (float) Min appearance similarity for ReID; raise to avoid identity swaps +with_reid: False # (bool) Enable ReID model use; needs extra model and compute +model: auto # (str) ReID model name/path; "auto" uses detector features if available diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/bytetrack.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/bytetrack.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9ece197b29df0e8c253a3a67ab16c6c2d107eaa9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/bytetrack.yaml @@ -0,0 +1,12 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# ByteTrack tracker defaults for mode="track" +# Docs: https://docs.ultralytics.com/modes/track + +tracker_type: bytetrack # (str) Tracker backend: bytetrack +track_high_thresh: 0.25 # (float) First-stage match threshold; raise for cleaner tracks, lower to keep more +track_low_thresh: 0.1 # (float) Second-stage threshold for low-score matches; balances recovery vs drift +new_track_thresh: 0.25 # (float) Start a new track if no match ≥ this; higher reduces false tracks +track_buffer: 30 # (int) Frames to keep lost tracks alive; higher handles occlusion, increases ID switches risk +match_thresh: 0.8 # (float) Association similarity threshold (IoU/cost); tune with detector quality +fuse_score: True # (bool) Fuse detection score with motion/IoU for matching; stabilizes weak detections diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/deepocsort.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/deepocsort.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b9c7296fca695564f67d43237a5a75404a43e73 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/deepocsort.yaml @@ -0,0 +1,26 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Deep OC-SORT tracker defaults for mode="track" +# Paper: https://arxiv.org/abs/2302.11813 +# Docs: https://docs.ultralytics.com/modes/track + +tracker_type: deepocsort # (str) Tracker backend: Deep OC-SORT with appearance features and GMC +track_high_thresh: 0.3 # (float) First-stage match threshold; raise for cleaner tracks, lower to keep more +track_low_thresh: 0.1 # (float) Second-stage threshold for low-score matches; used with use_byte=True +new_track_thresh: 0.3 # (float) Start a new track if no match ≥ this; higher reduces false tracks +track_buffer: 30 # (int) Frames to keep lost tracks alive; higher handles occlusion, increases ID switches risk +match_thresh: 0.8 # (float) Association similarity threshold (IoU/cost); tune with detector quality +fuse_score: True # (bool) Fuse detection score with motion/IoU for matching; stabilizes weak detections + +# OC-SORT specifics (inherited) +delta_t: 3 # (int) Temporal window for velocity direction computation in OCM +inertia: 0.2 # (float) Weight of velocity consistency cost in association +use_byte: False # (bool) Enable ByteTrack-style low-confidence second association pass + +# Deep OC-SORT specifics +gmc_method: none # (str) Global motion compensation: sparseOptFlow|orb|sift|ecc|none; enable for moving-camera scenes +with_reid: False # (bool) Enable ReID model use; needs extra model and compute +model: auto # (str) ReID model path; "auto" uses detector features, or use a .pt checkpoint or exported embedding model +proximity_thresh: 0.5 # (float) Min IoU to consider tracks proximate for ReID; higher is stricter +appearance_thresh: 0.9 # (float) Min appearance similarity for ReID; raise to avoid identity swaps +alpha_fixed_emb: 0.95 # (float) Base EMA factor for track embedding updates; higher = slower update diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/fasttrack.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/fasttrack.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aee3b1cac8b75e7a24a3efc1c5c215b48f77c35f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/fasttrack.yaml @@ -0,0 +1,24 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# FastTracker tracker defaults for mode="track" +# Occlusion-aware ByteTrack-style tracker with lightweight Kalman rollback and init IoU suppression. +# Paper: https://arxiv.org/abs/2508.14370 +# Docs: https://docs.ultralytics.com/modes/track + +tracker_type: fasttrack # (str) Tracker backend: fasttrack +track_high_thresh: 0.25 # (float) First-stage match threshold +track_low_thresh: 0.1 # (float) Second-stage threshold for low-score matches +new_track_thresh: 0.25 # (float) Start a new track if no match ≥ this +track_buffer: 30 # (int) Frames to keep lost tracks alive +match_thresh: 0.8 # (float) First-stage association similarity threshold +fuse_score: True # (bool) Fuse detection score with IoU when matching + +# --- FastTracker-specific knobs --- +reset_velocity_offset_occ: 5 # (int) History frames back to restore KF velocity on occlusion onset +reset_pos_offset_occ: 3 # (int) History frames back to restore KF position on occlusion onset +enlarge_bbox_occ: 1.1 # (float) One-shot bbox height scale while occluded (widens search region) +dampen_motion_occ: 0.5 # (float) Velocity dampening factor applied while occluded (0-1) +active_occ_to_lost_thresh: 10 # (int) Max consecutive occluded frames before marking lost +occ_cover_thresh: 0.7 # (float) Fraction of track's area covered by another to declare occlusion +occ_reappear_window: 40 # (int) Frames a recently-occluded lost track stays re-findable +init_iou_suppress: 0.7 # (float) Suppress new-track init if IoU with any active track ≥ this (1.0 disables) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/ocsort.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/ocsort.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4dffb0f048bcd9c0b88b80f17e4a32e24f502ab7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/ocsort.yaml @@ -0,0 +1,18 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# OC-SORT tracker defaults for mode="track" +# Paper: https://arxiv.org/abs/2203.14360 +# Docs: https://docs.ultralytics.com/modes/track + +tracker_type: ocsort # (str) Tracker backend: ocsort; observation-centric SORT for robust multi-object tracking +track_high_thresh: 0.25 # (float) First-stage match threshold; raise for cleaner tracks, lower to keep more +track_low_thresh: 0.1 # (float) Second-stage threshold for low-score matches; only used when use_byte=True +new_track_thresh: 0.25 # (float) Start a new track if no match ≥ this; higher reduces false tracks +track_buffer: 30 # (int) Frames to keep lost tracks alive; higher handles occlusion, increases ID switches risk +match_thresh: 0.8 # (float) Association similarity threshold (IoU/cost); tune with detector quality +fuse_score: True # (bool) Fuse detection score with motion/IoU for matching; stabilizes weak detections + +# OC-SORT specifics +delta_t: 3 # (int) Temporal window for velocity direction computation in OCM; higher smooths more +inertia: 0.2 # (float) Weight of velocity consistency cost in association; higher penalizes direction changes +use_byte: False # (bool) Enable ByteTrack-style low-confidence second association pass diff --git a/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/tracktrack.yaml b/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/tracktrack.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d4d50594b8752670f243d188dde3e8cff07ec56b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/cfg/trackers/tracktrack.yaml @@ -0,0 +1,36 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# TrackTrack defaults for mode="track" +# Multi-cue tracker with HMIoU, iterative assignment, and track-aware initialization +# Paper: "Focusing on Tracks for Online Multi-Object Tracking" (CVPR 2025) +# Docs: https://docs.ultralytics.com/modes/track + +tracker_type: tracktrack # (str) Tracker backend: tracktrack +track_high_thresh: 0.6 # (float) High-confidence detection threshold +track_low_thresh: 0.25 # (float) Low-confidence detection threshold for second stage +new_track_thresh: 0.7 # (float) Minimum score to start a new track via track-aware initialization (TAI) +track_buffer: 30 # (int) Frames to keep lost tracks alive +match_thresh: 0.7 # (float) Initial matching threshold for iterative assignment +lost_match_thr: 0.0 # (float) Looser rebind cost gate for still-Lost tracks; 0 disables the relaxed second pass. Raise above match_thresh (e.g. 0.9) for long-occlusion scenes + +# Association weights +iou_weight: 0.5 # (float) Weight for HMIoU distance in cost matrix +reid_weight: 0.5 # (float) Weight for cosine distance (or HMIoU fallback if no ReID) +conf_weight: 0.1 # (float) Weight for confidence distance +angle_weight: 0.05 # (float) Weight for corner angle distance + +# Iterative assignment +penalty_p: 0.2 # (float) Cost penalty for low-confidence detections +penalty_q: 0.4 # (float) Cost penalty for deleted/recovered detections +reduce_step: 0.05 # (float) Threshold reduction per iteration + +# Track-Aware Initialization (TAI) +tai_thr: 0.55 # (float) IoU threshold for TAI NMS suppression +min_track_len: 3 # (int) Minimum history length before track is confirmed + +# Camera motion compensation +gmc_method: sparseOptFlow # (str) GMC method: sparseOptFlow, orb, sift, ecc, none + +# ReID +with_reid: False # (bool) Enable ReID feature matching +model: auto # (str) ReID model path; 'auto' uses native YOLO features diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a1a6300ac7a15b055c95a3ec6de3cbf25c76e7d6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/__init__.py @@ -0,0 +1,28 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .base import BaseDataset +from .build import build_dataloader, build_grounding, build_yolo_dataset, load_inference_source +from .dataset import ( + ClassificationDataset, + GroundingDataset, + PolygonSemanticDataset, + SemanticDataset, + YOLOConcatDataset, + YOLODataset, + YOLOMultiModalDataset, +) + +__all__ = ( + "BaseDataset", + "ClassificationDataset", + "GroundingDataset", + "PolygonSemanticDataset", + "SemanticDataset", + "YOLOConcatDataset", + "YOLODataset", + "YOLOMultiModalDataset", + "build_dataloader", + "build_grounding", + "build_yolo_dataset", + "load_inference_source", +) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87735271ed287987b8c4e89fd3fa9c1a6f3eb348 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/annotator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/annotator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2c7a4602a3aee572a384d5813c8a83c989d0a3b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/annotator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/augment.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/augment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86b9e268a9ae04897e11e7f99ed328bc07c0300b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/augment.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:071c3f9448f87b60d8216ddf309110b96ff43e81bc986271c379205c977c55d0 +size 169999 diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f8afbac90da54e14cc938d1e730397c8a47b903 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/base.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/build.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/build.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71ecfeeb46a82e9e693f1e7f0311b7dd89e29819 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/build.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/converter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/converter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39279f533c9add7b918569c7b77daf065cb7f68f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/converter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/dataset.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/dataset.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b562c91eb40b4b30a76cca58542ef91ee354ae5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/dataset.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/loaders.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/loaders.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f02f84b0303e51095d23550c8dcbb7fc7580f878 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/loaders.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/split.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/split.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad18d341fc108cbb30f9761979738891aad5e438 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/split.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/split_dota.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/split_dota.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e02a279b9213c5de2f8981839c98e56318bd4a9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/split_dota.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acd734c07c94dc78996a0b9f13fec33fa71c52c1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/data/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/annotator.py b/.venv/lib/python3.12/site-packages/ultralytics/data/annotator.py new file mode 100644 index 0000000000000000000000000000000000000000..6717486bdc38946ae3e49d9dd471593558baa502 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/annotator.py @@ -0,0 +1,66 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +from ultralytics import SAM, YOLO + + +def auto_annotate( + data: str | Path, + det_model: str = "yolo26x.pt", + sam_model: str = "sam_b.pt", + device: str = "", + conf: float = 0.25, + iou: float = 0.45, + imgsz: int = 640, + max_det: int = 300, + classes: list[int] | None = None, + output_dir: str | Path | None = None, +) -> None: + """Automatically annotate images using a YOLO object detection model and a SAM segmentation model. + + This function processes images in a specified directory, detects objects using a YOLO model, and then generates + segmentation masks using a SAM model. The resulting annotations are saved as text files in YOLO format. + + Args: + data (str | Path): Path to a folder containing images to be annotated. + det_model (str): Path or name of the pre-trained YOLO detection model. + sam_model (str): Path or name of the pre-trained SAM segmentation model. + device (str): Device to run the models on (e.g., 'cpu', 'cuda', '0'). Empty string for auto-selection. + conf (float): Confidence threshold for detection model. + iou (float): IoU threshold for filtering overlapping boxes in detection results. + imgsz (int): Input image resize dimension. + max_det (int): Maximum number of detections per image. + classes (list[int], optional): Filter predictions to specified class IDs, returning only relevant detections. + output_dir (str | Path, optional): Directory to save the annotated results. If None, creates a default directory + based on the input data path. + + Examples: + >>> from ultralytics.data.annotator import auto_annotate + >>> auto_annotate(data="ultralytics/assets", det_model="yolo26n.pt", sam_model="mobile_sam.pt") + """ + det_model = YOLO(det_model) + sam_model = SAM(sam_model) + + data = Path(data) + if not output_dir: + output_dir = data.parent / f"{data.stem}_auto_annotate_labels" + Path(output_dir).mkdir(exist_ok=True, parents=True) + + det_results = det_model( + data, stream=True, device=device, conf=conf, iou=iou, imgsz=imgsz, max_det=max_det, classes=classes + ) + + for result in det_results: + if class_ids := result.boxes.cls.int().tolist(): # Extract class IDs from detection results + boxes = result.boxes.xyxy # Boxes object for bbox outputs + sam_results = sam_model(result.orig_img, bboxes=boxes, verbose=False, save=False, device=device) + segments = sam_results[0].masks.xyn + + with open(f"{Path(output_dir) / Path(result.path).stem}.txt", "w", encoding="utf-8") as f: + for i, s in enumerate(segments): + if len(s) >= 3: # fewer than 3 points is not a polygon, and writes a row no loader accepts + segment = map(str, s.reshape(-1).tolist()) + f.write(f"{class_ids[i]} " + " ".join(segment) + "\n") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/augment.py b/.venv/lib/python3.12/site-packages/ultralytics/data/augment.py new file mode 100644 index 0000000000000000000000000000000000000000..8075e67e270b51ed3df4ec5d4adc8dfa2ec18673 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/augment.py @@ -0,0 +1,3247 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import math +import random +from copy import deepcopy +from typing import Any + +import cv2 +import numpy as np +import torch +from PIL import Image +from torch.nn import functional as F + +from ultralytics.data.utils import polygons2masks, polygons2masks_overlap +from ultralytics.utils import LOGGER, IterableSimpleNamespace, colorstr, deprecation_warn +from ultralytics.utils.checks import check_version +from ultralytics.utils.instance import Instances +from ultralytics.utils.metrics import bbox_ioa +from ultralytics.utils.ops import segment2box, xywh2xyxy, xyxyxyxy2xywhr +from ultralytics.utils.torch_utils import TORCHVISION_0_10, TORCHVISION_0_11, TORCHVISION_0_13 + +DEFAULT_MEAN = (0.0, 0.0, 0.0) +DEFAULT_STD = (1.0, 1.0, 1.0) + + +class BaseTransform: + """Base class for image transformations in the Ultralytics library. + + This class provides a unified interface for applying transformations to images, object instances, and semantic + segmentation masks. Subclasses should override `apply_image`, `apply_instances`, and/or `apply_semantic` for simple + transforms, or override `__call__` directly for complex transforms that need shared state between image and + annotation modifications. + + Methods: + get_params: Compute transformation parameters shared across image, instances, and semantic mask. + apply_image: Apply transformation to the image in labels['img']. + apply_instances: Apply transformation to object instances in labels['instances']. + apply_semantic: Apply transformation to semantic mask in labels['semantic_mask']. + __call__: Orchestrate the transformation pipeline. + """ + + def __call__(self, labels): + """Apply transformation to labels dict. + + Args: + labels (dict): Dictionary containing 'img', optionally 'instances' and 'semantic_mask'. + + Returns: + (dict): Transformed labels dictionary. + """ + params = self.get_params(labels) + labels = self.apply_image(labels, params) + labels = self.apply_instances(labels, params) + labels = self.apply_semantic(labels, params) + labels = self.apply_depth(labels, params) + return labels + + def get_params(self, labels): + """Compute and return transformation parameters. + + This method allows sharing random state or computed matrices (e.g. affine matrix, flip + decision) between image, instances, and semantic mask transformations. + + Args: + labels (dict): Input labels dictionary. + + Returns: + (dict): Parameters to pass to apply_image, apply_instances, and apply_semantic. + """ + return {} + + def apply_image(self, labels, params=None): + """Apply transformation to image. + + Args: + labels (dict): Dictionary containing 'img'. + params (dict | None): Parameters from get_params. + + Returns: + (dict): Updated labels dictionary. + """ + return labels + + def apply_instances(self, labels, params=None): + """Apply transformation to object instances. + + Args: + labels (dict): Dictionary containing 'instances'. + params (dict | None): Parameters from get_params. + + Returns: + (dict): Updated labels dictionary. + """ + return labels + + def apply_semantic(self, labels, params=None): + """Apply transformation to semantic segmentation mask. + + Args: + labels (dict): Dictionary containing 'semantic_mask'. + params (dict | None): Parameters from get_params. + + Returns: + (dict): Updated labels dictionary. + """ + return labels + + def apply_depth(self, labels, params=None): + """Apply transformation to depth map. + + Args: + labels (dict): Dictionary containing 'depth'. + params (dict | None): Parameters from get_params. + + Returns: + (dict): Updated labels dictionary. + """ + return labels + + +class Compose: + """A class for composing multiple image transformations. + + Attributes: + transforms (list[Callable]): A list of transformation functions to be applied sequentially. + + Methods: + __call__: Apply a series of transformations to input data. + append: Append a new transform to the existing list of transforms. + insert: Insert a new transform at a specified index in the list of transforms. + __getitem__: Retrieve a specific transform or a set of transforms using indexing. + __setitem__: Set a specific transform or a set of transforms using indexing. + tolist: Convert the list of transforms to a standard Python list. + + Examples: + >>> transforms = [RandomFlip(), RandomPerspective(30)] + >>> compose = Compose(transforms) + >>> transformed_data = compose(data) + >>> compose.append(CenterCrop((224, 224))) + >>> compose.insert(0, RandomFlip()) + """ + + def __init__(self, transforms): + """Initialize the Compose object with a list of transforms. + + Args: + transforms (list[Callable]): A list of callable transform objects to be applied sequentially. + """ + self.transforms = transforms if isinstance(transforms, list) else [transforms] + + def __call__(self, data): + """Apply a series of transformations to input data. + + This method sequentially applies each transformation in the Compose object's transforms to the input data. + + Args: + data (Any): The input data to be transformed. This can be of any type, depending on the transformations in + the list. + + Returns: + (Any): The transformed data after applying all transformations in sequence. + + Examples: + >>> transforms = [Transform1(), Transform2(), Transform3()] + >>> compose = Compose(transforms) + >>> transformed_data = compose(input_data) + """ + for t in self.transforms: + data = t(data) + return data + + def append(self, transform): + """Append a new transform to the existing list of transforms. + + Args: + transform (BaseTransform): The transformation to be added to the composition. + + Examples: + >>> compose = Compose([RandomFlip(), RandomPerspective()]) + >>> compose.append(RandomHSV()) + """ + self.transforms.append(transform) + + def insert(self, index, transform): + """Insert a new transform at a specified index in the existing list of transforms. + + Args: + index (int): The index at which to insert the new transform. + transform (BaseTransform): The transform object to be inserted. + + Examples: + >>> compose = Compose([Transform1(), Transform2()]) + >>> compose.insert(1, Transform3()) + >>> len(compose.transforms) + 3 + """ + self.transforms.insert(index, transform) + + def __getitem__(self, index: list | int) -> Compose: + """Retrieve a specific transform or a set of transforms using indexing. + + Args: + index (int | list[int]): Index or list of indices of the transforms to retrieve. + + Returns: + (Compose | Any): A new Compose object if index is a list, or a single transform if index is an int. + + Raises: + AssertionError: If the index is not of type int or list. + + Examples: + >>> transforms = [RandomFlip(), RandomPerspective(10), RandomHSV(0.5, 0.5, 0.5)] + >>> compose = Compose(transforms) + >>> single_transform = compose[1] # Returns the RandomPerspective transform directly + >>> multiple_transforms = compose[[0, 1]] # Returns a Compose object with RandomFlip and RandomPerspective + """ + assert isinstance(index, (int, list)), f"The indices should be either list or int type but got {type(index)}" + return Compose([self.transforms[i] for i in index]) if isinstance(index, list) else self.transforms[index] + + def __setitem__(self, index: list | int, value: list | int) -> None: + """Set one or more transforms in the composition using indexing. + + Args: + index (int | list[int]): Index or list of indices to set transforms at. + value (Any | list[Any]): Transform or list of transforms to set at the specified index(es). + + Raises: + AssertionError: If index type is invalid, value type doesn't match index type, or index is out of range. + + Examples: + >>> compose = Compose([Transform1(), Transform2(), Transform3()]) + >>> compose[1] = NewTransform() # Replace second transform + >>> compose[[0, 1]] = [NewTransform1(), NewTransform2()] # Replace first two transforms + """ + assert isinstance(index, (int, list)), f"The indices should be either list or int type but got {type(index)}" + if isinstance(index, list): + assert isinstance(value, list), ( + f"The indices should be the same type as values, but got {type(index)} and {type(value)}" + ) + if isinstance(index, int): + index, value = [index], [value] + for i, v in zip(index, value): + assert i < len(self.transforms), f"list index {i} out of range {len(self.transforms)}." + self.transforms[i] = v + + def tolist(self): + """Convert the list of transforms to a standard Python list. + + Returns: + (list): A list containing all the transform objects in the Compose instance. + + Examples: + >>> transforms = [RandomFlip(), RandomPerspective(10), CenterCrop()] + >>> compose = Compose(transforms) + >>> transform_list = compose.tolist() + >>> print(len(transform_list)) + 3 + """ + return self.transforms + + def __repr__(self): + """Return a string representation of the Compose object. + + Returns: + (str): A string representation of the Compose object, including the list of transforms. + + Examples: + >>> transforms = [RandomFlip(), RandomPerspective(degrees=10, translate=0.1, scale=0.1)] + >>> compose = Compose(transforms) + >>> "RandomFlip" in repr(compose) and "RandomPerspective" in repr(compose) + True + """ + return f"{self.__class__.__name__}({', '.join([f'{t}' for t in self.transforms])})" + + +class BaseMixTransform(BaseTransform): + """Base class for mix transformations like Cutmix, MixUp and Mosaic. + + This class provides a foundation for implementing mix transformations on datasets. It handles the probability-based + application of transforms and manages the mixing of multiple images and labels. + + Attributes: + dataset (Any): The dataset object containing images and labels. + pre_transform (Callable | None): Optional transform to apply before mixing. + p (float): Probability of applying the mix transformation. + + Methods: + __call__: Apply the mix transformation to the input labels. + get_params: Prepare mixed labels and update text labels. + get_indexes: Abstract method to get indexes of images to be mixed. + _update_label_text: Update label text for mixed images. + + Examples: + >>> class CustomMixTransform(BaseMixTransform): + ... def apply_image(self, labels, params=None): + ... # Implement custom image mixing here + ... return labels + ... + ... def get_indexes(self): + ... return [random.randint(0, len(self.dataset) - 1) for _ in range(3)] + >>> dataset = YourDataset() + >>> transform = CustomMixTransform(dataset, p=0.5) + >>> mixed_labels = transform(original_labels) + """ + + def __init__(self, dataset, pre_transform=None, p=0.0) -> None: + """Initialize the BaseMixTransform object for mix transformations like CutMix, MixUp and Mosaic. + + This class serves as a base for implementing mix transformations in image processing pipelines. + + Args: + dataset (Any): The dataset object containing images and labels for mixing. + pre_transform (Callable | None): Optional transform to apply before mixing. + p (float): Probability of applying the mix transformation. Should be in the range [0.0, 1.0]. + """ + self.dataset = dataset + self.pre_transform = pre_transform + self.p = p + self.preserve_obb = getattr(dataset, "use_obb", False) + + def __call__(self, labels: dict[str, Any]) -> dict[str, Any]: + """Apply pre-processing transforms and cutmix/mixup/mosaic transforms to labels data. + + This method determines whether to apply the mix transform based on a probability factor. If applied, it selects + additional images, applies pre-transforms if specified, and then performs the mix transform. + + Args: + labels (dict[str, Any]): A dictionary containing label data for an image. + + Returns: + (dict[str, Any]): The transformed labels dictionary, which may include mixed data from other images. + + Examples: + >>> transform = BaseMixTransform(dataset, pre_transform=None, p=0.5) + >>> result = transform({"image": img, "bboxes": boxes, "cls": classes}) + """ + if random.uniform(0, 1) > self.p: + return labels + + params = self.get_params(labels) + labels = self.apply_image(labels, params) + labels = self.apply_instances(labels, params) + labels = self.apply_semantic(labels, params) + labels = self.apply_depth(labels, params) + labels.pop("mix_labels", None) + return labels + + def get_params(self, labels: dict[str, Any]) -> dict[str, Any]: + """Prepare mixed labels and update text labels. + + Args: + labels (dict[str, Any]): A dictionary containing label data for an image. + + Returns: + (dict[str, Any]): Parameters for apply_image, apply_instances, and apply_semantic. + """ + # Get index of one or three other images + indexes = self.get_indexes() + if isinstance(indexes, int): + indexes = [indexes] + + # Get images information will be used for Mosaic, CutMix or MixUp + mix_labels = [self.dataset.get_image_and_label(i) for i in indexes] + + if self.pre_transform is not None: + for i, data in enumerate(mix_labels): + mix_labels[i] = self.pre_transform(data) + labels["mix_labels"] = mix_labels + + # Update cls and texts + self._update_label_text(labels) + return {"mix_labels": mix_labels} + + def get_indexes(self): + """Get a random index for mosaic augmentation. + + Returns: + (int): A random index from the dataset. + + Examples: + >>> transform = BaseMixTransform(dataset) + >>> index = transform.get_indexes() + >>> print(index) # 7 + """ + return random.randint(0, len(self.dataset) - 1) + + @staticmethod + def _update_label_text(labels: dict[str, Any]) -> dict[str, Any]: + """Update label text and class IDs for mixed labels in image augmentation. + + This method processes the 'texts' and 'cls' fields of the input labels dictionary and any mixed labels, creating + a unified set of text labels and updating class IDs accordingly. + + Args: + labels (dict[str, Any]): A dictionary containing label information, including 'texts' and 'cls' fields, and + optionally a 'mix_labels' field with additional label dictionaries. + + Returns: + (dict[str, Any]): The updated labels dictionary with unified text labels and updated class IDs. + + Examples: + >>> labels = { + ... "texts": [["cat"], ["dog"]], + ... "cls": torch.tensor([[0], [1]]), + ... "mix_labels": [{"texts": [["bird"], ["fish"]], "cls": torch.tensor([[0], [1]])}], + ... } + >>> updated_labels = BaseMixTransform._update_label_text(labels) + >>> print(updated_labels["texts"]) + [['cat'], ['dog'], ['bird'], ['fish']] + >>> print(updated_labels["cls"]) + tensor([[0], + [1]]) + >>> print(updated_labels["mix_labels"][0]["cls"]) + tensor([[2], + [3]]) + """ + if "texts" not in labels: + return labels + + mix_texts = [*labels["texts"], *(item for x in labels["mix_labels"] for item in x["texts"])] + mix_texts = [list(x) for x in dict.fromkeys(tuple(x) for x in mix_texts)] + text2id = {tuple(text): i for i, text in enumerate(mix_texts)} + + for label in [labels] + labels["mix_labels"]: + for i, cls in enumerate(label["cls"].squeeze(-1).tolist()): + text = label["texts"][int(cls)] + label["cls"][i] = text2id[tuple(text)] + label["texts"] = mix_texts + return labels + + +class Mosaic(BaseMixTransform): + """Mosaic augmentation for image datasets. + + This class performs mosaic augmentation by combining multiple (4 or 9) images into a single mosaic image. The + augmentation is applied to a dataset with a given probability. + + Attributes: + dataset: The dataset on which the mosaic augmentation is applied. + imgsz (int): Image size (height and width) after mosaic pipeline of a single image. + p (float): Probability of applying the mosaic augmentation. Must be in the range 0-1. + n (int): The grid size, either 4 (for 2x2) or 9 (for 3x3). + border (tuple[int, int]): Border size for height and width. + + Methods: + get_indexes: Return a list of random indexes from the dataset. + get_params: Compute mosaic layout parameters. + apply_image: Allocate canvas and paste images into mosaic. + apply_instances: Concatenate and clip instances for mosaic. + _update_labels: Update labels with padding. + _cat_labels: Concatenate labels and clips mosaic border instances. + + Examples: + >>> from ultralytics.data.augment import Mosaic + >>> dataset = YourDataset(...) # Your image dataset + >>> mosaic_aug = Mosaic(dataset, imgsz=640, p=0.5, n=4) + >>> augmented_labels = mosaic_aug(original_labels) + """ + + def __init__(self, dataset, imgsz: int = 640, p: float = 1.0, n: int = 4): + """Initialize the Mosaic augmentation object. + + This class performs mosaic augmentation by combining multiple (4 or 9) images into a single mosaic image. The + augmentation is applied to a dataset with a given probability. + + Args: + dataset (Any): The dataset on which the mosaic augmentation is applied. + imgsz (int): Image size (height and width) after mosaic pipeline of a single image. + p (float): Probability of applying the mosaic augmentation. Must be in the range 0-1. + n (int): The grid size, either 4 (for 2x2) or 9 (for 3x3). + """ + assert 0 <= p <= 1.0, f"The probability should be in range [0, 1], but got {p}." + assert n in {4, 9}, "grid must be equal to 4 or 9." + super().__init__(dataset=dataset, p=p) + self.imgsz = imgsz + self.border = (-imgsz // 2, -imgsz // 2) # width, height + self.n = n + self.buffer_enabled = self.dataset.cache != "ram" + + def get_indexes(self): + """Return a list of random indexes from the dataset for mosaic augmentation. + + This method selects random image indexes either from a buffer or from the entire dataset, depending on the + 'buffer_enabled' attribute. It is used to choose images for creating mosaic augmentations. + + Returns: + (list[int]): A list of random image indexes. The length of the list is n-1, where n is the number of images + used in the mosaic (either 3 or 8, depending on whether n is 4 or 9). + + Examples: + >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=4) + >>> indexes = mosaic.get_indexes() + >>> print(len(indexes)) # Output: 3 + """ + if self.buffer_enabled: # select images from buffer + return random.choices(list(self.dataset.buffer), k=self.n - 1) + else: # select any images + return [random.randint(0, len(self.dataset) - 1) for _ in range(self.n - 1)] + + def get_params(self, labels: dict[str, Any]) -> dict[str, Any]: + """Compute mosaic layout parameters. + + Args: + labels (dict[str, Any]): Input labels dictionary. + + Returns: + (dict[str, Any]): Parameters including 'layout' with per-patch geometry. + """ + params = super().get_params(labels) + assert labels.get("rect_shape") is None, "rect and mosaic are mutually exclusive." + assert len(labels.get("mix_labels", [])), "There are no other images for mosaic augment." + + s = self.imgsz + layout = [] + if self.n == 4: + yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.border) + for i in range(4): + labels_patch = labels if i == 0 else labels["mix_labels"][i - 1] + img = labels_patch["img"] + h, w = labels_patch.get("resized_shape", img.shape[:2]) + if i == 0: # top left + x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc + x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h + elif i == 1: # top right + x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc + x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h + elif i == 2: # bottom left + x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h) + x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h) + elif i == 3: # bottom right + x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h) + x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h) + padw = x1a - x1b + padh = y1a - y1b + layout.append( + { + "labels_patch": labels_patch, + "x1a": x1a, + "y1a": y1a, + "x2a": x2a, + "y2a": y2a, + "x1b": x1b, + "y1b": y1b, + "x2b": x2b, + "y2b": y2b, + "padw": padw, + "padh": padh, + "img_shape": (h, w), + } + ) + elif self.n == 9: + hp, wp = -1, -1 + h0, w0 = None, None + for i in range(9): + labels_patch = labels if i == 0 else labels["mix_labels"][i - 1] + img = labels_patch["img"] + h, w = labels_patch.get("resized_shape", img.shape[:2]) + if i == 0: # center + c = s, s, s + w, s + h + h0, w0 = h, w + elif i == 1: # top + c = s, s - h, s + w, s + elif i == 2: # top right + c = s + wp, s - h, s + wp + w, s + elif i == 3: # right + c = s + w0, s, s + w0 + w, s + h + elif i == 4: # bottom right + c = s + w0, s + hp, s + w0 + w, s + hp + h + elif i == 5: # bottom + c = s + w0 - w, s + h0, s + w0, s + h0 + h + elif i == 6: # bottom left + c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h + elif i == 7: # left + c = s - w, s + h0 - h, s, s + h0 + elif i == 8: # top left + c = s - w, s + h0 - hp - h, s, s + h0 - hp + padw, padh = c[:2] + x1, y1, x2, y2 = (max(x, 0) for x in c) + layout.append( + { + "labels_patch": labels_patch, + "x1": x1, + "y1": y1, + "x2": x2, + "y2": y2, + "padw": padw, + "padh": padh, + "img_shape": (h, w), + } + ) + hp, wp = h, w + params["layout"] = layout + return params + + def apply_image(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply mosaic augmentation to the image. + + Args: + labels (dict[str, Any]): Dictionary containing 'img'. + params (dict | None): Parameters from get_params, including 'layout'. + + Returns: + (dict): Updated labels with mosaic image. + """ + layout = params["layout"] + if self.n == 4: + img4 = np.full((self.imgsz * 2, self.imgsz * 2, labels["img"].shape[2]), 114, dtype=np.uint8) + for item in layout: + labels_patch = item["labels_patch"] + img = labels_patch["img"] + x1a, y1a, x2a, y2a = item["x1a"], item["y1a"], item["x2a"], item["y2a"] + x1b, y1b, x2b, y2b = item["x1b"], item["y1b"], item["x2b"], item["y2b"] + img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] + labels["img"] = img4 + elif self.n == 9: + img9 = np.full((self.imgsz * 3, self.imgsz * 3, labels["img"].shape[2]), 114, dtype=np.uint8) + for item in layout: + labels_patch = item["labels_patch"] + img = labels_patch["img"] + x1, y1, x2, y2 = item["x1"], item["y1"], item["x2"], item["y2"] + padw, padh = item["padw"], item["padh"] + x1b, y1b = x1 - padw, y1 - padh + x2b, y2b = x1b + (x2 - x1), y1b + (y2 - y1) + img9[y1:y2, x1:x2] = img[y1b:y2b, x1b:x2b] + labels["img"] = img9[-self.border[0] : self.border[0], -self.border[1] : self.border[1]] + return labels + + def apply_instances(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply mosaic augmentation to instances. + + Args: + labels (dict[str, Any]): Dictionary containing 'instances' and 'cls'. + params (dict | None): Parameters from get_params, including 'layout'. + + Returns: + (dict): Updated labels with concatenated instances. + """ + layout = params["layout"] + mosaic_labels = [] + for item in layout: + if self.n == 4: + padw = item["padw"] + padh = item["padh"] + else: # n == 9 + padw = item["padw"] + self.border[0] + padh = item["padh"] + self.border[1] + labels_patch = self._update_labels(item["labels_patch"], padw, padh, item.get("img_shape")) + mosaic_labels.append(labels_patch) + final_labels = self._cat_labels(mosaic_labels) + labels.update(final_labels) + return labels + + def apply_semantic(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply mosaic augmentation to semantic mask. + + Args: + labels (dict[str, Any]): Dictionary containing 'semantic_mask'. + params (dict | None): Parameters from get_params. + + Returns: + (dict): Updated labels with concatenated semantic mask. + """ + if labels.get("semantic_mask") is None and all( + m.get("semantic_mask") is None for m in labels.get("mix_labels", []) + ): + return labels + + layout = params["layout"] + if self.n == 4: + mask4 = np.full((self.imgsz * 2, self.imgsz * 2), 255, dtype=np.uint8) + for item in layout: + labels_patch = item["labels_patch"] + mask = labels_patch.get("semantic_mask") + if mask is None: + continue + x1a, y1a, x2a, y2a = item["x1a"], item["y1a"], item["x2a"], item["y2a"] + x1b, y1b, x2b, y2b = item["x1b"], item["y1b"], item["x2b"], item["y2b"] + mask4[y1a:y2a, x1a:x2a] = mask[y1b:y2b, x1b:x2b] + labels["semantic_mask"] = mask4 + elif self.n == 9: + mask9 = np.full((self.imgsz * 3, self.imgsz * 3), 255, dtype=np.uint8) + for item in layout: + labels_patch = item["labels_patch"] + mask = labels_patch.get("semantic_mask") + if mask is None: + continue + x1, y1, x2, y2 = item["x1"], item["y1"], item["x2"], item["y2"] + padw, padh = item["padw"], item["padh"] + x1b, y1b = x1 - padw, y1 - padh + x2b, y2b = x1b + (x2 - x1), y1b + (y2 - y1) + mask9[y1:y2, x1:x2] = mask[y1b:y2b, x1b:x2b] + labels["semantic_mask"] = mask9[-self.border[0] : self.border[0], -self.border[1] : self.border[1]] + return labels + + @staticmethod + def _update_labels(labels, padw: int, padh: int, img_shape: tuple[int, int] | None = None) -> dict[str, Any]: + """Update label coordinates with padding values. + + This method adjusts the bounding box coordinates of object instances in the labels by adding padding + values. It also denormalizes the coordinates if they were previously normalized. + + Args: + labels (dict[str, Any]): A dictionary containing image and instance information. + padw (int): Padding width to be added to the x-coordinates. + padh (int): Padding height to be added to the y-coordinates. + img_shape (tuple[int, int] | None): Optional (h, w) of the original patch image. Needed because apply_image + may overwrite labels["img"] with the mosaic canvas before apply_instances runs. + + Returns: + (dict): Updated labels dictionary with adjusted instance coordinates. + + Examples: + >>> labels = {"img": np.zeros((100, 100, 3)), "instances": Instances(...)} + >>> padw, padh = 50, 50 + >>> updated_labels = Mosaic._update_labels(labels, padw, padh) + """ + nh, nw = img_shape if img_shape is not None else labels["img"].shape[:2] + labels["instances"].convert_bbox(format="xyxy") + labels["instances"].denormalize(nw, nh) + labels["instances"].add_padding(padw, padh) + return labels + + def _cat_labels(self, mosaic_labels: list[dict[str, Any]]) -> dict[str, Any]: + """Concatenate and process labels for mosaic augmentation. + + This method combines labels from multiple images used in mosaic augmentation, clips instances to the mosaic + border, and removes zero-area boxes. + + Args: + mosaic_labels (list[dict[str, Any]]): A list of label dictionaries for each image in the mosaic. + + Returns: + (dict[str, Any]): A dictionary containing concatenated and processed labels for the mosaic image, including: + - im_file (str): File path of the first image in the mosaic. + - ori_shape (tuple[int, int]): Original shape of the first image. + - resized_shape (tuple[int, int]): Shape of the mosaic image (imgsz * 2, imgsz * 2). + - cls (np.ndarray): Concatenated class labels. + - instances (Instances): Concatenated instance annotations. + - texts (list[str], optional): Text labels if present in the original labels. + + Examples: + >>> mosaic = Mosaic(dataset, imgsz=640) + >>> mosaic_labels = [{"cls": np.array([0, 1]), "instances": Instances(...)} for _ in range(4)] + >>> result = mosaic._cat_labels(mosaic_labels) + >>> print(result.keys()) + dict_keys(['im_file', 'ori_shape', 'resized_shape', 'cls', 'instances']) + """ + if not mosaic_labels: + return {} + cls = [] + instances = [] + imgsz = self.imgsz * 2 # mosaic imgsz + for labels in mosaic_labels: + cls.append(labels["cls"]) + instances.append(labels["instances"]) + # Final labels + final_labels = { + "im_file": mosaic_labels[0]["im_file"], + "ori_shape": mosaic_labels[0]["ori_shape"], + "resized_shape": (imgsz, imgsz), + "cls": np.concatenate(cls, 0), + "instances": Instances.concatenate(instances, axis=0), + } + final_labels["instances"].clip(imgsz, imgsz, preserve_obb=self.preserve_obb) + good = final_labels["instances"].remove_zero_area_boxes() + final_labels["cls"] = final_labels["cls"][good] + if "texts" in mosaic_labels[0]: + final_labels["texts"] = mosaic_labels[0]["texts"] + return final_labels + + +class MixUp(BaseMixTransform): + """Apply MixUp augmentation to image datasets. + + This class implements the MixUp augmentation technique as described in the paper [mixup: Beyond Empirical Risk + Minimization](https://arxiv.org/abs/1710.09412). MixUp combines two images and their labels using a random weight. + + Attributes: + dataset (Any): The dataset to which MixUp augmentation will be applied. + pre_transform (Callable | None): Optional transform to apply before MixUp. + p (float): Probability of applying MixUp augmentation. + + Methods: + get_params: Compute MixUp parameters including blend ratio. + apply_image: Blend images using MixUp. + apply_instances: Concatenate instances for MixUp. + + Examples: + >>> from ultralytics.data.augment import MixUp + >>> dataset = YourDataset(...) # Your image dataset + >>> mixup = MixUp(dataset, p=0.5) + >>> augmented_labels = mixup(original_labels) + """ + + def __init__(self, dataset, pre_transform=None, p: float = 0.0) -> None: + """Initialize the MixUp augmentation object. + + MixUp is an image augmentation technique that combines two images by taking a weighted sum of their pixel values + and labels. This implementation is designed for use with the Ultralytics YOLO framework. + + Args: + dataset (Any): The dataset to which MixUp augmentation will be applied. + pre_transform (Callable | None): Optional transform to apply to images before MixUp. + p (float): Probability of applying MixUp augmentation to an image. Must be in the range [0, 1]. + """ + super().__init__(dataset=dataset, pre_transform=pre_transform, p=p) + + def get_params(self, labels: dict[str, Any]) -> dict[str, Any]: + """Compute MixUp parameters. + + Args: + labels (dict[str, Any]): Input labels dictionary. + + Returns: + (dict[str, Any]): Parameters including mix ratio 'r'. + """ + params = super().get_params(labels) + params["r"] = np.random.beta(32.0, 32.0) + return params + + def apply_image(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Blend images using MixUp. + + Args: + labels (dict[str, Any]): Dictionary containing 'img'. + params (dict | None): Parameters from get_params, including 'r'. + + Returns: + (dict): Updated labels with blended image. + """ + r = params["r"] + labels2 = labels["mix_labels"][0] + labels["img"] = (labels["img"] * r + labels2["img"] * (1 - r)).astype(np.uint8) + return labels + + def apply_instances(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Concatenate instances for MixUp. + + Args: + labels (dict[str, Any]): Dictionary containing 'instances' and 'cls'. + params (dict | None): Parameters from get_params. + + Returns: + (dict): Updated labels with concatenated instances. + """ + labels2 = labels["mix_labels"][0] + labels["instances"] = Instances.concatenate([labels["instances"], labels2["instances"]], axis=0) + labels["cls"] = np.concatenate([labels["cls"], labels2["cls"]], 0) + return labels + + def apply_semantic(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply MixUp augmentation to semantic segmentation masks. + + Args: + labels (dict[str, Any]): Primary image labels containing 'semantic_mask' and 'mix_labels'. + params (dict[str, Any] | None): Parameters dict with key 'r' (mix ratio). Defaults to None. + + Returns: + (dict[str, Any]): Updated labels with the semantic mask replaced by the mixed image's mask if r < 0.5. + """ + if labels.get("semantic_mask") is None: + return labels + labels2 = labels["mix_labels"][0] + if labels2.get("semantic_mask") is None: + return labels + r = params["r"] + # Use mask from the image with higher weight to avoid fractional class indices + if r < 0.5: + labels["semantic_mask"] = labels2["semantic_mask"].copy() + return labels + + +class CutMix(BaseMixTransform): + """Apply CutMix augmentation to image datasets as described in the paper https://arxiv.org/abs/1905.04899. + + CutMix combines two images by replacing a random rectangular region of one image with the corresponding region from + another image, and adjusts the labels proportionally to the area of the mixed region. + + Attributes: + dataset (Any): The dataset to which CutMix augmentation will be applied. + pre_transform (Callable | None): Optional transform to apply before CutMix. + p (float): Probability of applying CutMix augmentation. + beta (float): Beta distribution parameter for sampling the mixing ratio. + num_areas (int): Number of areas to try to cut and mix. + + Methods: + get_params: Compute CutMix parameters including cut area and filtered indexes. + apply_image: Copy patch from secondary image into primary image. + apply_instances: Clip and concatenate instances for CutMix. + _rand_bbox: Generate random bounding box coordinates for the cut region. + + Examples: + >>> from ultralytics.data.augment import CutMix + >>> dataset = YourDataset(...) # Your image dataset + >>> cutmix = CutMix(dataset, p=0.5) + >>> augmented_labels = cutmix(original_labels) + """ + + def __init__(self, dataset, pre_transform=None, p: float = 0.0, beta: float = 1.0, num_areas: int = 3) -> None: + """Initialize the CutMix augmentation object. + + Args: + dataset (Any): The dataset to which CutMix augmentation will be applied. + pre_transform (Callable | None): Optional transform to apply before CutMix. + p (float): Probability of applying CutMix augmentation. + beta (float): Beta distribution parameter for sampling the mixing ratio. + num_areas (int): Number of areas to try to cut and mix. + """ + super().__init__(dataset=dataset, pre_transform=pre_transform, p=p) + self.beta = beta + self.num_areas = num_areas + + def _rand_bbox(self, width: int, height: int) -> tuple[int, int, int, int]: + """Generate random bounding box coordinates for the cut region. + + Args: + width (int): Width of the image. + height (int): Height of the image. + + Returns: + (tuple[int]): (x1, y1, x2, y2) coordinates of the bounding box. + """ + # Sample mixing ratio from Beta distribution + lam = np.random.beta(self.beta, self.beta) + + cut_ratio = np.sqrt(1.0 - lam) + cut_w = int(width * cut_ratio) + cut_h = int(height * cut_ratio) + + # Random center + cx = np.random.randint(width) + cy = np.random.randint(height) + + # Bounding box coordinates + x1 = np.clip(cx - cut_w // 2, 0, width) + y1 = np.clip(cy - cut_h // 2, 0, height) + x2 = np.clip(cx + cut_w // 2, 0, width) + y2 = np.clip(cy + cut_h // 2, 0, height) + + return x1, y1, x2, y2 + + def get_params(self, labels: dict[str, Any]) -> dict[str, Any]: + """Compute CutMix parameters. + + Args: + labels (dict[str, Any]): Input labels dictionary. + + Returns: + (dict[str, Any]): Parameters including 'skip', 'area', and 'indexes2'. + """ + params = super().get_params(labels) + h, w = labels["img"].shape[:2] + + cut_areas = np.asarray([self._rand_bbox(w, h) for _ in range(self.num_areas)], dtype=np.float32) + ioa1 = bbox_ioa(cut_areas, labels["instances"].bboxes) # (self.num_areas, num_boxes) + idx = np.nonzero(ioa1.sum(axis=1) <= 0)[0] + if len(idx) == 0: + params["skip"] = True + return params + + labels2 = labels["mix_labels"][0] + area = cut_areas[np.random.choice(idx)] # randomly select one + ioa2 = bbox_ioa(area[None], labels2["instances"].bboxes).squeeze(0) + indexes2 = np.nonzero(ioa2 >= (0.01 if len(labels["instances"].segments) else 0.1))[0] + if len(indexes2) == 0: + params["skip"] = True + return params + + params["area"] = area + params["indexes2"] = indexes2 + params["w"] = w + params["h"] = h + return params + + def apply_image(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply CutMix to the image. + + Args: + labels (dict[str, Any]): Dictionary containing 'img'. + params (dict | None): Parameters from get_params. + + Returns: + (dict): Updated labels with mixed image. + """ + if params.get("skip"): + return labels + x1, y1, x2, y2 = params["area"].astype(np.int32) + labels2 = labels["mix_labels"][0] + labels["img"][y1:y2, x1:x2] = labels2["img"][y1:y2, x1:x2] + return labels + + def apply_instances(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply CutMix to instances. + + Args: + labels (dict[str, Any]): Dictionary containing 'instances' and 'cls'. + params (dict | None): Parameters from get_params. + + Returns: + (dict): Updated labels with mixed instances. + """ + if params.get("skip"): + return labels + labels2 = labels["mix_labels"][0] + w, h = params["w"], params["h"] + area = params["area"] + indexes2 = params["indexes2"] + + instances2 = labels2["instances"][indexes2] + instances2.convert_bbox("xyxy") + instances2.denormalize(w, h) + + x1, y1, x2, y2 = area.astype(np.int32) + instances2.add_padding(-x1, -y1) + instances2.clip(x2 - x1, y2 - y1, preserve_obb=self.preserve_obb) + if self.preserve_obb: + indexes2 = indexes2[instances2.remove_zero_area_boxes()] + instances2.add_padding(x1, y1) + + labels["cls"] = np.concatenate([labels["cls"], labels2["cls"][indexes2]], axis=0) + labels["instances"] = Instances.concatenate([labels["instances"], instances2], axis=0) + return labels + + def apply_semantic(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply CutMix augmentation to semantic segmentation masks. + + Args: + labels (dict[str, Any]): Primary image labels containing 'semantic_mask' and 'mix_labels'. + params (dict[str, Any] | None): Parameters dict with 'area' (bounding box coordinates) and 'skip' (bool + flag). Defaults to None. + + Returns: + (dict[str, Any]): Updated labels with the semantic mask region replaced by the mixed image's mask. + """ + if params.get("skip"): + return labels + if labels.get("semantic_mask") is None: + return labels + x1, y1, x2, y2 = params["area"].astype(np.int32) + labels2 = labels["mix_labels"][0] + if labels2.get("semantic_mask") is not None: + mask = labels["semantic_mask"].copy() + mask[y1:y2, x1:x2] = labels2["semantic_mask"][y1:y2, x1:x2] + labels["semantic_mask"] = mask + return labels + + +class RandomPerspective(BaseTransform): + """Implement random perspective and affine transformations on images and corresponding annotations. + + This class applies random rotations, translations, scaling, shearing, and perspective transformations to images and + their associated bounding boxes, segments, and keypoints. It can be used as part of an augmentation pipeline for + object detection and instance segmentation tasks. + + Attributes: + degrees (float): Maximum absolute degree range for random rotations. + translate (float): Maximum translation as a fraction of the image size. + scale (float): Scaling factor range, e.g., scale=0.1 means 0.9-1.1. + shear (float): Maximum shear angle in degrees. + perspective (float): Perspective distortion factor. + size (tuple[int, int] | None): Output size (width, height). If None, uses the input image size. + + Methods: + get_params: Compute affine transformation matrix and related parameters. + apply_image: Warp the image using the affine matrix. + apply_instances: Transform bounding boxes, segments, and keypoints. + apply_semantic: Placeholder for semantic segmentation mask transformation. + apply_bboxes: Transform bounding boxes using the affine matrix. + apply_segments: Transform segments and generate new bounding boxes. + apply_keypoints: Transform keypoints using the affine matrix. + box_candidates: Filter transformed bounding boxes based on size and aspect ratio. + + Examples: + >>> transform = RandomPerspective(degrees=10, translate=0.1, scale=0.1, shear=10) + >>> image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8) + >>> labels = {"img": image, "cls": np.array([0, 1]), "instances": Instances(...)} + >>> result = transform(labels) + >>> transformed_image = result["img"] + >>> transformed_instances = result["instances"] + """ + + def __init__( + self, + degrees: float = 0.0, + translate: float = 0.1, + scale: float | tuple[float, float] = 0.5, + shear: float = 0.0, + perspective: float = 0.0, + size: tuple[int, int] | None = None, + preserve_obb: bool = False, + ): + """Initialize RandomPerspective object with transformation parameters. + + This class implements random perspective and affine transformations on images and corresponding bounding boxes, + segments, and keypoints. Transformations include rotation, translation, scaling, and shearing. + + Args: + degrees (float): Degree range for random rotations. + translate (float): Fraction of total width and height for random translation. + scale (float | tuple[float, float]): Scaling factor interval. If float, e.g. 0.5 means resize between + 50%-150%. If tuple, interpreted as absolute (min, max) scale factors. + shear (float): Shear intensity (angle in degrees). + perspective (float): Perspective distortion factor. + size (tuple[int, int] | None): Output size (width, height). If None, uses the input image size. + preserve_obb (bool): Preserve oriented-box direction when transformed segments cross image boundaries. + """ + self.degrees = degrees + self.translate = translate + self.scale = scale + self.shear = shear + self.perspective = perspective + self.size = size + self.preserve_obb = preserve_obb + + def _compute_affine_matrix(self, img: np.ndarray, size: tuple[int, int]) -> tuple[np.ndarray, float]: + """Compute the affine transformation matrix without applying it. + + Args: + img (np.ndarray): Input image used to determine center and dimensions. + size (tuple[int, int]): Size of the output image (width, height) used for clipping translation transform. + + Returns: + (M, scale): 3x3 transformation matrix and scale factor. + """ + # Center + C = np.eye(3, dtype=np.float32) + C[0, 2] = -img.shape[1] / 2 # x translation (pixels) + C[1, 2] = -img.shape[0] / 2 # y translation (pixels) + + # Perspective + P = np.eye(3, dtype=np.float32) + P[2, 0] = random.uniform(-self.perspective, self.perspective) # x perspective (about y) + P[2, 1] = random.uniform(-self.perspective, self.perspective) # y perspective (about x) + + # Rotation and Scale + R = np.eye(3, dtype=np.float32) + a = random.uniform(-self.degrees, self.degrees) + if isinstance(self.scale, (tuple, list)): + s = random.uniform(self.scale[0], self.scale[1]) + else: + s = random.uniform(1 - self.scale, 1 + self.scale) + R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s) + + # Shear + S = np.eye(3, dtype=np.float32) + S[0, 1] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180) # x shear (deg) + S[1, 0] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180) # y shear (deg) + + # Translation + T = np.eye(3, dtype=np.float32) + + T[0, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * size[0] # x translation (pixels) + T[1, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * size[1] # y translation (pixels) + + # Combined rotation matrix + M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT + return M, s + + def get_params(self, labels: dict[str, Any]) -> dict[str, Any]: + """Compute affine transformation parameters shared across image and instances. + + Args: + labels (dict[str, Any]): Input labels dictionary containing 'img'. + + Returns: + (dict): Parameters including 'M' (affine matrix), 'scale', 'orig_shape', and 'size'. + """ + img = labels["img"] + if (rect_shape := labels.get("rect_shape")) is not None: # rect has higher priority + size = (int(rect_shape[1]), int(rect_shape[0])) # rect mode batch shape (h, w) to (w, h) + else: + size = (img.shape[1], img.shape[0]) if self.size is None else self.size # w, h + orig_shape = img.shape[:2] + M, scale = self._compute_affine_matrix(img, size) + return {"M": M, "scale": scale, "orig_shape": orig_shape, "size": size} + + def apply_image(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply affine warp to the image. + + Args: + labels (dict[str, Any]): Dictionary containing 'img'. + params (dict | None): Parameters from get_params, including 'M' and 'size'. + + Returns: + (dict): Updated labels with warped image and 'resized_shape'. + """ + img = labels["img"] + M = params["M"] + size = params["size"] + # 4 values: cv2 tiles borderValue in blocks of 4, so a 3-tuple zeroes every 4th multispectral channel + if self.perspective: + img = cv2.warpPerspective(img, M, dsize=size, borderValue=(114, 114, 114, 114)) + else: # affine + img = cv2.warpAffine(img, M[:2], dsize=size, borderValue=(114, 114, 114, 114)) + if img.ndim == 2: + img = img[..., None] + labels["img"] = img + labels["resized_shape"] = img.shape[:2] + return labels + + def apply_instances(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply the affine transformation to object instances.""" + cls = labels["cls"] + instances = labels.pop("instances") + instances.convert_bbox(format="xyxy") + instances.denormalize(*params["orig_shape"][::-1]) + + M = params["M"] + scale = params["scale"] + + bboxes = self.apply_bboxes(instances.bboxes, M) + + segments = instances.segments + keypoints = instances.keypoints + # Update bboxes if there are segments. + if len(segments): + bboxes, segments = self.apply_segments(segments, M, params["size"]) + + if keypoints is not None: + keypoints = self.apply_keypoints(keypoints, M, params["size"]) + new_instances = Instances(bboxes, segments, keypoints, bbox_format="xyxy", normalized=False) + # Clip + new_instances.clip(*params["size"], preserve_obb=self.preserve_obb) + + # Filter instances + instances.scale(scale_w=scale, scale_h=scale, bbox_only=True) + # Make the bboxes have the same scale with new_bboxes + i = self.box_candidates( + box1=instances.bboxes.T, box2=new_instances.bboxes.T, area_thr=0.01 if len(segments) else 0.10 + ) + labels["instances"] = new_instances[i] + labels["cls"] = cls[i] + return labels + + def apply_bboxes(self, bboxes: np.ndarray, M: np.ndarray) -> np.ndarray: + """Apply affine transformation to bounding boxes. + + This function applies an affine transformation to a set of bounding boxes using the provided transformation + matrix. + + Args: + bboxes (np.ndarray): Bounding boxes in xyxy format with shape (N, 4), where N is the number of bounding + boxes. + M (np.ndarray): Affine transformation matrix with shape (3, 3). + + Returns: + (np.ndarray): Transformed bounding boxes in xyxy format with shape (N, 4). + + Examples: + >>> rp = RandomPerspective() + >>> bboxes = np.array([[10, 10, 20, 20], [30, 30, 40, 40]], dtype=np.float32) + >>> M = np.eye(3, dtype=np.float32) + >>> transformed_bboxes = rp.apply_bboxes(bboxes, M) + """ + n = len(bboxes) + if n == 0: + return bboxes + + xy = np.ones((n * 4, 3), dtype=bboxes.dtype) + xy[:, :2] = bboxes[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1 + xy = xy @ M.T # transform + xy = (xy[:, :2] / xy[:, 2:3] if self.perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine + + # Create new boxes + x = xy[:, [0, 2, 4, 6]] + y = xy[:, [1, 3, 5, 7]] + return np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1)), dtype=bboxes.dtype).reshape(4, n).T + + def apply_segments( + self, segments: np.ndarray, M: np.ndarray, size: tuple[int, int] + ) -> tuple[np.ndarray, np.ndarray]: + """Transform segments and derive their bounding boxes.""" + n, num = segments.shape[:2] + if n == 0: + return [], segments + + xy = np.ones((n * num, 3), dtype=segments.dtype) + segments = segments.reshape(-1, 2) + xy[:, :2] = segments + xy = xy @ M.T # transform + xy = xy[:, :2] / xy[:, 2:3] + segments = xy.reshape(n, -1, 2) + bboxes = np.stack([segment2box(xy, size[0], size[1]) for xy in segments], 0) + if not self.preserve_obb: + segments[..., 0] = segments[..., 0].clip(bboxes[:, 0:1], bboxes[:, 2:3]) + segments[..., 1] = segments[..., 1].clip(bboxes[:, 1:2], bboxes[:, 3:4]) + return bboxes, segments + + def apply_keypoints(self, keypoints: np.ndarray, M: np.ndarray, size: tuple[int, int]) -> np.ndarray: + """Apply affine transformation to keypoints. + + This method transforms the input keypoints using the provided affine transformation matrix. It handles + perspective rescaling if necessary and updates the visibility of keypoints that fall outside the image + boundaries after transformation. + + Args: + keypoints (np.ndarray): Array of keypoints with shape (N, K, 3), where N is the number of instances, K is + the number of keypoints per instance, and 3 represents (x, y, visibility). + M (np.ndarray): 3x3 affine transformation matrix. + size (tuple[int, int]): Size of the output image (width, height) used to determine visibility of keypoints. + + Returns: + (np.ndarray): Transformed keypoints array with the same shape as input (N, K, 3). + + Examples: + >>> random_perspective = RandomPerspective() + >>> keypoints = np.random.rand(5, 17, 3) # 5 instances, 17 keypoints each + >>> M = np.eye(3) # Identity transformation + >>> transformed_keypoints = random_perspective.apply_keypoints(keypoints, M) + """ + n, nkpt = keypoints.shape[:2] + if n == 0: + return keypoints + xy = np.ones((n * nkpt, 3), dtype=keypoints.dtype) + visible = keypoints[..., 2].reshape(n * nkpt, 1) + xy[:, :2] = keypoints[..., :2].reshape(n * nkpt, 2) + xy = xy @ M.T # transform + xy = xy[:, :2] / xy[:, 2:3] # perspective rescale or affine + out_mask = (xy[:, 0] < 0) | (xy[:, 1] < 0) | (xy[:, 0] > size[0]) | (xy[:, 1] > size[1]) + visible[out_mask] = 0 + return np.concatenate([xy, visible], axis=-1).reshape(n, nkpt, 3) + + def apply_semantic(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply affine transformation to semantic segmentation mask. + + Args: + labels (dict[str, Any]): Dictionary containing 'semantic_mask'. + params (dict | None): Parameters from get_params, including 'M' and 'size'. + + Returns: + (dict): Updated labels with transformed semantic mask. + """ + if "semantic_mask" not in labels or labels["semantic_mask"] is None: + return labels + mask = labels["semantic_mask"] + M = params["M"] + size = params["size"] + if (size[0] != mask.shape[1] or size[1] != mask.shape[0]) or (M != np.eye(3)).any(): + if self.perspective: + mask = cv2.warpPerspective(mask, M, dsize=size, flags=cv2.INTER_NEAREST, borderValue=255) + else: + mask = cv2.warpAffine(mask, M[:2], dsize=size, flags=cv2.INTER_NEAREST, borderValue=255) + labels["semantic_mask"] = mask + return labels + + def apply_depth(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply the same projective warp to metric depth maps. + + Depth values remain in meters; only their spatial support is warped. Nearest-neighbor interpolation avoids + manufacturing spurious near-zero "valid" pixels when sparse or invalid regions border real depth. + """ + depth = labels.get("depth") + if depth is None: + return labels + + M = params["M"] + size = params["size"] + if (size[0] != depth.shape[1] or size[1] != depth.shape[0]) or (M != np.eye(3)).any(): + if self.perspective: + depth = cv2.warpPerspective(depth, M, dsize=size, flags=cv2.INTER_NEAREST, borderValue=0) + else: + depth = cv2.warpAffine(depth, M[:2], dsize=size, flags=cv2.INTER_NEAREST, borderValue=0) + labels["depth"] = depth + return labels + + @staticmethod + def box_candidates( + box1: np.ndarray, + box2: np.ndarray, + wh_thr: int = 2, + ar_thr: int = 100, + area_thr: float = 0.1, + eps: float = 1e-16, + ) -> np.ndarray: + """Compute candidate boxes for further processing based on size and aspect ratio criteria. + + This method compares boxes before and after augmentation to determine if they meet specified thresholds for + width, height, aspect ratio, and area. It's used to filter out boxes that have been overly distorted or reduced + by the augmentation process. + + Args: + box1 (np.ndarray): Original boxes before augmentation, shape (4, N) where N is the number of boxes. Format + is [x1, y1, x2, y2] in absolute coordinates. + box2 (np.ndarray): Augmented boxes after transformation, shape (4, N). Format is [x1, y1, x2, y2] in + absolute coordinates. + wh_thr (int): Width and height threshold in pixels. Boxes smaller than this in either dimension are + rejected. + ar_thr (int): Aspect ratio threshold. Boxes with an aspect ratio greater than this value are rejected. + area_thr (float): Area ratio threshold. Boxes with an area ratio (new/old) less than this value are + rejected. + eps (float): Small epsilon value to prevent division by zero. + + Returns: + (np.ndarray): Boolean array of shape (N,) indicating which boxes are candidates. True values correspond to + boxes that meet all criteria. + + Examples: + >>> random_perspective = RandomPerspective() + >>> box1 = np.array([[0, 0, 100, 100], [0, 0, 50, 50]]).T + >>> box2 = np.array([[10, 10, 90, 90], [5, 5, 45, 45]]).T + >>> candidates = random_perspective.box_candidates(box1, box2) + >>> print(candidates) + [ True True] + """ + w1, h1 = box1[2] - box1[0], box1[3] - box1[1] + w2, h2 = box2[2] - box2[0], box2[3] - box2[1] + ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio + return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates + + +class RandomHSV(BaseTransform): + """Randomly adjust the Hue, Saturation, and Value (HSV) channels of an image. + + This class applies random HSV augmentation to images within predefined limits set by hgain, sgain, and vgain. + + Attributes: + hgain (float): Maximum variation for hue. Range is typically [0, 1]. + sgain (float): Maximum variation for saturation. Range is typically [0, 1]. + vgain (float): Maximum variation for value. Range is typically [0, 1]. + + Methods: + apply_image: Apply random HSV augmentation to an image. + + Examples: + >>> import numpy as np + >>> from ultralytics.data.augment import RandomHSV + >>> augmenter = RandomHSV(hgain=0.5, sgain=0.5, vgain=0.5) + >>> image = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8) + >>> labels = {"img": image} + >>> labels = augmenter(labels) + >>> augmented_image = labels["img"] + """ + + def __init__(self, hgain: float = 0.5, sgain: float = 0.5, vgain: float = 0.5) -> None: + """Initialize the RandomHSV object for random HSV (Hue, Saturation, Value) augmentation. + + This class applies random adjustments to the HSV channels of an image within specified limits. + + Args: + hgain (float): Maximum variation for hue. Should be in the range [0, 1]. + sgain (float): Maximum variation for saturation. Should be in the range [0, 1]. + vgain (float): Maximum variation for value. Should be in the range [0, 1]. + """ + self.hgain = hgain + self.sgain = sgain + self.vgain = vgain + + def apply_image(self, labels, params: dict[str, Any] | None = None): + """Apply random HSV augmentation to an image within predefined limits. + + This method modifies the input image by randomly adjusting its Hue, Saturation, and Value (HSV) channels. The + adjustments are made within the limits set by hgain, sgain, and vgain during initialization. + + Args: + labels (dict[str, Any]): A dictionary containing image data and metadata. Must include an 'img' key with the + image as a numpy array. + params (dict[str, Any] | None): Unused parameters for API compatibility. + + Returns: + (dict[str, Any]): The labels dictionary with the HSV-augmented image. + + Examples: + >>> hsv_augmenter = RandomHSV(hgain=0.5, sgain=0.5, vgain=0.5) + >>> labels = {"img": np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)} + >>> labels = hsv_augmenter.apply_image(labels) + >>> augmented_img = labels["img"] + """ + img = labels["img"] + if img.shape[-1] != 3: # only apply to 3-channel (BGR) images + return labels + if self.hgain or self.sgain or self.vgain: + dtype = img.dtype # uint8 + + r = np.random.uniform(-1, 1, 3) * [self.hgain, self.sgain, self.vgain] # random gains + x = np.arange(0, 256, dtype=r.dtype) + # lut_hue = ((x * (r[0] + 1)) % 180).astype(dtype) # original hue implementation from ultralytics<=8.3.78 + lut_hue = ((x + r[0] * 180) % 180).astype(dtype) + lut_sat = np.clip(x * (r[1] + 1), 0, 255).astype(dtype) + lut_val = np.clip(x * (r[2] + 1), 0, 255).astype(dtype) + lut_sat[0] = 0 # prevent pure white changing color, introduced in 8.3.79 + + hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV)) + im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))) + cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed + return labels + + +class RandomFlip(BaseTransform): + """Apply a random horizontal or vertical flip to an image with a given probability. + + This class performs random image flipping and updates corresponding instance annotations such as bounding boxes and + keypoints. + + Attributes: + p (float): Probability of applying the flip. Must be between 0 and 1. + direction (str): Direction of flip, either 'horizontal' or 'vertical'. + flip_idx (array-like): Index mapping for flipping keypoints, if applicable. + + Methods: + __call__: Apply the random flip transformation to an image and its annotations. + + Examples: + >>> transform = RandomFlip(p=0.5, direction="horizontal") + >>> result = transform({"img": image, "instances": instances}) + >>> flipped_image = result["img"] + >>> flipped_instances = result["instances"] + """ + + def __init__(self, p: float = 0.5, direction: str = "horizontal", flip_idx: list[int] | None = None) -> None: + """Initialize the RandomFlip class with probability and direction. + + This class applies a random horizontal or vertical flip to an image with a given probability. It also updates + any instances (bounding boxes, keypoints, etc.) accordingly. + + Args: + p (float): The probability of applying the flip. Must be between 0 and 1. + direction (str): The direction to apply the flip. Must be 'horizontal' or 'vertical'. + flip_idx (list[int] | None): Index mapping for flipping keypoints, if any. + + Raises: + AssertionError: If direction is not 'horizontal' or 'vertical', or if p is not between 0 and 1. + """ + assert direction in {"horizontal", "vertical"}, f"Support direction `horizontal` or `vertical`, got {direction}" + assert 0 <= p <= 1.0, f"The probability should be in range [0, 1], but got {p}." + + self.p = p + self.direction = direction + self.flip_idx = flip_idx + + def get_params(self, labels: dict[str, Any]) -> dict[str, Any]: + """Compute random flip parameters. + + Args: + labels (dict[str, Any]): Input labels dictionary containing 'img' and 'instances'. + + Returns: + (dict): Parameters including 'flip' (bool), 'h', 'w', 'direction', and 'flip_idx'. + """ + img = labels["img"] + instances = labels["instances"] + h, w = img.shape[:2] + h = 1 if instances.normalized else h + w = 1 if instances.normalized else w + return { + "flip": random.random() < self.p, + "h": h, + "w": w, + "direction": self.direction, + "flip_idx": self.flip_idx, + } + + def apply_image(self, labels: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]: + """Apply flip to the image. + + Args: + labels (dict[str, Any]): Dictionary containing 'img'. + params (dict): Parameters from get_params. + + Returns: + (dict): Updated labels with flipped (or unchanged) image. + """ + img = labels["img"] + if params["flip"]: + if params["direction"] == "vertical": + img = np.flipud(img) + elif params["direction"] == "horizontal": + img = np.fliplr(img) + labels["img"] = img + return labels + + def apply_instances(self, labels: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]: + """Apply flip to object instances. + + Args: + labels (dict[str, Any]): Dictionary containing 'instances'. + params (dict): Parameters from get_params. + + Returns: + (dict): Updated labels with flipped (or unchanged) instances. + """ + instances = labels.pop("instances") + instances.convert_bbox(format="xywh") + if params["flip"]: + if params["direction"] == "vertical": + instances.flipud(params["h"]) + elif params["direction"] == "horizontal": + instances.fliplr(params["w"]) + if params["flip_idx"] is not None and instances.keypoints is not None: + instances.keypoints = np.ascontiguousarray(instances.keypoints[:, params["flip_idx"], :]) + labels["instances"] = instances + return labels + + def apply_semantic(self, labels: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]: + """Apply flip to semantic segmentation mask. + + Args: + labels (dict[str, Any]): Dictionary containing 'semantic_mask'. + params (dict): Parameters from get_params. + + Returns: + (dict): Updated labels with flipped (or unchanged) semantic mask. + """ + if "semantic_mask" not in labels or labels["semantic_mask"] is None: + return labels + if params["flip"]: + if params["direction"] == "vertical": + labels["semantic_mask"] = np.flipud(labels["semantic_mask"]) + elif params["direction"] == "horizontal": + labels["semantic_mask"] = np.fliplr(labels["semantic_mask"]) + return labels + + def apply_depth(self, labels: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]: + """Apply flip to the paired metric depth map. + + Args: + labels (dict[str, Any]): Dictionary containing 'depth'. + params (dict): Parameters from get_params. + + Returns: + (dict): Updated labels with flipped (or unchanged) depth map. + """ + if labels.get("depth") is None: + return labels + if params["flip"]: + if params["direction"] == "vertical": + labels["depth"] = np.flipud(labels["depth"]) + elif params["direction"] == "horizontal": + labels["depth"] = np.fliplr(labels["depth"]) + return labels + + +class LetterBox(BaseTransform): + """Resize image and padding for detection, instance segmentation, pose. + + This class resizes and pads images to a specified shape while preserving aspect ratio. It also updates corresponding + labels and bounding boxes. + + Attributes: + new_shape (tuple): Target shape (height, width) for resizing. + auto (bool): Whether to use minimum rectangle. + scale_fill (bool): Whether to stretch the image to new_shape. + scaleup (bool): Whether to allow scaling up. If False, only scale down. + stride (int): Stride for rounding padding. + center (bool): Whether to center the image or align to top-left. + + Methods: + __call__: Resize and pad image, update labels and bounding boxes. + + Examples: + >>> transform = LetterBox(new_shape=(640, 640)) + >>> result = transform(labels) + >>> resized_img = result["img"] + >>> updated_instances = result["instances"] + """ + + def __init__( + self, + new_shape: tuple[int, int] = (640, 640), + auto: bool = False, + scale_fill: bool = False, + scaleup: bool = True, + center: bool = True, + stride: int = 32, + padding_value: int = 114, + interpolation: int = cv2.INTER_LINEAR, + ): + """Initialize LetterBox object for resizing and padding images. + + This class is designed to resize and pad images for object detection, instance segmentation, and pose estimation + tasks. It supports various resizing modes including auto-sizing, scale-fill, and letterboxing. + + Args: + new_shape (tuple[int, int]): Target size (height, width) for the resized image. + auto (bool): If True, use minimum rectangle to resize. If False, use new_shape directly. + scale_fill (bool): If True, stretch the image to new_shape without padding. + scaleup (bool): If True, allow scaling up. If False, only scale down. + center (bool): If True, center the placed image. If False, place image in top-left corner. + stride (int): Stride of the model (e.g., 32 for YOLOv5). + padding_value (int): Value for padding the image. Default is 114. + interpolation (int): Interpolation method for resizing. Default is cv2.INTER_LINEAR. + """ + self.new_shape = new_shape + self.auto = auto + self.scale_fill = scale_fill + self.scaleup = scaleup + self.stride = stride + self.center = center # Put the image in the middle or top-left + self.padding_value = padding_value + self.interpolation = interpolation + + def __call__(self, labels: dict[str, Any] | None = None, image: np.ndarray = None) -> dict[str, Any] | np.ndarray: + """Resize and pad an image for object detection, instance segmentation, or pose estimation tasks. + + This method applies letterboxing to the input image, which involves resizing the image while maintaining its + aspect ratio and adding padding to fit the new shape. It also updates any associated labels accordingly. + + Args: + labels (dict[str, Any] | None): A dictionary containing image data and associated labels, or empty dict if + None. + image (np.ndarray | None): The input image as a numpy array. If None, the image is taken from 'labels'. + + Returns: + (dict[str, Any] | np.ndarray): If 'labels' is provided, returns an updated dictionary with the resized and + padded image, updated labels, and additional metadata. If 'labels' is empty, returns the resized and + padded image only. + + Examples: + >>> letterbox = LetterBox(new_shape=(640, 640)) + >>> result = letterbox(labels={"img": np.zeros((480, 640, 3)), "instances": Instances(...)}) + >>> resized_img = result["img"] + >>> updated_instances = result["instances"] + """ + if labels is None: + labels = {} + return_image_only = len(labels) == 0 + if image is not None: + labels["img"] = image + params = self.get_params(labels) + labels = self.apply_image(labels, params) + if not return_image_only: + labels = self.apply_instances(labels, params) + labels = self.apply_semantic(labels, params) + if return_image_only: + return labels["img"] + return labels + + def get_params(self, labels: dict[str, Any]) -> dict[str, Any]: + """Compute letterboxing parameters. + + Args: + labels (dict[str, Any]): Input labels dictionary containing 'img'. + + Returns: + (dict): Parameters including 'orig_shape', 'new_shape', 'ratio', padding, and resize info. + """ + img = labels["img"] + shape = img.shape[:2] # current shape [height, width] + new_shape = labels.pop("rect_shape", self.new_shape) + if isinstance(new_shape, int): + new_shape = (new_shape, new_shape) + + # Scale ratio (new / old) + r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) + if not self.scaleup: # only scale down, do not scale up (for better val mAP) + r = min(r, 1.0) + + # Compute padding + ratio = r, r # width, height ratios + new_unpad = round(shape[1] * r), round(shape[0] * r) + dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding + if self.auto: # minimum rectangle + dw, dh = np.mod(dw, self.stride), np.mod(dh, self.stride) # wh padding + elif self.scale_fill: # stretch + dw, dh = 0.0, 0.0 + new_unpad = (new_shape[1], new_shape[0]) + ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios + + if self.center: + dw /= 2 # divide padding into 2 sides + dh /= 2 + + top, bottom = round(dh - 0.1) if self.center else 0, round(dh + 0.1) + left, right = round(dw - 0.1) if self.center else 0, round(dw + 0.1) + + return { + "orig_shape": shape, + "new_shape": new_shape, + "ratio": ratio, + "new_unpad": new_unpad, + "top": top, + "bottom": bottom, + "left": left, + "right": right, + } + + def apply_image(self, labels: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]: + """Resize and pad the image. + + Args: + labels (dict[str, Any]): Dictionary containing 'img'. + params (dict): Parameters from get_params. + + Returns: + (dict): Updated labels with resized and padded image. + """ + img = labels["img"] + shape = img.shape[:2] + new_unpad = params["new_unpad"] + + if shape[::-1] != new_unpad: # resize + img = cv2.resize(img, new_unpad, interpolation=self.interpolation) + if img.ndim == 2: + img = img[..., None] + + h, w, c = img.shape + top, bottom = params["top"], params["bottom"] + left, right = params["left"], params["right"] + if c == 3: + img = cv2.copyMakeBorder( + img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(self.padding_value,) * 3 + ) + else: # multispectral + pad_img = np.full((h + top + bottom, w + left + right, c), fill_value=self.padding_value, dtype=img.dtype) + pad_img[top : top + h, left : left + w] = img + img = pad_img + + labels["img"] = img + labels["resized_shape"] = params["new_shape"] + return labels + + def apply_semantic(self, labels: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]: + """Apply letterboxing to semantic segmentation mask. + + Args: + labels (dict[str, Any]): Dictionary containing 'semantic_mask'. + params (dict): Parameters from get_params. + + Returns: + (dict): Updated labels with resized and padded semantic mask. + """ + if "semantic_mask" not in labels or labels["semantic_mask"] is None: + return labels + mask = labels["semantic_mask"] + shape = params["orig_shape"] + new_unpad = params["new_unpad"] + if shape[::-1] != new_unpad: + mask = cv2.resize(mask, new_unpad, interpolation=cv2.INTER_NEAREST) + top, bottom = params["top"], params["bottom"] + left, right = params["left"], params["right"] + mask = cv2.copyMakeBorder(mask, top, bottom, left, right, cv2.BORDER_CONSTANT, value=255) + labels["semantic_mask"] = mask + return labels + + def apply_instances(self, labels: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]: + """Update instance coordinates after letterboxing. + + Args: + labels (dict[str, Any]): Dictionary containing 'instances'. + params (dict): Parameters from get_params. + + Returns: + (dict): Updated labels with transformed instances. + """ + if "instances" in labels: + labels = self._update_labels(labels, params["ratio"], params["left"], params["top"], params["orig_shape"]) + if labels.get("ratio_pad"): + gain_h, gain_w = labels["ratio_pad"] + ratio_w, ratio_h = params["ratio"] + labels["ratio_pad"] = ( + (gain_h * ratio_h, gain_w * ratio_w), + (params["left"], params["top"]), + ) # for evaluation + return labels + + @staticmethod + def _update_labels( + labels: dict[str, Any], ratio: tuple[float, float], padw: float, padh: float, orig_shape: tuple[int, int] + ) -> dict[str, Any]: + """Update labels after applying letterboxing to an image. + + This method modifies the bounding box coordinates of instances in the labels to account for resizing and padding + applied during letterboxing. + + Args: + labels (dict[str, Any]): A dictionary containing image labels and instances. + ratio (tuple[float, float]): Scaling ratios (width, height) applied to the image. + padw (float): Padding width added to the image. + padh (float): Padding height added to the image. + orig_shape (tuple[int, int]): Original image shape (height, width) before resizing. + + Returns: + (dict[str, Any]): Updated labels dictionary with modified instance coordinates. + + Examples: + >>> letterbox = LetterBox(new_shape=(640, 640)) + >>> labels = {"instances": Instances(...)} + >>> ratio = (0.5, 0.5) + >>> padw, padh = 10, 20 + >>> updated_labels = letterbox._update_labels(labels, ratio, padw, padh, (480, 640)) + """ + labels["instances"].convert_bbox(format="xyxy") + labels["instances"].denormalize(*orig_shape[::-1]) + labels["instances"].scale(*ratio) + labels["instances"].add_padding(padw, padh) + return labels + + +class CopyPaste(BaseMixTransform): + """CopyPaste class for applying Copy-Paste augmentation to image datasets. + + This class implements the Copy-Paste augmentation technique as described in the paper "Simple Copy-Paste is a Strong + Data Augmentation Method for Instance Segmentation" (https://arxiv.org/abs/2012.07177). In `flip` mode it pastes + mirrored copies of the image's own objects, in `mixup` mode objects from a randomly sampled dataset entry. + + Attributes: + dataset (Any): The dataset to which Copy-Paste augmentation will be applied. + pre_transform (Callable | None): Optional transform to apply before Copy-Paste. + p (float): Fraction of eligible objects pasted; in `mixup` mode also the probability of applying it. + + Methods: + get_params: Compute CopyPaste parameters including selected instances and mask. + apply_image: Draw contours and paste pixels for CopyPaste. + apply_instances: Concatenate selected instances for CopyPaste. + + Examples: + >>> from ultralytics.data.augment import CopyPaste + >>> dataset = YourDataset(...) # Your image dataset + >>> copypaste = CopyPaste(dataset, p=0.5) + >>> augmented_labels = copypaste(original_labels) + """ + + def __init__(self, dataset=None, pre_transform=None, p: float = 0.5, mode: str = "flip") -> None: + """Initialize CopyPaste object with dataset, pre_transform, paste fraction and mode.""" + super().__init__(dataset=dataset, pre_transform=pre_transform, p=p) + if mode not in ("flip", "mixup"): + raise ValueError(f"Expected `mode` to be `flip` or `mixup`, but got {mode}.") + self.mode = mode + + def __call__(self, labels: dict[str, Any]) -> dict[str, Any]: + """Apply Copy-Paste augmentation to an image and its labels.""" + if len(labels["instances"].segments) == 0 or self.p == 0: + return labels + if self.mode == "flip": + params = self.get_params(labels) + labels = self.apply_image(labels, params) + labels = self.apply_instances(labels, params) + labels = self.apply_semantic(labels, params) + return labels + return super().__call__(labels) + + def get_params(self, labels: dict[str, Any]) -> dict[str, Any]: + """Compute CopyPaste parameters. + + Args: + labels (dict[str, Any]): Input labels dictionary. + + Returns: + (dict[str, Any]): Parameters including 'instances2', 'selected', and 'im_new'. + """ + params = {} + if self.mode == "mixup": + params = super().get_params(labels) + labels2 = labels.get("mix_labels", [{}])[0] + else: + labels2 = {} + + h, w = labels["img"].shape[:2] + instances = deepcopy(labels["instances"]) + instances.convert_bbox(format="xyxy") + instances.denormalize(w, h) + + instances2 = deepcopy(labels2.get("instances")) if labels2 else None + if instances2 is None: + instances2 = deepcopy(instances) + instances2.fliplr(w) + + ioa = bbox_ioa(instances2.bboxes, instances.bboxes) + indexes = np.nonzero((ioa < 0.30).all(1))[0] + indexes = indexes[np.argsort(ioa.max(1)[indexes])] + selected = indexes[: round(self.p * len(indexes))] + + im_new = np.zeros((h, w), np.uint8) + + params["instances"] = instances + params["instances2"] = instances2 + params["selected"] = selected + params["im_new"] = im_new + params["labels2_cls"] = labels2.get("cls") + params["labels2_img"] = labels2.get("img") + return params + + def apply_image(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply CopyPaste to the image. + + Args: + labels (dict[str, Any]): Dictionary containing 'img'. + params (dict | None): Parameters from get_params. + + Returns: + (dict): Updated labels with pasted objects. + """ + im = labels["img"].copy() + + instances2 = params["instances2"] + selected = params["selected"] + im_new = params["im_new"] + + for j in selected: + cv2.drawContours(im_new, instances2.segments[[j]].astype(np.int32), -1, 1, cv2.FILLED) + + result = params.get("labels2_img") + if result is None: + result = cv2.flip(im, 1) + if result.ndim == 2: + result = result[..., None] + + i = im_new.astype(bool) + im[i] = result[i] + labels["img"] = im + return labels + + def apply_instances(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply CopyPaste to instances. + + Args: + labels (dict[str, Any]): Dictionary containing 'instances' and 'cls'. + params (dict | None): Parameters from get_params. + + Returns: + (dict): Updated labels with concatenated instances. + """ + instances = params["instances"] + instances2 = params["instances2"] + selected = params["selected"] + cls = labels["cls"] + labels2_cls = params.get("labels2_cls") + + if len(selected): + cls = np.concatenate((cls, (labels2_cls if labels2_cls is not None else cls)[selected]), axis=0) + instances = Instances.concatenate([instances, instances2[selected]], axis=0) + + labels["cls"] = cls + labels["instances"] = instances + return labels + + def apply_semantic(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Apply CopyPaste to semantic segmentation masks.""" + mask = labels.get("semantic_mask") + if mask is None: + return labels + + source = labels.get("mix_labels", [{}])[0].get("semantic_mask") if self.mode == "mixup" else cv2.flip(mask, 1) + if source is None: + return labels + pasted = params["im_new"].astype(bool) + mask = mask.copy() + mask[pasted] = source[pasted] + labels["semantic_mask"] = mask + return labels + + +class Albumentations(BaseTransform): + """Albumentations transformations for image augmentation. + + This class applies various image transformations using the Albumentations library. It includes operations such as + Blur, Median Blur, conversion to grayscale, Contrast Limited Adaptive Histogram Equalization (CLAHE), random changes + in brightness and contrast, RandomGamma, and image quality reduction through compression. + + Attributes: + p (float): Probability of applying the transformations. + transform (albumentations.Compose): Composed Albumentations transforms. + contains_spatial (bool): Indicates if the transforms include spatial operations. + + Methods: + __call__: Apply the Albumentations transformations to the input labels. + + Examples: + >>> transform = Albumentations(p=0.5) + >>> augmented_labels = transform(labels) + + Notes: + - Requires Albumentations version 1.0.3 or higher. + - Spatial transforms are handled differently to ensure bbox compatibility. + - Some transforms are applied with very low probability (0.01) by default. + """ + + def __init__(self, p: float = 1.0, transforms: list | None = None, flip_idx: list[int] | None = None) -> None: + """Initialize the Albumentations transform object for YOLO bbox formatted parameters. + + This class applies various image augmentations using the Albumentations library, including Blur, Median Blur, + conversion to grayscale, Contrast Limited Adaptive Histogram Equalization, random changes of brightness and + contrast, RandomGamma, and image quality reduction through compression. + + Args: + p (float): Probability of applying the augmentations. Must be between 0 and 1. + transforms (list | None): Custom Albumentations transforms, either objects or `A.to_dict()` dicts as stored + in checkpoints. If None, uses default transforms. + flip_idx (list[int] | None): Keypoint index mapping for reflection transforms. + """ + self.p = p + self.flip_idx = flip_idx + self.transform = None + prefix = colorstr("albumentations: ") + + try: + import os + + os.environ["NO_ALBUMENTATIONS_UPDATE"] = "1" # suppress Albumentations upgrade message + import albumentations as A + + check_version(A.__version__, "1.0.3", hard=True) # version requirement + if transforms and isinstance(transforms[0], dict): + transforms = [A.from_dict(t) for t in transforms] # restore transforms serialized by the trainer + topology_changing = getattr(A, "RandomGridShuffle", ()) + + def transform_types(t) -> tuple[bool, list]: + """Return the spatial flag and topology-changing transforms, recursing into compositions.""" + nested = [transform_types(x) for x in t.transforms] if isinstance(t, A.BaseCompose) else [] + return ( + isinstance(t, A.DualTransform) or any(x[0] for x in nested), + ([t] if isinstance(t, topology_changing) else []) + [y for x in nested for y in x[1]], + ) + + # Transforms, use custom transforms if provided, otherwise use defaults + T = ( + [ + A.Blur(p=0.01), + A.MedianBlur(p=0.01), + A.ToGray(p=0.01), + A.CLAHE(p=0.01), + A.RandomBrightnessContrast(p=0.0), + A.RandomGamma(p=0.0), + A.ImageCompression(quality_range=(75, 100), p=0.0), + ] + if transforms is None + else transforms + ) + + # Compose transforms + transform_types = [transform_types(transform) for transform in T] + self.contains_spatial = any(x[0] for x in transform_types) + self.topology_transforms = [transform for x in transform_types for transform in x[1]] + for transform in self.topology_transforms: + transform.set_deterministic(True, save_key="topology") + self.transform = ( + A.Compose( + T, + bbox_params=A.BboxParams(format="yolo", label_fields=["class_labels", "idx"]), + keypoint_params=A.KeypointParams(format="xy", remove_invisible=False, label_fields=["pidx"]), + ) + if self.contains_spatial + else A.Compose(T) + ) + if hasattr(self.transform, "set_random_seed"): + # Required for deterministic transforms in albumentations>=1.4.21 + self.transform.set_random_seed(torch.initial_seed()) + LOGGER.info(prefix + ", ".join(f"{x}".replace("always_apply=False, ", "") for x in T if x.p)) + except ImportError: # package not installed, skip + pass + except Exception as e: + LOGGER.info(f"{prefix}{e}") + + def __call__(self, labels: dict[str, Any]) -> dict[str, Any]: + """Apply Albumentations transformations to input labels. + + This method applies a series of image augmentations using the Albumentations library. It can perform both + spatial and non-spatial transformations on the input image and its corresponding labels. + + Args: + labels (dict[str, Any]): A dictionary containing image data and annotations. Expected keys are: + - 'img': np.ndarray representing the image + - 'cls': np.ndarray of class labels + - 'instances': object containing bounding boxes and other instance information + - 'semantic_mask': optional np.ndarray of semantic class IDs + - 'depth': optional np.ndarray of metric depth values + + Returns: + (dict[str, Any]): The input dictionary with augmented image and updated annotations. + + Examples: + >>> transform = Albumentations(p=0.5) + >>> labels = { + ... "img": np.random.rand(640, 640, 3), + ... "cls": np.array([0, 1]), + ... "instances": Instances( + ... bboxes=np.array([[0, 0, 1, 1], [0.5, 0.5, 0.8, 0.8]]), segments=np.zeros((0, 1000, 2)) + ... ), + ... } + >>> augmented = transform(labels) + >>> assert augmented["img"].shape == (640, 640, 3) + + Notes: + - The method applies transformations with probability self.p. + - Spatial transforms update bounding boxes, while non-spatial transforms only modify the image. + - Requires the Albumentations library to be installed. + """ + if self.transform is None or random.random() >= self.p: + return labels + + im = labels["img"] + if im.shape[2] not in {1, 3}: # Albumentations supports grayscale and color images only + return labels + + if self.contains_spatial: + cls = labels["cls"] + key = "semantic_mask" if labels.get("semantic_mask") is not None else "depth" + mask = labels.get(key) + instances = labels["instances"] + instances.convert_bbox("xywh") + instances.normalize(*im.shape[:2][::-1]) + segments, keypoints = instances.segments, instances.keypoints + h, w = im.shape[:2] + points = segments.reshape(-1, 2) + if keypoints is not None: + points = np.concatenate((points, keypoints[..., :2].reshape(-1, 2))) + points = (points * (w, h)).astype(np.float32) + annotation_points = len(points) + if keypoints is not None: + points = np.concatenate((points, np.array(((0, 0), (w, 0), (0, h)), dtype=np.float32))) + new = self.transform( + image=im, + bboxes=instances.bboxes, + class_labels=cls, + idx=np.arange(len(cls)), + keypoints=points, + pidx=np.arange(len(points)), + **({"topology": {}} if self.topology_transforms else {}), + **({"mask": mask} if mask is not None else {}), + ) + if (segments.size or keypoints is not None) and new.get("topology"): + raise NotImplementedError("RandomGridShuffle cannot preserve polygon or keypoint topology") + if mask is not None or len(new["class_labels"]) or not len(cls): + h, w = new["image"].shape[:2] + i = np.array(new["idx"], dtype=int) + n = segments.size // 2 + lost = np.ones(len(points), bool) + lost[np.array(new["pidx"], dtype=int)] = False + moved = points.copy() + moved[~lost] = np.array(new["keypoints"], dtype=np.float32) + if n: + segment_lost = lost[:n].reshape(segments.shape[:2]) + segment_points = moved[:n].reshape(segments.shape) + i = i[~segment_lost.all(1)[i]] + for segment, missing in zip(segment_points, segment_lost): + v = np.flatnonzero(~missing) + if len(v) and missing.any(): + segment[missing] = segment[ + v[np.searchsorted(v, np.flatnonzero(missing)).clip(0, len(v) - 1)] + ] + moved[:n] = segment_points.reshape(-1, 2) + if keypoints is not None: + xy = moved[n:annotation_points].reshape(*keypoints.shape[:2], 2)[i] + out = ((xy < 0) | (xy > (w, h))).any(-1, keepdims=True) + gone = lost[n:annotation_points].reshape(*keypoints.shape[:2], 1)[i] | out + keypoints = np.concatenate((xy.clip(0, (w, h)), np.where(gone, 0, keypoints[i][..., 2:])), -1) + anchors = moved[annotation_points:] + a, b = anchors[1] - anchors[0], anchors[2] - anchors[0] + reflected = not lost[annotation_points:].any() and a[0] * b[1] - a[1] * b[0] < 0 + if self.flip_idx and reflected: + keypoints = np.ascontiguousarray(keypoints[:, self.flip_idx]) + if n: + segments = moved[:n].reshape(segments.shape)[i] + bboxes = np.array([segment2box(s, w, h) for s in segments], np.float32).reshape(-1, 4) + segments[..., 0] = segments[..., 0].clip(bboxes[:, 0:1], bboxes[:, 2:3]) + segments[..., 1] = segments[..., 1].clip(bboxes[:, 1:2], bboxes[:, 3:4]) + instances = Instances(bboxes, segments, keypoints, bbox_format="xyxy", normalized=False) + instances.normalize(w, h) + else: + if keypoints is not None: + keypoints[..., 0] /= w + keypoints[..., 1] /= h + instances.update(np.array(new["bboxes"], dtype=np.float32).reshape(-1, 4), keypoints=keypoints) + labels["img"] = new["image"] + labels["cls"] = cls[i].reshape(-1, 1) + labels["instances"] = instances + if mask is not None: + labels[key] = new["mask"] + else: + labels["img"] = self.transform(image=labels["img"])["image"] # transformed + + return labels + + +class Format(BaseTransform): + """A class for formatting image annotations for object detection, instance segmentation, and pose estimation tasks. + + This class standardizes image and instance annotations to be used by the `collate_fn` in PyTorch DataLoader. + + Attributes: + bbox_format (str): Format for bounding boxes. Options are 'xywh' or 'xyxy'. + normalize (bool): Whether to normalize bounding boxes. + return_mask (bool): Whether to return instance masks for segmentation. + return_keypoint (bool): Whether to return keypoints for pose estimation. + return_obb (bool): Whether to return oriented bounding boxes. + mask_ratio (int): Downsample ratio for masks. + mask_overlap (bool): Whether to overlap masks. + batch_idx (bool): Whether to keep batch indexes. + bgr (float): The probability to return BGR images. + + Methods: + __call__: Format labels dictionary with image, classes, bounding boxes, and optionally masks and keypoints. + _format_img: Convert image from Numpy array to PyTorch tensor. + _format_segments: Convert polygon points to bitmap masks. + + Examples: + >>> formatter = Format(bbox_format="xywh", normalize=True, return_mask=True) + >>> formatted_labels = formatter(labels) + >>> img = formatted_labels["img"] + >>> bboxes = formatted_labels["bboxes"] + >>> masks = formatted_labels["masks"] + """ + + def __init__( + self, + bbox_format: str = "xywh", + normalize: bool = True, + return_mask: bool = False, + return_keypoint: bool = False, + return_obb: bool = False, + mask_ratio: int = 4, + mask_overlap: bool = True, + batch_idx: bool = True, + bgr: float = 0.0, + ): + """Initialize the Format class with given parameters for image and instance annotation formatting. + + This class standardizes image and instance annotations for object detection, instance segmentation, and pose + estimation tasks, preparing them for use in PyTorch DataLoader's `collate_fn`. + + Args: + bbox_format (str): Format for bounding boxes. Options are 'xywh', 'xyxy', etc. + normalize (bool): Whether to normalize bounding boxes to [0,1]. + return_mask (bool): If True, returns instance masks for segmentation tasks. + return_keypoint (bool): If True, returns keypoints for pose estimation tasks. + return_obb (bool): If True, returns oriented bounding boxes. + mask_ratio (int): Downsample ratio for masks. + mask_overlap (bool): If True, allows mask overlap. + batch_idx (bool): If True, keeps batch indexes. + bgr (float): Probability of returning BGR images instead of RGB. + """ + self.bbox_format = bbox_format + self.normalize = normalize + self.return_mask = return_mask # set False when training detection only + self.return_keypoint = return_keypoint + self.return_obb = return_obb + self.mask_ratio = mask_ratio + self.mask_overlap = mask_overlap + self.batch_idx = batch_idx # keep the batch indexes + self.bgr = bgr + + def get_params(self, labels: dict[str, Any]) -> dict[str, Any]: + """Compute formatting parameters shared across image and instance formatting. + + Extracts image dimensions and pops instance annotations from labels, converting bounding box format + and denormalizing coordinates for downstream tensor creation. + + Args: + labels (dict[str, Any]): Input labels dictionary containing 'img', 'cls', and 'instances'. + + Returns: + (dict[str, Any]): Parameters including 'h', 'w', 'cls', 'instances', and 'nl'. + """ + img = labels.get("img") + h, w = img.shape[:2] if img is not None else (0, 0) + cls = labels.pop("cls", np.array([])) + instances = labels.pop("instances", None) + if instances is not None: + instances.convert_bbox(format=self.bbox_format) + instances.denormalize(w, h) + return {"h": h, "w": w, "cls": cls, "instances": instances, "nl": len(instances) if instances else 0} + + def apply_image(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Format image from Numpy array to PyTorch tensor. + + Args: + labels (dict[str, Any]): Dictionary containing 'img' as a numpy array. + params (dict[str, Any] | None): Unused parameters for API compatibility. + + Returns: + (dict[str, Any]): Updated labels with 'img' as a PyTorch tensor. + """ + img = labels.pop("img", None) + if img is not None: + labels["img"] = self._format_img(img) + return labels + + def apply_instances(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Format instance annotations into PyTorch tensors. + + Converts class labels, bounding boxes, masks, and keypoints into tensors suitable for + collation in PyTorch DataLoader. + + Args: + labels (dict[str, Any]): Dictionary to populate with formatted tensors. + params (dict[str, Any]): Parameters from get_params containing 'h', 'w', 'cls', 'instances', 'nl'. + + Returns: + (dict[str, Any]): Updated labels with formatted instance tensors. + """ + cls = params.get("cls", np.array([])) + instances = params.get("instances") + assert instances is not None, "instances are required for Format.apply_instances" + h = params.get("h", 0) + w = params.get("w", 0) + nl = params.get("nl", 0) + + if self.return_mask: + if self.mask_ratio > min(h, w): + raise ValueError( + f"mask_ratio={self.mask_ratio} downsamples imgsz={(h, w)} masks to zero size; use mask_ratio <= {min(h, w)}" + ) + if nl: + masks, instances, cls = self._format_segments(instances, cls, w, h) + masks = torch.from_numpy(masks) + cls_tensor = torch.from_numpy(cls.squeeze(1)) + if not masks.shape[0] or not cls_tensor.numel(): + sem_masks = torch.zeros(h // self.mask_ratio, w // self.mask_ratio) + elif self.mask_overlap: + sem_masks = cls_tensor[masks[0].long() - 1] # (H, W) from (1, H, W) instance indices + else: + # Create sem_masks consistent with mask_overlap=True + sem_masks = (masks * cls_tensor[:, None, None]).max(0).values # (H, W) from (N, H, W) binary + overlap = masks.sum(dim=0) > 1 # (H, W) + if overlap.any(): + weights = masks.sum(axis=(1, 2)) + weighted_masks = masks * weights[:, None, None] # (N, H, W) + weighted_masks[masks == 0] = weights.max() + 1 # handle background + smallest_idx = weighted_masks.argmin(dim=0) # (H, W) + sem_masks[overlap] = cls_tensor[smallest_idx[overlap]] + else: + masks = torch.zeros(1 if self.mask_overlap else nl, h // self.mask_ratio, w // self.mask_ratio) + sem_masks = torch.zeros(h // self.mask_ratio, w // self.mask_ratio) + labels["masks"] = masks + labels["sem_masks"] = sem_masks.float() + labels["cls"] = torch.from_numpy(cls) if nl else torch.zeros(nl, 1) + labels["bboxes"] = torch.from_numpy(instances.bboxes) if nl else torch.zeros((nl, 4)) + if self.return_keypoint: + labels["keypoints"] = ( + torch.empty(0, 3) if instances.keypoints is None else torch.from_numpy(instances.keypoints) + ) + if self.normalize: + labels["keypoints"][..., 0] /= w + labels["keypoints"][..., 1] /= h + if self.return_obb: + labels["bboxes"] = xyxyxyxy2xywhr(torch.from_numpy(instances.segments)) + # NOTE: need to normalize obb in xywhr format for width-height consistency + if self.normalize: + labels["bboxes"][:, [0, 2]] /= w + labels["bboxes"][:, [1, 3]] /= h + # Then we can use collate_fn + if self.batch_idx: + labels["batch_idx"] = torch.zeros(nl) + return labels + + def _format_img(self, img: np.ndarray) -> torch.Tensor: + """Format an image for YOLO from a Numpy array to a PyTorch tensor. + + This function performs the following operations: + 1. Ensures the image has 3 dimensions (adds a channel dimension if needed). + 2. Transposes the image from HWC to CHW format. + 3. Optionally reverses the color channels (e.g., BGR to RGB) based on the bgr probability. + 4. Converts the image to a contiguous array. + 5. Converts the Numpy array to a PyTorch tensor. + + Args: + img (np.ndarray): Input image as a Numpy array with shape (H, W, C) or (H, W). + + Returns: + (torch.Tensor): Formatted image as a PyTorch tensor with shape (C, H, W). + + Examples: + >>> import numpy as np + >>> img = np.random.rand(100, 100, 3) + >>> formatted_img = self._format_img(img) + >>> print(formatted_img.shape) + torch.Size([3, 100, 100]) + """ + if len(img.shape) < 3: + img = img[..., None] + img = img.transpose(2, 0, 1) + img = np.ascontiguousarray(img[::-1] if random.uniform(0, 1) > self.bgr and img.shape[0] == 3 else img) + img = torch.from_numpy(img) + return img + + def _format_segments( + self, instances: Instances, cls: np.ndarray, w: int, h: int + ) -> tuple[np.ndarray, Instances, np.ndarray]: + """Convert polygon segments to bitmap masks. + + Args: + instances (Instances): Object containing segment information. + cls (np.ndarray): Class labels for each instance. + w (int): Width of the image. + h (int): Height of the image. + + Returns: + masks (np.ndarray): Bitmap masks with shape (N, H, W) or (1, H, W) if mask_overlap is True. + instances (Instances): Updated instances object with sorted segments if mask_overlap is True. + cls (np.ndarray): Updated class labels, sorted if mask_overlap is True. + + Notes: + - If self.mask_overlap is True, masks are overlapped and sorted by area. + - If self.mask_overlap is False, each mask is represented separately. + - Masks are downsampled according to self.mask_ratio. + """ + segments = instances.segments + if self.mask_overlap: + masks, sorted_idx = polygons2masks_overlap((h, w), segments, downsample_ratio=self.mask_ratio) + masks = masks[None] # (640, 640) -> (1, 640, 640) + instances = instances[sorted_idx] + cls = cls[sorted_idx] + else: + masks = polygons2masks((h, w), segments, color=1, downsample_ratio=self.mask_ratio) + + return masks, instances, cls + + +class SemanticFormat(Format): + """Format transform for semantic segmentation that converts images and masks to tensors. + + This transform handles the letterboxed semantic mask by resizing it to match the image dimensions and converts both + to the appropriate tensor formats. + """ + + def apply_image(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Format image and semantic mask for semantic segmentation. + + Args: + labels (dict[str, Any]): Dictionary containing 'img' and 'semantic_mask'. + params (dict[str, Any] | None): Unused parameters for API compatibility. + + Returns: + (dict[str, Any]): Updated labels with 'img' and 'semantic_mask' as tensors. + """ + img = labels.pop("img", None) + if img is not None: + labels["img"] = self._format_img(img) + mask = labels.get("semantic_mask") + if mask is not None: + labels["semantic_mask"] = torch.from_numpy(mask.copy()).to(torch.int32) + return labels + + def apply_instances(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Remove instance-level keys not needed for semantic segmentation. + + Args: + labels (dict[str, Any]): Dictionary to clean up. + params (dict[str, Any] | None): Unused parameters for API compatibility. + + Returns: + (dict[str, Any]): Updated labels with unused keys removed. + """ + for k in ("cls", "instances", "resized_shape", "ori_shape", "ratio_pad"): + labels.pop(k, None) + return labels + + +class LoadVisualPrompt(BaseTransform): + """Create visual prompts from bounding boxes or masks for model input.""" + + def __init__(self, scale_factor: float = 1 / 8) -> None: + """Initialize the LoadVisualPrompt with a scale factor. + + Args: + scale_factor (float): Factor to scale the input image dimensions. + """ + self.scale_factor = scale_factor + + @staticmethod + def make_mask(boxes: torch.Tensor, h: int, w: int) -> torch.Tensor: + """Create binary masks from bounding boxes. + + Args: + boxes (torch.Tensor): Bounding boxes in xyxy format, shape: (N, 4). + h (int): Height of the mask. + w (int): Width of the mask. + + Returns: + (torch.Tensor): Binary masks with shape (N, h, w). + """ + x1, y1, x2, y2 = torch.chunk(boxes[:, :, None], 4, 1) # x1 shape(n,1,1) + r = torch.arange(w)[None, None, :] # rows shape(1,1,w) + c = torch.arange(h)[None, :, None] # cols shape(1,h,1) + + return (r >= x1) * (r < x2) * (c >= y1) * (c < y2) + + def get_params(self, labels: dict[str, Any]) -> dict[str, Any]: + """Compute visual prompt parameters. + + Args: + labels (dict[str, Any]): Input labels dictionary. + + Returns: + (dict): Parameters including 'imgsz', 'bboxes', 'masks', and 'cls'. + """ + imgsz = labels["img"].shape[1:] + bboxes, masks = None, None + if "bboxes" in labels: + bboxes = labels["bboxes"] + bboxes = xywh2xyxy(bboxes) * torch.tensor(imgsz)[[1, 0, 1, 0]] # denormalize boxes + elif "masks" in labels: + masks = labels["masks"] + + cls = labels["cls"].squeeze(-1).to(torch.int) + return {"imgsz": imgsz, "bboxes": bboxes, "masks": masks, "cls": cls} + + def apply_image(self, labels: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]: + """Create visual prompts and add them to labels. + + Args: + labels (dict[str, Any]): Dictionary containing image data and annotations. + params (dict): Parameters from get_params. + + Returns: + (dict): Updated labels with visual prompts added. + """ + visuals = self.get_visuals(params["cls"], params["imgsz"], bboxes=params["bboxes"], masks=params["masks"]) + labels["visuals"] = visuals + return labels + + def get_visuals( + self, + category: int | np.ndarray | torch.Tensor, + shape: tuple[int, int], + bboxes: np.ndarray | torch.Tensor = None, + masks: np.ndarray | torch.Tensor = None, + ) -> torch.Tensor: + """Generate visual masks based on bounding boxes or masks. + + Args: + category (int | np.ndarray | torch.Tensor): The category labels for the objects. + shape (tuple[int, int]): The shape of the image (height, width). + bboxes (np.ndarray | torch.Tensor, optional): Bounding boxes for the objects, xyxy format. + masks (np.ndarray | torch.Tensor, optional): Masks for the objects. + + Returns: + (torch.Tensor): A tensor containing the visual masks for each category. + + Raises: + ValueError: If neither bboxes nor masks are provided. + """ + masksz = (int(shape[0] * self.scale_factor), int(shape[1] * self.scale_factor)) + if bboxes is not None: + if isinstance(bboxes, np.ndarray): + bboxes = torch.from_numpy(bboxes) + bboxes *= self.scale_factor + masks = self.make_mask(bboxes, *masksz).float() + elif masks is not None: + if isinstance(masks, np.ndarray): + masks = torch.from_numpy(masks) # (N, H, W) + masks = F.interpolate(masks.unsqueeze(1), masksz, mode="nearest").squeeze(1).float() + else: + raise ValueError("LoadVisualPrompt must have bboxes or masks in the label") + if not isinstance(category, torch.Tensor): + category = torch.tensor(category, dtype=torch.int) + cls_unique, inverse_indices = torch.unique(category, sorted=True, return_inverse=True) + # NOTE: `cls` indices from RandomLoadText should be continuous. + # if len(cls_unique): + # assert len(cls_unique) == cls_unique[-1] + 1, ( + # f"Expected a continuous range of class indices, but got {cls_unique}" + # ) + visuals = torch.zeros(cls_unique.shape[0], *masksz) + for idx, mask in zip(inverse_indices, masks): + visuals[idx] = torch.logical_or(visuals[idx], mask) + return visuals + + +class RandomLoadText(BaseTransform): + """Randomly sample positive and negative texts and update class indices accordingly. + + This class is responsible for sampling texts from a given set of class texts, including both positive (present in + the image) and negative (not present in the image) samples. It updates the class indices to reflect the sampled + texts and can optionally pad the text list to a fixed length. + + Attributes: + prompt_format (str): Format string for text prompts. + neg_samples (tuple[int, int]): Range for randomly sampling negative texts. + max_samples (int): Maximum number of different text samples in one image. + padding (bool): Whether to pad texts to max_samples. + padding_value (list[str]): The text used for padding when padding is True. + + Methods: + __call__: Process the input labels and return updated classes and texts. + + Examples: + >>> loader = RandomLoadText(prompt_format="Object: {}", neg_samples=(5, 10), max_samples=20) + >>> labels = {"cls": [0, 1, 2], "texts": [["cat"], ["dog"], ["bird"]], "instances": [...]} + >>> updated_labels = loader(labels) + >>> print(updated_labels["texts"]) + ['Object: cat', 'Object: dog', 'Object: bird', 'Object: elephant', 'Object: car'] + """ + + def __init__( + self, + prompt_format: str = "{}", + neg_samples: tuple[int, int] = (80, 80), + max_samples: int = 80, + padding: bool = False, + padding_value: list[str] | None = None, + ) -> None: + """Initialize the RandomLoadText class for randomly sampling positive and negative texts. + + This class is designed to randomly sample positive texts and negative texts, and update the class indices + accordingly to the number of samples. It can be used for text-based object detection tasks. + + Args: + prompt_format (str): Format string for the prompt. The format string should contain a single pair of curly + braces {} where the text will be inserted. + neg_samples (tuple[int, int]): A range to randomly sample negative texts. The first integer specifies the + minimum number of negative samples, and the second integer specifies the maximum. + max_samples (int): The maximum number of different text samples in one image. + padding (bool): Whether to pad texts to max_samples. If True, the number of texts will always be equal to + max_samples. + padding_value (list[str]): The padding text to use when padding is True. + """ + self.prompt_format = prompt_format + self.neg_samples = neg_samples + self.max_samples = max_samples + self.padding = padding + self.padding_value = padding_value if padding_value is not None else [""] + + def get_params(self, labels: dict[str, Any]) -> dict[str, Any]: + """Compute text sampling parameters. + + Args: + labels (dict[str, Any]): Input labels dictionary containing 'texts', 'cls', and 'instances'. + + Returns: + (dict): Parameters including 'valid_idx', 'new_cls', and 'texts'. + """ + assert "texts" in labels, "No texts found in labels." + class_texts = labels["texts"] + num_classes = len(class_texts) + cls = np.asarray(labels.pop("cls"), dtype=int) + pos_labels = np.unique(cls).tolist() + + if len(pos_labels) > self.max_samples: + pos_labels = random.sample(pos_labels, k=self.max_samples) + + neg_samples = min(min(num_classes, self.max_samples) - len(pos_labels), random.randint(*self.neg_samples)) + neg_labels = [i for i in range(num_classes) if i not in pos_labels] + neg_labels = random.sample(neg_labels, k=neg_samples) + + sampled_labels = pos_labels + neg_labels + # Randomness + # random.shuffle(sampled_labels) + + label2ids = {label: i for i, label in enumerate(sampled_labels)} + valid_idx = np.zeros(len(labels["instances"]), dtype=bool) + new_cls = [] + for i, label in enumerate(cls.squeeze(-1).tolist()): + if label not in label2ids: + continue + valid_idx[i] = True + new_cls.append([label2ids[label]]) + + # Randomly select one prompt when there's more than one prompts + texts = [] + for label in sampled_labels: + prompts = class_texts[label] + assert len(prompts) > 0 + prompt = self.prompt_format.format(prompts[random.randrange(len(prompts))]) + texts.append(prompt) + + if self.padding: + valid_labels = len(pos_labels) + len(neg_labels) + num_padding = self.max_samples - valid_labels + if num_padding > 0: + texts += random.choices(self.padding_value, k=num_padding) + + assert len(texts) == self.max_samples + + return {"valid_idx": valid_idx, "new_cls": np.array(new_cls), "texts": texts} + + def apply_instances(self, labels: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]: + """Filter instances and update class labels based on sampled texts. + + Args: + labels (dict[str, Any]): Dictionary containing 'instances' and 'cls'. + params (dict): Parameters from get_params. + + Returns: + (dict): Updated labels with filtered instances and new class/text entries. + """ + labels["instances"] = labels["instances"][params["valid_idx"]] + labels["cls"] = params["new_cls"] + labels["texts"] = params["texts"] + return labels + + +def v8_transforms(dataset, imgsz: int, hyp: IterableSimpleNamespace): + """Apply a series of image transformations for training. + + This function creates a composition of image augmentation techniques to prepare images for YOLO training. It + includes operations such as mosaic, copy-paste, random perspective, mixup, and various color adjustments. + + Args: + dataset (Dataset): The dataset object containing image data and annotations. + imgsz (int): The target image size for resizing. + hyp (IterableSimpleNamespace): A namespace of hyperparameters controlling various aspects of the + transformations. + + Returns: + (Compose): A composition of image transformations to be applied to the dataset. + + Examples: + >>> from ultralytics.cfg import DEFAULT_CFG + >>> from ultralytics.data.dataset import YOLODataset + >>> from ultralytics.utils import IterableSimpleNamespace + >>> dataset = YOLODataset(img_path="path/to/images", data={"names": {0: "person"}}, imgsz=640) + >>> hyp = IterableSimpleNamespace( + ... **{ + ... **vars(DEFAULT_CFG), + ... "mosaic": 1.0, + ... "copy_paste": 0.5, + ... "degrees": 10.0, + ... "translate": 0.2, + ... "scale": 0.9, + ... } + ... ) + >>> transforms = v8_transforms(dataset, imgsz=640, hyp=hyp) + >>> augmented_data = transforms(dataset[0]) + + >>> # With custom albumentations + >>> import albumentations as A + >>> augmentations = [A.Blur(p=0.01), A.CLAHE(p=0.01)] + >>> hyp.augmentations = augmentations + >>> transforms = v8_transforms(dataset, imgsz=640, hyp=hyp) + """ + mosaic = Mosaic(dataset, imgsz=imgsz, p=hyp.mosaic) + affine = RandomPerspective( + degrees=hyp.degrees, + translate=hyp.translate, + scale=hyp.scale, + shear=hyp.shear, + perspective=hyp.perspective, + size=(imgsz, imgsz), + preserve_obb=getattr(dataset, "use_obb", False), + ) + + pre_transform = Compose([mosaic, affine]) + if hyp.copy_paste_mode == "flip": + pre_transform.insert(1, CopyPaste(dataset, p=hyp.copy_paste, mode=hyp.copy_paste_mode)) + else: + pre_transform.append( + CopyPaste( + dataset, + pre_transform=Compose([Mosaic(dataset, imgsz=imgsz, p=hyp.mosaic), affine]), + p=hyp.copy_paste, + mode=hyp.copy_paste_mode, + ) + ) + flip_idx = dataset.data.get("flip_idx", []) # for keypoints augmentation + if getattr(dataset, "use_keypoints", False): + kpt_shape = dataset.data.get("kpt_shape", None) + if len(flip_idx) == 0 and (hyp.fliplr > 0.0 or hyp.flipud > 0.0): + hyp.fliplr = hyp.flipud = 0.0 # both fliplr and flipud require flip_idx + LOGGER.warning("No 'flip_idx' array defined in data.yaml, disabling 'fliplr' and 'flipud' augmentations.") + elif flip_idx and (len(flip_idx) != kpt_shape[0]): + raise ValueError(f"data.yaml flip_idx={flip_idx} length must be equal to kpt_shape[0]={kpt_shape[0]}") + + return Compose( + [ + pre_transform, + MixUp(dataset, pre_transform=pre_transform, p=hyp.mixup), + CutMix(dataset, pre_transform=pre_transform, p=hyp.cutmix), + Albumentations(p=1.0, transforms=getattr(hyp, "augmentations", None), flip_idx=flip_idx), + RandomHSV(hgain=hyp.hsv_h, sgain=hyp.hsv_s, vgain=hyp.hsv_v), + RandomFlip(direction="vertical", p=hyp.flipud, flip_idx=flip_idx), + RandomFlip(direction="horizontal", p=hyp.fliplr, flip_idx=flip_idx), + ] + ) # transforms + + +# Classification augmentations ----------------------------------------------------------------------------------------- +def classify_transforms( + size: tuple[int, int] | int = 224, + mean: tuple[float, float, float] = DEFAULT_MEAN, + std: tuple[float, float, float] = DEFAULT_STD, + interpolation: str = "BILINEAR", + crop_fraction: float | None = None, +): + """Create a composition of image transforms for classification tasks. + + This function generates a sequence of torchvision transforms suitable for preprocessing images for classification + models during evaluation or inference. The transforms include resizing, center cropping, conversion to tensor, and + normalization. + + Args: + size (tuple[int, int] | int): The target size for the transformed image. If an int, it defines the shortest + edge. If a tuple, it defines (height, width). + mean (tuple[float, float, float]): Mean values for each RGB channel used in normalization. + std (tuple[float, float, float]): Standard deviation values for each RGB channel used in normalization. + interpolation (str): Interpolation method of either 'NEAREST', 'BILINEAR' or 'BICUBIC'. + crop_fraction (float | None): Deprecated, will be removed in a future version. + + Returns: + (torchvision.transforms.Compose): A composition of torchvision transforms. + + Examples: + >>> transforms = classify_transforms(size=224) + >>> img = Image.open("path/to/image.jpg") + >>> transformed_img = transforms(img) + """ + import torchvision.transforms as T # scope for faster 'import ultralytics' + + scale_size = size if isinstance(size, (tuple, list)) and len(size) == 2 else (size, size) + + if crop_fraction: + deprecation_warn("crop_fraction") + + # Square target uses the scalar shortest-edge mode (preserves aspect); non-square resizes to the exact (h, w). + resize = scale_size[0] if scale_size[0] == scale_size[1] else scale_size + tfl = [ + T.Resize(resize, interpolation=getattr(T.InterpolationMode, interpolation)), + T.CenterCrop(size), + T.ToTensor(), + T.Normalize(mean=torch.tensor(mean), std=torch.tensor(std)), + ] + return T.Compose(tfl) + + +# Classification training augmentations -------------------------------------------------------------------------------- +def classify_augmentations( + size: int = 224, + mean: tuple[float, float, float] = DEFAULT_MEAN, + std: tuple[float, float, float] = DEFAULT_STD, + scale: tuple[float, float] | None = None, + ratio: tuple[float, float] | None = None, + hflip: float = 0.5, + vflip: float = 0.0, + auto_augment: str | None = None, + hsv_h: float = 0.015, # image HSV-Hue augmentation (fraction) + hsv_s: float = 0.4, # image HSV-Saturation augmentation (fraction) + hsv_v: float = 0.4, # image HSV-Value augmentation (fraction) + force_color_jitter: bool = False, + erasing: float = 0.0, + interpolation: str = "BILINEAR", +): + """Create a composition of image augmentation transforms for classification tasks. + + This function generates a set of image transformations suitable for training classification models. It includes + options for resizing, flipping, color jittering, auto augmentation, and random erasing. + + Args: + size (int): Target size for the image after transformations. + mean (tuple[float, float, float]): Mean values for each RGB channel used in normalization. + std (tuple[float, float, float]): Standard deviation values for each RGB channel used in normalization. + scale (tuple[float, float] | None): Range of the proportion of the original image area to crop. + ratio (tuple[float, float] | None): Range of aspect ratio for the cropped area. + hflip (float): Probability of horizontal flip. + vflip (float): Probability of vertical flip. + auto_augment (str | None): Auto augmentation policy. Can be 'randaugment', 'augmix', 'autoaugment' or None. + hsv_h (float): Image HSV-Hue augmentation factor. + hsv_s (float): Image HSV-Saturation augmentation factor. + hsv_v (float): Image HSV-Value augmentation factor. + force_color_jitter (bool): Whether to apply color jitter even if auto augment is enabled. + erasing (float): Probability of random erasing. + interpolation (str): Interpolation method of either 'NEAREST', 'BILINEAR' or 'BICUBIC'. + + Returns: + (torchvision.transforms.Compose): A composition of image augmentation transforms. + + Examples: + >>> transforms = classify_augmentations(size=224, auto_augment="randaugment") + >>> augmented_image = transforms(original_image) + """ + # Transforms to apply if Albumentations not installed + import torchvision.transforms as T # scope for faster 'import ultralytics' + + if not isinstance(size, int): + raise TypeError(f"classify_augmentations() size {size} must be integer, not (list, tuple)") + scale = tuple(scale or (0.08, 1.0)) # default imagenet scale range + ratio = tuple(ratio or (3.0 / 4.0, 4.0 / 3.0)) # default imagenet ratio range + interpolation = getattr(T.InterpolationMode, interpolation) + primary_tfl = [T.RandomResizedCrop(size, scale=scale, ratio=ratio, interpolation=interpolation)] + if hflip > 0.0: + primary_tfl.append(T.RandomHorizontalFlip(p=hflip)) + if vflip > 0.0: + primary_tfl.append(T.RandomVerticalFlip(p=vflip)) + + secondary_tfl = [] + disable_color_jitter = False + if auto_augment: + assert isinstance(auto_augment, str), f"Provided argument should be string, but got type {type(auto_augment)}" + # color jitter is typically disabled if AA/RA on, + # this allows override without breaking old hparm cfgs + disable_color_jitter = not force_color_jitter + + if auto_augment == "randaugment": + if TORCHVISION_0_11: + secondary_tfl.append(T.RandAugment(interpolation=interpolation)) + else: + LOGGER.warning('"auto_augment=randaugment" requires torchvision >= 0.11.0. Disabling it.') + + elif auto_augment == "augmix": + if TORCHVISION_0_13: + secondary_tfl.append(T.AugMix(interpolation=interpolation)) + else: + LOGGER.warning('"auto_augment=augmix" requires torchvision >= 0.13.0. Disabling it.') + + elif auto_augment == "autoaugment": + if TORCHVISION_0_10: + secondary_tfl.append(T.AutoAugment(interpolation=interpolation)) + else: + LOGGER.warning('"auto_augment=autoaugment" requires torchvision >= 0.10.0. Disabling it.') + + else: + raise ValueError( + f'Invalid auto_augment policy: {auto_augment}. Should be one of "randaugment", ' + f'"augmix", "autoaugment" or None' + ) + + if not disable_color_jitter: + secondary_tfl.append(T.ColorJitter(brightness=hsv_v, contrast=hsv_v, saturation=hsv_s, hue=hsv_h)) + + final_tfl = [ + T.ToTensor(), + T.Normalize(mean=torch.tensor(mean), std=torch.tensor(std)), + T.RandomErasing(p=erasing, inplace=True), + ] + + return T.Compose(primary_tfl + secondary_tfl + final_tfl) + + +class DepthFormat(Format): + """Format transform for monocular depth estimation: image via Format, depth map resized and tensorized. + + Mirrors SemanticFormat: the base Format.apply_image converts the image (HWC BGR -> CHW RGB tensor), and the + apply_depth hook (run after apply_image in BaseTransform.__call__) resizes the paired depth map to the letterboxed + image size and emits it as a (1, H, W) float tensor. + """ + + def apply_depth(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Resize depth to the formatted image size (nearest) and emit a (1, H, W) float tensor. + + Args: + labels (dict[str, Any]): Dictionary with 'img' (already a CHW tensor) and optionally 'depth'. + params (dict[str, Any] | None): Unused parameters for API compatibility. + + Returns: + (dict[str, Any]): Updated labels with 'depth' as a (1, H, W) float tensor. + """ + depth = labels.get("depth") + if depth is None or "img" not in labels: + return labels + _, h, w = labels["img"].shape + if depth.shape[:2] != (h, w): + depth = cv2.resize(depth, (w, h), interpolation=cv2.INTER_NEAREST) + labels["depth"] = torch.from_numpy(np.ascontiguousarray(depth[None])).float() + return labels + + def apply_instances(self, labels: dict[str, Any], params: dict[str, Any] | None = None) -> dict[str, Any]: + """Remove instance-level keys not needed for depth estimation. + + Args: + labels (dict[str, Any]): Dictionary to clean up. + params (dict[str, Any] | None): Unused parameters for API compatibility. + + Returns: + (dict[str, Any]): Updated labels with unused keys removed. + """ + for k in ("cls", "instances", "resized_shape", "ori_shape", "ratio_pad"): + labels.pop(k, None) + return labels + + +# NOTE: keep this class for backward compatibility +class ClassifyLetterBox: + """A class for resizing and padding images for classification tasks. + + This class is designed to be part of a transformation pipeline, e.g., T.Compose([LetterBox(size), ToTensor()]). It + resizes and pads images to a specified size while maintaining the original aspect ratio. + + Attributes: + h (int): Target height of the image. + w (int): Target width of the image. + auto (bool): If True, automatically calculates the short side using stride. + stride (int): The stride value, used when 'auto' is True. + + Methods: + __call__: Apply the letterbox transformation to an input image. + + Examples: + >>> transform = ClassifyLetterBox(size=(640, 640), auto=False, stride=32) + >>> img = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) + >>> result = transform(img) + >>> print(result.shape) + (640, 640, 3) + """ + + def __init__(self, size: int | tuple[int, int] = (640, 640), auto: bool = False, stride: int = 32): + """Initialize the ClassifyLetterBox object for image preprocessing. + + This class is designed to be part of a transformation pipeline for image classification tasks. It resizes and + pads images to a specified size while maintaining the original aspect ratio. + + Args: + size (int | tuple[int, int]): Target size for the letterboxed image. If an int, a square image of (size, + size) is created. If a tuple, it should be (height, width). + auto (bool): If True, automatically calculates the short side based on stride. + stride (int): The stride value, used when 'auto' is True. + """ + super().__init__() + self.h, self.w = (size, size) if isinstance(size, int) else size + self.auto = auto # pass max size integer, automatically solve for short side using stride + self.stride = stride # used with auto + + def __call__(self, im: np.ndarray) -> np.ndarray: + """Resize and pad an image using the letterbox method. + + This method resizes the input image to fit within the specified dimensions while maintaining its aspect ratio, + then pads the resized image to match the target size. + + Args: + im (np.ndarray): Input image as a numpy array with shape (H, W, C). + + Returns: + (np.ndarray): Resized and padded image as a numpy array with shape (hs, ws, 3), where hs and ws are the + target height and width respectively. + + Examples: + >>> letterbox = ClassifyLetterBox(size=(640, 640)) + >>> image = np.random.randint(0, 255, (720, 1280, 3), dtype=np.uint8) + >>> resized_image = letterbox(image) + >>> print(resized_image.shape) + (640, 640, 3) + """ + imh, imw = im.shape[:2] + r = min(self.h / imh, self.w / imw) # ratio of new/old dimensions + h, w = round(imh * r), round(imw * r) # resized image dimensions + + # Calculate padding dimensions + hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else (self.h, self.w) + top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1) + + # Create padded image + im_out = np.full((hs, ws, 3), 114, dtype=im.dtype) + im_out[top : top + h, left : left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR) + return im_out + + +# NOTE: keep this class for backward compatibility +class CenterCrop: + """Apply center cropping to images for classification tasks. + + This class performs center cropping on input images, resizing them to a specified size while maintaining the aspect + ratio. It is designed to be part of a transformation pipeline, e.g., T.Compose([CenterCrop(size), ToTensor()]). + + Attributes: + h (int): Target height of the cropped image. + w (int): Target width of the cropped image. + + Methods: + __call__: Apply the center crop transformation to an input image. + + Examples: + >>> transform = CenterCrop(640) + >>> image = np.random.randint(0, 255, (1080, 1920, 3), dtype=np.uint8) + >>> cropped_image = transform(image) + >>> print(cropped_image.shape) + (640, 640, 3) + """ + + def __init__(self, size: int | tuple[int, int] = (640, 640)): + """Initialize the CenterCrop object for image preprocessing. + + This class is designed to be part of a transformation pipeline, e.g., T.Compose([CenterCrop(size), ToTensor()]). + It performs a center crop on input images to a specified size. + + Args: + size (int | tuple[int, int]): The desired output size of the crop. If size is an int, a square crop (size, + size) is made. If size is a sequence like (h, w), it is used as the output size. + """ + super().__init__() + self.h, self.w = (size, size) if isinstance(size, int) else size + + def __call__(self, im: Image.Image | np.ndarray) -> np.ndarray: + """Apply center cropping to an input image. + + This method crops the largest centered square from the image and resizes it to the specified dimensions. + + Args: + im (np.ndarray | PIL.Image.Image): The input image as a numpy array of shape (H, W, C) or a PIL Image + object. + + Returns: + (np.ndarray): The center-cropped and resized image as a numpy array of shape (self.h, self.w, C). + + Examples: + >>> transform = CenterCrop(size=224) + >>> image = np.random.randint(0, 255, (640, 480, 3), dtype=np.uint8) + >>> cropped_image = transform(image) + >>> assert cropped_image.shape == (224, 224, 3) + """ + if isinstance(im, Image.Image): # convert from PIL to numpy array if required + im = np.asarray(im) + imh, imw = im.shape[:2] + m = min(imh, imw) # min dimension + top, left = (imh - m) // 2, (imw - m) // 2 + return cv2.resize(im[top : top + m, left : left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR) + + +# NOTE: keep this class for backward compatibility +class ToTensor: + """Convert an image from a numpy array to a PyTorch tensor. + + This class is designed to be part of a transformation pipeline, e.g., T.Compose([LetterBox(size), ToTensor()]). + + Attributes: + half (bool): If True, converts the image to half precision (float16). + + Methods: + __call__: Apply the tensor conversion to an input image. + + Examples: + >>> transform = ToTensor(half=True) + >>> img = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8) + >>> tensor_img = transform(img) + >>> print(tensor_img.shape, tensor_img.dtype) + torch.Size([3, 640, 640]) torch.float16 + + Notes: + The input image is expected to be in BGR format with shape (H, W, C). + The output tensor will be in BGR format with shape (C, H, W), normalized to [0, 1]. + """ + + def __init__(self, half: bool = False): + """Initialize the ToTensor object for converting images to PyTorch tensors. + + This class is designed to be used as part of a transformation pipeline for image preprocessing in the + Ultralytics YOLO framework. It converts numpy arrays or PIL Images to PyTorch tensors, with an option for + half-precision (float16) conversion. + + Args: + half (bool): If True, converts the tensor to half precision (float16). + """ + super().__init__() + self.half = half + + def __call__(self, im: np.ndarray) -> torch.Tensor: + """Transform an image from a numpy array to a PyTorch tensor. + + This method converts the input image from a numpy array to a PyTorch tensor, applying optional half-precision + conversion and normalization. The image is transposed from HWC to CHW format. + + Args: + im (np.ndarray): Input image as a numpy array with shape (H, W, C) in BGR order. + + Returns: + (torch.Tensor): The transformed image as a PyTorch tensor in float32 or float16, normalized to [0, 1] with + shape (C, H, W) in BGR order. + + Examples: + >>> transform = ToTensor(half=True) + >>> img = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8) + >>> tensor_img = transform(img) + >>> print(tensor_img.shape, tensor_img.dtype) + torch.Size([3, 640, 640]) torch.float16 + """ + im = np.ascontiguousarray(im.transpose((2, 0, 1))) # HWC to CHW -> contiguous + im = torch.from_numpy(im) # to torch + im = im.half() if self.half else im.float() # uint8 to fp16/32 + im /= 255.0 # 0-255 to 0.0-1.0 + return im diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/base.py b/.venv/lib/python3.12/site-packages/ultralytics/data/base.py new file mode 100644 index 0000000000000000000000000000000000000000..362c628d68d3dd894097932e43081e254f88d142 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/base.py @@ -0,0 +1,489 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import glob +import math +import os +import random +import shutil +from copy import copy, deepcopy +from multiprocessing.pool import ThreadPool +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from ultralytics.data.utils import FORMATS_HELP_MSG, HELP_URL, IMG_FORMATS, check_file_speeds, get_split_fraction +from ultralytics.utils import DEFAULT_CFG, LOCAL_RANK, LOGGER, NUM_THREADS, TQDM +from ultralytics.utils.patches import imread + + +class BaseDataset(Dataset): + """Base dataset class for loading and processing image data. + + This class provides core functionality for loading images, caching, and preparing data for training and inference in + object detection tasks. + + Attributes: + img_path (str | list[str]): Path to the folder containing images. + imgsz (int): Target image size for resizing. + augment (bool): Whether to apply data augmentation. + single_cls (bool): Whether to treat all objects as a single class. + prefix (str): Prefix to print in log messages. + fraction (float | int): Dataset ratio or image count to use. + channels (int): Number of channels in the images (1 for grayscale, 3 for color). Color images loaded with OpenCV + are in BGR channel order. + cv2_flag (int): OpenCV flag for reading images. + im_files (list[str]): List of image file paths. + labels (list[dict]): List of label data dictionaries. + ni (int): Number of images in the dataset. + rect (bool): Whether to use rectangular training. + batch_size (int): Size of batches. + stride (int): Stride used in the model. + pad (float): Padding value. + buffer (list): Buffer for mosaic images. + max_buffer_length (int): Maximum buffer size. + ims (list): List of loaded images. + im_hw0 (list): List of original image dimensions (h, w). + im_hw (list): List of resized image dimensions (h, w). + npy_files (list[Path]): List of numpy file paths. + cache (str | None): Cache setting ('ram', 'disk', or None for no caching). + transforms (callable): Image transformation function. + batch_shapes (np.ndarray): Batch shapes for rectangular training. + batch (np.ndarray): Batch index of each image. + + Methods: + get_img_files: Read image files from the specified path. + update_labels: Update labels to include only specified classes. + load_image: Load an image from the dataset. + cache_images: Cache images to memory or disk. + cache_images_to_disk: Save an image as an *.npy file for faster loading. + check_cache_disk: Check image caching requirements vs available disk space. + check_cache_ram: Check image caching requirements vs available memory. + set_rectangle: Sort images by aspect ratio and set batch shapes for rectangular training. + get_image_and_label: Get and return label information from the dataset. + update_labels_info: Custom label format method to be implemented by subclasses. + build_transforms: Build transformation pipeline to be implemented by subclasses. + get_labels: Get labels method to be implemented by subclasses. + """ + + class _ImageCache: + """Store images in one tensor, shared copy-on-write by fork workers and as shared memory by pickled ones.""" + + def __init__(self, images: list[np.ndarray]): + """Pack images into one contiguous uint8 tensor and their layouts into NumPy arrays.""" + self.shapes = np.array([im.shape for im in images]) + self.dtypes = np.array([im.dtype.str for im in images]) + self.offsets = np.concatenate(([0], np.cumsum([im.nbytes for im in images]))) + self.buffer = torch.empty(int(self.offsets[-1]), dtype=torch.uint8) + buffer = self.buffer.numpy() + for i, im in enumerate(images): + buffer[self.offsets[i] : self.offsets[i + 1]] = im.reshape(-1).view(np.uint8) + images[i] = None + + def __getitem__(self, i: int) -> np.ndarray: + """Return an image view by index.""" + i = range(len(self.shapes))[i] + return ( + self.buffer.numpy()[self.offsets[i] : self.offsets[i + 1]].view(self.dtypes[i]).reshape(self.shapes[i]) + ) + + def __getstate__(self) -> dict[str, Any]: + """Pickle the buffer by value, as each worker's own copy, when Linux shared memory is too small to share it.""" + state = self.__dict__.copy() + shm = Path("/dev/shm") # also carries worker batches, so require the same 2x margin as check_cache_ram() + if not self.buffer.is_shared() and shm.is_dir() and shutil.disk_usage(shm).free < 2 * self.offsets[-1]: + LOGGER.warning(f"{shm} too small to share {self.offsets[-1] / (1 << 30):.1f}GB image cache, copying it") + state["buffer"] = self.buffer.numpy() + return state + + def __setstate__(self, state: dict[str, Any]): + """Restore the buffer as a tensor.""" + state["buffer"] = torch.as_tensor(state["buffer"]) + self.__dict__.update(state) + + def __init__( + self, + img_path: str | list[str], + imgsz: int = 640, + cache: bool | str = False, + augment: bool = True, + hyp: dict[str, Any] = DEFAULT_CFG, + prefix: str = "", + rect: bool = False, + batch_size: int = 16, + stride: int = 32, + pad: float = 0.5, + single_cls: bool = False, + classes: list[int] | None = None, + fraction: float = 1.0, + channels: int = 3, + ): + """Initialize BaseDataset with given configuration and options. + + Args: + img_path (str | list[str]): Path to the folder containing images or list of image paths. + imgsz (int): Image size for resizing. + cache (bool | str): Cache images to RAM or disk during training. + augment (bool): If True, data augmentation is applied. + hyp (dict[str, Any]): Hyperparameters to apply data augmentation. + prefix (str): Prefix to print in log messages. + rect (bool): If True, rectangular training is used. + batch_size (int): Size of batches. + stride (int): Stride used in the model. + pad (float): Padding value. + single_cls (bool): If True, single class training is used. + classes (list[int], optional): List of included classes. + fraction (float | int): Dataset ratio or image count to use. + channels (int): Number of channels in the images (1 for grayscale, 3 for color). Color images loaded with + OpenCV are in BGR channel order. + """ + super().__init__() + self.img_path = img_path + self.imgsz = imgsz + self.augment = augment + self.single_cls = single_cls + self.prefix = prefix + self.fraction = get_split_fraction(fraction, "train") + self.channels = channels + self.cv2_flag = cv2.IMREAD_GRAYSCALE if channels == 1 else cv2.IMREAD_COLOR + self.im_files = self.get_img_files(self.img_path) + self.labels = self.get_labels() + self.update_labels(include_class=classes) # single_cls and include_class + self.ni = len(self.labels) # number of images + self.rect = rect + self.batch_size = batch_size + self.stride = stride + self.pad = pad + if self.rect: + assert self.batch_size is not None + self.set_rectangle() + + # Buffer thread for mosaic images + self.buffer = [] # buffer size = batch size + self.max_buffer_length = min((self.ni, self.batch_size * 8, 1000)) if self.augment else 0 + + # Cache images (options are cache = True, False, None, "ram", "disk") + self.ims, self.im_hw0, self.im_hw = [None] * self.ni, [None] * self.ni, [None] * self.ni + self.npy_files = [Path(f).with_suffix(".npy") for f in self.im_files] + self.cache = cache.lower() if isinstance(cache, str) else "ram" if cache is True else None + if self.cache == "ram" and self.check_cache_ram(): + if hyp.deterministic: + LOGGER.warning( + "cache='ram' may produce non-deterministic training results. " + "Consider cache='disk' as a deterministic alternative if your disk space allows." + ) + self.cache_images() + elif self.cache == "disk" and self.check_cache_disk(): + self.cache_images() + + # Transforms + self.transforms = self.build_transforms(hyp=copy(hyp)) # subclasses zero unsupported keys, never the caller's + + def get_img_files(self, img_path: str | list[str]) -> list[str]: + """Read image files from the specified path. + + Args: + img_path (str | list[str]): Path or list of paths to image directories or files. + + Returns: + (list[str]): List of image file paths. + + Raises: + FileNotFoundError: If no images are found or the path doesn't exist. + """ + try: + f = [] # image files + for p in img_path if isinstance(img_path, list) else [img_path]: + p = Path(p) # os-agnostic + if p.is_dir(): # dir + f += glob.glob(str(Path(glob.escape(p)) / "**" / "*.*"), recursive=True) + # F = list(p.rglob('*.*')) # pathlib + elif p.is_file(): # file + with open(p, encoding="utf-8") as t: + t = t.read().strip().splitlines() + parent = str(p.parent) + os.sep + f += [x.replace("./", parent, 1) if x.startswith("./") else x for x in t] # local to global + # F += [p.parent / x.lstrip(os.sep) for x in t] # local to global (pathlib) + else: + raise FileNotFoundError(f"{self.prefix}{p} does not exist") + im_files = sorted(x.replace("/", os.sep) for x in f if x.rpartition(".")[-1].lower() in IMG_FORMATS) + # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS]) # pathlib + assert im_files, f"{self.prefix}No images found in {img_path}. {FORMATS_HELP_MSG}" + except Exception as e: + raise FileNotFoundError(f"{self.prefix}Error loading data from {img_path}\n{HELP_URL}") from e + count = self.fraction if isinstance(self.fraction, int) else max(1, round(len(im_files) * self.fraction)) + im_files = im_files[:count] if count < len(im_files) else im_files + check_file_speeds(im_files, prefix=self.prefix) # check image read speeds + return im_files + + def update_labels(self, include_class: list[int] | None) -> None: + """Update labels to include only specified classes. + + Args: + include_class (list[int], optional): List of classes to include. If None, all classes are included. + """ + include_class_array = np.array(include_class).reshape(1, -1) + for i in range(len(self.labels)): + if include_class is not None: + cls = self.labels[i]["cls"] + bboxes = self.labels[i]["bboxes"] + segments = self.labels[i]["segments"] + keypoints = self.labels[i].get("keypoints") + j = (cls == include_class_array).any(1) + self.labels[i]["cls"] = cls[j] + self.labels[i]["bboxes"] = bboxes[j] + if segments: + self.labels[i]["segments"] = [segments[si] for si, idx in enumerate(j) if idx] + if keypoints is not None: + self.labels[i]["keypoints"] = keypoints[j] + if self.single_cls: + self.labels[i]["cls"][:] = 0 + + def load_image( + self, i: int, rect_mode: bool = True, resize_short: bool = False + ) -> tuple[np.ndarray, tuple[int, int], tuple[int, int]]: + """Load an image from dataset index 'i'. + + Args: + i (int): Index of the image to load. + rect_mode (bool): Whether to use rectangular resizing (long side to imgsz). + resize_short (bool): Whether to resize the shorter side to imgsz while maintaining aspect ratio. Overrides + rect_mode when True. + + Returns: + im (np.ndarray): Loaded image as a NumPy array. + hw_original (tuple[int, int]): Original image dimensions in (height, width) format. + hw_resized (tuple[int, int]): Resized image dimensions in (height, width) format. + + Raises: + FileNotFoundError: If the image file is not found. + """ + im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i] + if im is None: # not cached in RAM + if fn.exists(): # load npy + try: + im = np.load(fn) + npy_channels = im.shape[-1] if im.ndim >= 3 else 1 + if npy_channels != self.channels: + LOGGER.warning( + f"{self.prefix}Removing stale *.npy image file {fn} with {npy_channels} channels, expected {self.channels}" + ) + Path(fn).unlink(missing_ok=True) + im = imread(f, flags=self.cv2_flag) + except Exception as e: + LOGGER.warning(f"{self.prefix}Removing corrupt *.npy image file {fn} due to: {e}") + Path(fn).unlink(missing_ok=True) + im = imread(f, flags=self.cv2_flag) # BGR + else: # read image + im = imread(f, flags=self.cv2_flag) # BGR + if im is None: + raise FileNotFoundError(f"Image Not Found {f}") + + h0, w0 = im.shape[:2] # orig hw + if rect_mode: # resize long side to imgsz while maintaining aspect ratio + if resize_short: # resize short side to imgsz while maintaining aspect ratio + r = self.imgsz / min(h0, w0) # ratio + if r != 1: # if sizes are not equal + w, h = (math.ceil(w0 * r), self.imgsz) if h0 < w0 else (self.imgsz, math.ceil(h0 * r)) + im = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR) + else: + r = self.imgsz / max(h0, w0) # ratio + if r != 1: # if sizes are not equal + w, h = (min(math.ceil(w0 * r), self.imgsz), min(math.ceil(h0 * r), self.imgsz)) + im = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR) + elif not (h0 == w0 == self.imgsz): # resize by stretching image to square imgsz + im = cv2.resize(im, (self.imgsz, self.imgsz), interpolation=cv2.INTER_LINEAR) + if im.ndim == 2: + im = im[..., None] + + # Add to buffer if training with augmentations + if self.augment and self.cache != "ram": + self.ims[i], self.im_hw0[i], self.im_hw[i] = im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized + self.buffer.append(i) + if 1 < len(self.buffer) >= self.max_buffer_length: # prevent empty buffer + j = self.buffer.pop(0) + if self.cache != "ram": + self.ims[j], self.im_hw0[j], self.im_hw[j] = None, None, None + + return im, (h0, w0), im.shape[:2] + + return self.ims[i], self.im_hw0[i], self.im_hw[i] + + def cache_images(self) -> None: + """Cache images to memory or disk for faster training.""" + b, gb = 0, 1 << 30 # bytes of cached images, bytes per gigabytes + fcn, storage = (self.cache_images_to_disk, "Disk") if self.cache == "disk" else (self.load_image, "RAM") + with ThreadPool(NUM_THREADS) as pool: + results = pool.imap(fcn, range(self.ni)) + pbar = TQDM(enumerate(results), total=self.ni, disable=LOCAL_RANK > 0) + for i, x in pbar: + if self.cache == "disk": + b += self.npy_files[i].stat().st_size if self.npy_files[i].exists() else 0 # failed writes unlink + else: # 'ram' + self.ims[i], self.im_hw0[i], self.im_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i) + b += self.ims[i].nbytes + pbar.desc = f"{self.prefix}Caching images ({b / gb:.1f}GB {storage})" + pbar.close() + if self.cache == "ram": + self.ims = self._ImageCache(self.ims) + + def cache_images_to_disk(self, i: int) -> None: + """Save an image as an *.npy file for faster loading.""" + f = self.npy_files[i] + if not f.exists(): + try: + np.save(f.as_posix(), imread(self.im_files[i], flags=self.cv2_flag), allow_pickle=False) + except Exception as e: + f.unlink(missing_ok=True) + LOGGER.warning(f"{self.prefix}WARNING ⚠️ Failed to cache image {f}: {e}") + + def check_cache_disk(self, safety_margin: float = 0.1) -> bool: + """Check if there's enough disk space for caching images. + + Args: + safety_margin (float): Safety margin factor for disk space calculation. + + Returns: + (bool): True if there's enough disk space, False otherwise. + """ + b, gb = 0, 1 << 30 # bytes of cached images, bytes per gigabytes + n = min(self.ni, 30) # extrapolate from 30 random images + for _ in range(n): + im_file = random.choice(self.im_files) + im = imread(im_file) + if im is None: + continue + b += im.nbytes + if not os.access(Path(im_file).parent, os.W_OK): + self.cache = None + LOGGER.warning(f"{self.prefix}Skipping caching images to disk, directory not writable") + return False + disk_required = b * self.ni / n * (1 + safety_margin) # bytes required to cache dataset to disk + total, _used, free = shutil.disk_usage(Path(self.im_files[0]).parent) + if disk_required > free: + self.cache = None + LOGGER.warning( + f"{self.prefix}{disk_required / gb:.1f}GB disk space required, " + f"with {int(safety_margin * 100)}% safety margin but only " + f"{free / gb:.1f}/{total / gb:.1f}GB free, not caching images to disk" + ) + return False + return True + + def check_cache_ram(self, safety_margin: float = 1.0) -> bool: + """Check if there's enough RAM for caching images. + + Args: + safety_margin (float): Safety margin factor for RAM calculation. + + Returns: + (bool): True if there's enough RAM, False otherwise. + """ + b, gb = 0, 1 << 30 # bytes of cached images, bytes per gigabytes + n = min(self.ni, 30) # extrapolate from 30 random images + for _ in range(n): + b += self.load_image(random.randrange(self.ni))[0].nbytes + mem_required = b * self.ni / n * (1 + safety_margin) # GB required to cache dataset into RAM + mem = __import__("psutil").virtual_memory() + if mem_required > mem.available: + self.cache = None + LOGGER.warning( + f"{self.prefix}{mem_required / gb:.1f}GB RAM required to cache images " + f"with {int(safety_margin * 100)}% safety margin but only " + f"{mem.available / gb:.1f}/{mem.total / gb:.1f}GB available, not caching images" + ) + return False + return True + + def set_rectangle(self) -> None: + """Sort images by aspect ratio and set batch shapes for rectangular training.""" + bi = np.floor(np.arange(self.ni) / self.batch_size).astype(int) # batch index + nb = bi[-1] + 1 # number of batches + + s = np.array([x.pop("shape") for x in self.labels]) # hw + ar = s[:, 0] / s[:, 1] # aspect ratio + irect = ar.argsort() + self.im_files = [self.im_files[i] for i in irect] + self.labels = [self.labels[i] for i in irect] + ar = ar[irect] + + # Set training image shapes + shapes = [[1, 1]] * nb + for i in range(nb): + ari = ar[bi == i] + mini, maxi = ari.min(), ari.max() + if maxi < 1: + shapes[i] = [maxi, 1] + elif mini > 1: + shapes[i] = [1, 1 / mini] + + self.batch_shapes = np.ceil(np.array(shapes) * self.imgsz / self.stride + self.pad).astype(int) * self.stride + self.batch = bi # batch index of image + + def __getitem__(self, index: int) -> dict[str, Any]: + """Return transformed label information for given index.""" + return self.transforms(self.get_image_and_label(index)) + + def get_image_and_label(self, index: int) -> dict[str, Any]: + """Get and return label information from the dataset. + + Args: + index (int): Index of the image to retrieve. + + Returns: + (dict[str, Any]): Label dictionary with image and metadata. + """ + label = deepcopy(self.labels[index]) # requires deepcopy() https://github.com/ultralytics/ultralytics/pull/1948 + label.pop("shape", None) # shape is for rect, remove it + label["img"], label["ori_shape"], label["resized_shape"] = self.load_image(index) + label["ratio_pad"] = ( + label["resized_shape"][0] / label["ori_shape"][0], + label["resized_shape"][1] / label["ori_shape"][1], + ) # for evaluation + if self.rect: + label["rect_shape"] = self.batch_shapes[self.batch[index]] + return self.update_labels_info(label) + + def __len__(self) -> int: + """Return the length of the labels list for the dataset.""" + return len(self.labels) + + def update_labels_info(self, label: dict[str, Any]) -> dict[str, Any]: + """Customize your label format here.""" + return label + + def build_transforms(self, hyp: dict[str, Any] | None = None): + """Users can customize augmentations here. + + Examples: + >>> if self.augment: + ... # Training transforms + ... return Compose([]) + >>> else: + ... # Val transforms + ... return Compose([]) + """ + raise NotImplementedError + + def get_labels(self) -> list[dict[str, Any]]: + """Users can customize their own format here. + + Examples: + Ensure output is a dictionary with the following keys: + >>> dict( + ... im_file=im_file, + ... shape=shape, # format: (height, width) + ... cls=cls, + ... bboxes=bboxes, # xywh + ... segments=segments, # xy + ... keypoints=keypoints, # xy + ... normalized=True, # or False + ... bbox_format="xyxy", # or xywh, ltwh + ... ) + """ + raise NotImplementedError diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/build.py b/.venv/lib/python3.12/site-packages/ultralytics/data/build.py new file mode 100644 index 0000000000000000000000000000000000000000..481c95d04cbf8aa9baf7b9baac76b0f9c7f048e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/build.py @@ -0,0 +1,486 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import math +import os +import random +from collections.abc import Iterator +from pathlib import Path +from typing import Any +from urllib.parse import urlsplit + +import numpy as np +import torch +import torch.distributed as dist +from PIL import Image +from torch.utils.data import Dataset, dataloader, distributed + +from ultralytics.cfg import IterableSimpleNamespace +from ultralytics.data.dataset import ( + DepthDataset, + GroundingDataset, + PolygonSemanticDataset, + SemanticDataset, + YOLODataset, + YOLOMultiModalDataset, +) +from ultralytics.data.loaders import ( + LOADERS, + LoadImagesAndVideos, + LoadPilAndNumpy, + LoadScreenshots, + LoadStreams, + LoadTensor, + SourceTypes, + autocast_list, +) +from ultralytics.data.utils import IMG_FORMATS, VID_FORMATS, add_polygon_background, get_split_fraction +from ultralytics.utils import RANK, colorstr +from ultralytics.utils.checks import check_file +from ultralytics.utils.torch_utils import TORCH_1_13, TORCH_2_0, TORCH_2_7, get_torch_device_backend + + +class InfiniteDataLoader(dataloader.DataLoader): + """DataLoader that reuses workers for infinite iteration. + + This dataloader extends the PyTorch DataLoader to provide infinite recycling of workers, which improves efficiency + for training loops that need to iterate through the dataset multiple times without recreating workers. + + Attributes: + batch_sampler (_RepeatSampler): A sampler that repeats indefinitely. + iterator (Iterator): The iterator from the parent DataLoader. + + Methods: + __len__: Return the length of the batch sampler's sampler. + __iter__: Yield batches from the underlying iterator. + __del__: Ensure workers are properly terminated. + close: Gracefully shut down persistent workers when the DataLoader is no longer needed. + reset: Reset the iterator, useful when modifying dataset settings during training. + + Examples: + Create an infinite DataLoader for training + >>> dataset = YOLODataset(...) + >>> dataloader = InfiniteDataLoader(dataset, batch_size=16, shuffle=True) + >>> for batch in dataloader: # Infinite iteration + >>> train_step(batch) + """ + + def __init__(self, *args: Any, **kwargs: Any): + """Initialize the InfiniteDataLoader with the same arguments as DataLoader.""" + if not TORCH_2_0: + kwargs.pop("prefetch_factor", None) # not supported by earlier versions + super().__init__(*args, **kwargs) + object.__setattr__(self, "batch_sampler", _RepeatSampler(self.batch_sampler)) + self.iterator = None # fork workers on first iteration, not while another loader's pin-memory thread starts up + + def __len__(self) -> int: + """Return the length of the batch sampler's sampler.""" + return len(self.batch_sampler.sampler) + + def __iter__(self) -> Iterator: + """Yield one epoch of batches from the persistent iterator.""" + if self.iterator is None: + self.iterator = self._get_iterator() + for _ in range(len(self)): + yield next(self.iterator) + + def __del__(self): + """Ensure that workers are properly terminated when the DataLoader is deleted.""" + try: + for w in getattr(self.iterator, "_workers", ()): # force terminate + if w.is_alive(): + w.terminate() + self.close() + except Exception: + pass + + def close(self): + """Shut down persistent workers, unregistering them from torch's SIGCHLD watchdog before interpreter exit.""" + if hasattr(self.iterator, "_workers"): + self.iterator._shutdown_workers() # joins workers and calls torch._C._remove_worker_pids + + def reset(self): + """Reset the iterator to allow modifications to the dataset during training.""" + self.close() # free old worker pipes before creating new iterator + self.iterator = None + + +class _RepeatSampler: + """Sampler that repeats forever for infinite iteration. + + This sampler wraps another sampler and yields its contents indefinitely, allowing for infinite iteration over a + dataset without recreating the sampler. + + Attributes: + sampler (torch.utils.data.Sampler): The sampler to repeat. + """ + + def __init__(self, sampler: Any): + """Initialize the _RepeatSampler with a sampler to repeat indefinitely.""" + self.sampler = sampler + + def __iter__(self) -> Iterator: + """Iterate over the sampler indefinitely, yielding its contents.""" + while True: + yield from iter(self.sampler) + + +class ContiguousDistributedSampler(torch.utils.data.Sampler): + """Distributed sampler that assigns contiguous batch-aligned chunks of the dataset to each GPU. + + Unlike PyTorch's DistributedSampler which distributes samples in a round-robin fashion (GPU 0 gets indices + [0,2,4,...], GPU 1 gets [1,3,5,...]), this sampler gives each GPU contiguous batches of the dataset (GPU 0 gets + batches [0,1,2,...], GPU 1 gets batches [k,k+1,...], etc.). This preserves any ordering or grouping in the original + dataset, which is critical when samples are organized by similarity (e.g., images sorted by size to enable efficient + batching without padding when using rect=True). + + The sampler handles uneven batch counts by distributing remainder batches to the first few ranks, ensuring all + samples are covered exactly once across all GPUs. + + Args: + dataset (Dataset): Dataset to sample from. Must implement __len__. + num_replicas (int, optional): Number of distributed processes. Defaults to world size. + batch_size (int, optional): Batch size used by dataloader. Defaults to dataset.batch_size or 1. + rank (int, optional): Rank of current process. Defaults to current rank. + shuffle (bool, optional): Whether to shuffle indices within each rank's chunk. Defaults to False. When True, + shuffling is deterministic and controlled by set_epoch() for reproducibility. + + Examples: + >>> # For validation with size-grouped images + >>> sampler = ContiguousDistributedSampler(val_dataset, batch_size=32, shuffle=False) + >>> loader = DataLoader(val_dataset, batch_size=32, sampler=sampler) + >>> # For training with shuffling + >>> sampler = ContiguousDistributedSampler(train_dataset, batch_size=32, shuffle=True) + >>> for epoch in range(num_epochs): + ... sampler.set_epoch(epoch) + ... for batch in loader: + ... ... + """ + + def __init__( + self, + dataset: Dataset, + num_replicas: int | None = None, + batch_size: int | None = None, + rank: int | None = None, + shuffle: bool = False, + ) -> None: + """Initialize the sampler with dataset and distributed training parameters.""" + if num_replicas is None: + num_replicas = dist.get_world_size() if dist.is_initialized() else 1 + if rank is None: + rank = dist.get_rank() if dist.is_initialized() else 0 + if batch_size is None: + batch_size = getattr(dataset, "batch_size", 1) + + self.num_replicas = num_replicas + self.rank = rank + self.epoch = 0 + self.shuffle = shuffle + self.total_size = len(dataset) + # Use unit batches when one input batch would span the dataset. + self.batch_size = 1 if batch_size >= self.total_size else batch_size + self.num_batches = math.ceil(self.total_size / self.batch_size) + + def _get_rank_indices(self) -> tuple[int, int]: + """Calculate the start and end sample indices for this rank.""" + # Calculate which batches this rank handles + batches_per_rank_base = self.num_batches // self.num_replicas + remainder = self.num_batches % self.num_replicas + + # This rank gets an extra batch if rank < remainder + batches_for_this_rank = batches_per_rank_base + (1 if self.rank < remainder else 0) + + # Calculate starting batch: base position + number of extra batches given to earlier ranks + start_batch = self.rank * batches_per_rank_base + min(self.rank, remainder) + end_batch = start_batch + batches_for_this_rank + + # Convert batch indices to sample indices + start_idx = min(start_batch * self.batch_size, self.total_size) + end_idx = min(end_batch * self.batch_size, self.total_size) + + return start_idx, end_idx + + def __iter__(self) -> Iterator: + """Generate indices for this rank's contiguous chunk of the dataset.""" + start_idx, end_idx = self._get_rank_indices() + indices = list(range(start_idx, end_idx)) + + if self.shuffle: + g = torch.Generator() + g.manual_seed(self.epoch) + indices = [indices[i] for i in torch.randperm(len(indices), generator=g).tolist()] + + return iter(indices) + + def __len__(self) -> int: + """Return the number of samples in this rank's chunk.""" + start_idx, end_idx = self._get_rank_indices() + return end_idx - start_idx + + def set_epoch(self, epoch: int) -> None: + """Set the epoch for this sampler to ensure different shuffling patterns across epochs. + + Args: + epoch (int): Epoch number to use as the random seed for shuffling. + """ + self.epoch = epoch + + +def seed_worker(worker_id: int) -> None: + """Set dataloader worker seed for reproducibility across worker processes.""" + worker_seed = torch.initial_seed() % 2**32 + np.random.seed(worker_seed) + random.seed(worker_seed) + + +def build_yolo_dataset( + cfg: IterableSimpleNamespace, + img_path: str, + batch: int, + data: dict[str, Any], + mode: str = "train", + rect: bool = False, + stride: int = 32, + multi_modal: bool = False, + fraction: float | None = None, +) -> Dataset: + """Build and return a YOLO dataset based on configuration parameters.""" + pad = 0.0 if mode == "train" else 0.5 + rect = cfg.rect or rect + if cfg.task == "depth": + dataset = DepthDataset + pad, rect = 0.0, rect and mode == "train" # depth val letterbox stretches, so pad and rect_shape are ignored + elif cfg.task == "semantic": + dataset = SemanticDataset if data.get("masks_dir") else PolygonSemanticDataset + if dataset is PolygonSemanticDataset: + add_polygon_background(data) # polygon labels need a background class; idempotent if already added + pad = 0.0 # no pad for semantic + elif multi_modal: + dataset = YOLOMultiModalDataset + else: + dataset = YOLODataset + + if data.get("complete"): + fraction = 1.0 # already limited during dataset download + elif fraction is None: + fraction = get_split_fraction(cfg.fraction, "train" if mode == "train" else cfg.split) + return dataset( + img_path=img_path, + imgsz=cfg.imgsz, + batch_size=batch, + augment=mode == "train", + hyp=cfg, + rect=rect, + cache=cfg.cache or None, + single_cls=cfg.single_cls or False, + stride=stride, + pad=pad, + prefix=colorstr(f"{mode}: "), + task=cfg.task, + classes=cfg.classes, + data=data, + fraction=fraction, + ) + + +def build_grounding( + cfg: IterableSimpleNamespace, + img_path: str, + json_file: str, + batch: int, + mode: str = "train", + rect: bool = False, + stride: int = 32, + max_samples: int = 80, +) -> Dataset: + """Build and return a GroundingDataset based on configuration parameters.""" + return GroundingDataset( + img_path=img_path, + json_file=json_file, + max_samples=max_samples, + imgsz=cfg.imgsz, + batch_size=batch, + augment=mode == "train", # augmentation + hyp=cfg, + rect=cfg.rect or rect, # rectangular batches + cache=cfg.cache or None, + single_cls=cfg.single_cls or False, + stride=stride, + pad=0.0 if mode == "train" else 0.5, + prefix=colorstr(f"{mode}: "), + task=cfg.task, + classes=cfg.classes, + fraction=get_split_fraction(cfg.fraction, mode), + ) + + +def build_dataloader( + dataset, + batch: int, + workers: int, + shuffle: bool = True, + rank: int = -1, + drop_last: bool = False, + pin_memory: bool = True, + device: torch.device | str = "cuda", +) -> InfiniteDataLoader: + """Create and return an InfiniteDataLoader for training or validation. + + Args: + dataset (Dataset): Dataset to load data from. + batch (int): Batch size for the dataloader. + workers (int): Number of worker processes for data loading. + shuffle (bool, optional): Whether to shuffle the dataset. + rank (int, optional): Process rank in distributed training. -1 for single-GPU training. + drop_last (bool, optional): Whether to drop the last incomplete batch. + pin_memory (bool, optional): Whether to use pinned memory for dataloader. + device (torch.device | str, optional): Device used by the dataloader consumer. + + Returns: + (InfiniteDataLoader): A dataloader that can be used for training or validation. + + Examples: + Create a dataloader for training + >>> dataset = YOLODataset(...) + >>> dataloader = build_dataloader(dataset, batch=16, workers=4, shuffle=True) + """ + dataset_len = len(dataset) + batch = min(batch, dataset_len) + seed = torch.initial_seed() - RANK - 1 + sampler = ( + None + if rank == -1 + else distributed.DistributedSampler(dataset, shuffle=shuffle, seed=seed) + if shuffle + else ContiguousDistributedSampler(dataset) + ) + samples = len(sampler) if sampler is not None else dataset_len + drop_last = drop_last and bool(batch) and dataset_len % batch != 0 + batches = (samples // batch if drop_last else math.ceil(samples / batch)) if batch else 0 + device_type = getattr(device, "type", str(device).split(":")[0]) + nd = get_torch_device_backend(device).device_count() if device_type not in {"cpu", "mps"} else 0 + # Do not create more worker processes than final loader batches. Single-batch loaders run in-process to avoid + # persistent DataLoader worker pools that add overhead and can stall tiny datasets while holding CUDA context. + nw = min(os.cpu_count() // max(nd, 1), workers, 0 if batches <= 1 else batches) # number of workers + generator = torch.Generator() + generator.manual_seed((6148914691236517205 + RANK + seed) % (1 << 64)) + pin_memory = nd > 0 and pin_memory + pin_memory_device = ( + device_type if pin_memory and device_type in {"npu", "xpu"} and TORCH_1_13 and not TORCH_2_7 else None + ) + return InfiniteDataLoader( + dataset=dataset, + batch_size=batch, + shuffle=shuffle and sampler is None, + num_workers=nw, + sampler=sampler, + prefetch_factor=(4 if shuffle else 2) if nw > 0 else None, # validation holds fewer batches between passes + pin_memory=pin_memory, + collate_fn=getattr(dataset, "collate_fn", None), + worker_init_fn=seed_worker, + generator=generator, + drop_last=drop_last, + **({"pin_memory_device": pin_memory_device} if pin_memory_device else {}), + ) + + +def check_source( + source: str | int | Path | list | tuple | np.ndarray | Image.Image | torch.Tensor, +) -> tuple[Any, bool, bool, bool, bool, bool]: + """Check the type of input source and return corresponding flag values. + + Args: + source (str | int | Path | list | tuple | np.ndarray | PIL.Image | torch.Tensor): The input source to check. + + Returns: + source (str | int | Path | list | tuple | np.ndarray | PIL.Image | torch.Tensor): The processed source. + webcam (bool): Whether the source is a webcam. + screenshot (bool): Whether the source is a screenshot. + from_img (bool): Whether the source is an image or list of images. + in_memory (bool): Whether the source is an in-memory object. + tensor (bool): Whether the source is a torch.Tensor. + + Examples: + Check a file path source + >>> source, webcam, screenshot, from_img, in_memory, tensor = check_source("image.jpg") + + Check a webcam source + >>> source, webcam, screenshot, from_img, in_memory, tensor = check_source(0) + """ + webcam, screenshot, from_img, in_memory, tensor = False, False, False, False, False + if isinstance(source, (str, int, Path)): # int for local usb camera + source = str(source) + source_lower = source.lower() + is_url = source_lower.startswith(("https://", "http://", "rtsp://", "rtmp://", "tcp://")) + is_file = (urlsplit(source_lower).path if is_url else source_lower).rpartition(".")[-1] in ( + IMG_FORMATS | VID_FORMATS + ) + webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file) + screenshot = source_lower == "screen" + if is_url and is_file: + source = check_file(source) # download + elif isinstance(source, LOADERS): + in_memory = True + elif isinstance(source, (list, tuple)): + source = autocast_list(source) # convert all list elements to PIL or np arrays + from_img = True + elif isinstance(source, (Image.Image, np.ndarray)): + from_img = True + elif isinstance(source, torch.Tensor): + tensor = True + else: + raise TypeError("Unsupported image type. For supported types see https://docs.ultralytics.com/modes/predict") + + return source, webcam, screenshot, from_img, in_memory, tensor + + +def load_inference_source( + source: str | int | Path | list | tuple | np.ndarray | Image.Image | torch.Tensor, + batch: int = 1, + vid_stride: int = 1, + buffer: bool = False, + channels: int = 3, +): + """Load an inference source for object detection and apply necessary transformations. + + Args: + source (str | int | Path | list | tuple | np.ndarray | PIL.Image | torch.Tensor): The input source for + inference. + batch (int, optional): Batch size for dataloaders. + vid_stride (int, optional): The frame interval for video sources. + buffer (bool, optional): Whether stream frames will be buffered. + channels (int, optional): The number of input channels for the model. + + Returns: + (Dataset): A dataset object for the specified input source with attached source_type attribute. + + Examples: + Load an image source for inference + >>> dataset = load_inference_source("image.jpg", batch=1) + + Load a video stream source + >>> dataset = load_inference_source("rtsp://example.com/stream", vid_stride=2) + """ + source, stream, screenshot, from_img, in_memory, tensor = check_source(source) + source_type = source.source_type if in_memory else SourceTypes(stream, screenshot, from_img, tensor) + + # DataLoader + if tensor: + dataset = LoadTensor(source) + elif in_memory: + dataset = source + elif stream: + dataset = LoadStreams(source, vid_stride=vid_stride, buffer=buffer, channels=channels) + elif screenshot: + dataset = LoadScreenshots(source, channels=channels) + elif from_img: + dataset = LoadPilAndNumpy(source, channels=channels) + else: + dataset = LoadImagesAndVideos(source, batch=batch, vid_stride=vid_stride, channels=channels) + + # Attach source types to the dataset + dataset.source_type = source_type + + return dataset diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/converter.py b/.venv/lib/python3.12/site-packages/ultralytics/data/converter.py new file mode 100644 index 0000000000000000000000000000000000000000..29382745f64d0fb79f93661ff2e94befc17d6c03 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/converter.py @@ -0,0 +1,1160 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import asyncio +import hashlib +import json +import math +import random +import shutil +from collections import defaultdict +from concurrent.futures import ThreadPoolExecutor, as_completed +from pathlib import Path +from tempfile import TemporaryDirectory + +import cv2 +import numpy as np +from filelock import AsyncFileLock, Timeout +from PIL import Image + +from ultralytics.data.utils import get_split_fraction +from ultralytics.utils import ASSETS_URL, DATASETS_DIR, LOGGER, NUM_THREADS, TQDM, YAML, clean_url +from ultralytics.utils.checks import check_file +from ultralytics.utils.downloads import download, zip_directory +from ultralytics.utils.files import increment_path + + +def coco91_to_coco80_class() -> list[int]: + """Convert 91-index COCO class IDs to 80-index COCO class IDs. + + Returns: + (list[int | None]): A list of 91 elements where the index represents the 91-index class ID and the value is the + corresponding 80-index class ID, or None if there is no mapping. + """ + return [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + None, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + None, + 24, + 25, + None, + None, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + None, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + None, + 60, + None, + None, + 61, + None, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + None, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + None, + ] + + +def coco80_to_coco91_class() -> list[int]: + r"""Convert 80-index (val2014) to 91-index (paper). + + Returns: + (list[int]): A list of 80 class IDs where each value is the corresponding 91-index class ID. + + Examples: + >>> import numpy as np + >>> a = np.loadtxt("data/coco.names", dtype="str", delimiter="\n") + >>> b = np.loadtxt("data/coco_paper.names", dtype="str", delimiter="\n") + + Convert the darknet to COCO format + >>> x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] + + Convert the COCO to darknet format + >>> x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] + + References: + https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/ + """ + return [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 27, + 28, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 67, + 70, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + ] + + +def convert_coco( + labels_dir: str = "../coco/annotations/", + save_dir: str = "coco_converted/", + use_segments: bool = False, + use_keypoints: bool = False, + cls91to80: bool = True, + lvis: bool = False, +): + """Convert COCO dataset annotations to a YOLO annotation format suitable for training YOLO models. + + Args: + labels_dir (str, optional): Path to directory containing COCO dataset annotation files. + save_dir (str, optional): Path to directory to save results to. + use_segments (bool, optional): Whether to include segmentation masks in the output. + use_keypoints (bool, optional): Whether to include keypoint annotations in the output. + cls91to80 (bool, optional): Whether to map 91 COCO class IDs to the corresponding 80 COCO class IDs. + lvis (bool, optional): Whether to convert data in lvis dataset way. + + Examples: + >>> from ultralytics.data.converter import convert_coco + + Convert COCO annotations to YOLO format + >>> convert_coco("coco/annotations/", use_segments=True, use_keypoints=False, cls91to80=False) + + Convert LVIS annotations to YOLO format + >>> convert_coco("lvis/annotations/", use_segments=True, use_keypoints=False, cls91to80=False, lvis=True) + """ + # Create dataset directory + save_dir = increment_path(save_dir) # increment if save directory already exists + for p in save_dir / "labels", save_dir / "images": + p.mkdir(parents=True, exist_ok=True) # make dir + + # Convert classes + coco80 = coco91_to_coco80_class() + + # Import json + for json_file in sorted(Path(labels_dir).resolve().glob("*.json")): + lname = "" if lvis else json_file.stem.replace("instances_", "") + fn = Path(save_dir) / "labels" / lname # folder name + fn.mkdir(parents=True, exist_ok=True) + if lvis: + # NOTE: create folders for both train and val in advance, + # since LVIS val set contains images from COCO 2017 train in addition to the COCO 2017 val split. + (fn / "train2017").mkdir(parents=True, exist_ok=True) + (fn / "val2017").mkdir(parents=True, exist_ok=True) + with open(json_file, encoding="utf-8") as f: + data = json.load(f) + + # Create image dict + images = {f"{x['id']:d}": x for x in data["images"]} + # Create image-annotations dict + annotations = defaultdict(list) + for ann in data["annotations"]: + annotations[ann["image_id"]].append(ann) + + image_txt = [] + dropped = False + # Write labels file + for img_id, anns in TQDM(annotations.items(), desc=f"Annotations {json_file}"): + img = images[f"{img_id:d}"] + h, w = img["height"], img["width"] + f = str(Path(img["coco_url"]).relative_to("http://images.cocodataset.org")) if lvis else img["file_name"] + if lvis: + image_txt.append(str(Path("./images") / f)) + + bboxes = [] + segments = [] + keypoints = [] + for ann in anns: + if ann.get("iscrowd", False): + continue + # The COCO box format is [top left x, top left y, width, height] + box = np.array(ann["bbox"], dtype=np.float64) + box[:2] += box[2:] / 2 # xy top-left corner to center + box[[0, 2]] /= w # normalize x + box[[1, 3]] /= h # normalize y + if box[2] <= 0 or box[3] <= 0: # if w <= 0 and h <= 0 + continue + + cls = coco80[ann["category_id"] - 1] if cls91to80 else ann["category_id"] - 1 # class + box = [cls, *box.tolist()] + if box not in bboxes: + if use_keypoints: + if ann.get("keypoints") is None: + continue + keypoints.append( + box + (np.array(ann["keypoints"]).reshape(-1, 3) / np.array([w, h, 1])).reshape(-1).tolist() + ) + bboxes.append(box) + if use_segments: + seg = ann.get("segmentation") + polygons = ( + [ + p + for p in seg or [] + if isinstance(p, list) + and len(p) >= 6 + and not len(p) % 2 + and all(isinstance(c, (int, float)) for c in p) + ] + if isinstance(seg, list) + else [] + ) + if not polygons: + dropped = True + cx, cy, bw, bh = box[1:] + x1, y1, x2, y2 = cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2 + segments.append([cls, x1, y1, x2, y1, x2, y2, x1, y2]) + elif len(polygons) > 1: + s = merge_multi_segment(polygons) + s = (np.concatenate(s, axis=0) / np.array([w, h])).reshape(-1).tolist() + segments.append([cls, *s]) + else: + s = [j for i in polygons for j in i] # all segments concatenated + s = (np.array(s).reshape(-1, 2) / np.array([w, h])).reshape(-1).tolist() + segments.append([cls, *s]) + + # Write + with open((fn / f).with_suffix(".txt"), "a", encoding="utf-8") as file: + for i in range(len(bboxes)): + if use_keypoints: + line = (*(keypoints[i]),) # cls, box, keypoints + else: + line = (*(segments[i] if use_segments else bboxes[i]),) # cls, box or segments + file.write(("%g " * len(line)).rstrip() % line + "\n") + + if dropped and not use_keypoints: # segments are unused when keypoints own the output + LOGGER.warning( + f"{json_file}: annotations without a usable polygon, because the segmentation is missing, " + "empty, or not a point list such as an RLE mask, use a segment shaped like their bounding box." + ) + + if lvis: + filename = Path(save_dir) / json_file.name.replace("lvis_v1_", "").replace(".json", ".txt") + with open(filename, "a", encoding="utf-8") as f: + f.writelines(f"{line}\n" for line in image_txt) + + LOGGER.info(f"{'LVIS' if lvis else 'COCO'} data converted successfully.\nResults saved to {save_dir.resolve()}") + + +def convert_segment_masks_to_yolo_seg(masks_dir: str, output_dir: str, classes: int): + """Convert a dataset of segmentation mask images to the YOLO segmentation format. + + This function takes the directory containing the binary format mask images and converts them into YOLO segmentation + format. The converted masks are saved in the specified output directory. + + Args: + masks_dir (str): The path to the directory where all mask images (png, jpg) are stored. + output_dir (str): The path to the directory where the converted YOLO segmentation masks will be stored. + classes (int): Total number of classes in the dataset, e.g., 80 for COCO. + + Examples: + >>> from ultralytics.data.converter import convert_segment_masks_to_yolo_seg + + The classes here is the total classes in the dataset, for COCO dataset we have 80 classes + >>> convert_segment_masks_to_yolo_seg("path/to/masks_directory", "path/to/output/directory", classes=80) + + Notes: + The expected directory structure for the masks is: + + - masks + ├─ mask_image_01.png or mask_image_01.jpg + ├─ mask_image_02.png or mask_image_02.jpg + ├─ mask_image_03.png or mask_image_03.jpg + └─ mask_image_04.png or mask_image_04.jpg + + After execution, the labels will be organized in the following structure: + + - output_dir + ├─ mask_yolo_01.txt + ├─ mask_yolo_02.txt + ├─ mask_yolo_03.txt + └─ mask_yolo_04.txt + """ + pixel_to_class_mapping = {i + 1: i for i in range(classes)} + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + for mask_path in sorted(Path(masks_dir).iterdir()): + if mask_path.suffix in {".png", ".jpg"}: + mask = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE) # Read the mask image in grayscale + img_height, img_width = mask.shape # Get image dimensions + LOGGER.info(f"Processing {mask_path} imgsz = {img_height} x {img_width}") + + unique_values = np.unique(mask) # Get unique pixel values representing different classes + yolo_format_data = [] + + for value in unique_values: + if value == 0: + continue # Skip background + class_index = pixel_to_class_mapping.get(value, -1) + if class_index == -1: + LOGGER.warning(f"Unknown class for pixel value {value} in file {mask_path}, skipping.") + continue + + # Create a binary mask for the current class and find contours + contours, _ = cv2.findContours( + (mask == value).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE + ) # Find contours + + for contour in contours: + if len(contour) >= 3: # YOLO requires at least 3 points for a valid segmentation + contour = contour.squeeze() # Remove single-dimensional entries + yolo_format = [class_index] + for point in contour: + # Normalize the coordinates + yolo_format.append(round(point[0] / img_width, 6)) # Rounding to 6 decimal places + yolo_format.append(round(point[1] / img_height, 6)) + yolo_format_data.append(yolo_format) + # Save Ultralytics YOLO format data to file + output_path = output_dir / f"{mask_path.stem}.txt" + with open(output_path, "w", encoding="utf-8") as file: + for item in yolo_format_data: + line = " ".join(map(str, item)) + file.write(line + "\n") + LOGGER.info(f"Processed and stored at {output_path} imgsz = {img_height} x {img_width}") + + +def convert_dota_to_yolo_obb(dota_root_path: str): + """Convert DOTA dataset annotations to YOLO OBB (Oriented Bounding Box) format. + + The function processes images in the 'train' and 'val' folders of the DOTA dataset. For each image, it reads the + associated label from the original labels directory and writes new labels in YOLO OBB format to a new directory. + + Args: + dota_root_path (str): The root directory path of the DOTA dataset. + + Examples: + >>> from ultralytics.data.converter import convert_dota_to_yolo_obb + >>> convert_dota_to_yolo_obb("path/to/DOTA") + + Notes: + The directory structure assumed for the DOTA dataset: + + - DOTA + ├─ images + │ ├─ train + │ └─ val + └─ labels + ├─ train_original + └─ val_original + + After execution, the function will organize the labels into: + + - DOTA + └─ labels + ├─ train + └─ val + """ + dota_root_path = Path(dota_root_path) + + # Class names to indices mapping + class_mapping = { + "plane": 0, + "ship": 1, + "storage-tank": 2, + "baseball-diamond": 3, + "tennis-court": 4, + "basketball-court": 5, + "ground-track-field": 6, + "harbor": 7, + "bridge": 8, + "large-vehicle": 9, + "small-vehicle": 10, + "helicopter": 11, + "roundabout": 12, + "soccer-ball-field": 13, + "swimming-pool": 14, + "container-crane": 15, + "airport": 16, + "helipad": 17, + } + + def convert_label(image_name: str, image_width: int, image_height: int, orig_label_dir: Path, save_dir: Path): + """Convert a single image's DOTA annotation to YOLO OBB format and save it to a specified directory.""" + orig_label_path = orig_label_dir / f"{image_name}.txt" + save_path = save_dir / f"{image_name}.txt" + + with orig_label_path.open("r") as f, save_path.open("w") as g: + lines = f.readlines() + for line in lines: + parts = line.strip().split() + if len(parts) < 9: + continue + class_name = parts[8] + class_idx = class_mapping[class_name] + coords = [float(p) for p in parts[:8]] + normalized_coords = [ + coords[i] / image_width if i % 2 == 0 else coords[i] / image_height for i in range(8) + ] + formatted_coords = [f"{coord:.6g}" for coord in normalized_coords] + g.write(f"{class_idx} {' '.join(formatted_coords)}\n") + + for phase in ("train", "val"): + image_dir = dota_root_path / "images" / phase + orig_label_dir = dota_root_path / "labels" / f"{phase}_original" + save_dir = dota_root_path / "labels" / phase + + save_dir.mkdir(parents=True, exist_ok=True) + + image_paths = list(image_dir.iterdir()) + for image_path in TQDM(image_paths, desc=f"Processing {phase} images"): + if image_path.suffix != ".png": + continue + image_name_without_ext = image_path.stem + img = cv2.imread(str(image_path)) + h, w = img.shape[:2] + convert_label(image_name_without_ext, w, h, orig_label_dir, save_dir) + + +def min_index(arr1: np.ndarray, arr2: np.ndarray): + """Find a pair of indexes with the shortest distance between two arrays of 2D points. + + Args: + arr1 (np.ndarray): A NumPy array of shape (N, 2) representing N 2D points. + arr2 (np.ndarray): A NumPy array of shape (M, 2) representing M 2D points. + + Returns: + (tuple[int, int]): A tuple (idx1, idx2) where idx1 is the index in arr1 and idx2 is the index in arr2 of the + pair with the shortest distance. + """ + dis = ((arr1[:, None, :] - arr2[None, :, :]) ** 2).sum(-1) + return np.unravel_index(np.argmin(dis, axis=None), dis.shape) + + +def merge_multi_segment(segments: list[list]): + """Merge multiple segments into one list by connecting the coordinates with the minimum distance between each + segment. + + This function connects these coordinates with a thin line to merge all segments into one. + + Args: + segments (list[list]): Original segmentations in COCO's JSON file. Each element is a list of coordinates, like + [segmentation1, segmentation2,...]. + + Returns: + (list[np.ndarray]): A list of connected segments represented as NumPy arrays. + """ + s = [] + segments = [np.array(i).reshape(-1, 2) for i in segments] + idx_list = [[] for _ in range(len(segments))] + + # Record the indexes with min distance between each segment + for i in range(1, len(segments)): + idx1, idx2 = min_index(segments[i - 1], segments[i]) + idx_list[i - 1].append(idx1) + idx_list[i].append(idx2) + + # Use two round to connect all the segments + for k in range(2): + # Forward connection + if k == 0: + for i, idx in enumerate(idx_list): + # Middle segments have two indexes, reverse the index of middle segments + if len(idx) == 2 and idx[0] > idx[1]: + idx = idx[::-1] + segments[i] = segments[i][::-1, :] + + segments[i] = np.roll(segments[i], -idx[0], axis=0) + segments[i] = np.concatenate([segments[i], segments[i][:1]]) + # Deal with the first segment and the last one + if i in {0, len(idx_list) - 1}: + s.append(segments[i]) + else: + idx = [0, idx[1] - idx[0]] + s.append(segments[i][idx[0] : idx[1] + 1]) + + else: + for i in range(len(idx_list) - 1, -1, -1): + if i not in {0, len(idx_list) - 1}: + idx = idx_list[i] + nidx = abs(idx[1] - idx[0]) + s.append(segments[i][nidx:]) + return s + + +def yolo_bbox2segment(im_dir: str | Path, save_dir: str | Path | None = None, sam_model: str = "sam_b.pt", device=None): + """Convert existing object detection dataset (bounding boxes) to segmentation dataset in YOLO format. + + Generates segmentation data using SAM auto-annotator as needed. + + Args: + im_dir (str | Path): Path to image directory to convert. + save_dir (str | Path, optional): Path to save the generated labels, labels will be saved into `labels-segment` + in the same directory level of `im_dir` if save_dir is None. + sam_model (str): Segmentation model to use for intermediate segmentation data. + device (int | str, optional): The specific device to run SAM models. + + Notes: + The input directory structure assumed for dataset: + + - im_dir + ├─ 001.jpg + ├─ ... + └─ NNN.jpg + - labels + ├─ 001.txt + ├─ ... + └─ NNN.txt + """ + from ultralytics import SAM + from ultralytics.data import YOLODataset + from ultralytics.utils.ops import xywh2xyxy + + # NOTE: add placeholder to pass class index check + dataset = YOLODataset(im_dir, data={"names": list(range(1000)), "channels": 3}) + if len(dataset.labels[0]["segments"]) > 0: # if it's segment data + LOGGER.info("Segmentation labels detected, no need to generate new ones!") + return + + LOGGER.info("Detection labels detected, generating segment labels by SAM model!") + sam_model = SAM(sam_model) + for label in TQDM(dataset.labels, total=len(dataset.labels), desc="Generating segment labels"): + h, w = label["shape"] + boxes = label["bboxes"] + if len(boxes) == 0: # skip empty labels + continue + boxes[:, [0, 2]] *= w + boxes[:, [1, 3]] *= h + im = cv2.imread(label["im_file"]) + sam_results = sam_model(im, bboxes=xywh2xyxy(boxes), verbose=False, save=False, device=device) + label["segments"] = sam_results[0].masks.xyn + + save_dir = Path(save_dir) if save_dir else Path(im_dir).parent / "labels-segment" + save_dir.mkdir(parents=True, exist_ok=True) + for label in dataset.labels: + texts = [] + lb_name = Path(label["im_file"]).with_suffix(".txt").name + txt_file = save_dir / lb_name + cls = label["cls"] + for i, s in enumerate(label["segments"]): + if len(s) < 3: # fewer than 3 points is not a polygon, and writes a row no loader accepts + continue + line = (int(cls[i]), *s.reshape(-1)) + texts.append(("%g " * len(line)).rstrip() % line) + with open(txt_file, "a", encoding="utf-8") as f: + f.writelines(text + "\n" for text in texts) + LOGGER.info(f"Generated segment labels saved in {save_dir}") + + +def create_synthetic_coco_dataset(): + """Create a synthetic COCO dataset with random images based on filenames from label lists. + + This function downloads COCO labels, reads image filenames from label list files, creates synthetic images for + train2017 and val2017 subsets, and organizes them in the COCO dataset structure. It uses multithreading to generate + images efficiently. + + Examples: + >>> from ultralytics.data.converter import create_synthetic_coco_dataset + >>> create_synthetic_coco_dataset() + + Notes: + - Requires internet connection to download label files. + - Generates random RGB images of varying sizes (480x480 to 640x640 pixels). + - Existing test2017 directory is removed as it's not needed. + - Reads image filenames from train2017.txt and val2017.txt files. + """ + + def create_synthetic_image(image_file: Path): + """Generate a synthetic image with random size and color for dataset augmentation or testing purposes.""" + if not image_file.exists(): + size = (random.randint(480, 640), random.randint(480, 640)) + Image.new( + "RGB", + size=size, + color=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), + ).save(image_file) + + # Download labels + dir = DATASETS_DIR / "coco" + download([f"{ASSETS_URL}/coco2017labels-segments.zip"], dir=dir.parent) + + # Create synthetic images + shutil.rmtree(dir / "labels" / "test2017", ignore_errors=True) # Remove test2017 directory as not needed + with ThreadPoolExecutor(max_workers=NUM_THREADS) as executor: + for subset in ("train2017", "val2017"): + subset_dir = dir / "images" / subset + subset_dir.mkdir(parents=True, exist_ok=True) + + # Read image filenames from label list file + label_list_file = dir / f"{subset}.txt" + if label_list_file.exists(): + with open(label_list_file, encoding="utf-8") as f: + image_files = [dir / line.strip() for line in f] + + # Submit all tasks + futures = [executor.submit(create_synthetic_image, image_file) for image_file in image_files] + for _ in TQDM(as_completed(futures), total=len(futures), desc=f"Generating images for {subset}"): + pass # The actual work is done in the background + else: + LOGGER.warning(f"Labels file {label_list_file} does not exist. Skipping image creation for {subset}.") + + LOGGER.info("Synthetic COCO dataset created successfully.") + + +def convert_to_multispectral(path: str | Path, n_channels: int = 10, replace: bool = False, zip: bool = False): + """Convert RGB images to multispectral images by interpolating across wavelength bands. + + This function takes RGB images and interpolates them to create multispectral images with a specified number of + channels. It can process either a single image or a directory of images. + + Args: + path (str | Path): Path to an image file or directory containing images to convert. + n_channels (int): Number of spectral channels to generate in the output image. + replace (bool): Whether to replace the original image file with the converted one. + zip (bool): Whether to zip the converted images into a zip file. + + Examples: + Convert a single image + >>> convert_to_multispectral("path/to/image.jpg", n_channels=10) + + Convert a dataset + >>> convert_to_multispectral("coco8", n_channels=10) + """ + from ultralytics.data.utils import IMG_FORMATS + + path = Path(path) + if path.is_dir(): + # Process directory + im_files = [f for ext in (IMG_FORMATS - {"tif", "tiff"}) for f in path.rglob(f"*.{ext}")] + for im_path in im_files: + try: + convert_to_multispectral(im_path, n_channels) + if replace: + im_path.unlink() + except Exception as e: + LOGGER.info(f"Error converting {im_path}: {e}") + + if zip: + zip_directory(path) + else: + # Process a single image + output_path = path.with_suffix(".tiff") + img = cv2.cvtColor(cv2.imread(str(path)), cv2.COLOR_BGR2RGB) + + # Interpolate all pixels at once with linear interpolation and extrapolation across RGB wavelengths + rgb_wavelengths = np.array([650, 510, 475]) # R, G, B wavelengths (nm) + target_wavelengths = np.linspace(450, 700, n_channels) + order = np.argsort(rgb_wavelengths) # ascending wavelengths for segment lookup + xp = rgb_wavelengths[order] + seg = np.clip(np.searchsorted(xp, target_wavelengths) - 1, 0, len(xp) - 2) # segment per target + w = (target_wavelengths - xp[seg]) / (xp[seg + 1] - xp[seg]) # weights (<0 or >1 -> extrapolation) + img = img[..., order] + multispectral = img[..., seg] * (1 - w) + img[..., seg + 1] * w + cv2.imwritemulti(str(output_path), np.clip(multispectral, 0, 255).astype(np.uint8).transpose(2, 0, 1)) + LOGGER.info(f"Converted {output_path}") + + +def _infer_ndjson_kpt_shape(image_records: list) -> list: + """Infer kpt_shape [num_keypoints, dims] from NDJSON pose annotations. + + Scans up to 50 pose annotations across image records. Annotation format is [classId, cx, cy, w, h, kp1_x, kp1_y, + kp1_vis, ...] so keypoint values start at index 5. + + Tries dims=3 first (x, y, visibility) with visibility validation ({0, 1, 2}), then falls back to dims=2 (x, y only) + when values are unambiguously not divisible by 3. + """ + kpt_lengths = [] + samples = [] # raw keypoint value slices for visibility checking + for record in image_records: + for ann in record.get("annotations", {}).get("pose", []): + kpt_len = len(ann) - 5 # subtract classId + bbox (4 values) + if kpt_len > 0: + kpt_lengths.append(kpt_len) + samples.append(ann[5:]) + if len(kpt_lengths) >= 50: + break + if len(kpt_lengths) >= 50: + break + + if not kpt_lengths or len(set(kpt_lengths)) != 1: + raise ValueError("Pose dataset missing required 'kpt_shape'. See https://docs.ultralytics.com/datasets/pose") + + n = kpt_lengths[0] + + # Try dims=3: requires divisible by 3 and every 3rd value (visibility) in {0, 1, 2} + if n % 3 == 0 and all(v in (0, 1, 2) for s in samples for v in s[2::3]): + return [n // 3, 3] + + # Try dims=2: only when NOT divisible by 3 (avoids misclassifying dims=3 data) + if n % 2 == 0 and n % 3 != 0: + return [n // 2, 2] + + raise ValueError("Pose dataset missing required 'kpt_shape'. See https://docs.ultralytics.com/datasets/pose") + + +async def convert_ndjson_to_yolo(ndjson_path: str | Path, output_path=None, fraction=1.0, *, split=None) -> Path: + """Convert NDJSON dataset format to Ultralytics YOLO dataset structure. + + This function converts datasets stored in NDJSON (Newline Delimited JSON) format to the standard YOLO format. For + detection/segmentation/pose/obb tasks, it creates separate directories for images and labels. Depth datasets use + parallel images/ and depth/ trees with scaled uint16 PNG targets. Classification tasks use the ImageNet-style + {split}/{class_name}/ folder structure. Downloads run concurrently. + + The NDJSON format consists of: + - First line: Dataset metadata with class names, task type, and configuration + - Subsequent lines: Individual image records with annotations and optional URLs + + Args: + ndjson_path (str | Path): Path to the input NDJSON file containing dataset information. + output_path (str | Path | None, optional): Directory where the converted YOLO dataset will be saved. If None, + uses the DATASETS_DIR directory. Defaults to None. + fraction (float | int | list): Train ratio/count or [train, val, test] ratios/counts to download. + split (str, optional): Validation split requested by training. Unused test images are skipped. + + Returns: + (Path): Path to the generated data.yaml file (detection) or dataset directory (classification). + + Examples: + Convert a local NDJSON file: + >>> yaml_path = await convert_ndjson_to_yolo("dataset.ndjson") + >>> print(f"Dataset converted to: {yaml_path}") + + Convert with custom output directory: + >>> yaml_path = await convert_ndjson_to_yolo("dataset.ndjson", output_path="./converted_datasets") + + Use with YOLO training + >>> from ultralytics import YOLO + >>> model = YOLO("yolo26n.pt") + >>> model.train(data="https://github.com/ultralytics/assets/releases/download/v0.0.0/coco8-ndjson.ndjson") + """ + source = str(ndjson_path) + output_path = Path(output_path or DATASETS_DIR) + output_path.mkdir(parents=True, exist_ok=True) + if isinstance(fraction, list): + fraction = [get_split_fraction(fraction, split) for split in ("train", "val", "test")[: len(fraction)]] + else: + fraction = get_split_fraction(fraction, "train") + local = Path(source).is_file() + source_id = str(Path(source).resolve()) if local else clean_url(source) + source_hash = hashlib.sha256(repr((source_id, fraction)).encode() + (split or "").encode()).hexdigest()[:8] + cache_path = output_path / f".{Path(source_id).stem}-{source_hash}.cache" + + async def convert() -> Path: + cache_path.unlink(missing_ok=True) + with TemporaryDirectory() as download_dir: + result = await _convert_ndjson_to_yolo( + Path(check_file(source, download_dir=download_dir)), output_path, local, fraction, split + ) + cache_path.write_text(str(result.relative_to(output_path))) + return result + + try: + async with AsyncFileLock(cache_path.with_suffix(".lock"), timeout=0): + return await convert() + except Timeout: + pass + + async with AsyncFileLock(cache_path.with_suffix(".lock")): + if cache_path.is_file(): + result = output_path / cache_path.read_text() + marker = result / ".ndjson.yaml" if result.is_dir() else result + if marker.is_file(): + return result + return await convert() + + +async def _convert_ndjson_to_yolo(ndjson_path: Path, output_path: Path, local: bool, fraction, split=None) -> Path: + """Convert a resolved NDJSON source while its conversion lock is held.""" + from ultralytics.utils.checks import check_requirements + + check_requirements("aiohttp") + import aiohttp + + def read_records(): + with ndjson_path.open() as file: + return [json.loads(line) for line in file if line.strip()] + + lines = await asyncio.get_running_loop().run_in_executor(None, read_records) + dataset_record, image_records = lines[0], lines[1:] + task = dataset_record.get("task", "detect") + is_classification = task == "classify" + is_depth = task == "depth" + depth_scale = dataset_record.get("depth_scale", 1000) + if is_depth and ( + not isinstance(depth_scale, (int, float)) + or isinstance(depth_scale, bool) + or not math.isfinite(depth_scale) + or depth_scale <= 0 + ): + raise ValueError("Depth datasets require a positive finite depth_scale") + class_names = {int(k): v for k, v in dataset_record.get("class_names", {}).items()} + classification_ids = set() + + local_path = dataset_record.pop("path", None) if local and not (is_classification or is_depth) else None + + if split == "train" or ( + split == "val" and (not is_classification or any(r.get("split") == "val" for r in image_records)) + ): + fraction = [get_split_fraction(fraction, split) for split in ("train", "val")] + [0.0] + + # Hash stable content plus source identity. Query strings are excluded because signed URLs change on every export. + _h = hashlib.sha256(repr(fraction).encode() + (split or "").encode()) + for i, r in enumerate(lines): + if i: + split, source_name = r.get("split"), r.get("file") + if split not in {"train", "val", "test"}: + raise ValueError(f"Invalid NDJSON split: {split!r}") + if not isinstance(source_name, str) or not source_name: + raise ValueError(f"Invalid NDJSON image name: {source_name!r}") + if local_path: + if source_name != Path(source_name).name: + raise ValueError(f"Invalid NDJSON image name: {source_name!r}") + r["url"] = (ndjson_path.parent / local_path / "images" / split / source_name).resolve() + # Preserve safe content hashes already present in the filename or URL while indexes prevent collisions. + # Depth targets use the same stem, so image and target URLs follow the same output mechanics. + suffix = source_name.rsplit(".", 1)[-1] + stems = (Path(clean_url(r.get("url") or "")).stem, Path(source_name).stem) + content_hash = next( + (s.lower() for s in stems if len(s) == 32 and all(c in "0123456789abcdef" for c in s)), None + ) + stem = f"{content_hash}_{i}" if content_hash else i + r["file"] = f"{stem}.{suffix}" if suffix.isalnum() and len(suffix) <= 10 else f"{stem}.jpg" + if is_classification: + ids = r.get("annotations", {}).get("classification", []) + class_id = ids[0] if ids else 0 + if not isinstance(class_id, int): + raise ValueError(f"Invalid NDJSON classification ID: {class_id!r}") + classification_ids.add(class_id) + hash_record = {k: v for k, v in r.items() if k != "url"} + if isinstance(r.get("depth"), dict): + hash_record["depth"] = {k: v for k, v in r["depth"].items() if k != "url"} + if r["depth"].get("url"): + hash_record["depth"]["_source"] = clean_url(r["depth"]["url"]) + if r.get("file"): + hash_record["_source"] = clean_url(r["url"]) if r.get("url") else str(ndjson_path.parent.resolve()) + _h.update(json.dumps(hash_record, sort_keys=True).encode()) + _hash = _h.hexdigest()[:8] + class_dirs = {class_id: f"{i:06d}" for i, class_id in enumerate(sorted(classification_ids))} + classification_names = {i: class_names.get(class_id, str(class_id)) for i, class_id in enumerate(class_dirs)} + + # Depth adds one sibling URL per image record. File naming, caching, and retries remain shared. + if is_depth: + for record in image_records: + depth = record.get("depth") + if not isinstance(depth, dict) or not isinstance(depth.get("url"), str) or not depth["url"]: + raise ValueError(f"Depth record '{record.get('file', '')}' is missing depth.url") + + # Hash-qualified dirs allow identical datasets to reuse downloads while preventing changed datasets from mutating + # files that another training job may still be reading. + dataset_dir = output_path / f"{ndjson_path.stem}-{_hash}" + metadata_path = dataset_dir / (".ndjson.yaml" if is_classification else "data.yaml") + if metadata_path.is_file(): + try: + if (cached := YAML.load(metadata_path)).get("hash") == _hash and cached.get("complete") is True: + return dataset_dir if is_classification else metadata_path + except Exception: + pass + splits = {record["split"] for record in image_records} + if not is_classification: + if "train" not in splits: + raise ValueError(f"Dataset missing required 'train' split. Found splits: {sorted(splits)}") + if "val" not in splits: + train_records = [r for r in image_records if r.get("split") == "train"] + if len(train_records) < 2: + raise ValueError( + f"Dataset has only {len(train_records)} image(s) and no 'val' split. " + f"Need at least 2 images to auto-split into train/val." + ) + random.Random(0).shuffle(train_records) # local RNG to avoid mutating global training seed + val_count = max(1, len(train_records) // 10) + for r in train_records[:val_count]: + r["split"] = "val" + splits.add("val") + LOGGER.warning( + f"No 'val' split found in dataset. " + f"Auto-splitting {len(train_records)} images into {len(train_records) - val_count} train, {val_count} val. " + f"For best results, manually assign validation images in Platform dataset page." + ) + + inferred_nc = None + + if not is_classification: + class_ids = { + int(label[0]) + for record in image_records + for labels in record.get("annotations", {}).values() + for label in labels + if label + } + if class_ids or class_names: + max_class_id = max(class_ids | set(class_names)) + if class_names: + for i in range(max_class_id + 1): + class_names.setdefault(i, f"class{i}") + else: + inferred_nc = max_class_id + 1 + if task == "pose" and "kpt_shape" not in dataset_record: + dataset_record["kpt_shape"] = _infer_ndjson_kpt_shape(image_records) + + selected = [] + for split in ("train", "val", "test"): + limit = get_split_fraction(fraction, split) + if limit: + records = sorted((r for r in image_records if r["split"] == split), key=lambda r: r["file"]) + # A nonzero fraction keeps at least one image, as BaseDataset.get_img_files does at training time + count = min(limit if type(limit) is int else max(1, round(len(records) * limit)), len(records)) + selected.extend(records[i] for i in np.linspace(0, len(records) - 1, count, dtype=int)) + image_records = selected + split_counts = {split: sum(r["split"] == split for r in image_records) for split in ("train", "val", "test")} + + dataset_dir.mkdir(parents=True, exist_ok=True) + data_yaml = None + + if not is_classification: + # Detection/segmentation/pose/obb/depth: prepare YAML and create base structure + if is_depth: + data_yaml = {"task": "depth", "nc": 1, "names": {0: "depth"}, "depth_scale": depth_scale} + else: + data_yaml = dict(dataset_record) + if class_names: + data_yaml["names"] = class_names + elif inferred_nc is not None: + data_yaml["nc"] = inferred_nc + data_yaml.pop("class_names", None) + data_yaml.pop("type", None) # Remove NDJSON-specific fields + for split in sorted(splits): + (dataset_dir / "images" / split).mkdir(parents=True, exist_ok=True) + (dataset_dir / ("depth" if is_depth else "labels") / split).mkdir(parents=True, exist_ok=True) + data_yaml[split] = f"images/{split}" + + async def ensure_file(session, path, url): + """Return True when the file exists locally, otherwise download one URL with the retry policy.""" + if path.exists(): + return True + if not url: + return False + path.parent.mkdir(parents=True, exist_ok=True) + if isinstance(url, Path): + if not url.is_file(): + return False + await asyncio.get_running_loop().run_in_executor(None, shutil.copy2, url, path) + return True + for attempt in range(3): + error = None + try: + async with session.get(url, timeout=aiohttp.ClientTimeout(sock_connect=30, sock_read=30)) as response: + response.raise_for_status() + path.write_bytes(await response.read()) + return True + except aiohttp.ClientResponseError as e: + error = e + if e.status not in {408, 429} and e.status < 500: + LOGGER.warning(f"Failed to download {clean_url(url)}: HTTP {e.status}") + return False + except (aiohttp.ClientError, asyncio.TimeoutError) as e: + error = e + except Exception as e: # OSError, disk full, permissions — not transient, don't retry + LOGGER.warning(f"Failed to save {clean_url(url)}: {e}") + return False + if attempt < 2: + await asyncio.sleep(2**attempt) + else: + LOGGER.warning( + f"Failed to download {clean_url(url)} after 3 attempts: {type(error).__name__ if error else 'unknown'}" + ) + return False + + async def process_record(session, semaphore, record): + """Process single image record with async session.""" + async with semaphore: + split, original_name = record["split"], record["file"] + annotations = record.get("annotations", {}) + + if is_classification: + # Classification: place image in {split}/{class_name}/ folder + class_ids = annotations.get("classification", []) + class_id = class_ids[0] if class_ids else 0 + class_name = class_dirs[class_id] + image_path = dataset_dir / split / class_name / original_name + else: + image_path = dataset_dir / "images" / split / original_name + if not is_depth: + stem = original_name.rsplit(".", 1)[0] or original_name + label_path = dataset_dir / "labels" / split / f"{stem}.txt" + lines_to_write = [] + for key in annotations: + lines_to_write = [" ".join(map(str, item)) for item in annotations[key]] + break + label_path.write_text("\n".join(lines_to_write) + "\n" if lines_to_write else "") + + image_ok = await ensure_file(session, image_path, record.get("url")) + if not is_depth: + return image_ok + + stem = original_name.rsplit(".", 1)[0] or original_name + depth_path = dataset_dir / "depth" / split / f"{stem}.png" + depth_ok = await ensure_file(session, depth_path, record["depth"]["url"]) + if not image_ok or not depth_ok: + image_path.unlink(missing_ok=True) + depth_path.unlink(missing_ok=True) + return False + return True + + # Keep download concurrency high without creating one live coroutine per record for very large datasets. + semaphore = asyncio.Semaphore(min(128, len(image_records))) + async with aiohttp.ClientSession(trust_env=True) as session: + pbar = TQDM( + total=len(image_records), + desc=f"Converting {ndjson_path.name} fraction={fraction} → {dataset_dir} " + f"using {split_counts['train']} train, {split_counts['val']} val, {split_counts['test']} test images", + ) + + async def tracked_process(record): + result = await process_record(session, semaphore, record) + pbar.update(1) + return result + + success_count = 0 + for start in range(0, len(image_records), 1024): + results = await asyncio.gather(*[tracked_process(record) for record in image_records[start : start + 1024]]) + success_count += sum(results) + pbar.close() + + # Validate images were downloaded successfully + if not image_records or success_count < len(image_records): + raise RuntimeError(f"Downloaded {success_count}/{len(image_records)} images from {ndjson_path}") + + if is_classification: + # Classification: return dataset directory (check_cls_dataset expects a directory path) + # Keep class paths safe while check_cls_dataset restores the original display names. + YAML.save(metadata_path, {"names": classification_names, "hash": _hash, "complete": True}) + return dataset_dir + else: + # Detection: write data.yaml with hash for future change detection + data_yaml.update(hash=_hash, complete=True) + YAML.save(metadata_path, data_yaml) + return metadata_path diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/dataset.py b/.venv/lib/python3.12/site-packages/ultralytics/data/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..117b554b2bbd98c80c1d6a37f39021e609229b78 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/dataset.py @@ -0,0 +1,1319 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import json +from collections import defaultdict +from itertools import repeat +from multiprocessing.pool import ThreadPool +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from PIL import Image +from torch.utils.data import ConcatDataset + +from ultralytics.utils import LOCAL_RANK, LOGGER, NUM_THREADS, TQDM, colorstr +from ultralytics.utils.instance import Instances +from ultralytics.utils.ops import resample_segments, segments2boxes +from ultralytics.utils.torch_utils import TORCHVISION_0_18 + +from .augment import ( + Compose, + DepthFormat, + Format, + LetterBox, + RandomLoadText, + SemanticFormat, + classify_augmentations, + classify_transforms, + v8_transforms, +) +from .base import BaseDataset +from .converter import merge_multi_segment +from .utils import ( + HELP_URL, + check_file_speeds, + get_hash, + get_split_fraction, + img2label_paths, + load_dataset_cache_file, + load_depth, + polygons2masks_overlap, + save_dataset_cache_file, + verify_image, + verify_image_depth, + verify_image_label, + verify_image_mask, +) + +# Ultralytics dataset *.cache version, >= 1.0.0 for Ultralytics YOLO models +DATASET_CACHE_VERSION = "1.0.4" + + +class YOLODataset(BaseDataset): + """Dataset class for loading object detection and/or segmentation labels in YOLO format. + + This class supports loading data for object detection, instance segmentation, pose estimation, and oriented bounding + box (OBB) tasks using the YOLO format. + + Attributes: + format_class (type[Format]): Formatter appended by build_transforms; subclasses override it per task. + use_segments (bool): Indicates if segmentation masks should be used. + use_keypoints (bool): Indicates if keypoints should be used for pose estimation. + use_obb (bool): Indicates if oriented bounding boxes should be used. + data (dict): Dataset configuration dictionary. + + Methods: + cache_labels: Cache dataset labels, check images and read shapes. + get_labels: Return list of label dictionaries for YOLO training. + get_label_files: Return companion label files for the dataset's images. + verify_args: Return the per-image verification function and its arguments. + result_to_label: Convert one verification result into a label dict. + verify_labels: Check box/segment consistency of the loaded labels. + build_transforms: Build and append transforms to the list. + close_mosaic: Disable mosaic, copy_paste, mixup and cutmix augmentations and build transformations. + update_labels_info: Update label format for different tasks. + collate_fn: Collate data samples into batches. + + Examples: + >>> dataset = YOLODataset(img_path="path/to/images", data={"names": {0: "person"}}, task="detect") + >>> dataset.get_labels() + """ + + format_class = Format + + def __init__(self, *args, data: dict | None = None, task: str = "detect", **kwargs): + """Initialize the YOLODataset. + + Args: + data (dict, optional): Dataset configuration dictionary. + task (str): Task type, one of 'detect', 'segment', 'pose', or 'obb'. + *args (Any): Additional positional arguments for the parent class. + **kwargs (Any): Additional keyword arguments for the parent class. + """ + self.use_segments = task == "segment" + self.use_keypoints = task == "pose" + self.use_obb = task == "obb" + self.data = data + nkpt, ndim = self.data.get("kpt_shape", (0, 0)) + if self.use_keypoints and (nkpt <= 0 or ndim not in {2, 3}): # checked before the label cache is consulted + raise ValueError( + "'kpt_shape' in data.yaml missing or incorrect. Should be a list with [number of " + "keypoints, number of dims (2 for x,y or 3 for x,y,visible)], i.e. 'kpt_shape: [17, 3]'" + ) + super().__init__(*args, channels=self.data.get("channels", 3), **kwargs) + + def cache_labels(self, path: Path = Path("./labels.cache")) -> dict: + """Cache dataset labels, check images and read shapes. + + This is the shared scanning skeleton for file-based datasets; subclasses customize it through the + `get_label_files`, `get_cache_hash`, `verify_args`, `result_to_label` and `scan_summary` hooks instead of + duplicating this method. + + Args: + path (Path): Path where to save the cache file. + + Returns: + (dict): Dictionary containing cached labels and related information. + """ + x = {"labels": []} + nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages + desc = f"{self.prefix}Scanning {path.parent / path.stem}..." + total = len(self.im_files) + with ThreadPool(NUM_THREADS) as pool: + func, iterable = self.verify_args() + results = pool.imap(func=func, iterable=iterable) + pbar = TQDM(results, desc=desc, total=total) + for result in pbar: + label, nm_f, nf_f, ne_f, nc_f, msg = self.result_to_label(result) + nm += nm_f + nf += nf_f + ne += ne_f + nc += nc_f + if label is not None: + x["labels"].append(label) + if msg: + msgs.append(msg) + pbar.desc = f"{desc} {self.scan_summary(nf, nm, ne, nc)}" + pbar.close() + + if msgs: + LOGGER.info("\n".join(msgs)) + if nf == 0: + if self.augment: # training requires labels; unlabeled val splits (e.g. COCO test-dev) only warn + raise ValueError(f"{self.prefix}No labels found in {path}. {HELP_URL}") + LOGGER.warning(f"{self.prefix}No labels found in {path}. {HELP_URL}") + x["hash"] = self.get_cache_hash() + x["results"] = nf, nm, ne, nc, total + x["msgs"] = msgs # warnings + if x["labels"]: + save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION) + return x + + def get_label_files(self) -> list[str]: + """Return the companion label files for the dataset's images, storing them on the instance. + + Returns: + (list[str]): List of label file paths. + """ + self.label_files = img2label_paths(self.im_files) + return self.label_files + + def get_cache_hash(self) -> str: + """Return the hash used to validate a label cache against the current dataset files and scan settings. + + Returns: + (str): Dataset cache hash. + """ + scan_args = (self.use_keypoints, len(self.data["names"]), self.data.get("kpt_shape"), self.single_cls) + return get_hash(self.label_files + self.im_files + [str(scan_args)]) + + def scan_summary(self, nf: int, nm: int, ne: int, nc: int) -> str: + """Return a one-line summary of scan counters for progress bars and cache logs. + + Args: + nf (int): Number of found images. + nm (int): Number of missing labels. + ne (int): Number of empty labels. + nc (int): Number of corrupt images. + + Returns: + (str): Scan summary message. + """ + return f"{nf} images, {nm + ne} backgrounds, {nc} corrupt" + + def verify_args(self) -> tuple: + """Return the per-image verification function and its argument iterable used by `cache_labels`. + + Returns: + (tuple): (verify function, zipped argument iterable) for ThreadPool.imap. + """ + nkpt, ndim = self.data.get("kpt_shape", (0, 0)) + return verify_image_label, zip( + self.im_files, + self.label_files, + repeat(self.prefix), + repeat(self.use_keypoints), + repeat(len(self.data["names"])), + repeat(nkpt), + repeat(ndim), + repeat(self.single_cls), + ) + + def result_to_label(self, result: list) -> tuple[dict | None, int, int, int, int, str]: + """Convert one verification result into a label dict and scan counter increments. + + Args: + result (list): One result from the verification function returned by `verify_args`. + + Returns: + (tuple): (label dict or None, missing, found, empty, corrupt, message). + """ + im_file, lb, shape, segments, keypoint, nm_f, nf_f, ne_f, nc_f, msg = result + label = ( + { + "im_file": im_file, + "shape": shape, + "cls": lb[:, 0:1], # n, 1 + "bboxes": lb[:, 1:], # n, 4 + "segments": segments, + "keypoints": keypoint, + "normalized": True, + "bbox_format": "xywh", + } + if im_file + else None + ) + return label, nm_f, nf_f, ne_f, nc_f, msg + + def verify_labels(self, labels: list[dict], cache_path: Path) -> None: + """Check that the dataset is all boxes or all segments, removing mixed segments if necessary. + + Args: + labels (list[dict]): List of label dictionaries. + cache_path (Path): Path of the dataset cache file, used in warning messages. + """ + # Check if the dataset is all boxes or all segments + lengths = ((len(lb["cls"]), len(lb["bboxes"]), len(lb["segments"])) for lb in labels) + len_cls, len_boxes, len_segments = (sum(x) for x in zip(*lengths)) + if self.use_segments and len_boxes != len_segments: + raise ValueError( + f"Segment dataset requires equal numbers of boxes and segments, but got len(segments) = " + f"{len_segments}, len(boxes) = {len_boxes}. Please supply a segment dataset, not a detect dataset." + ) + if len_segments and len_boxes != len_segments: + LOGGER.warning( + f"Box and segment counts should be equal, but got len(segments) = {len_segments}, " + f"len(boxes) = {len_boxes}. To resolve this only boxes will be used and all segments will be removed. " + "To avoid this please supply either a detect or segment dataset, not a detect-segment mixed dataset." + ) + for lb in labels: + lb["segments"] = [] + if len_cls == 0: + LOGGER.warning(f"Labels are missing or empty in {cache_path}, training may not work correctly. {HELP_URL}") + + def _load_or_scan_cache(self, cache_path: Path, cache_hash: str) -> tuple[dict, bool]: + """Load a dataset cache file if it matches the current version and hash, otherwise rescan and rebuild it. + + Args: + cache_path (Path): Path of the cache file. + cache_hash (str): Expected hash of the dataset files. + + Returns: + (tuple): (cache dict, True if a valid existing cache file was loaded). + """ + try: + cache, exists = load_dataset_cache_file(cache_path), True # attempt to load a *.cache file + assert cache["version"] == DATASET_CACHE_VERSION # matches current version + assert cache["hash"] == cache_hash # identical hash + except (FileNotFoundError, AssertionError, AttributeError, ModuleNotFoundError): + cache, exists = self.cache_labels(cache_path), False # run cache ops + return cache, exists + + def get_labels(self) -> list[dict]: + """Return list of label dictionaries for YOLO training. + + This method loads labels from disk or cache, verifies their integrity, and prepares them for training. + + Returns: + (list[dict]): List of label dictionaries, each containing information about an image and its annotations. + """ + label_files = self.get_label_files() + cache_path = Path(label_files[0]).parent.with_suffix(".cache") + cache, exists = self._load_or_scan_cache(cache_path, self.get_cache_hash()) + + # Display cache + nf, nm, ne, nc, n = cache.pop("results") # found, missing, empty, corrupt, total + if exists and LOCAL_RANK in {-1, 0}: + d = f"Scanning {cache_path}... {self.scan_summary(nf, nm, ne, nc)}" + TQDM(None, desc=self.prefix + d, total=n, initial=n) # display results + if cache["msgs"]: + LOGGER.info("\n".join(cache["msgs"])) # display warnings + + # Read cache + labels = cache["labels"] + if not labels: + issues = "\n ".join(sorted(set(cache["msgs"]))) or "no error details" + raise RuntimeError(f"No valid images found in {cache_path}.\n {issues}\n{HELP_URL}") + [cache.pop(k) for k in ("hash", "version", "msgs")] # remove items + self.im_files = [lb["im_file"] for lb in labels] # update im_files + self.verify_labels(labels, cache_path) + return labels + + def build_transforms(self, hyp: dict | None = None) -> Compose: + """Build and append transforms to the list. + + Args: + hyp (dict, optional): Hyperparameters for transforms. + + Returns: + (Compose): Composed transforms. + """ + if self.augment: + hyp.mosaic = hyp.mosaic if self.augment and not self.rect else 0.0 + hyp.mixup = hyp.mixup if self.augment and not self.rect else 0.0 + hyp.cutmix = hyp.cutmix if self.augment and not self.rect else 0.0 + transforms = v8_transforms(self, self.imgsz, hyp) + else: + transforms = Compose([LetterBox(new_shape=(self.imgsz, self.imgsz), scaleup=False)]) + transforms.append( + self.format_class( + bbox_format="xywh", + normalize=True, + return_mask=self.use_segments, + return_keypoint=self.use_keypoints, + return_obb=self.use_obb, + batch_idx=True, + mask_ratio=hyp.mask_ratio, + mask_overlap=hyp.overlap_mask, + bgr=hyp.bgr if self.augment else 0.0, # only affect training. + ) + ) + return transforms + + def build_text_transforms(self, transforms: Compose, max_samples: int) -> Compose: + """Insert text augmentation for text-based subclasses providing `category_freq`. + + Args: + transforms (Compose): Transforms composed by build_transforms. + max_samples (int): Maximum number of text samples per image. + + Returns: + (Compose): Transforms with RandomLoadText inserted before Format when augmenting. + """ + if self.augment: + # NOTE: hard-coded the args for now. + # NOTE: this implementation is different from official yoloe, + # the strategy of selecting negative is restricted in one dataset, + # while official pre-saved neg embeddings from all datasets at once. + transform = RandomLoadText( + max_samples=min(max_samples, 80), + padding=True, + padding_value=self._get_neg_texts(self.category_freq), + ) + transforms.insert(-1, transform) + return transforms + + @staticmethod + def _get_neg_texts(category_freq: dict) -> list[str]: + """Get negative text samples with frequency above the dataset threshold.""" + threshold = min(max(category_freq.values()), 100) + return [k for k, v in category_freq.items() if v >= threshold] + + def close_mosaic(self, hyp: dict) -> None: + """Disable mosaic, copy_paste, mixup and cutmix augmentations by setting their values to 0.0. + + Args: + hyp (dict): Hyperparameters for transforms. + """ + hyp.mosaic = 0.0 + hyp.copy_paste = 0.0 + hyp.mixup = 0.0 + hyp.cutmix = 0.0 + self.transforms = self.build_transforms(hyp) + + def update_labels_info(self, label: dict) -> dict: + """Update label format for different tasks. + + Args: + label (dict): Label dictionary containing bboxes, segments, keypoints, etc. + + Returns: + (dict): Updated label dictionary with instances. + + Notes: + cls is not with bboxes now, classification and semantic segmentation need an independent cls label + Can also support classification and semantic segmentation by adding or removing dict keys there. + """ + bboxes = label.pop("bboxes") + segments = label.pop("segments", []) + keypoints = label.pop("keypoints", None) + bbox_format = label.pop("bbox_format") + normalized = label.pop("normalized") + + # NOTE: do NOT resample oriented boxes + segment_resamples = 100 if self.use_obb else 1000 + if len(segments) > 0: + # make sure segments interpolate correctly if original length is greater than segment_resamples + max_len = max(len(s) for s in segments) + segment_resamples = (max_len + 1) if segment_resamples < max_len else segment_resamples + # list[np.array(segment_resamples, 2)] * num_samples + segments = np.stack(resample_segments(segments, n=segment_resamples), axis=0) + else: + segments = np.zeros((0, segment_resamples, 2), dtype=np.float32) + label["instances"] = Instances(bboxes, segments, keypoints, bbox_format=bbox_format, normalized=normalized) + return label + + @staticmethod + def collate_fn(batch: list[dict]) -> dict: + """Collate data samples into batches. + + Args: + batch (list[dict]): List of dictionaries containing sample data. + + Returns: + (dict): Collated batch with stacked tensors. + """ + new_batch = {} + batch = [dict(sorted(b.items())) for b in batch] # make sure the keys are in the same order + keys = batch[0].keys() + values = list(zip(*[list(b.values()) for b in batch])) + for i, k in enumerate(keys): + value = values[i] + if k in {"img", "text_feats", "semantic_mask", "sem_masks", "depth"}: + value = torch.stack(value, 0) + elif k == "visuals": + value = torch.nn.utils.rnn.pad_sequence(value, batch_first=True) + if k in {"masks", "keypoints", "bboxes", "cls", "segments", "obb"}: + value = torch.cat(value, 0) + new_batch[k] = value + if "batch_idx" in new_batch: + new_batch["batch_idx"] = list(new_batch["batch_idx"]) + for i in range(len(new_batch["batch_idx"])): + new_batch["batch_idx"][i] += i # add target image index for build_targets() + new_batch["batch_idx"] = torch.cat(new_batch["batch_idx"], 0) + return new_batch + + +class DepthDataset(YOLODataset): + """Dataset for monocular depth estimation with paired RGB + depth map loading. + + Extends YOLODataset to load depth ground truth maps alongside RGB images. Depth maps are stored as PNG or NPY files + in a parallel directory structure (images/train/*.jpg → depth/train/*.{png,npy}). + + Examples: + >>> dataset = DepthDataset(img_path="/data/nyu/images/train", data={"nc": 1}) + """ + + format_class = DepthFormat + + def _depth_path_for(self, im_file: str) -> str: + """Map an image path to its companion PNG or NPY depth target.""" + parts = list(Path(im_file).parts) + for i in range(len(parts) - 1, -1, -1): + if parts[i] == "images": + parts[i] = "depth" + break + path = Path(*parts).with_suffix(".png") + return str(path if path.is_file() else path.with_suffix(".npy")) + + def get_label_files(self) -> list[str]: + """Return the depth paths paired with the dataset's images. + + Returns: + (list[str]): List of depth file paths. + """ + self.depth_files_by_image = {f: self._depth_path_for(f) for f in self.im_files} + self.depth_files = list(self.depth_files_by_image.values()) + return self.depth_files + + def get_cache_hash(self) -> str: + """Return a hash over the paired depth and image files. + + Returns: + (str): Dataset cache hash. + """ + return get_hash(self.depth_files + self.im_files + [str(self.data.get("depth_scale", 1000))]) + + def scan_summary(self, nf: int, nm: int, ne: int, nc: int) -> str: + """Return a one-line summary of image-depth scan counters.""" + return f"{nf} images, {nm} missing depth, {nc} corrupt" + + def verify_args(self) -> tuple: + """Return the depth verification function and its argument iterable.""" + return verify_image_depth, zip( + self.im_files, self.depth_files, repeat(self.prefix), repeat(self.data.get("depth_scale", 1000)) + ) + + def result_to_label(self, result: tuple) -> tuple[dict | None, int, int, int, int, str]: + """Convert one verify_image_depth result into a label dict and scan counter increments.""" + im_file, shape, nf_f, nm_f, nc_f, msg = result + label = ( + { + "im_file": im_file, + "shape": shape, + "cls": np.array([], dtype=np.float32), + "bboxes": np.zeros((0, 4), dtype=np.float32), + "segments": [], + "normalized": True, + "bbox_format": "xywh", + } + if im_file + else None + ) + return label, nm_f, nf_f, 0, nc_f, msg + + def verify_labels(self, labels: list[dict], cache_path: Path) -> None: + """Skip box and segment checks; depth datasets carry no box or segment annotations.""" + + def _load_depth(self, index): + """Return the native-resolution depth map for an image.""" + return load_depth(self.depth_files_by_image[self.im_files[index]], self.data.get("depth_scale", 1000)) + + def get_image_and_label(self, index): + """Load image, label, and depth map for the given index.""" + label = super().get_image_and_label(index) + h, w = label["resized_shape"] + depth = self._load_depth(index) + if depth.shape[:2] != (h, w): + depth = cv2.resize(depth, (w, h), interpolation=cv2.INTER_NEAREST) + label["depth"] = depth + return label + + def build_transforms(self, hyp=None): + """Build transforms for depth estimation. + + Args: + hyp (dict): Hyperparameters. + + Returns: + (Compose): Composed transforms. + """ + # NOTE: For now following arguments are not supported + hyp.mosaic = hyp.mixup = hyp.cutmix = hyp.copy_paste = 0.0 + transforms = super().build_transforms(hyp) + if not self.augment: + # stretch the image instead of padding + transforms[-2] = LetterBox(new_shape=(self.imgsz, self.imgsz), scale_fill=True) + return transforms + + +class YOLOMultiModalDataset(YOLODataset): + """Dataset class for loading object detection and/or segmentation labels in YOLO format with multi-modal support. + + This class extends YOLODataset to add text information for multi-modal model training, enabling models to process + both image and text data. + + Methods: + update_labels_info: Add text information for multi-modal model training. + build_transforms: Enhance data transformations with text augmentation. + + Examples: + >>> dataset = YOLOMultiModalDataset(img_path="path/to/images", data={"names": {0: "person"}}, task="detect") + >>> batch = next(iter(dataset)) + >>> print(batch.keys()) # Should include 'texts' + """ + + def __init__(self, *args, data: dict | None = None, task: str = "detect", **kwargs): + """Initialize a YOLOMultiModalDataset. + + Args: + data (dict, optional): Dataset configuration dictionary. + task (str): Task type, one of 'detect', 'segment', 'pose', or 'obb'. + *args (Any): Additional positional arguments for the parent class. + **kwargs (Any): Additional keyword arguments for the parent class. + """ + super().__init__(*args, data=data, task=task, **kwargs) + + def update_labels_info(self, label: dict) -> dict: + """Add text information for multi-modal model training. + + Args: + label (dict): Label dictionary containing bboxes, segments, keypoints, etc. + + Returns: + (dict): Updated label dictionary with instances and texts. + """ + labels = super().update_labels_info(label) + # NOTE: some categories are concatenated with its synonyms by `/`. + # NOTE: and `RandomLoadText` would randomly select one of them if there are multiple words. + labels["texts"] = [v.split("/") for _, v in self.data["names"].items()] + + return labels + + def build_transforms(self, hyp: dict | None = None) -> Compose: + """Enhance data transformations with text augmentation for multi-modal training. + + Args: + hyp (dict, optional): Hyperparameters for transforms. + + Returns: + (Compose): Composed transforms including text augmentation if applicable. + """ + return self.build_text_transforms(super().build_transforms(hyp), self.data["nc"]) + + @property + def category_names(self): + """Return category names for the dataset. + + Returns: + (set[str]): Set of class names. + """ + names = self.data["names"].values() + return {n.strip() for name in names for n in name.split("/")} # category names + + @property + def category_freq(self): + """Return frequency of each category in the dataset.""" + texts = [v.split("/") for v in self.data["names"].values()] + category_freq = defaultdict(int) + for label in self.labels: + for c in label["cls"].squeeze(-1): # to check + text = texts[int(c)] + for t in text: + t = t.strip() + category_freq[t] += 1 + # a background-only dataset sees no class, leaving every class an equally valid negative + return category_freq or dict.fromkeys((t.strip() for text in texts for t in text), 0) + + +class GroundingDataset(YOLODataset): + """Dataset class for object detection tasks using annotations from a JSON file in grounding format. + + This dataset is designed for grounding tasks where annotations are provided in a JSON file rather than the standard + YOLO format text files. + + Attributes: + json_file (str): Path to the JSON file containing annotations. + + Methods: + get_labels: Load annotations from a JSON file and prepare them for training. + build_transforms: Configure augmentations for training with optional text loading. + + Examples: + >>> dataset = GroundingDataset(img_path="path/to/images", json_file="annotations.json", task="detect") + >>> len(dataset) # Number of valid images with annotations + """ + + def __init__(self, *args, task: str = "detect", json_file: str = "", max_samples: int = 80, **kwargs): + """Initialize a GroundingDataset for object detection. + + Args: + json_file (str): Path to the JSON file containing annotations. + task (str): Must be 'detect' or 'segment' for GroundingDataset. + max_samples (int): Maximum number of samples to load for text augmentation. + *args (Any): Additional positional arguments for the parent class. + **kwargs (Any): Additional keyword arguments for the parent class. + """ + assert task in {"detect", "segment"}, "GroundingDataset currently only supports `detect` and `segment` tasks" + self.json_file = json_file + self.max_samples = max_samples + super().__init__(*args, task=task, data={"channels": 3}, **kwargs) + + def get_img_files(self, img_path: str) -> list[str]: + """Return every image under `img_path`; the annotations, not `fraction`, decide which ones are used.""" + self.fraction = 1.0 # a truncated inventory would leave later images outside the cache key + self.scan_files = super().get_img_files(img_path) + return self.scan_files + + def get_cache_hash(self) -> str: + """Return a hash over the annotation file and images scanned against it.""" + return get_hash([self.json_file, *self.scan_files]) + + def _verify_instance_counts(self, labels: list[dict[str, Any]]) -> None: + """Verify instance counts for known grounding datasets.""" + expected_counts = { + "final_mixed_train_no_coco_segm": 3662412, + "final_mixed_train_no_coco": 3681235, + "final_flickr_separateGT_train_segm": 638214, + "final_flickr_separateGT_train": 640704, + } + + instance_count = sum(label["bboxes"].shape[0] for label in labels) + for data_name, count in expected_counts.items(): + if data_name in self.json_file: + assert instance_count == count, f"'{self.json_file}' has {instance_count} instances, expected {count}." + return + LOGGER.warning(f"Skipping instance count verification for unrecognized dataset '{self.json_file}'") + + def cache_labels(self, path: Path = Path("./labels.cache")) -> dict[str, Any]: + """Load annotations from a JSON file, filter, and normalize bounding boxes for each image. + + Args: + path (Path): Path where to save the cache file. + + Returns: + (dict[str, Any]): Dictionary containing cached labels and related information. + """ + x = {"labels": []} + LOGGER.info("Loading annotation file...") + with open(self.json_file) as f: + annotations = json.load(f) + images = {f"{x['id']:d}": x for x in annotations["images"]} + img_to_anns = defaultdict(list) + for ann in annotations["annotations"]: + img_to_anns[ann["image_id"]].append(ann) + dropped = False + for img_id, anns in TQDM(img_to_anns.items(), desc=f"Reading annotations {self.json_file}"): + img = images[f"{img_id:d}"] + h, w, f = img["height"], img["width"], img["file_name"] + im_file = Path(self.img_path) / f + if not im_file.exists(): + continue + bboxes = [] + segments = [] + segmented = False + cat2id = {} + texts = [] + for ann in anns: + if ann["iscrowd"]: + continue + box = np.array(ann["bbox"], dtype=np.float32) + box[:2] += box[2:] / 2 + box[[0, 2]] /= float(w) + box[[1, 3]] /= float(h) + if box[2] <= 0 or box[3] <= 0: + continue + + caption = img["caption"] + cat_name = " ".join([caption[t[0] : t[1]] for t in ann["tokens_positive"]]).lower().strip() + if not cat_name: + continue + + if cat_name not in cat2id: + cat2id[cat_name] = len(cat2id) + texts.append([cat_name]) + cls = cat2id[cat_name] # class + box = [cls, *box.tolist()] + if box not in bboxes: + bboxes.append(box) + raw_seg = ann.get("segmentation") + segmented |= raw_seg is not None + seg = raw_seg if isinstance(raw_seg, list) else [] + polygons = [ + p + for p in seg + if isinstance(p, list) + and len(p) >= 6 + and not len(p) % 2 + and all(isinstance(c, (int, float)) for c in p) + ] + dropped |= bool(raw_seg) and (not isinstance(raw_seg, list) or len(polygons) < len(seg)) + if not polygons: # keep one segment per box so an image mixing the two kinds stays aligned + cx, cy, bw, bh = box[1:] + x1, y1, x2, y2 = cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2 + segments.append([cls, x1, y1, x2, y1, x2, y2, x1, y2]) # segments2boxes returns the box + continue + elif len(polygons) > 1: + s = merge_multi_segment(polygons) + s = (np.concatenate(s, axis=0) / np.array([w, h], dtype=np.float32)).reshape(-1).tolist() + else: + s = [j for i in polygons for j in i] # all segments concatenated + s = ( + (np.array(s, dtype=np.float32).reshape(-1, 2) / np.array([w, h], dtype=np.float32)) + .reshape(-1) + .tolist() + ) + segments.append([cls, *s]) + lb = np.array(bboxes, dtype=np.float32) if len(bboxes) else np.zeros((0, 5), dtype=np.float32) + + if segmented: + segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in segments] # (cls, xy1...) + lb[:, 1:] = segments2boxes(segments) # boxes follow the polygons + else: + segments = [] # no annotation carried a segmentation, so store no masks + + x["labels"].append( + { + "im_file": im_file, + "shape": (h, w), + "cls": lb[:, 0:1], # n, 1 + "bboxes": lb[:, 1:], # n, 4 + "segments": segments, + "normalized": True, + "bbox_format": "xywh", + "texts": texts, + } + ) + if dropped: + LOGGER.warning( + f"{self.json_file}: ignored segmentations that are not polygon point lists, such as RLE masks. " + "Annotations left without a polygon use a segment shaped like their bounding box." + ) + x["hash"] = self.get_cache_hash() + save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION) + return x + + def get_labels(self) -> list[dict]: + """Load labels from cache or generate them from JSON file. + + Returns: + (list[dict]): List of label dictionaries, each containing information about an image and its annotations. + """ + cache_path = Path(self.json_file).with_suffix(".cache") + cache, _ = self._load_or_scan_cache(cache_path, self.get_cache_hash()) + [cache.pop(k) for k in ("hash", "version")] # remove items + labels = cache["labels"] + if not labels: + raise RuntimeError(f"No images from {self.json_file} found in {self.img_path}. {HELP_URL}") + if not any(label["texts"] for label in labels): # category_freq is empty, so negative texts cannot be built + raise RuntimeError( + f"No annotations in {self.json_file} survived filtering. Every one is iscrowd, resolves to an empty " + f"caption span or has a zero-size box. {HELP_URL}" + ) + self._verify_instance_counts(labels) + self.im_files = [str(label["im_file"]) for label in labels] + if LOCAL_RANK in {-1, 0}: + LOGGER.info(f"Load {self.json_file} from cache file {cache_path}") + return labels + + def build_transforms(self, hyp: dict | None = None) -> Compose: + """Configure augmentations for training with optional text loading. + + Args: + hyp (dict, optional): Hyperparameters for transforms. + + Returns: + (Compose): Composed transforms including text augmentation if applicable. + """ + return self.build_text_transforms(super().build_transforms(hyp), self.max_samples) + + @property + def category_names(self): + """Return unique category names from the dataset.""" + return {t.strip() for label in self.labels for text in label["texts"] for t in text} + + @property + def category_freq(self): + """Return frequency of each category in the dataset.""" + category_freq = defaultdict(int) + for label in self.labels: + for text in label["texts"]: + for t in text: + t = t.strip() + category_freq[t] += 1 + return category_freq + + +class YOLOConcatDataset(ConcatDataset): + """Dataset as a concatenation of multiple datasets. + + This class is useful to assemble different existing datasets for YOLO training, ensuring they use the same collation + function. + + Methods: + collate_fn: Static method that collates data samples into batches using YOLODataset's collation function. + + Examples: + >>> dataset1 = YOLODataset(...) + >>> dataset2 = YOLODataset(...) + >>> combined_dataset = YOLOConcatDataset([dataset1, dataset2]) + """ + + @staticmethod + def collate_fn(batch: list[dict]) -> dict: + """Collate data samples into batches. + + Args: + batch (list[dict]): List of dictionaries containing sample data. + + Returns: + (dict): Collated batch with stacked tensors. + """ + return YOLODataset.collate_fn(batch) + + def close_mosaic(self, hyp: dict) -> None: + """Disable mosaic, copy_paste, mixup and cutmix augmentations by setting their values to 0.0. + + Args: + hyp (dict): Hyperparameters for transforms. + """ + for dataset in self.datasets: + if not hasattr(dataset, "close_mosaic"): + continue + dataset.close_mosaic(hyp) + + +class SemanticDataset(YOLODataset): + """Dataset for semantic segmentation with PNG mask labels. + + Expects a directory structure where each image has a corresponding PNG mask file with the same stem. Pixel values in + masks represent class IDs, with 255 as the ignore label. + + The mask directory is specified in the dataset YAML via 'masks_dir' key, and mirrors the images/ directory structure + (e.g., images/train/ -> masks/train/). + + Attributes: + data (dict): Dataset configuration from YAML. + mask_files (list[str]): List of mask file paths corresponding to images. + include_class (np.ndarray | None): Class ids to keep per pixel (None keeps all). + masks (dict[int, np.ndarray]): Resized masks of the images in the mosaic buffer, evicted with them. + """ + + format_class = SemanticFormat + + def __init__(self, *args, data: dict | None = None, **kwargs): + """Initialize SemanticDataset. + + Args: + *args (Any): Additional positional arguments for the parent class. + data (dict): Dataset configuration dictionary. + **kwargs (Any): Additional keyword arguments for the parent class. + """ + self.data = data or {} + self.label_mapping = self._parse_label_mapping(self.data.get("label_mapping")) + self.label_lut, self.inverse_lut = self._build_label_luts() + self.mask_files = [] + self.include_class = None + self.masks = {} # masks of the buffered images, evicted with the image buffer + super().__init__(*args, data=data, **kwargs) + + def update_labels(self, include_class: list[int] | None) -> None: + """Update labels to include only specified classes. + + Args: + include_class (list[int], optional): List of classes to include. If None, all classes are included. + """ + if self.single_cls: + raise NotImplementedError( + "'single_cls=True' is not supported for semantic segmentation: it forces a single-channel " + "model but cannot collapse multi-class masks. Use a dataset with 'nc: 1' for binary " + "(foreground/background) segmentation instead." + ) + self.include_class = None if include_class is None else np.asarray(include_class, dtype=np.int32).reshape(-1) + if self.include_class is not None and int(self.data.get("nc", 0)) == 1: + LOGGER.warning( + "'classes' filtering is ignored for single-class (binary) semantic segmentation: keeping only " + "the sole class would discard all background supervision." + ) + self.include_class = None + + def _parse_label_mapping(self, mapping): + """Normalize label_mapping entries from dataset YAML into integer-to-integer ids.""" + if mapping is None: + return {} + if not isinstance(mapping, dict): + raise TypeError(f"Expected 'label_mapping' to be a dict in dataset YAML, but got {type(mapping).__name__}.") + + normalized = {} + for src, dst in mapping.items(): + src = int(src) + if isinstance(dst, str): + dst = dst.strip() + dst = 255 if dst == "ignore_label" else int(dst) + elif dst is None: + dst = 255 + else: + dst = int(dst) + normalized[src] = dst + return normalized + + def _build_label_luts(self) -> tuple[np.ndarray, np.ndarray]: + """Build the 256-entry forward and inverse lookup tables for the dataset label mapping.""" + forward, inverse = np.arange(256, dtype=np.uint8), np.arange(256, dtype=np.uint8) + for k, v in self.label_mapping.items(): # ids outside 0-255 never match a uint8 mask pixel + if 0 <= k < 256: + forward[k] = v + if 0 <= v < 256: + inverse[v] = k & 0xFF # cityscapes maps -1; the inverse caller casts the result to uint8 + return forward, inverse + + def get_label_files(self) -> list[str]: + """Return the mask PNG paths paired with the dataset's images. + + Returns: + (list[str]): List of mask file paths. + """ + self.mask_files = img2label_paths(self.im_files, label_dir=self.data.get("masks_dir", "masks"), suffix=".png") + return self.mask_files + + def get_cache_hash(self) -> str: + """Return a hash for semantic cache validation that also includes label_mapping changes. + + Returns: + (str): Dataset cache hash. + """ + mapping = json.dumps(self.label_mapping, sort_keys=True, separators=(",", ":")) + return get_hash(self.im_files + self.mask_files + [f"label_mapping:{mapping}"]) + + def scan_summary(self, nf: int, nm: int, ne: int, nc: int) -> str: + """Return a one-line summary of image-mask scan counters.""" + return f"{nf} images, {nm} missing masks, {nc} corrupt" + + def verify_args(self) -> tuple: + """Return the mask verification function and its argument iterable.""" + return verify_image_mask, zip(self.im_files, self.mask_files, repeat(self.prefix)) + + def result_to_label(self, result: tuple) -> tuple[dict | None, int, int, int, int, str]: + """Convert one verify_image_mask result into a label dict and scan counter increments.""" + im_file, mask_file, shape, is_1bit, nm_f, nf_f, nc_f, msg = result + label = ( + { + "im_file": im_file, + "mask_file": mask_file, + "shape": shape, + "is_1bit": is_1bit, + "cls": np.array([], dtype=np.float32), + "bboxes": np.zeros((0, 4), dtype=np.float32), + "segments": [], + "normalized": True, + "bbox_format": "xywh", + } + if im_file + else None + ) + return label, nm_f, nf_f, 0, nc_f, msg + + def verify_labels(self, labels: list[dict], cache_path: Path) -> None: + """Skip box and segment checks; semantic masks carry no box or segment annotations.""" + + def get_labels(self) -> list[dict]: + """Load semantic labels from cache or scan image-mask paths. + + Returns: + (list[dict]): List of label dictionaries with mask file paths and image shapes. + """ + labels = super().get_labels() + self.mask_files = [lb["mask_file"] for lb in labels] + return labels + + def load_image(self, i, rect_mode=True): + """Load an image for semantic segmentation, scaling the short side to imgsz when rect_mode=True.""" + return super().load_image(i, rect_mode=rect_mode, resize_short=self.augment) + + def load_mask(self, index: int, image_shape: tuple[int, int] | None = None) -> np.ndarray: + """Load a semantic mask and apply optional dataset label mapping.""" + mask_file = self.labels[index]["mask_file"] + mask = cv2.imread(mask_file, cv2.IMREAD_GRAYSCALE) + if mask is None: + raise FileNotFoundError(f"Semantic mask not found or unreadable: {mask_file}") + if int(self.data.get("nc", 0)) == 1 and self.labels[index]["is_1bit"]: + mask[mask == 255] = 1 # cv2 expands 1-bit PNG foreground to 255. + if self.label_mapping: + mask = self.convert_label(mask, inverse=False) + return mask.astype(np.uint8, copy=False) + + def convert_label(self, label, inverse=False): + """Convert label values using the dataset's label mapping. + + Args: + label (np.ndarray): Segmentation label array with integer ids in 0-255. + inverse (bool): If True, apply inverse mapping (mapped -> original). Defaults to False. + + Returns: + (np.ndarray): New uint8 array with converted values. + """ + lut = self.inverse_lut if inverse else self.label_lut + return cv2.LUT(label, lut) if label.dtype == np.uint8 else lut[label] # cv2.LUT needs a uint8 input + + def get_image_and_label(self, index): + """Get image, label and semantic mask for the given index. + + Overrides parent to include the semantic mask, served from RAM for the images Mosaic draws from the buffer. + + Args: + index (int): Dataset index. + + Returns: + (dict): Label dict with 'img', 'semantic_mask', and metadata. + """ + label = super().get_image_and_label(index) + h, w = label["img"].shape[:2] + mask = self.masks.get(index) + if mask is None: + mask = self.load_mask(index, image_shape=(h, w)) + if self.include_class is not None: # keep only selected classes; remap the rest to the ignore label + mask[~np.isin(mask, self.include_class)] = 255 + if mask.shape[:2] != (h, w): + mask = cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST) + if index in self.buffer: # image is RAM-resident for mosaic reuse, keep its mask with it + self.masks[index] = mask + if len(self.masks) > len(self.buffer): + self.masks = {i: self.masks[i] for i in self.buffer if i in self.masks} + label["semantic_mask"] = mask + return label + + +class PolygonSemanticDataset(SemanticDataset, YOLODataset): + """Semantic segmentation dataset that rasterizes YOLO polygon labels into masks on the fly. + + Used when the dataset YAML lacks 'masks_dir'. Pixels not covered by any polygon become a dedicated background class. + Requires `add_polygon_background(data)` to be called first: for nc > 1 it bumps `data['nc']` to user_nc + 1 with + background at `nc - 1`; for nc == 1 it keeps nc=1 and rasterizes a {0=bg, 1=fg} binary mask for use with + BCEWithLogitsLoss. + """ + + def __init__(self, *args, data: dict | None = None, **kwargs): + """Initialize PolygonSemanticDataset. + + Args: + *args (Any): Additional positional arguments for the parent class. + data (dict): Dataset configuration dictionary. + **kwargs (Any): Additional keyword arguments for the parent class. + """ + nc = (data or {}).get("nc") or len((data or {}).get("names", {})) + self.bg_class_idx = data.get("bg_class_idx", max(int(nc) - 1, 0)) + super().__init__(*args, data=data, **kwargs) + + # Rebind label scanning to YOLODataset's polygon .txt implementations; the MRO (SemanticDataset, YOLODataset) + # would otherwise resolve SemanticDataset's PNG-mask hooks and its get_labels, which syncs mask_files from + # label dicts that polygon labels do not have. + get_labels = YOLODataset.get_labels + get_label_files = YOLODataset.get_label_files + get_cache_hash = YOLODataset.get_cache_hash + scan_summary = YOLODataset.scan_summary + verify_args = YOLODataset.verify_args + result_to_label = YOLODataset.result_to_label + verify_labels = YOLODataset.verify_labels + + def load_mask(self, index: int, image_shape: tuple[int, int] | None = None) -> np.ndarray: + """Rasterize this image's polygons into a (H, W) uint8 semantic mask, bg = self.bg_class_idx.""" + h, w = image_shape + label = self.labels[index] + cls = label.get("cls") + segments = label.get("segments") or [] + if cls is None or len(cls) == 0 or len(segments) == 0: + return np.full((h, w), self.bg_class_idx, dtype=np.uint8) + + # Denormalize polygons (stored as normalized xy) to pixel coordinates at (h, w). + scale = np.array([w, h], dtype=np.float32) + polys = [np.asarray(s, dtype=np.float32).reshape(-1, 2) * scale for s in segments] + # Returns (H, W) instance index map: 0 = no polygon, 1..N = sorted instance index. + inst, sorted_idx = polygons2masks_overlap((h, w), polys, downsample_ratio=1) + out = np.full((h, w), self.bg_class_idx, dtype=np.uint8) + fg = inst > 0 + if int(self.data.get("nc", 0)) == 1: # binary: fg=1 regardless of label cls value + out[fg] = 1 + else: + cls_arr = np.asarray(cls).reshape(-1).astype(np.int32)[sorted_idx] + out[fg] = cls_arr[inst[fg] - 1].astype(np.uint8) + return out + + +class ClassificationDataset: + """Dataset class for image classification tasks wrapping torchvision ImageFolder functionality. + + This class offers functionalities like image augmentation, caching, and verification. It's designed to efficiently + handle large datasets for training deep learning models, with optional image transformations and caching mechanisms + to speed up training. + + Attributes: + cache_ram (bool): Indicates if caching in RAM is enabled. + cache_disk (bool): Indicates if caching on disk is enabled. + samples (list): A list of lists, each containing the path to an image, its class index, path to its .npy cache + file (if caching on disk), and optionally the loaded image array (if caching in RAM). + torch_transforms (callable): PyTorch transforms to be applied to the images. + root (str): Root directory of the dataset. + prefix (str): Prefix for logging and cache filenames. + + Methods: + __getitem__: Return transformed image and class index for the given sample index. + __len__: Return the total number of samples in the dataset. + verify_images: Verify all images in dataset. + cache_images: Decode images into one contiguous RAM cache. + """ + + def __init__(self, root: str, args, augment: bool = False, prefix: str = "", names: dict[int, str] | None = None): + """Initialize YOLO classification dataset with root directory, arguments, augmentations, and cache settings. + + Args: + root (str): Path to the dataset directory where images are stored in a class-specific folder structure. + args (Namespace): Configuration containing dataset-related settings such as image size, augmentation + parameters, and cache settings. + augment (bool, optional): Whether to apply augmentations to the dataset. + prefix (str, optional): Prefix for logging and cache filenames, aiding in dataset identification. + names (dict[int, str], optional): Model class names; class folders are aligned to this order by name and + folders the model lacks are dropped, since each split's ImageFolder scan is indexed on its own. + """ + import torchvision # scope for faster 'import ultralytics' + + # Base class assigned as attribute rather than used as base class to allow for scoping slow torchvision import + if TORCHVISION_0_18: # 'allow_empty' argument first introduced in torchvision 0.18 + self.base = torchvision.datasets.ImageFolder(root=root, allow_empty=True) + else: + self.base = torchvision.datasets.ImageFolder(root=root) + is_ndjson = (Path(root).parent / ".ndjson.yaml").is_file() + self.samples = self.base.samples + self.root = self.base.root + + # Initialize attributes + fraction = 1.0 if is_ndjson else get_split_fraction(args.fraction, prefix or ("train" if augment else "val")) + count = fraction if isinstance(fraction, int) else max(int(fraction > 0), round(len(self.samples) * fraction)) + self.samples = ( + [self.samples[i] for i in np.linspace(0, len(self.samples) - 1, count, dtype=int)] + if count < len(self.samples) + else self.samples + ) + self.prefix = colorstr(f"{prefix}: ") if prefix else "" + self.cache_ram = args.cache is True or str(args.cache).lower() == "ram" # cache images into RAM + self.cache_disk = str(args.cache).lower() == "disk" # cache images on hard drive as uncompressed *.npy files + self.samples = self.verify_images() # filter out bad images + classes = self.base.classes # this split's class folders, sorted, indexed by the ImageFolder target + if args.single_cls: + index = dict.fromkeys(classes, 0) + elif is_ndjson: # folders are the class ids + index = {c: int(c) for c in classes} + elif names and not set(classes).isdisjoint(names.values()): # align to the model's class order by name + index = {n: i for i, n in names.items()} + else: # folder names carry no class meaning, e.g. ImageNet wnids under humanized names + index = {c: i for i, c in enumerate(classes)} + extra = {c for c in classes if index.get(c, len(names)) >= len(names)} if names else set() # not in the model + n = len(self.samples) + self.samples = [(f, index[classes[t]]) for f, t in self.samples if classes[t] not in extra] + if extra: + LOGGER.warning( + f"{self.prefix}Skipping {n - len(self.samples)} samples from classes the model lacks: {sorted(extra)}" + ) + self.samples = [[*list(x), Path(x[0]).with_suffix(".npy"), None] for x in self.samples] # file, index, npy, im + if self.cache_ram: + self.cache_images() + scale = (1.0 - args.scale, 1.0) # (0.08, 1.0) + self.torch_transforms = ( + classify_augmentations( + size=args.imgsz, + scale=scale, + hflip=args.fliplr, + vflip=args.flipud, + erasing=args.erasing, + auto_augment=args.auto_augment, + hsv_h=args.hsv_h, + hsv_s=args.hsv_s, + hsv_v=args.hsv_v, + ) + if augment + else classify_transforms(size=args.imgsz) + ) + + def __getitem__(self, i: int) -> dict: + """Return transformed image and class index for the given sample index. + + Args: + i (int): Index of the sample to retrieve. + + Returns: + (dict): Dictionary containing the image and its class index. + """ + f, j, fn, im = self.samples[i] # filename, index, filename.with_suffix('.npy'), image + if self.cache_ram: + im = self.img_cache[i] + elif self.cache_disk: + if not fn.exists(): # load npy + np.save(fn.as_posix(), cv2.imread(f), allow_pickle=False) + im = np.load(fn) + else: # read image + im = cv2.imread(f) # BGR + # Convert NumPy array to PIL image + im = Image.fromarray(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)) + sample = self.torch_transforms(im) + return {"img": sample, "cls": j} + + def __len__(self) -> int: + """Return the total number of samples in the dataset.""" + return len(self.samples) + + def cache_images(self) -> None: + """Decode all images once into a single contiguous uint8 buffer before DataLoader workers fork. + + A Python list of per-image arrays is duplicated into every forked worker by copy-on-write refcounting + (https://github.com/ultralytics/ultralytics/issues/9824); one shared buffer is read-only across + workers instead, so RAM stays flat. Original image sizes are preserved for the transforms. + """ + with ThreadPool(NUM_THREADS) as pool: + ims = list( + TQDM( + pool.imap(lambda s: cv2.imread(s[0]), self.samples), + total=len(self.samples), + desc=f"{self.prefix}Caching images", + disable=LOCAL_RANK > 0, + ) + ) + self.img_cache = BaseDataset._ImageCache(ims) + + def verify_images(self) -> list[tuple]: + """Verify all images in dataset. + + Returns: + (list[tuple]): List of valid samples after verification. + """ + desc = f"{self.prefix}Scanning {self.root}..." + path = Path(self.root).with_suffix(".cache") # *.cache file path + + try: + check_file_speeds([file for (file, _) in self.samples[:5]], prefix=self.prefix) # check image read speeds + cache = load_dataset_cache_file(path) # attempt to load a *.cache file + assert cache["version"] == DATASET_CACHE_VERSION # matches current version + assert cache["hash"] == get_hash([x[0] for x in self.samples] + self.base.classes) # files and classes + nf, nc, n, samples = cache.pop("results") # found, corrupt, total, samples + if LOCAL_RANK in {-1, 0}: + d = f"{desc} {nf} images, {nc} corrupt" + TQDM(None, desc=d, total=n, initial=n) + if cache["msgs"]: + LOGGER.info("\n".join(cache["msgs"])) # display warnings + return samples + + # NOTE: ModuleNotFoundError to prevent numpy version conflicts when loading cache files created with different numpy versions + except (FileNotFoundError, AssertionError, AttributeError, ModuleNotFoundError): + # Run scan if *.cache retrieval failed + nf, nc, msgs, samples, x = 0, 0, [], [], {} + with ThreadPool(NUM_THREADS) as pool: + results = pool.imap(func=verify_image, iterable=zip(self.samples, repeat(self.prefix))) + pbar = TQDM(results, desc=desc, total=len(self.samples)) + for sample, nf_f, nc_f, msg in pbar: + if nf_f: + samples.append(sample) + if msg: + msgs.append(msg) + nf += nf_f + nc += nc_f + pbar.desc = f"{desc} {nf} images, {nc} corrupt" + pbar.close() + if msgs: + LOGGER.info("\n".join(msgs)) + x["hash"] = get_hash([x[0] for x in self.samples] + self.base.classes) + x["results"] = nf, nc, len(samples), samples + x["msgs"] = msgs # warnings + save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION) + return samples diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/loaders.py b/.venv/lib/python3.12/site-packages/ultralytics/data/loaders.py new file mode 100644 index 0000000000000000000000000000000000000000..77c697d0336a970c30c0ef80662fe4491d6efdfe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/loaders.py @@ -0,0 +1,746 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import glob +import math +import os +import time +import urllib +from dataclasses import dataclass +from functools import partial +from io import BytesIO +from multiprocessing.pool import ThreadPool +from pathlib import Path +from threading import Thread +from typing import Any + +import cv2 +import numpy as np +import torch +from PIL import Image, ImageOps + +from ultralytics.data.utils import FORMATS_HELP_MSG, IMG_FORMATS, VID_FORMATS +from ultralytics.utils import IS_COLAB, IS_KAGGLE, LOGGER, NUM_THREADS, ops +from ultralytics.utils.checks import check_requirements +from ultralytics.utils.patches import PIL_FALLBACK_SUFFIXES, imread + + +@dataclass +class SourceTypes: + """Class to represent various types of input sources for predictions. + + This class uses dataclass to define boolean flags for different types of input sources that can be used for making + predictions with YOLO models. + + Attributes: + stream (bool): Flag indicating if the input source is a video stream. + screenshot (bool): Flag indicating if the input source is a screenshot. + from_img (bool): Flag indicating if the input source is an in-memory image (PIL/numpy) or list of images. + tensor (bool): Flag indicating if the input source is a tensor. + + Examples: + >>> source_types = SourceTypes(stream=True, screenshot=False, from_img=False) + >>> print(source_types.stream) + True + >>> print(source_types.from_img) + False + """ + + stream: bool = False + screenshot: bool = False + from_img: bool = False + tensor: bool = False + + +class LoadStreams: + """Stream Loader for various types of video streams. + + Supports RTSP, RTMP, HTTP, and TCP streams. This class handles the loading and processing of multiple video streams + simultaneously, making it suitable for real-time video analysis tasks. + + Attributes: + sources (list[str]): The source input paths or URLs for the video streams. + vid_stride (int): Video frame-rate stride. + buffer (bool): Whether to buffer input streams. + running (bool): Flag to indicate if the streaming thread is running. + mode (str): Set to 'stream' indicating real-time capture. + imgs (list[list[np.ndarray]]): List of image frames for each stream. + fps (list[float]): List of FPS for each stream. + frames (list[int]): List of total frames for each stream. + threads (list[Thread]): List of threads for each stream. + shape (list[tuple[int, int, int]]): List of shapes for each stream. + caps (list[cv2.VideoCapture]): List of cv2.VideoCapture objects for each stream. + bs (int): Batch size for processing. + cv2_flag (int): OpenCV flag for image reading (grayscale or color/BGR). + + Methods: + update: Read stream frames in daemon thread. + close: Close stream loader and release resources. + __iter__: Returns an iterator object for the class. + __next__: Returns source paths, transformed, and original images for processing. + __len__: Return the length of the sources object. + + Examples: + >>> stream_loader = LoadStreams("rtsp://example.com/stream1.mp4") + >>> for sources, imgs, _ in stream_loader: + ... # Process the images + ... pass + >>> stream_loader.close() + + Notes: + - The class uses threading to efficiently load frames from multiple streams simultaneously. + - It automatically handles YouTube links, converting them to the best available stream URL. + - The class implements a buffer system to manage frame storage and retrieval. + """ + + def __init__(self, sources: str = "file.streams", vid_stride: int = 1, buffer: bool = False, channels: int = 3): + """Initialize stream loader for multiple video sources, supporting various stream types. + + Args: + sources (str): Path to streams file or single stream URL. + vid_stride (int): Video frame-rate stride. + buffer (bool): Whether to buffer input streams. + channels (int): Number of image channels (1 for grayscale, 3 for color). + """ + torch.backends.cudnn.benchmark = True # faster for fixed-size inference + self.buffer = buffer # buffer input streams + self.running = True # running flag for Thread + self.mode = "stream" + self.vid_stride = vid_stride # video frame-rate stride + self.cv2_flag = cv2.IMREAD_GRAYSCALE if channels == 1 else cv2.IMREAD_COLOR # grayscale or color (BGR) + + sources = Path(sources).read_text().rsplit() if os.path.isfile(sources) else [sources] + n = len(sources) + self.bs = n + self.fps = [0] * n # frames per second + self.frames = [0] * n + self.threads = [None] * n + self.caps = [None] * n # video capture objects + self.imgs = [[] for _ in range(n)] # images + self.shape = [[] for _ in range(n)] # image shapes + self.sources = [ops.clean_str(x).replace(os.sep, "_") for x in sources] # clean source names for later + try: + for i, s in enumerate(sources): # index, source + # Start thread to read frames from video stream + st = f"{i + 1}/{n}: {s}... " + if urllib.parse.urlparse(s).hostname in {"www.youtube.com", "youtube.com", "youtu.be"}: # YouTube video + # YouTube format i.e. 'https://www.youtube.com/watch?v=Jsn8D3aC840' or 'https://youtu.be/Jsn8D3aC840' + s = get_best_youtube_url(s) + s = int(s) if s.isnumeric() else s # i.e. s = '0' local webcam + if s == 0 and (IS_COLAB or IS_KAGGLE): + raise NotImplementedError( + "'source=0' webcam not supported in Colab and Kaggle notebooks. " + "Try running 'source=0' in a local environment." + ) + self.caps[i] = cv2.VideoCapture(s) # store video capture object + if not self.caps[i].isOpened(): + raise ConnectionError(f"{st}Failed to open {s}") + w = int(self.caps[i].get(cv2.CAP_PROP_FRAME_WIDTH)) + h = int(self.caps[i].get(cv2.CAP_PROP_FRAME_HEIGHT)) + fps = self.caps[i].get(cv2.CAP_PROP_FPS) # warning: may return 0 or nan + self.frames[i] = max(int(self.caps[i].get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float( + "inf" + ) # infinite stream fallback + self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30 # 30 FPS fallback + + success, im = self.caps[i].read() # guarantee first frame + if not success or im is None: + raise ConnectionError(f"{st}Failed to read images from {s}") + im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)[..., None] if self.cv2_flag == cv2.IMREAD_GRAYSCALE else im + self.imgs[i].append(im) + self.shape[i] = im.shape + self.threads[i] = Thread(target=self.update, args=([i, self.caps[i], s]), daemon=True) + LOGGER.info(f"{st}Success ✅ ({self.frames[i]} frames of shape {w}x{h} at {self.fps[i]:.2f} FPS)") + self.threads[i].start() + except Exception: + self.close() # release opened captures and stop started threads before re-raising + raise + LOGGER.info("") # newline + + def update(self, i: int, cap: cv2.VideoCapture, stream: str): + """Read stream frames in daemon thread and update image buffer.""" + n, f = 0, self.frames[i] # frame number, total frames + while self.running and cap.isOpened() and n < (f - 1): + if len(self.imgs[i]) < 30: # keep a <=30-image buffer + n += 1 + cap.grab() # .read() = .grab() followed by .retrieve() + if n % self.vid_stride == 0: + success, im = cap.retrieve() + if not success or im is None: + im = np.zeros(self.shape[i], dtype=np.uint8) + LOGGER.warning("Video stream unresponsive, please check your IP camera connection.") + cap.open(stream) # re-open stream if signal was lost + elif self.cv2_flag == cv2.IMREAD_GRAYSCALE: + im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)[..., None] + if self.buffer: + self.imgs[i].append(im) + else: + self.imgs[i] = [im] + else: + time.sleep(0.01) # wait until the buffer is empty + + def close(self): + """Terminate stream loader, stop threads, and release video capture resources.""" + self.running = False # stop flag for Thread + for thread in self.threads: + if thread is not None and thread.is_alive(): + thread.join(timeout=5) # Add timeout + for cap in self.caps: # Iterate through the stored VideoCapture objects + if cap is None: + continue + try: + cap.release() # release video capture + except Exception as e: + LOGGER.warning(f"Could not release VideoCapture object: {e}") + + def __iter__(self): + """Return an iterator object and reset the frame counter.""" + self.count = -1 + return self + + def __next__(self) -> tuple[list[str], list[np.ndarray], list[str]]: + """Return the next batch of frames from multiple video streams for processing.""" + self.count += 1 + + images = [] + for i, x in enumerate(self.imgs): + # Wait until a frame is available in each buffer + while not x: + if not self.threads[i].is_alive(): + self.close() + raise StopIteration + time.sleep(1 / min(self.fps)) + x = self.imgs[i] + if not x: + LOGGER.warning(f"Waiting for stream {i}") + + # Get and remove the first frame from imgs buffer + if self.buffer: + images.append(x.pop(0)) + + # Get the last frame, and clear the rest from the imgs buffer + else: + images.append(x.pop(-1) if x else np.zeros(self.shape[i], dtype=np.uint8)) + x.clear() + + return self.sources, images, [""] * self.bs + + def __len__(self) -> int: + """Return the number of video streams in the LoadStreams object.""" + return self.bs + + +class LoadScreenshots: + """Ultralytics screenshot dataloader for capturing and processing screen images. + + This class manages the loading of screenshot images for processing with YOLO. It is suitable for use with `yolo + predict source=screen`. + + Attributes: + screen (int): The screen number to capture. + left (int): The left coordinate for screen capture area. + top (int): The top coordinate for screen capture area. + width (int): The width of the screen capture area. + height (int): The height of the screen capture area. + mode (str): Set to 'stream' indicating real-time capture. + frame (int): Counter for captured frames. + sct (mss.mss): Screen capture object from `mss` library. + bs (int): Batch size, set to 1. + fps (int): Frames per second, set to 30. + monitor (dict[str, int]): Monitor configuration details. + cv2_flag (int): OpenCV flag for image reading (grayscale or color/BGR). + + Methods: + __iter__: Returns an iterator object. + __next__: Captures the next screenshot and returns it. + + Examples: + >>> loader = LoadScreenshots("0 100 100 640 480") # screen 0, top-left (100,100), 640x480 + >>> for sources, imgs, info in loader: + ... print(f"Captured frame: {imgs[0].shape}") + """ + + def __init__(self, source: str, channels: int = 3): + """Initialize screenshot capture with specified screen and region parameters. + + Args: + source (str): Screen capture source string in format "screen_num left top width height". + channels (int): Number of image channels (1 for grayscale, 3 for color). + """ + check_requirements("mss") + import mss + + source, *params = source.split() + self.screen, left, top, width, height = 0, None, None, None, None # default to full screen 0 + if len(params) == 1: + self.screen = int(params[0]) + elif len(params) == 4: + left, top, width, height = (int(x) for x in params) + elif len(params) == 5: + self.screen, left, top, width, height = (int(x) for x in params) + self.mode = "stream" + self.frame = 0 + self.sct = mss.mss() + self.bs = 1 + self.fps = 30 + self.cv2_flag = cv2.IMREAD_GRAYSCALE if channels == 1 else cv2.IMREAD_COLOR # grayscale or color (BGR) + + # Parse monitor shape + monitor = self.sct.monitors[self.screen] + self.top = monitor["top"] if top is None else (monitor["top"] + top) + self.left = monitor["left"] if left is None else (monitor["left"] + left) + self.width = width or monitor["width"] + self.height = height or monitor["height"] + self.monitor = {"left": self.left, "top": self.top, "width": self.width, "height": self.height} + + def __iter__(self): + """Return an iterator object for the screenshot capture.""" + return self + + def __next__(self) -> tuple[list[str], list[np.ndarray], list[str]]: + """Capture and return the next screenshot as a numpy array using the mss library.""" + im0 = np.asarray(self.sct.grab(self.monitor))[:, :, :3] # BGRA to BGR + im0 = cv2.cvtColor(im0, cv2.COLOR_BGR2GRAY)[..., None] if self.cv2_flag == cv2.IMREAD_GRAYSCALE else im0 + s = f"screen {self.screen} (LTWH): {self.left},{self.top},{self.width},{self.height}: " + + self.frame += 1 + return [str(self.screen)], [im0], [s] # screen, img, string + + +class LoadImagesAndVideos: + """A class for loading and processing images and videos for YOLO object detection. + + This class manages the loading and pre-processing of image and video data from various sources, including single + image files, video files, and lists of image and video paths. + + Attributes: + files (list[str]): List of image and video file paths. + nf (int): Total number of files (images and videos). + video_flag (list[bool]): Flags indicating whether a file is a video (True) or an image (False). + mode (str): Current mode, 'image' or 'video'. + vid_stride (int): Stride for video frame-rate. + bs (int): Batch size. + cap (cv2.VideoCapture): Video capture object for OpenCV. + frame (int): Frame counter for video. + frames (int): Total number of frames in the video. + count (int): Counter for iteration, initialized at 0 during __iter__(). + ni (int): Number of images. + cv2_flag (int): OpenCV flag for image reading (grayscale or color/BGR). + + Methods: + __init__: Initialize the LoadImagesAndVideos object. + __iter__: Returns an iterator object for VideoStream or ImageFolder. + __next__: Returns the next batch of images or video frames along with their paths and metadata. + _new_video: Creates a new video capture object for the given path. + __len__: Returns the number of batches in the object. + + Examples: + >>> loader = LoadImagesAndVideos("path/to/data", batch=32, vid_stride=1) + >>> for paths, imgs, info in loader: + ... # Process batch of images or video frames + ... pass + + Notes: + - Supports various image formats including HEIC. + - Handles both local files and directories. + - Can read from a text file containing paths to images and videos. + """ + + def __init__(self, path: str | Path | list, batch: int = 1, vid_stride: int = 1, channels: int = 3): + """Initialize dataloader for images and videos, supporting various input formats. + + Args: + path (str | Path | list): Path to images/videos, directory, or list of paths. + batch (int): Batch size for processing. + vid_stride (int): Video frame-rate stride. + channels (int): Number of image channels (1 for grayscale, 3 for color). + """ + parent = None + if isinstance(path, str) and Path(path).suffix in {".txt", ".csv"}: # txt/csv file with source paths + parent, content = Path(path).parent, Path(path).read_text() + path = content.splitlines() if Path(path).suffix == ".txt" else content.split(",") # list of sources + path = [p.strip() for p in path] + files = [] + for p in sorted(path) if isinstance(path, (list, tuple)) else [path]: + a = str(Path(p).absolute()) # do not use .resolve() https://github.com/ultralytics/ultralytics/issues/2912 + if "*" in a: + files.extend(sorted(glob.glob(a, recursive=True))) # glob + elif os.path.isdir(a): + files.extend(sorted(glob.glob(os.path.join(glob.escape(a), "*.*")))) # dir + elif os.path.isfile(a): + files.append(a) # files (absolute or relative to CWD) + elif parent and (parent / p).is_file(): + files.append(str((parent / p).absolute())) # files (relative to *.txt file parent) + else: + raise FileNotFoundError(f"{p} does not exist") + + # Define files as images or videos + images, videos = [], [] + for f in files: + suffix = f.rpartition(".")[-1].lower() # Get file extension without the dot and lowercase + if suffix in IMG_FORMATS: + images.append(f) + elif suffix in VID_FORMATS: + videos.append(f) + ni, nv = len(images), len(videos) + + self.files = images + videos + self.nf = ni + nv # number of files + self.ni = ni # number of images + self.video_flag = [False] * ni + [True] * nv + self.mode = "video" if ni == 0 else "image" # default to video if no images + self.vid_stride = vid_stride # video frame-rate stride + self.bs = batch + self.cv2_flag = cv2.IMREAD_GRAYSCALE if channels == 1 else cv2.IMREAD_COLOR # grayscale or color (BGR) + if any(videos): + self._new_video(videos[0]) # new video + else: + self.cap = None + if self.nf == 0: + raise FileNotFoundError(f"No images or videos found in {p}. {FORMATS_HELP_MSG}") + + def __iter__(self): + """Iterate through image/video files, yielding source paths, images, and metadata.""" + self.count = 0 + return self + + def __next__(self) -> tuple[list[str], list[np.ndarray], list[str]]: + """Return the next batch of images or video frames with their paths and metadata.""" + paths, imgs, info = [], [], [] + while len(imgs) < self.bs: + if self.count >= self.nf: # end of file list + if imgs: + return paths, imgs, info # return last partial batch + else: + raise StopIteration + + path = self.files[self.count] + if self.video_flag[self.count]: + self.mode = "video" + if not self.cap or not self.cap.isOpened(): + self._new_video(path) + + success = False + for _ in range(self.vid_stride): + success = self.cap.grab() + if not success: + break # end of video or failure + + if success: + success, im0 = self.cap.retrieve() + if success and im0 is not None: + if self.cv2_flag == cv2.IMREAD_GRAYSCALE: + im0 = cv2.cvtColor(im0, cv2.COLOR_BGR2GRAY)[..., None] + self.frame += 1 + paths.append(path) + imgs.append(im0) + info.append(f"video {self.count + 1}/{self.nf} (frame {self.frame}/{self.frames}) {path}: ") + if self.frame == self.frames: # end of video + self.count += 1 + self.cap.release() + else: + # Move to the next file if the current video ended or failed to open + self.count += 1 + if self.cap: + self.cap.release() + if self.count < self.nf: + self._new_video(self.files[self.count]) + else: + # Handle image files + self.mode = "image" + if self.bs >= 8 and NUM_THREADS > 1 and (n := min(self.bs - len(imgs), self.ni - self.count)) >= 8: + image_paths = self.files[self.count : self.count + n] + # Keep fallback formats serial: their lazy PIL plugin registration is not thread-safe. + if not any(Path(x).suffix.lower() in PIL_FALLBACK_SUFFIXES for x in image_paths): + with ThreadPool(min(n, NUM_THREADS)) as pool: + decoded = pool.map(partial(imread, flags=self.cv2_flag), image_paths) + for i, (image_path, im0) in enumerate(zip(image_paths, decoded)): + self._append_image(paths, imgs, info, image_path, im0, self.count + i + 1) + self.count += n # move to the next batch of files + if self.count >= self.ni and imgs: # flush images before starting videos + break + continue + + im0 = imread(path, flags=self.cv2_flag) # BGR + self._append_image(paths, imgs, info, path, im0, self.count + 1) + self.count += 1 # move to the next file + if self.count >= self.ni and imgs: # end of image list, flush only a non-empty batch + break + + return paths, imgs, info + + def _append_image(self, paths: list, imgs: list, info: list, path: str, im0: np.ndarray | None, idx: int): + """Append a decoded image to the batch lists, or warn and skip it if decoding failed.""" + if im0 is None: + LOGGER.warning(f"Image Read Error {path}") + else: + paths.append(path) + imgs.append(im0) + info.append(f"image {idx}/{self.nf} {path}: ") + + def _new_video(self, path: str): + """Create a new video capture object for the given path and initialize video-related attributes.""" + self.frame = 0 + self.cap = cv2.VideoCapture(path) + self.fps = int(self.cap.get(cv2.CAP_PROP_FPS)) + if not self.cap.isOpened(): + raise FileNotFoundError(f"Failed to open video {path}") + self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT) / self.vid_stride) + + def __len__(self) -> int: + """Return the number of batches in the dataset.""" + return math.ceil(self.nf / self.bs) # number of batches + + +class LoadPilAndNumpy: + """Load images from PIL and Numpy arrays for batch processing. + + This class manages loading and pre-processing of image data from both PIL and Numpy formats. It performs basic + validation and format conversion to ensure that the images are in the required format for downstream processing. + + Attributes: + paths (list[str]): List of image paths or autogenerated filenames. + im0 (list[np.ndarray]): List of images stored as Numpy arrays. + mode (str): Type of data being processed, set to 'image'. + bs (int): Batch size, equivalent to the length of `im0`. + + Methods: + _single_check: Validate and format a single image to a Numpy array. + + Examples: + >>> from PIL import Image + >>> import numpy as np + >>> pil_img = Image.new("RGB", (100, 100)) + >>> np_img = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8) + >>> loader = LoadPilAndNumpy([pil_img, np_img]) + >>> paths, images, _ = next(iter(loader)) + >>> print(f"Loaded {len(images)} images") + Loaded 2 images + """ + + def __init__(self, im0: Image.Image | np.ndarray | list, channels: int = 3): + """Initialize a loader for PIL and Numpy images, converting inputs to a standardized format. + + Args: + im0 (PIL.Image.Image | np.ndarray | list): Single image or list of images in PIL or numpy format. + channels (int): Number of image channels (1 for grayscale, 3 for color). + """ + if not isinstance(im0, list): + im0 = [im0] + if not im0: # an empty batch otherwise fails unnamed inside np.stack in Predictor.preprocess + raise FileNotFoundError("No images found in source, predict requires at least one image.") + # use `image{i}.jpg` when Image.filename returns an empty path. + self.paths = [getattr(im, "filename", "") or f"image{i}.jpg" for i, im in enumerate(im0)] + self.im0 = [self._single_check(im, channels) for im in im0] + self.mode = "image" + self.bs = len(self.im0) + self.count = 0 + + @staticmethod + def _single_check(im: Image.Image | np.ndarray, channels: int = 3) -> np.ndarray: + """Validate an image and normalize its channel count. + + Notes: + - PIL inputs are converted to NumPy and returned in OpenCV-compatible BGR order for color images. + - NumPy color inputs are assumed to use OpenCV-compatible BGR order. + """ + if not isinstance(im, (Image.Image, np.ndarray)): + raise TypeError(f"Expected PIL/np.ndarray image type, but got {type(im)}") + pil = isinstance(im, Image.Image) + if pil: + flag = "L" if channels == 1 else "RGB" + im = np.asarray(im if im.mode == flag else im.convert(flag)) # convert() copies even when mode matches + if flag == "L": + im = im[..., None] + im = np.atleast_3d(im) + # Both routes validate here: a zero dimension divides by zero in LetterBox, and a batched array reads + # shape[2] as a channel count it is not. Raised rather than asserted so `python -O` keeps the check, and + # ahead of the cvtColor calls, which assert on an empty input instead of raising this message. + if im.ndim != 3 or not all(im.shape): + raise ValueError(f"Expected a single (H, W, C) image, but got array of shape {im.shape}") + if pil: + return im if channels == 1 else cv2.cvtColor(im, cv2.COLOR_RGB2BGR) + c = im.shape[2] + if c == channels: + return im + if c == 2: # gray + alpha + im, c = im[..., :1], 1 + u8 = im.dtype == np.uint8 # cvtColor rejects dtypes NumPy indexing accepts, float64 among them + if c == 1: + if u8 and channels == 3: + return cv2.cvtColor(im[..., 0], cv2.COLOR_GRAY2BGR) + return np.repeat(im, channels, axis=2) + if channels == 1: + return cv2.cvtColor(im, cv2.COLOR_BGRA2GRAY if c == 4 else cv2.COLOR_BGR2GRAY)[..., None] + return cv2.cvtColor(im, cv2.COLOR_BGRA2BGR) if u8 and c == 4 else np.ascontiguousarray(im[..., :3]) + + def __len__(self) -> int: + """Return the length of the 'im0' attribute, representing the number of loaded images.""" + return len(self.im0) + + def __next__(self) -> tuple[list[str], list[np.ndarray], list[str]]: + """Return the next batch of images, paths, and metadata for processing.""" + if self.count == 1: # loop only once as it's batch inference + raise StopIteration + self.count += 1 + return self.paths, self.im0, [""] * self.bs + + def __iter__(self): + """Iterate through PIL/numpy images, yielding paths, raw images, and metadata for processing.""" + self.count = 0 + return self + + +class LoadTensor: + """A class for loading and processing tensor data for object detection tasks. + + This class handles the loading and pre-processing of image data from PyTorch tensors, preparing them for further + processing in object detection pipelines. + + Attributes: + im0 (torch.Tensor): The input tensor containing the image(s) with shape (B, C, H, W). + bs (int): Batch size, inferred from the shape of `im0`. + mode (str): Current processing mode, set to 'image'. + paths (list[str]): List of image paths or auto-generated filenames. + + Methods: + _single_check: Validates and formats an input tensor. + + Examples: + >>> import torch + >>> tensor = torch.rand(1, 3, 640, 640) + >>> loader = LoadTensor(tensor) + >>> paths, images, info = next(iter(loader)) + >>> print(f"Processed {len(images)} images") + """ + + def __init__(self, im0: torch.Tensor) -> None: + """Initialize LoadTensor object for processing torch.Tensor image data. + + Args: + im0 (torch.Tensor): Input tensor with shape (B, C, H, W). + """ + self.im0 = self._single_check(im0) + self.bs = self.im0.shape[0] + self.mode = "image" + self.paths = [f"image{i}.jpg" for i in range(self.bs)] + self.count = 0 + + @staticmethod + def _single_check(im: torch.Tensor, stride: int = 32) -> torch.Tensor: + """Validate and format a single image tensor, ensuring correct shape and normalization.""" + s = ( + f"torch.Tensor inputs should be BCHW i.e. shape(1, 3, 640, 640) " + f"divisible by stride {stride}. Input shape{tuple(im.shape)} is incompatible." + ) + if len(im.shape) != 4: + if len(im.shape) != 3: + raise ValueError(s) + LOGGER.warning(s) + im = im.unsqueeze(0) + if not all(im.shape) or im.shape[2] % stride or im.shape[3] % stride: + raise ValueError(s) # a zero dimension reaches im.max() below on an empty tensor + if im.max() > 1.0 + (torch.finfo(im.dtype).eps if im.is_floating_point() else 0): + LOGGER.warning( + f"torch.Tensor inputs should be normalized 0.0-1.0 but max value is {im.max()}. Dividing input by 255." + ) + im = im.float() / 255.0 + + return im + + def __iter__(self): + """Yield an iterator object for iterating through tensor image data.""" + self.count = 0 + return self + + def __next__(self) -> tuple[list[str], torch.Tensor, list[str]]: + """Yield the next batch of tensor images and metadata for processing.""" + if self.count == 1: + raise StopIteration + self.count += 1 + return self.paths, self.im0, [""] * self.bs + + def __len__(self) -> int: + """Return the batch size of the tensor input.""" + return self.bs + + +def autocast_list(source: list[Any]) -> list[Image.Image | np.ndarray]: + """Convert a list of sources into a list of numpy arrays or PIL images for Ultralytics prediction.""" + files = [] + for im in source: + if isinstance(im, (str, Path)): # filename or uri + if str(im).startswith("http"): # requests follows HTTP 308 redirects that urllib lacks pre-3.11 + import requests # scoped as slow import + + im = BytesIO(requests.get(im).content) + im = Image.open(im) + filename = im.filename + im = ImageOps.exif_transpose(im) + im.filename = filename + files.append(im) + elif isinstance(im, (Image.Image, np.ndarray)): # PIL or np Image + files.append(im) + else: + raise TypeError( + f"type {type(im).__name__} is not a supported Ultralytics prediction source type. \n" + f"See https://docs.ultralytics.com/modes/predict for supported source types." + ) + + return files + + +def get_best_youtube_url(url: str, method: str = "pytube") -> str | None: + """Retrieve the URL of the best quality MP4 video stream from a given YouTube video. + + Args: + url (str): The URL of the YouTube video. + method (str): The method to use for extracting video info. Options are "pytube", "pafy", and "yt-dlp". + + Returns: + (str | None): The URL of the best quality MP4 video stream, or None if no suitable stream is found. + + Examples: + >>> url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" + >>> best_url = get_best_youtube_url(url) + >>> print(best_url) + https://rr4---sn-q4flrnek.googlevideo.com/videoplayback?expire=... + + Notes: + - Requires additional libraries based on the chosen method: pytubefix, pafy, or yt-dlp. + - The function prioritizes streams with at least 1080p resolution when available. + - For the "yt-dlp" method, it looks for formats with video codec, no audio, and *.mp4 extension. + """ + if method == "pytube": + # Switched from pytube to pytubefix to resolve https://github.com/pytube/pytube/issues/1954 + check_requirements("pytubefix>=6.5.2") + from pytubefix import YouTube + + streams = YouTube(url).streams.filter(file_extension="mp4", only_video=True) + streams = sorted(streams, key=lambda s: s.resolution, reverse=True) # sort streams by resolution + for stream in streams: + if stream.resolution and int(stream.resolution[:-1]) >= 1080: # check if resolution is at least 1080p + return stream.url + + elif method == "pafy": + check_requirements(("pafy", "youtube_dl==2020.12.2")) + import pafy + + return pafy.new(url).getbestvideo(preftype="mp4").url + + elif method == "yt-dlp": + check_requirements("yt-dlp") + import yt_dlp + + with yt_dlp.YoutubeDL({"quiet": True}) as ydl: + info_dict = ydl.extract_info(url, download=False) # extract info + for f in reversed(info_dict.get("formats", [])): # reversed because best is usually last + # Find a format with video codec, no audio, *.mp4 extension at least 1920x1080 size + good_size = (f.get("width") or 0) >= 1920 or (f.get("height") or 0) >= 1080 + if good_size and f["vcodec"] != "none" and f["acodec"] == "none" and f["ext"] == "mp4": + return f.get("url") + + +# Define constants +LOADERS = (LoadStreams, LoadPilAndNumpy, LoadImagesAndVideos, LoadScreenshots) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/scripts/download_weights.sh b/.venv/lib/python3.12/site-packages/ultralytics/data/scripts/download_weights.sh new file mode 100644 index 0000000000000000000000000000000000000000..d2d1c0f6f77f7258543257d226337e8ff600c4df --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/scripts/download_weights.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Download latest models from https://github.com/ultralytics/assets/releases +# Example usage: bash ultralytics/data/scripts/download_weights.sh +# parent +# └── weights +# ├── yolov8n.pt ← downloads here +# ├── yolov8s.pt +# └── ... + +python << EOF +from ultralytics.utils.downloads import attempt_download_asset + +assets = [f"yolov8{size}{suffix}.pt" for size in "nsmlx" for suffix in ("", "-cls", "-seg", "-pose")] +for x in assets: + attempt_download_asset(f"weights/{x}") +EOF diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/scripts/get_coco.sh b/.venv/lib/python3.12/site-packages/ultralytics/data/scripts/get_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..4490a14d25424450eccb4ece5e8febda13ba826b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/scripts/get_coco.sh @@ -0,0 +1,61 @@ +#!/bin/bash +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Download COCO 2017 dataset https://cocodataset.org +# Example usage: bash data/scripts/get_coco.sh +# parent +# ├── ultralytics +# └── datasets +# └── coco ← downloads here + +# Arguments (optional) Usage: bash data/scripts/get_coco.sh --train --val --test --segments +if [ "$#" -gt 0 ]; then + for opt in "$@"; do + case "${opt}" in + --train) train=true ;; + --val) val=true ;; + --test) test=true ;; + --segments) segments=true ;; + --sama) sama=true ;; + esac + done +else + train=true + val=true + test=false + segments=false + sama=false +fi + +# Download/unzip labels +d='../datasets' # unzip directory +url=https://github.com/ultralytics/assets/releases/download/v0.0.0/ +if [ "$segments" == "true" ]; then + f='coco2017labels-segments.zip' # 169 MB +elif [ "$sama" == "true" ]; then + f='coco2017labels-segments-sama.zip' # 199 MB https://www.sama.com/sama-coco-dataset/ +else + f='coco2017labels.zip' # 46 MB +fi +echo 'Downloading' $url$f ' ...' +curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f & + +# Download/unzip images +d='../datasets/coco/images' # unzip directory +url=http://images.cocodataset.org/zips/ +if [ "$train" == "true" ]; then + f='train2017.zip' # 19G, 118k images + echo 'Downloading' $url$f '...' + curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f & +fi +if [ "$val" == "true" ]; then + f='val2017.zip' # 1G, 5k images + echo 'Downloading' $url$f '...' + curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f & +fi +if [ "$test" == "true" ]; then + f='test2017.zip' # 7G, 41k images (optional) + echo 'Downloading' $url$f '...' + curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f & +fi +wait # finish background tasks diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/scripts/get_coco128.sh b/.venv/lib/python3.12/site-packages/ultralytics/data/scripts/get_coco128.sh new file mode 100644 index 0000000000000000000000000000000000000000..36306cf0dcbfd94cdcfc88181365959623e271ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/scripts/get_coco128.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Download COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) +# Example usage: bash data/scripts/get_coco128.sh +# parent +# ├── ultralytics +# └── datasets +# └── coco128 ← downloads here + +# Download/unzip images and labels +d='../datasets' # unzip directory +url=https://github.com/ultralytics/assets/releases/download/v0.0.0/ +f='coco128.zip' # or 'coco128-segments.zip', 68 MB +echo 'Downloading' $url$f ' ...' +curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f & + +wait # finish background tasks diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/scripts/get_imagenet.sh b/.venv/lib/python3.12/site-packages/ultralytics/data/scripts/get_imagenet.sh new file mode 100644 index 0000000000000000000000000000000000000000..2674de19dcf288988bf9ab95818dbd91ffe235a3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/scripts/get_imagenet.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Download ILSVRC2012 ImageNet dataset https://image-net.org +# Example usage: bash data/scripts/get_imagenet.sh +# parent +# ├── ultralytics +# └── datasets +# └── imagenet ← downloads here + +# Arguments (optional) Usage: bash data/scripts/get_imagenet.sh --train --val +if [ "$#" -gt 0 ]; then + for opt in "$@"; do + case "${opt}" in + --train) train=true ;; + --val) val=true ;; + esac + done +else + train=true + val=true +fi + +# Make dir +d='../datasets/imagenet' # unzip directory +mkdir -p $d && cd $d + +# Download/unzip train +if [ "$train" == "true" ]; then + wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_train.tar # download 138G, 1281167 images + mkdir train && mv ILSVRC2012_img_train.tar train/ && cd train + tar -xf ILSVRC2012_img_train.tar && rm -f ILSVRC2012_img_train.tar + find . -name "*.tar" | while read NAME; do + mkdir -p "${NAME%.tar}" + tar -xf "${NAME}" -C "${NAME%.tar}" + rm -f "${NAME}" + done + cd .. +fi + +# Download/unzip val +if [ "$val" == "true" ]; then + wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_val.tar # download 6.3G, 50000 images + mkdir val && mv ILSVRC2012_img_val.tar val/ && cd val && tar -xf ILSVRC2012_img_val.tar + wget -qO- https://raw.githubusercontent.com/soumith/imagenetloader.torch/master/valprep.sh | bash # move into subdirs +fi + +# Delete corrupted image (optional: PNG under JPEG name that may cause dataloaders to fail) +# rm train/n04266014/n04266014_10835.JPEG + +# TFRecords (optional) +# wget https://raw.githubusercontent.com/tensorflow/models/master/research/slim/datasets/imagenet_lsvrc_2015_synsets.txt diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/split.py b/.venv/lib/python3.12/site-packages/ultralytics/data/split.py new file mode 100644 index 0000000000000000000000000000000000000000..12956a473632e39f87086090923fd2d52f9d7d7a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/split.py @@ -0,0 +1,138 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import random +import shutil +from pathlib import Path + +from ultralytics.data.utils import IMG_FORMATS, img2label_paths +from ultralytics.utils import DATASETS_DIR, LOGGER, TQDM + + +def split_classify_dataset(source_dir: str | Path, train_ratio: float = 0.8) -> Path: + """Split classification dataset into train and val directories in a new directory. + + Creates a new directory '{source_dir}_split' with train/val subdirectories, preserving the original class structure + with an 80/20 split by default. Only files with extensions matching IMG_FORMATS are copied. + + Directory structure: + Before: + caltech/ + ├── class1/ + │ ├── img1.jpg + │ ├── img2.jpg + │ └── ... + ├── class2/ + │ ├── img1.jpg + │ └── ... + └── ... + + After: + caltech_split/ + ├── train/ + │ ├── class1/ + │ │ ├── img1.jpg + │ │ └── ... + │ ├── class2/ + │ │ ├── img1.jpg + │ │ └── ... + │ └── ... + └── val/ + ├── class1/ + │ ├── img2.jpg + │ └── ... + ├── class2/ + │ └── ... + └── ... + + Args: + source_dir (str | Path): Path to classification dataset root directory. + train_ratio (float): Ratio for train split, between 0 and 1. + + Returns: + (Path): Path to the created split directory. + + Examples: + Split dataset with default 80/20 ratio + >>> split_classify_dataset("path/to/caltech") + + Split with custom ratio + >>> split_classify_dataset("path/to/caltech", 0.75) + """ + source_path = Path(source_dir) + split_path = Path(f"{source_path}_split") + train_path, val_path = split_path / "train", split_path / "val" + + # Create directory structure + split_path.mkdir(exist_ok=True) + train_path.mkdir(exist_ok=True) + val_path.mkdir(exist_ok=True) + + # Process class directories + class_dirs = [d for d in source_path.iterdir() if d.is_dir()] + total_images = sum(len([f for f in d.glob("*.*") if f.suffix[1:].lower() in IMG_FORMATS]) for d in class_dirs) + stats = f"{len(class_dirs)} classes, {total_images} images" + LOGGER.info(f"Splitting {source_path} ({stats}) into {train_ratio:.0%} train, {1 - train_ratio:.0%} val...") + + for class_dir in class_dirs: + # Create class directories + (train_path / class_dir.name).mkdir(exist_ok=True) + (val_path / class_dir.name).mkdir(exist_ok=True) + + # Split and copy files + image_files = [f for f in class_dir.glob("*.*") if f.suffix[1:].lower() in IMG_FORMATS] + random.shuffle(image_files) + split_idx = int(len(image_files) * train_ratio) + + for img in image_files[:split_idx]: + shutil.copy2(img, train_path / class_dir.name / img.name) + + for img in image_files[split_idx:]: + shutil.copy2(img, val_path / class_dir.name / img.name) + + LOGGER.info(f"Split complete in {split_path} ✅") + return split_path + + +def autosplit( + path: Path = DATASETS_DIR / "coco8/images", + weights: tuple[float, float, float] = (0.9, 0.1, 0.0), + annotated_only: bool = False, +) -> None: + """Automatically split a dataset into train/val/test splits and save the resulting splits into autosplit_*.txt + files. + + Args: + path (Path): Path to images directory. + weights (tuple[float, float, float]): Train, validation, and test split fractions. + annotated_only (bool): If True, only images with an associated txt file are used. + + Examples: + Split images with default weights + >>> from ultralytics.data.split import autosplit + >>> autosplit() + + Split with custom weights and annotated images only + >>> autosplit(path="path/to/images", weights=(0.8, 0.15, 0.05), annotated_only=True) + """ + path = Path(path) # images dir + files = sorted(x for x in path.rglob("*.*") if x.suffix[1:].lower() in IMG_FORMATS) # image files only + n = len(files) # number of files + random.seed(0) # for reproducibility + indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split + + txt = ["autosplit_train.txt", "autosplit_val.txt", "autosplit_test.txt"] # 3 txt files + for x in txt: + if (path.parent / x).exists(): + (path.parent / x).unlink() # remove existing + + LOGGER.info(f"Autosplitting images from {path}" + ", using *.txt labeled images only" * annotated_only) + for i, img in TQDM(zip(indices, files), total=n): + if not annotated_only or Path(img2label_paths([img])[0]).exists(): # check label + with open(path.parent / txt[i], "a", encoding="utf-8") as f: + f.write(f"./{img.relative_to(path.parent).as_posix()}" + "\n") # add image to txt file + + +if __name__ == "__main__": + split_classify_dataset("caltech101") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/split_dota.py b/.venv/lib/python3.12/site-packages/ultralytics/data/split_dota.py new file mode 100644 index 0000000000000000000000000000000000000000..f79e82615986f16134891d987443521bc529f794 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/split_dota.py @@ -0,0 +1,344 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import itertools +from glob import glob +from math import ceil +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +from PIL import Image + +from ultralytics.data.utils import exif_size, img2label_paths +from ultralytics.utils import TQDM +from ultralytics.utils.checks import check_requirements + + +def bbox_iof(polygon1: np.ndarray, bbox2: np.ndarray, eps: float = 1e-6) -> np.ndarray: + """Calculate Intersection over Foreground (IoF) between polygons and bounding boxes. + + Args: + polygon1 (np.ndarray): Polygon coordinates with shape (N, 8). + bbox2 (np.ndarray): Bounding boxes with shape (M, 4). + eps (float, optional): Small value to prevent division by zero. + + Returns: + (np.ndarray): IoF scores with shape (N, M). + + Notes: + Polygon format: [x1, y1, x2, y2, x3, y3, x4, y4]. + Bounding box format: [x_min, y_min, x_max, y_max]. + """ + check_requirements("shapely>=2.0.0") + from shapely.geometry import Polygon + + polygon1 = polygon1.reshape(-1, 4, 2) + lt_point = np.min(polygon1, axis=-2) # left-top + rb_point = np.max(polygon1, axis=-2) # right-bottom + bbox1 = np.concatenate([lt_point, rb_point], axis=-1) + + lt = np.maximum(bbox1[:, None, :2], bbox2[..., :2]) + rb = np.minimum(bbox1[:, None, 2:], bbox2[..., 2:]) + wh = np.clip(rb - lt, 0, np.inf) + h_overlaps = wh[..., 0] * wh[..., 1] + + left, top, right, bottom = (bbox2[..., i] for i in range(4)) + polygon2 = np.stack([left, top, right, top, right, bottom, left, bottom], axis=-1).reshape(-1, 4, 2) + + sg_polys1 = [Polygon(p) for p in polygon1] + sg_polys2 = [Polygon(p) for p in polygon2] + overlaps = np.zeros(h_overlaps.shape) + for p in zip(*np.nonzero(h_overlaps)): + overlaps[p] = sg_polys1[p[0]].intersection(sg_polys2[p[-1]]).area + unions = np.array([p.area for p in sg_polys1], dtype=np.float32) + unions = unions[..., None] + + unions = np.clip(unions, eps, np.inf) + outputs = overlaps / unions + if outputs.ndim == 1: + outputs = outputs[..., None] + return outputs + + +def load_yolo_dota(data_root: str, split: str = "train") -> list[dict[str, Any]]: + """Load DOTA dataset annotations and image information. + + Args: + data_root (str): Data root directory. + split (str, optional): The split data set, could be 'train' or 'val'. + + Returns: + (list[dict[str, Any]]): List of annotation dictionaries containing image information. + + Notes: + The directory structure assumed for the DOTA dataset: + - data_root + - images + - train + - val + - labels + - train + - val + """ + assert split in {"train", "val"}, f"Split must be 'train' or 'val', not {split}." + im_dir = Path(data_root) / "images" / split + assert im_dir.exists(), f"Can't find {im_dir}, please check your data root." + im_files = glob(str(Path(data_root) / "images" / split / "*")) + lb_files = img2label_paths(im_files) + annos = [] + for im_file, lb_file in zip(im_files, lb_files): + w, h = exif_size(Image.open(im_file)) + with open(lb_file, encoding="utf-8") as f: + lb = [x.split() for x in f.read().strip().splitlines() if len(x)] + lb = np.array(lb, dtype=np.float32) + annos.append({"ori_size": (h, w), "label": lb, "filepath": im_file}) + return annos + + +def get_windows( + im_size: tuple[int, int], + crop_sizes: tuple[int, ...] = (1024,), + gaps: tuple[int, ...] = (200,), + im_rate_thr: float = 0.6, + eps: float = 0.01, +) -> np.ndarray: + """Get the coordinates of sliding windows for image cropping. + + Args: + im_size (tuple[int, int]): Original image size, (H, W). + crop_sizes (tuple[int, ...], optional): Crop size of windows. + gaps (tuple[int, ...], optional): Gap between crops. + im_rate_thr (float, optional): Threshold for the ratio of image area within a window to the total window area. + eps (float, optional): Epsilon value for math operations. + + Returns: + (np.ndarray): Array of window coordinates of shape (N, 4) where each row is [x_start, y_start, x_stop, y_stop]. + """ + h, w = im_size + windows = [] + for crop_size, gap in zip(crop_sizes, gaps): + assert crop_size > gap, f"invalid crop_size gap pair [{crop_size} {gap}]" + step = crop_size - gap + + xn = 1 if w <= crop_size else ceil((w - crop_size) / step + 1) + xs = [step * i for i in range(xn)] + if len(xs) > 1 and xs[-1] + crop_size > w: + xs[-1] = w - crop_size + + yn = 1 if h <= crop_size else ceil((h - crop_size) / step + 1) + ys = [step * i for i in range(yn)] + if len(ys) > 1 and ys[-1] + crop_size > h: + ys[-1] = h - crop_size + + start = np.array(list(itertools.product(xs, ys)), dtype=np.int64) + stop = start + crop_size + windows.append(np.concatenate([start, stop], axis=1)) + windows = np.concatenate(windows, axis=0) + + im_in_wins = windows.copy() + im_in_wins[:, 0::2] = np.clip(im_in_wins[:, 0::2], 0, w) + im_in_wins[:, 1::2] = np.clip(im_in_wins[:, 1::2], 0, h) + im_areas = (im_in_wins[:, 2] - im_in_wins[:, 0]) * (im_in_wins[:, 3] - im_in_wins[:, 1]) + win_areas = (windows[:, 2] - windows[:, 0]) * (windows[:, 3] - windows[:, 1]) + im_rates = im_areas / win_areas + if not (im_rates > im_rate_thr).any(): + max_rate = im_rates.max() + im_rates[abs(im_rates - max_rate) < eps] = 1 + return windows[im_rates > im_rate_thr] + + +def get_window_obj(anno: dict[str, Any], windows: np.ndarray, iof_thr: float = 0.7) -> list[np.ndarray]: + """Get objects for each window based on IoF threshold.""" + h, w = anno["ori_size"] + label = anno["label"] + if len(label): + label[:, 1::2] *= w + label[:, 2::2] *= h + iofs = bbox_iof(label[:, 1:], windows) + # Unnormalized and misaligned coordinates + return [(label[iofs[:, i] >= iof_thr]) for i in range(len(windows))] # window_anns + else: + return [np.zeros((0, 9), dtype=np.float32) for _ in range(len(windows))] # window_anns + + +def crop_and_save( + anno: dict[str, Any], + windows: np.ndarray, + window_objs: list[np.ndarray], + im_dir: str, + lb_dir: str, + allow_background_images: bool = True, +) -> None: + """Crop images and save new labels for each window. + + Args: + anno (dict[str, Any]): Annotation dict, including 'filepath', 'label', 'ori_size' as its keys. + windows (np.ndarray): Array of windows coordinates with shape (N, 4). + window_objs (list[np.ndarray]): A list of labels inside each window. + im_dir (str): The output directory path of images. + lb_dir (str): The output directory path of labels. + allow_background_images (bool, optional): Whether to include background images without labels. + + Notes: + The directory structure assumed for the DOTA dataset: + - data_root + - images + - train + - val + - labels + - train + - val + """ + im = cv2.imread(anno["filepath"]) + name = Path(anno["filepath"]).stem + for i, window in enumerate(windows): + x_start, y_start, x_stop, y_stop = window.tolist() + new_name = f"{name}__{x_stop - x_start}__{x_start}___{y_start}" + patch_im = im[y_start:y_stop, x_start:x_stop] + ph, pw = patch_im.shape[:2] + + label = window_objs[i] + if len(label) or allow_background_images: + cv2.imwrite(str(Path(im_dir) / f"{new_name}.jpg"), patch_im) + if len(label): + label[:, 1::2] -= x_start + label[:, 2::2] -= y_start + label[:, 1::2] /= pw + label[:, 2::2] /= ph + + with open(Path(lb_dir) / f"{new_name}.txt", "w", encoding="utf-8") as f: + for lb in label: + formatted_coords = [f"{coord:.6g}" for coord in lb[1:]] + f.write(f"{int(lb[0])} {' '.join(formatted_coords)}\n") + + +def split_images_and_labels( + data_root: str, + save_dir: str, + split: str = "train", + crop_sizes: tuple[int, ...] = (1024,), + gaps: tuple[int, ...] = (200,), +) -> None: + """Split both images and labels for a given dataset split. + + Args: + data_root (str): Root directory of the dataset. + save_dir (str): Directory to save the split dataset. + split (str, optional): The split data set, could be 'train' or 'val'. + crop_sizes (tuple[int, ...], optional): Tuple of crop sizes. + gaps (tuple[int, ...], optional): Tuple of gaps between crops. + + Notes: + The directory structure assumed for the DOTA dataset: + - data_root + - images + - split + - labels + - split + and the output directory structure is: + - save_dir + - images + - split + - labels + - split + """ + im_dir = Path(save_dir) / "images" / split + im_dir.mkdir(parents=True, exist_ok=True) + lb_dir = Path(save_dir) / "labels" / split + lb_dir.mkdir(parents=True, exist_ok=True) + + annos = load_yolo_dota(data_root, split=split) + for anno in TQDM(annos, total=len(annos), desc=split): + windows = get_windows(anno["ori_size"], crop_sizes, gaps) + window_objs = get_window_obj(anno, windows) + crop_and_save(anno, windows, window_objs, str(im_dir), str(lb_dir)) + + +def split_trainval( + data_root: str, save_dir: str, crop_size: int = 1024, gap: int = 200, rates: tuple[float, ...] = (1.0,) +) -> None: + """Split train and val sets of DOTA dataset with multiple scaling rates. + + Args: + data_root (str): Root directory of the dataset. + save_dir (str): Directory to save the split dataset. + crop_size (int, optional): Base crop size. + gap (int, optional): Base gap between crops. + rates (tuple[float, ...], optional): Scaling rates for crop_size and gap. + + Notes: + The directory structure assumed for the DOTA dataset: + - data_root + - images + - train + - val + - labels + - train + - val + and the output directory structure is: + - save_dir + - images + - train + - val + - labels + - train + - val + """ + crop_sizes, gaps = [], [] + for r in rates: + crop_sizes.append(int(crop_size / r)) + gaps.append(int(gap / r)) + for split in ("train", "val"): + split_images_and_labels(data_root, save_dir, split, crop_sizes, gaps) + + +def split_test( + data_root: str, save_dir: str, crop_size: int = 1024, gap: int = 200, rates: tuple[float, ...] = (1.0,) +) -> None: + """Split test set of DOTA dataset, labels are not included within this set. + + Args: + data_root (str): Root directory of the dataset. + save_dir (str): Directory to save the split dataset. + crop_size (int, optional): Base crop size. + gap (int, optional): Base gap between crops. + rates (tuple[float, ...], optional): Scaling rates for crop_size and gap. + + Notes: + The directory structure assumed for the DOTA dataset: + - data_root + - images + - test + and the output directory structure is: + - save_dir + - images + - test + """ + crop_sizes, gaps = [], [] + for r in rates: + crop_sizes.append(int(crop_size / r)) + gaps.append(int(gap / r)) + save_dir = Path(save_dir) / "images" / "test" + save_dir.mkdir(parents=True, exist_ok=True) + + im_dir = Path(data_root) / "images" / "test" + assert im_dir.exists(), f"Can't find {im_dir}, please check your data root." + im_files = glob(str(im_dir / "*")) + for im_file in TQDM(im_files, total=len(im_files), desc="test"): + w, h = exif_size(Image.open(im_file)) + windows = get_windows((h, w), crop_sizes=crop_sizes, gaps=gaps) + im = cv2.imread(im_file) + name = Path(im_file).stem + for window in windows: + x_start, y_start, x_stop, y_stop = window.tolist() + new_name = f"{name}__{x_stop - x_start}__{x_start}___{y_start}" + patch_im = im[y_start:y_stop, x_start:x_stop] + cv2.imwrite(str(save_dir / f"{new_name}.jpg"), patch_im) + + +if __name__ == "__main__": + split_trainval(data_root="DOTAv2", save_dir="DOTAv2-split") + split_test(data_root="DOTAv2", save_dir="DOTAv2-split") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/data/utils.py b/.venv/lib/python3.12/site-packages/ultralytics/data/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fdca0e04388aef8b2251230d11c672e35fa2dc71 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/data/utils.py @@ -0,0 +1,857 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import os +import random +import subprocess +import time +import zipfile +from pathlib import Path +from tarfile import is_tarfile +from typing import Any + +import cv2 +import numpy as np +from PIL import Image, ImageOps + +from ultralytics.nn.autobackend import check_class_names +from ultralytics.utils import ( + ASSETS_URL, + DATASETS_DIR, + LOGGER, + ROOT, + SETTINGS_FILE, + YAML, + clean_url, + colorstr, + emojis, + is_dir_writeable, +) +from ultralytics.utils.checks import check_file, check_font, is_ascii, normalize_platform_uri +from ultralytics.utils.downloads import download, safe_download +from ultralytics.utils.ops import segments2boxes + +HELP_URL = "See https://docs.ultralytics.com/datasets for dataset formatting guidance." +IMG_FORMATS = { + "avif", + "bmp", + "dng", + "heic", + "heif", + "jp2", + "jpeg", + "jpg", + "mpo", + "png", + "tif", + "tiff", + "webp", +} +VID_FORMATS = {"asf", "avi", "gif", "m4v", "mkv", "mov", "mp4", "mpeg", "mpg", "ts", "wmv", "webm"} # videos +FORMATS_HELP_MSG = f"Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}" +DATASET_KEY_TYPES = { # dataset YAML keys and their permitted types + "path": (str,), + "train": (str, list), + "val": (str, list), + "test": (str, list), + "names": (list, dict), + "kpt_shape": (list,), + "flip_idx": (list,), +} + +DEPTH_PNG_SCALE = 1000 # uint16 millimeters by default; zero is invalid + + +def save_depth_png(path: str | Path, depth: np.ndarray, scale: float = DEPTH_PNG_SCALE) -> None: + """Save metric depth as a scaled uint16 PNG with zero reserved for invalid pixels.""" + if not isinstance(scale, (int, float)) or isinstance(scale, bool) or not np.isfinite(scale) or scale <= 0: + raise ValueError("Depth scale must be a positive finite number") + depth = np.asarray(depth, dtype=np.float32).squeeze() + if depth.ndim != 2: + raise ValueError(f"Depth map must be 2D, got shape {depth.shape}") + valid = np.isfinite(depth) & (depth > 0) + encoded = np.zeros(depth.shape, dtype=np.uint16) + if valid.any(): + scaled = np.rint(depth[valid] * scale) + if scaled.max() > np.iinfo(np.uint16).max: + raise ValueError(f"Depth map exceeds the {np.iinfo(np.uint16).max / scale:g} meter PNG limit") + encoded[valid] = np.maximum(scaled, 1).astype(np.uint16) + if not cv2.imwrite(str(path), encoded): + raise OSError(f"Failed to save depth map to {path}") + + +def load_depth(path: str | Path, scale: float = DEPTH_PNG_SCALE) -> np.ndarray: + """Load metric depth from a scaled uint16 PNG or floating-point meter NPY.""" + path = Path(path) + if path.suffix.lower() == ".npy": + depth = np.load(path, allow_pickle=False) + if depth.ndim != 2 or depth.dtype.kind != "f": + raise ValueError(f"Depth map {path} must be a 2D floating-point NPY array") + return np.nan_to_num(depth.astype(np.float32, copy=False), copy=False, nan=0.0, posinf=0.0, neginf=0.0) + if not isinstance(scale, (int, float)) or isinstance(scale, bool) or not np.isfinite(scale) or scale <= 0: + raise ValueError("Depth scale must be a positive finite number") + with Image.open(path) as image: + if image.format != "PNG" or image.mode not in {"I", "I;16"}: + raise ValueError(f"Depth PNG {path} must be a 2D uint16 map") + encoded = np.asarray(image) + depth = encoded.astype(np.float32) + depth /= scale + return depth + + +def img2label_paths(img_paths: list[str | Path], label_dir: str = "labels", suffix: str = ".txt") -> list[str]: + """Convert image paths to label paths by replacing 'images' with 'labels' and extension with '.txt'.""" + sa, sb = f"{os.sep}images{os.sep}", f"{os.sep}{label_dir}{os.sep}" # /images/, /labels/ substrings + return [sb.join(os.fspath(x).rsplit(sa, 1)).rsplit(".", 1)[0] + f"{suffix}" for x in img_paths] + + +def check_file_speeds( + files: list[str], threshold_ms: float = 10, threshold_mb: float = 50, max_files: int = 5, prefix: str = "" +): + """Check dataset file access speed and provide performance feedback. + + This function tests the access speed of dataset files by measuring ping (stat call) time and read speed. It samples + up to `max_files` files from the provided list and warns if access times exceed the threshold. + + Args: + files (list[str]): List of file paths to check for access speed. + threshold_ms (float, optional): Threshold in milliseconds for ping time warnings. + threshold_mb (float, optional): Threshold in megabytes per second for read speed warnings. + max_files (int, optional): The maximum number of files to check. + prefix (str, optional): Prefix string to add to log messages. + + Examples: + >>> from pathlib import Path + >>> image_files = list(Path("dataset/images").glob("*.jpg")) + >>> check_file_speeds(image_files, threshold_ms=15) + """ + if not files: + LOGGER.warning(f"{prefix}Image speed checks: No files to check") + return + + # Sample files (max 5) + files = random.sample(files, min(max_files, len(files))) + + # Test ping (stat time) + ping_times = [] + file_sizes = [] + read_speeds = [] + + for f in files: + try: + # Measure ping (stat call) + start = time.perf_counter() + file_size = os.stat(f).st_size + ping_times.append((time.perf_counter() - start) * 1000) # ms + file_sizes.append(file_size) + + # Measure read speed + start = time.perf_counter() + with open(f, "rb") as file_obj: + _ = file_obj.read() + read_time = time.perf_counter() - start + if read_time > 0: # Avoid division by zero + read_speeds.append(file_size / (1 << 20) / read_time) # MB/s + except Exception: + pass + + if not ping_times: + LOGGER.warning(f"{prefix}Image speed checks: failed to access files") + return + + # Calculate stats with uncertainties + avg_ping = np.mean(ping_times) + std_ping = np.std(ping_times, ddof=1) if len(ping_times) > 1 else 0 + size_msg = f", size: {np.mean(file_sizes) / (1 << 10):.1f} KB" + ping_msg = f"ping: {avg_ping:.1f}±{std_ping:.1f} ms" + + if read_speeds: + avg_speed = np.mean(read_speeds) + std_speed = np.std(read_speeds, ddof=1) if len(read_speeds) > 1 else 0 + speed_msg = f", read: {avg_speed:.1f}±{std_speed:.1f} MB/s" + else: + avg_speed = float("inf") + speed_msg = "" + + if avg_ping < threshold_ms and avg_speed > threshold_mb: + LOGGER.info(f"{prefix}Fast image access ✅ ({ping_msg}{speed_msg}{size_msg})") + else: + LOGGER.warning( + f"{prefix}Slow image access detected ({ping_msg}{speed_msg}{size_msg}). " + f"Use local storage instead of remote/mounted storage for better performance. " + f"See https://docs.ultralytics.com/guides/model-training-tips" + ) + + +def get_hash(paths: list[str]) -> str: + """Return a hash of paths and their file sizes and modification times.""" + h = __import__("hashlib").sha256() + for p in paths: + h.update(p.encode()) + h.update(b"\0") + try: + stat = os.stat(p) + except OSError: + h.update(b"\0") + continue + h.update(f"{stat.st_size}:{stat.st_mtime_ns}".encode()) + h.update(b"\0") + return h.hexdigest() + + +def exif_size(img: Image.Image) -> tuple[int, int]: + """Return exif-corrected PIL size.""" + s = img.size # (width, height) + if img.format == "JPEG": # only support JPEG images + try: + if exif := img.getexif(): + rotation = exif.get(274, None) # the EXIF key for the orientation tag is 274 + if rotation in {6, 8}: # rotation 270 or 90 + s = s[1], s[0] + except Exception: + pass + return s + + +def check_image(im_file: str) -> tuple[str, tuple[int, int]]: + """Verify an image file for integrity and correct corrupt JPEGs if found. + + Args: + im_file (str): Path to the image file to check. + + Returns: + (str): A message describing any corrective action taken, or an empty string if the image is valid. + (tuple[int, int]): Image shape as (height, width) in pixels. + + Raises: + AssertionError: If the image size is less than 10 pixels in any dimension or the format is invalid. + """ + msg = "" + im = Image.open(im_file) + im.verify() # PIL verify + shape = exif_size(im) # image size + shape = (shape[1], shape[0]) # hw + assert (shape[0] > 9) & (shape[1] > 9), f"image size {shape} <10 pixels" + assert im.format.lower() in IMG_FORMATS, f"Invalid image format {im.format}. {FORMATS_HELP_MSG}" + if im.format.lower() in {"jpg", "jpeg"}: + with open(im_file, "rb") as f: + f.seek(-2, 2) + if f.read() != b"\xff\xd9": # corrupt JPEG + ImageOps.exif_transpose(Image.open(im_file)).save(im_file, "JPEG", subsampling=0, quality=100) + msg = f"{im_file}: corrupt JPEG restored and saved" + return msg, shape + + +def verify_image(args: tuple) -> tuple: + """Verify one image.""" + (im_file, cls), prefix = args + # Number (found, corrupt), message + nf, nc, msg = 0, 0, "" + try: + msg = check_image(im_file)[0] + msg = f"{prefix}{msg}" if msg else "" + nf = 1 + except Exception as e: + nc = 1 + msg = f"{prefix}{im_file}: ignoring corrupt image/label: {e}" + return (im_file, cls), nf, nc, msg + + +def verify_image_depth(args: tuple) -> tuple: + """Verify that an image and its paired depth map exist and are readable.""" + im_file, depth_file, prefix, scale = args + # Number (found, missing, corrupt), message + nf, nm, nc, msg = 0, 0, 0, "" + try: + msg, shape = check_image(im_file) + msg = f"{prefix}{msg}" if msg else "" + if not os.path.isfile(depth_file): + nm = 1 + msg = f"{prefix}{im_file}: ignoring image with missing depth map {depth_file}" + return None, None, nf, nm, nc, msg + if Path(depth_file).suffix.lower() == ".npy": + depth = np.load(depth_file, mmap_mode="r", allow_pickle=False) + assert depth.ndim == 2 and depth.dtype.kind == "f", "depth NPY must be 2D and floating-point" + depth_shape = depth.shape + else: + assert ( + isinstance(scale, (int, float)) and not isinstance(scale, bool) and np.isfinite(scale) and scale > 0 + ), "depth_scale must be a positive finite number" + with Image.open(depth_file) as depth: + assert depth.format == "PNG" and depth.mode in {"I", "I;16"}, ( + f"depth map {depth_file} must be an integer grayscale PNG" + ) + depth_shape = (depth.height, depth.width) + depth.verify() + assert abs(np.log((depth_shape[1] / depth_shape[0]) / (shape[1] / shape[0]))) <= 0.02, ( + f"depth map shape {depth_shape} does not match image shape {shape}" + ) + nf = 1 + return im_file, shape, nf, nm, nc, msg + except Exception as e: + nc = 1 + msg = f"{prefix}{im_file}: ignoring corrupt image/depth: {e}" + return None, None, nf, nm, nc, msg + + +def verify_image_mask(args: tuple) -> tuple: + """Verify that an image and its semantic mask exist, are readable, and have matching shapes.""" + im_file, mask_file, prefix = args + # Number (found, missing, corrupt), message + nf, nm, nc, msg = 0, 0, 0, "" + try: + msg, shape = check_image(im_file) + msg = f"{prefix}{msg}" if msg else "" + if not os.path.isfile(mask_file): + for ext in IMG_FORMATS: # check other suffixes + alt_mask_file = mask_file.rsplit(".", 1)[0] + f".{ext}" + if os.path.isfile(alt_mask_file): + mask_file = alt_mask_file + break + if os.path.isfile(mask_file): + mask = cv2.imread(mask_file, cv2.IMREAD_GRAYSCALE) + assert mask is not None, f"mask file {mask_file} is unreadable" + assert mask.shape[:2] == shape, f"mask size {mask.shape[:2]} does not match image size {shape}" + with Image.open(mask_file) as im: + is_1bit = im.mode == "1" # recorded for every mask so a yaml 'nc' edit never needs a rescan + nf = 1 + else: + nm = 1 + msg = f"{prefix}{im_file}: ignoring image with missing mask {mask_file}" + return None, None, None, None, nm, nf, nc, msg + return im_file, mask_file, shape, is_1bit, nm, nf, nc, msg + except Exception as e: + nc = 1 + msg = f"{prefix}{im_file}: ignoring corrupt image/mask: {e}" + return None, None, None, None, nm, nf, nc, msg + + +def verify_image_label(args: tuple) -> list: + """Verify one image-label pair.""" + im_file, lb_file, prefix, keypoint, num_cls, nkpt, ndim, single_cls = args + # Number (missing, found, empty, corrupt), message, segments, keypoints + nm, nf, ne, nc, msg, segments, keypoints = 0, 0, 0, 0, "", [], None + try: + # Verify images + msg, shape = check_image(im_file) + msg = f"{prefix}{msg}" if msg else "" + + # Verify labels + if os.path.isfile(lb_file): + nf = 1 # label found + with open(lb_file, encoding="utf-8") as f: + lb = [x.split() for x in f.read().strip().splitlines() if len(x)] + if any(len(x) > 6 for x in lb) and (not keypoint): # is segment + assert not any(len(x) == 5 for x in lb), "labels mix segment and detection rows" + classes = np.array([x[0] for x in lb], dtype=np.float32) + segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb] # (cls, xy1...) + lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh) + lb = np.array(lb, dtype=np.float32) + if nl := len(lb): + if keypoint: + assert lb.shape[1] == (5 + nkpt * ndim), f"labels require {(5 + nkpt * ndim)} columns each" + points = lb[:, 5:].reshape(-1, ndim)[:, :2] + else: + assert lb.shape[1] == 5, f"labels require 5 columns, {lb.shape[1]} columns detected" + points = lb[:, 1:] + # Coordinate points check with 1% tolerance + assert points.max() <= 1.01, f"non-normalized or out of bounds coordinates {points[points > 1.01]}" + assert lb.min() >= -0.01, f"negative class labels or coordinate {lb[lb < -0.01]}" + + # All labels + max_cls = 0 if single_cls else lb[:, 0].max() # max label count + assert max_cls < num_cls, ( + f"Label class {int(max_cls)} exceeds dataset class count {num_cls}. " + f"Possible class labels are 0-{num_cls - 1}" + ) + _, i = np.unique(lb, axis=0, return_index=True) + if len(i) < nl: # duplicate row check + lb = lb[i] # remove duplicates + if segments: + segments = [segments[x] for x in i] + msg = f"{prefix}{im_file}: {nl - len(i)} duplicate labels removed" + else: + ne = 1 # label empty + lb = np.zeros((0, (5 + nkpt * ndim) if keypoint else 5), dtype=np.float32) + else: + nm = 1 # label missing + lb = np.zeros((0, (5 + nkpt * ndim) if keypoint else 5), dtype=np.float32) + if keypoint: + keypoints = lb[:, 5:].reshape(-1, nkpt, ndim) + if ndim == 2: + kpt_mask = np.where((keypoints[..., 0] < 0) | (keypoints[..., 1] < 0), 0.0, 1.0).astype(np.float32) + keypoints = np.concatenate([keypoints, kpt_mask[..., None]], axis=-1) # (nl, nkpt, 3) + lb = lb[:, :5] + return im_file, lb, shape, segments, keypoints, nm, nf, ne, nc, msg + except Exception as e: + nc = 1 + msg = f"{prefix}{im_file}: ignoring corrupt image/label: {e}" + return [None, None, None, None, None, nm, nf, ne, nc, msg] + + +def visualize_image_annotations(image_path: str, txt_path: str, label_map: dict[int, str]): + """Visualize YOLO annotations (bounding boxes and class labels) on an image. + + This function reads an image and its corresponding annotation file in YOLO format, then draws bounding boxes around + detected objects and labels them with their respective class names. The bounding box colors are assigned based on + the class ID, and the text color is dynamically adjusted for readability, depending on the background color's + luminance. + + Args: + image_path (str): Path to the image file to annotate. The file must be readable by PIL. + txt_path (str): Path to the annotation file in YOLO format, which should contain one line per object. + label_map (dict[int, str]): A dictionary that maps class IDs (integers) to class labels (strings). + + Examples: + >>> label_map = {0: "cat", 1: "dog", 2: "bird"} # Should include all annotated classes + >>> visualize_image_annotations("path/to/image.jpg", "path/to/annotations.txt", label_map) + """ + import matplotlib.pyplot as plt + + from ultralytics.utils.plotting import colors + + img = np.array(Image.open(image_path)) + img_height, img_width = img.shape[:2] + annotations = [] + with open(txt_path, encoding="utf-8") as file: + for line in file: + class_id, x_center, y_center, width, height = map(float, line.split()) + x = (x_center - width / 2) * img_width + y = (y_center - height / 2) * img_height + w = width * img_width + h = height * img_height + annotations.append((x, y, w, h, int(class_id))) + _, ax = plt.subplots(1) # Plot the image and annotations + for x, y, w, h, label in annotations: + color = tuple(c / 255 for c in colors(label, False)) # Get and normalize an RGB color for Matplotlib + rect = plt.Rectangle((x, y), w, h, linewidth=2, edgecolor=color, facecolor="none") # Create a rectangle + ax.add_patch(rect) + luminance = 0.2126 * color[0] + 0.7152 * color[1] + 0.0722 * color[2] # Formula for luminance + ax.text(x, y - 5, label_map[label], color="white" if luminance < 0.5 else "black", backgroundcolor=color) + ax.imshow(img) + plt.show() + + +def polygon2mask( + imgsz: tuple[int, int], polygons: list[np.ndarray], color: int = 1, downsample_ratio: int = 1 +) -> np.ndarray: + """Convert a list of polygons to a binary mask of the specified image size. + + Args: + imgsz (tuple[int, int]): The size of the image as (height, width). + polygons (list[np.ndarray]): A list of polygons. Each polygon is a 1D array of coordinates with length M, where + M % 2 = 0 (alternating x, y values). + color (int, optional): The color value to fill in the polygons on the mask. + downsample_ratio (int, optional): Factor by which to downsample the mask. + + Returns: + (np.ndarray): A binary mask of the specified image size with the polygons filled in. + """ + mask = np.zeros(imgsz, dtype=np.uint8) + polygons = np.asarray(polygons, dtype=np.int32) + polygons = polygons.reshape((polygons.shape[0], -1, 2)) + cv2.fillPoly(mask, polygons, color=color) + nh, nw = (imgsz[0] // downsample_ratio, imgsz[1] // downsample_ratio) + # Note: fillPoly first then resize is trying to keep the same loss calculation method when mask-ratio=1 + return cv2.resize(mask, (nw, nh)) + + +def polygons2masks( + imgsz: tuple[int, int], polygons: list[np.ndarray], color: int, downsample_ratio: int = 1 +) -> np.ndarray: + """Convert a list of polygons to a set of binary masks of the specified image size. + + Args: + imgsz (tuple[int, int]): The size of the image as (height, width). + polygons (list[np.ndarray]): A list of polygons. Each polygon is an array of coordinates that can be reshaped to + (-1, 2) as (x, y) point pairs. + color (int): The color value to fill in the polygons on the masks. + downsample_ratio (int, optional): Factor by which to downsample each mask. + + Returns: + (np.ndarray): A set of binary masks of the specified image size with the polygons filled in. + """ + return np.array([polygon2mask(imgsz, [x.reshape(-1)], color, downsample_ratio) for x in polygons]) + + +def polygons2masks_overlap( + imgsz: tuple[int, int], segments: list[np.ndarray], downsample_ratio: int = 1 +) -> tuple[np.ndarray, np.ndarray]: + """Return a downsampled overlap mask and sorted area indices.""" + masks = np.zeros( + (imgsz[0] // downsample_ratio, imgsz[1] // downsample_ratio), + dtype=np.int32 if len(segments) > 255 else np.uint8, + ) + areas = [] + ms = [] + for segment in segments: + mask = polygon2mask( + imgsz, + [segment.reshape(-1)], + downsample_ratio=downsample_ratio, + color=1, + ) + ms.append(mask.astype(masks.dtype)) + areas.append(mask.sum()) + areas = np.asarray(areas) + index = np.argsort(-areas) + ms = np.array(ms)[index] + # Running max: the old `masks + mask` sum hit 2 * i + 1 and overflowed uint8 past 128 overlapping instances + for i in range(len(segments)): + np.maximum(masks, ms[i] * (i + 1), out=masks) + return masks, index + + +def find_dataset_yaml(path: Path) -> Path: + """Find and return the YAML file associated with a Detect, Segment or Pose dataset. + + This function searches for a YAML file at the root level of the provided directory first, and if not found, it + performs a recursive search. It prefers YAML files that have the same stem as the provided path. + + Args: + path (Path): The directory path to search for the YAML file. + + Returns: + (Path): The path of the found YAML file. + """ + files = list(path.glob("*.yaml")) or list(path.rglob("*.yaml")) # try root level first and then recursive + assert files, f"No YAML file found in '{path.resolve()}'" + if len(files) > 1: + files = [f for f in files if f.stem == path.stem] # prefer *.yaml files that match + assert len(files) == 1, f"Expected 1 YAML file in '{path.resolve()}', but found {len(files)}.\n{files}" + return files[0] + + +def get_split_fraction(fraction: float | list[float | int], split: str) -> float | int: + """Return a split ratio/count, normalizing boundary values to 0.0 (none) or 1.0 (all).""" + if isinstance(fraction, list) and split in (splits := ("train", "val", "test")): + index = splits.index(split) + fraction = fraction[index] if index < len(fraction) else 1.0 + elif split != "train": + fraction = 1.0 + fraction = float(fraction) if fraction in {0, 1} else fraction + if split in {"train", "val"} and fraction == 0: + raise ValueError(f"{split} fraction must select at least one image") + return fraction + + +def convert_ndjson_to_yolo_if_needed(data: str | Path, fraction=1.0, *, split=None) -> str | Path: + """Convert an NDJSON dataset or Platform dataset URI to YOLO format.""" + data = normalize_platform_uri(data) # accept Platform web URLs (https://platform.ultralytics.com/.../datasets/...) + data_str = str(data) + if clean_url(data_str).endswith(".ndjson") or (data_str.startswith("ul://") and "/datasets/" in data_str): + import asyncio + + from ultralytics.data.converter import convert_ndjson_to_yolo + + return asyncio.run(convert_ndjson_to_yolo(data, fraction=fraction, split=split)) + return data + + +def check_det_dataset(dataset: str, autodownload: bool = True, split: str = "") -> dict[str, Any]: + """Download, verify, and/or unzip a dataset if not found locally. + + This function checks the availability of a specified dataset, and if not found, it has the option to download and + unzip the dataset. It then reads and parses the accompanying YAML data, ensuring key requirements are met and also + resolves paths related to the dataset. + + Args: + dataset (str): Path to the dataset or dataset descriptor (like a YAML file). + autodownload (bool, optional): Whether to automatically download the dataset if not found. + split (str, optional): Dataset split required by the caller. + + Returns: + (dict[str, Any]): Parsed dataset information and paths. + """ + dataset = str(dataset) + if "://" not in dataset and not Path(dataset).exists() and Path(dataset).suffix not in {".yaml", ".yml"}: + # allow bare dataset names, e.g. 'coco8' -> 'coco8.yaml', 'DOTAv1.5' -> 'DOTAv1.5.yaml' + dataset = next((f"{dataset}{x}" for x in (".yaml", ".yml") if check_file(f"{dataset}{x}", hard=False)), dataset) + file = Path(check_file(dataset)) + if file.is_dir(): + file = find_dataset_yaml(file) + + # Download (optional) + extract_dir = "" + if zipfile.is_zipfile(file) or is_tarfile(file): + new_dir = safe_download(file, dir=DATASETS_DIR, unzip=True, delete=False) + file = find_dataset_yaml(DATASETS_DIR / new_dir) + extract_dir, autodownload = file.parent, False + + # Read YAML + data = YAML.load(file, append_filename=True) # dictionary + + # Checks + for key, valid_types in DATASET_KEY_TYPES.items(): + if data.get(key) is not None and not isinstance(data[key], valid_types): + expected = " or ".join(t.__name__ for t in valid_types) + raise TypeError(f"{dataset} '{key}' must be {expected}, not {type(data[key]).__name__}") + + for k in "train", "val": + if k not in data: + if k != "val" or "validation" not in data: + raise SyntaxError( + emojis(f"{dataset} '{k}:' key missing ❌.\n'train' and 'val' are required in all data YAMLs.") + ) + LOGGER.warning("renaming data YAML 'validation' key to 'val' to match YOLO format.") + data["val"] = data.pop("validation") # replace 'validation' key with 'val' key + if split and not data.get(split): + raise FileNotFoundError(f"{dataset} '{split}:' images not found ❌") + # `names` compared to None, not membership: a bare `names:` parses to None and len(None) below + # raises. `nc` stays membership so a valueless `nc:` still reaches its "must be an integer" error. + if data.get("names") is None and "nc" not in data: + raise SyntaxError(emojis(f"{dataset} key missing ❌.\n either 'names' or 'nc' are required in all data YAMLs.")) + if "nc" in data and not isinstance(data["nc"], int): + try: + nc = float(data["nc"]) # accept integer-like values, e.g. '10' or 10.0, but not 1.9 or placeholders + if nc != int(nc): + raise ValueError + data["nc"] = int(nc) + except (TypeError, ValueError): + raise SyntaxError(emojis(f"{dataset} 'nc: {data['nc']}' must be an integer ❌.")) + if data.get("names") is not None and data.get("nc") is not None and len(data["names"]) != data["nc"]: + raise SyntaxError(emojis(f"{dataset} 'names' length {len(data['names'])} and 'nc: {data['nc']}' must match.")) + if data.get("names") is None: + data["names"] = [f"class_{i}" for i in range(data["nc"])] + else: + data["nc"] = len(data["names"]) + + data["names"] = check_class_names(data["names"]) + data["channels"] = data.get("channels", 3) # get image channels, default to 3 + + # Resolve paths + path = Path(extract_dir or data.get("path") or Path(data.get("yaml_file", "")).parent) # dataset root + if not path.exists() and not path.is_absolute(): + path = (DATASETS_DIR / path).resolve() # path relative to DATASETS_DIR + + # Set paths + data["path"] = path # download scripts + for k in "train", "val", "test", "minival": + if data.get(k): # prepend path + if isinstance(data[k], str): + x = (path / data[k]).resolve() + if not x.exists() and data[k].startswith("../"): + x = (path / data[k][3:]).resolve() + data[k] = str(x) + else: + data[k] = [str((path / x).resolve()) for x in data[k]] + + # Parse YAML + val, s = (data.get(x) for x in (split or "val", "download")) + if val: + val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path + if not all(x.exists() for x in val): + name = clean_url(dataset) # dataset name with URL auth stripped + LOGGER.info("") + m = f"Dataset '{name}' images not found, missing path '{next(x for x in val if not x.exists())}'" + if s and autodownload: + LOGGER.warning(m) + else: + m += f"\nNote dataset download directory is '{DATASETS_DIR}'. You can update this in '{SETTINGS_FILE}'" + raise FileNotFoundError(m) + t = time.time() + r = None # success + if s.startswith("http") and s.endswith(".zip"): # URL + safe_download(url=s, dir=DATASETS_DIR, delete=True) + elif s.startswith("bash "): # bash script + LOGGER.info(f"Running {s} ...") + subprocess.run(s.split(), check=True) + else: # python script + exec(s, {"yaml": data}) # noqa: S102 + dt = f"({round(time.time() - t, 1)}s)" + s = f"success ✅ {dt}, saved to {colorstr('bold', DATASETS_DIR)}" if r in {0, None} else f"failure {dt} ❌" + LOGGER.info(f"Dataset download {s}\n") + if data.get("masks_dir") is None and (path / "masks").is_dir(): # after download so scripts can create it + data["masks_dir"] = "masks" # PNG semantic masks in the default folder select SemanticDataset + check_font("Arial.ttf" if is_ascii(data["names"]) else "Arial.Unicode.ttf") # download fonts + + return data # dictionary + + +def check_cls_dataset(dataset: str | Path, split: str = "") -> dict[str, Any]: + """Check a classification dataset such as Imagenet. + + This function accepts a `dataset` name and attempts to retrieve the corresponding dataset information. If the + dataset is not found locally, it attempts to download the dataset from the internet and save it locally. + + Args: + dataset (str | Path): The name of the dataset. + split (str, optional): The split of the dataset. Either 'val', 'test', or ''. + + Returns: + (dict[str, Any]): A dictionary containing the following keys: + + - 'train' (Path): The directory path containing the training set of the dataset. + - 'val' (Path): The directory path containing the validation set of the dataset. + - 'test' (Path): The directory path containing the test set of the dataset. + - 'nc' (int): The number of classes in the dataset. + - 'names' (dict[int, str]): A dictionary of class names in the dataset. + """ + if split and split not in {"train", "val", "test"}: + raise ValueError(f"Invalid classification dataset split '{split}'. Use 'train', 'val', or 'test'.") + + # Download (optional if dataset=https://file.zip is passed directly) + if str(dataset).startswith(("http:/", "https:/")): + dataset = safe_download(dataset, dir=DATASETS_DIR, unzip=True, delete=False) + elif str(dataset).endswith((".zip", ".tar", ".gz")): + file = check_file(dataset) + dataset = safe_download(file, dir=DATASETS_DIR, unzip=True, delete=False) + + dataset = Path(dataset) + data_dir = (dataset if dataset.is_dir() else (DATASETS_DIR / dataset)).resolve() + if not data_dir.is_dir(): + if data_dir.suffix != "": + raise ValueError( + f'Classification datasets must be a directory (data="path/to/dir") not a file (data="{dataset}"), ' + "See https://docs.ultralytics.com/datasets/classify" + ) + LOGGER.info("") + LOGGER.warning(f"Dataset not found, missing path {data_dir}, attempting download...") + t = time.time() + if str(dataset) == "imagenet": + subprocess.run(["bash", str(ROOT / "data/scripts/get_imagenet.sh")], check=True) + else: + download(f"{ASSETS_URL}/{dataset}.zip", dir=data_dir.parent) + LOGGER.info(f"Dataset download success ✅ ({time.time() - t:.1f}s), saved to {colorstr('bold', data_dir)}\n") + train_set = data_dir / "train" + if not train_set.is_dir(): + LOGGER.warning(f"Dataset 'split=train' not found at {train_set}") + if image_files := [f for f in data_dir.rglob("*.*") if f.suffix[1:].lower() in IMG_FORMATS]: + from ultralytics.data.split import split_classify_dataset + + LOGGER.info(f"Found {len(image_files)} images in subdirectories. Attempting to split...") + data_dir = split_classify_dataset(data_dir, train_ratio=0.8) + train_set = data_dir / "train" + else: + raise FileNotFoundError(f"No images found in {data_dir} or its subdirectories.") + val_set = ( + data_dir / "val" + if (data_dir / "val").exists() + else data_dir / "validation" + if (data_dir / "validation").exists() + else data_dir / "valid" + if (data_dir / "valid").exists() + else None + ) # data/test or data/val + test_set = data_dir / "test" if (data_dir / "test").exists() else None # data/val or data/test + if split == "val" and not val_set: + LOGGER.warning("Dataset 'split=val' not found, using 'split=test' instead.") + val_set = test_set + elif split == "test" and not test_set: + LOGGER.warning("Dataset 'split=test' not found, using 'split=val' instead.") + test_set = val_set + + if (ndjson_names := data_dir / ".ndjson.yaml").is_file(): + names = YAML.load(ndjson_names)["names"] + else: + names = dict(enumerate(sorted(x.name for x in (data_dir / "train").iterdir() if x.is_dir()))) + nc = len(names) + + # Print to console + for k, v in {"train": train_set, "val": val_set, "test": test_set}.items(): + prefix = f"{colorstr(f'{k}:')} {v}..." + if v is None: + LOGGER.info(prefix) + else: + files = [path for path in v.rglob("*.*") if path.suffix[1:].lower() in IMG_FORMATS] + nf = len(files) # number of files + nd = len({file.parent for file in files}) # number of directories + if nf == 0: + if k == "train": + raise FileNotFoundError(f"{dataset} '{k}:' no training images found") + else: + LOGGER.warning(f"{prefix} found {nf} images in {nd} classes (no images found)") + elif nd != nc and not ndjson_names.is_file(): + LOGGER.error(f"{prefix} found {nf} images in {nd} classes (requires {nc} classes, not {nd})") + else: + class_count = f"{nd}/{nc}" if ndjson_names.is_file() else nd + LOGGER.info(f"{prefix} found {nf} images in {class_count} classes ✅ ") + + return {"train": train_set, "val": val_set, "test": test_set, "nc": nc, "names": names, "channels": 3} + + +def compress_one_image(f: str, f_new: str | None = None, max_dim: int = 1920, quality: int = 50): + """Compress a single image file to reduced size while preserving its aspect ratio and quality using either the + Python Imaging Library (PIL) or OpenCV library. If the input image is smaller than the maximum dimension, it + will not be resized. + + Args: + f (str): The path to the input image file. + f_new (str, optional): The path to the output image file. If not specified, the input file will be overwritten. + max_dim (int, optional): The maximum dimension (width or height) of the output image. + quality (int, optional): The image compression quality as a percentage. + + Examples: + >>> from pathlib import Path + >>> from ultralytics.data.utils import compress_one_image + >>> for f in Path("path/to/dataset").rglob("*.jpg"): + >>> compress_one_image(f) + """ + try: # use PIL + Image.MAX_IMAGE_PIXELS = None # Fix DecompressionBombError, allow optimization of image > ~178.9 million pixels + im = Image.open(f) + if im.mode in {"RGBA", "LA"}: # Convert to RGB if needed (for JPEG) + im = im.convert("RGB") + r = max_dim / max(im.height, im.width) # ratio + if r < 1.0: # image too large + im = im.resize((int(im.width * r), int(im.height * r))) + im.save(f_new or f, "JPEG", quality=quality, optimize=True) # save + except Exception as e: # use OpenCV + LOGGER.warning(f"Image compression PIL failure {f}: {e}") + im = cv2.imread(f) + im_height, im_width = im.shape[:2] + r = max_dim / max(im_height, im_width) # ratio + if r < 1.0: # image too large + im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_AREA) + cv2.imwrite(str(f_new or f), im) + + +def load_dataset_cache_file(path: Path) -> dict: + """Load an Ultralytics *.cache dictionary from path.""" + import gc + + gc.disable() # reduce pickle load time https://github.com/ultralytics/ultralytics/pull/1585 + cache = np.load(str(path), allow_pickle=True).item() # load dict + gc.enable() + return cache + + +def save_dataset_cache_file(prefix: str, path: Path, x: dict, version: str): + """Save an Ultralytics dataset *.cache dictionary x to path.""" + x["version"] = version # add cache version + if is_dir_writeable(path.parent): + if path.exists(): + path.unlink() # remove *.cache file if exists + try: + with open(str(path), "wb") as file: # context manager here fixes windows async np.save bug + np.save(file, x) + LOGGER.info(f"{prefix}New cache created: {path}") + except Exception as e: + Path(path).unlink(missing_ok=True) # remove partially written file + LOGGER.warning(f"{prefix}WARNING ⚠️ Failed to save cache to {path}: {e}") + else: + LOGGER.warning(f"{prefix}Cache directory {path.parent} is not writable, cache not saved.") + + +def add_polygon_background(data: dict) -> dict: + """Set up the background class for polygon-based semantic datasets without 'masks_dir'. + + - nc > 1: appends a 'background' class at id=nc and bumps data['nc'] to nc+1; polygon + cls values are kept as foreground ids. + - nc == 1: keeps nc=1 (binary segmentation). Polygon rasterization + yields a {0=bg, 1=fg} mask regardless of the label cls value. + """ + if data.get("masks_dir") or data.get("_polygon_bg_added"): + return data + nc = int(data.get("nc") or len(data.get("names") or {})) + if nc == 1: # binary: bg=0, fg=1 (implicit); model uses BCE on a single output channel + data["bg_class_idx"] = 0 + else: + names = dict(data.get("names") or {}) + names[nc] = "background" + data["bg_class_idx"] = nc + data["nc"] = nc + 1 + data["names"] = names + data["_polygon_bg_added"] = True + return data diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/engine/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..77a19dcf0f8093de419453747db2e7e719f96349 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/engine/__init__.py @@ -0,0 +1 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91a2c3ec8b9b8de3e7216394d9d3910eeef1d974 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/exporter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/exporter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..702b39d36d571fedbc776891b87b57aba4caeb64 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/exporter.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ed3bc0a9a5eb3dfd2aabddeb99d8f3e59d274220aa752937b9292dbeccf5bf9 +size 110844 diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/model.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68e60e4bfe8efb1bb2b5a19e64e01ffdb645d21f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/model.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/predictor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/predictor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a49644b408384687edfa6ad8e935bb2a86be31b5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/predictor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/results.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/results.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..565885305a8c71e3b7ec4305fe74ed9cb8c8149a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/results.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/trainer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/trainer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3abb37b39a78796feac7e8561f79a55b9690c940 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/trainer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/tuner.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/tuner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e071169b429e638dd354d84b6f22228caf5a2dd9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/tuner.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/validator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/validator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ee8f5ce16daed23e561da80a928a0fd16febe13 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/engine/__pycache__/validator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/exporter.py b/.venv/lib/python3.12/site-packages/ultralytics/engine/exporter.py new file mode 100644 index 0000000000000000000000000000000000000000..83887930fbfb8863614c97c3a731eddf7a6abacb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/engine/exporter.py @@ -0,0 +1,1984 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Export a YOLO PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit. + +Format | `format=argument` | Model +--- | --- | --- +PyTorch | - | yolo26n.pt +TorchScript | `torchscript` | yolo26n.torchscript +ONNX | `onnx` | yolo26n.onnx +OpenVINO | `openvino` | yolo26n_openvino_model/ +TensorRT | `engine` | yolo26n.engine +CoreML | `coreml` | yolo26n.mlpackage +TensorFlow SavedModel | `saved_model` | yolo26n_saved_model/ +TensorFlow GraphDef | `pb` | yolo26n.pb +TensorFlow Edge TPU | `edgetpu` | yolo26n_edgetpu.tflite +PaddlePaddle | `paddle` | yolo26n_paddle_model/ +MNN | `mnn` | yolo26n.mnn +NCNN | `ncnn` | yolo26n_ncnn_model/ +IMX | `imx` | yolo26n_imx_model/ +RKNN | `rknn` | yolo26n_rknn_model/ +ExecuTorch | `executorch` | yolo26n_executorch_model/ +Axelera AI | `axelera` | yolo26n_axelera_model/ +DEEPX | `deepx` | yolo26n_deepx_model/ +Qualcomm QNN | `qnn` | yolo26n_qnn.onnx +LiteRT | `litert` | yolo26n.tflite +Hailo | `hailo` | yolo26n_hailo_model/ +Huawei Ascend | `ascend` | yolo26n_ascend_model/ +Apple Core AI | `coreai` | yolo26n.aimodel + +Requirements: + $ pip install "ultralytics[export]" + +Python: + from ultralytics import YOLO + model = YOLO('yolo26n.pt') + results = model.export(format='onnx') + results = model.export(format='onnx', quantize=8, data='coco8.yaml') # INT8 ONNX + +CLI: + $ yolo export model=yolo26n.pt format=onnx + $ yolo export model=yolo26n.pt format=onnx quantize=8 data=coco8.yaml + +Inference: + $ yolo predict model=yolo26n.pt # PyTorch + yolo26n.torchscript # TorchScript + yolo26n.onnx # ONNX Runtime or OpenCV DNN with dnn=True + yolo26n_openvino_model # OpenVINO + yolo26n.engine # TensorRT + yolo26n.mlpackage # CoreML (macOS-only) + yolo26n_saved_model # TensorFlow SavedModel + yolo26n.pb # TensorFlow GraphDef + yolo26n_edgetpu.tflite # TensorFlow Edge TPU + yolo26n_paddle_model # PaddlePaddle + yolo26n.mnn # MNN + yolo26n_ncnn_model # NCNN + yolo26n_imx_model # IMX + yolo26n_rknn_model # RKNN + yolo26n_executorch_model # ExecuTorch + yolo26n_axelera_model # Axelera AI + yolo26n_deepx_model # DEEPX + yolo26n_qnn.onnx # Qualcomm QNN + yolo26n.tflite # LiteRT + yolo26n_ascend_model # Huawei Ascend + yolo26n.aimodel # Apple Core AI (macOS 26+, Apple silicon) +""" + +from __future__ import annotations + +import json +import os +import shutil +import time +from copy import deepcopy +from datetime import datetime +from functools import partial +from pathlib import Path + +import numpy as np +import torch + +from ultralytics import __version__ +from ultralytics.cfg import QUANTIZE_DOCS_URL, TASK2CALIBRATIONDATA, TASK2DATA, get_cfg +from ultralytics.data import build_dataloader, build_yolo_dataset +from ultralytics.data.dataset import ClassificationDataset +from ultralytics.data.utils import check_cls_dataset, check_det_dataset, get_split_fraction +from ultralytics.nn.autobackend import AutoBackend, check_class_names, default_class_names +from ultralytics.nn.modules import ( + OBB, + OBB26, + Attention, + C2f, + Classify, + Depth, + Detect, + Pose, + Pose26, + RTDETRDecoder, + Segment, + Segment26, + SemanticSegment, +) +from ultralytics.nn.tasks import ClassificationModel, DepthModel, DetectionModel, SegmentationModel, WorldModel +from ultralytics.utils import ( + ARM64, + DEFAULT_CFG, + IS_DOCKER, + LINUX, + LOGGER, + MACOS, + MACOS_VERSION, + QNN_HTP_TARGETS, + RKNN_CHIPS, + SETTINGS, + TORCH_VERSION, + WINDOWS, + YAML, + callbacks, + colorstr, + get_default_args, + is_jetson, +) +from ultralytics.utils.checks import ( + IS_PYTHON_MINIMUM_3_9, + IS_PYTHON_MINIMUM_3_13, + check_imgsz, + check_requirements, + check_version, + is_intel, +) +from ultralytics.utils.export.axelera import AXELERA_SDK +from ultralytics.utils.files import file_size +from ultralytics.utils.metrics import batch_probiou +from ultralytics.utils.nms import TorchNMS +from ultralytics.utils.ops import Profile +from ultralytics.utils.patches import arange_patch +from ultralytics.utils.torch_utils import ( + TORCH_1_11, + TORCH_1_13, + TORCH_2_1, + TORCH_2_3, + TORCH_2_8, + TORCH_2_9, + is_qat, + select_device, +) + + +def export_formats(): + """Return a dictionary of Ultralytics YOLO export formats.""" + # Format, Argument, Suffix, CPU, GPU, Arguments, Env + x = [ + ["PyTorch", "-", ".pt", True, True, [], "base"], + [ + "TorchScript", + "torchscript", + ".torchscript", + True, + True, + ["batch", "quantize", "nms", "dynamic"], + "base", + ], + [ + "ONNX", + "onnx", + ".onnx", + True, + True, + ["batch", "data", "dynamic", "quantize", "opset", "simplify", "nms", "fraction"], + "base", + ], + [ + "OpenVINO", + "openvino", + "_openvino_model", + True, + False, + ["batch", "data", "dynamic", "quantize", "nms", "fraction"], + "base", + ], + [ + "TensorRT", + "engine", + ".engine", + False, + True, + ["batch", "data", "dynamic", "quantize", "opset", "simplify", "workspace", "nms", "fraction"], + "base", + ], + ["CoreML", "coreml", ".mlpackage", True, False, ["batch", "dynamic", "quantize", "nms"], "coreml"], + [ + "TensorFlow SavedModel", + "saved_model", + "_saved_model", + True, + True, + ["batch", "data", "fraction", "quantize", "opset", "keras", "nms"], + "tensorflow", + ], + ["TensorFlow GraphDef", "pb", ".pb", True, True, ["batch", "opset"], "tensorflow"], + [ + "TensorFlow Edge TPU", + "edgetpu", + "_edgetpu.tflite", + True, + False, + ["data", "fraction", "quantize", "opset"], + "tensorflow", + ], + ["PaddlePaddle", "paddle", "_paddle_model", True, True, ["batch"], "base"], + ["MNN", "mnn", ".mnn", True, True, ["batch", "dynamic", "quantize", "opset", "simplify", "nms"], "mnn"], + ["NCNN", "ncnn", "_ncnn_model", True, True, ["batch", "quantize"], "ncnn"], + ["IMX", "imx", "_imx_model", True, True, ["data", "quantize", "fraction", "nms"], "isolated-imx"], + [ + "RKNN", + "rknn", + "_rknn_model", + False, + False, + ["batch", "name", "quantize", "opset", "simplify", "data", "fraction"], + "isolated-rknn", + ], + ["ExecuTorch", "executorch", "_executorch_model", True, False, ["batch"], "executorch"], + [ + "Axelera AI", + "axelera", + "_axelera_model", + False, + False, + ["batch", "quantize", "fraction", "data"], + "isolated-axelera", + ], + [ + "DEEPX", + "deepx", + "_deepx_model", + False, + False, + ["data", "quantize", "opset", "simplify", "optimize"], + "isolated-deepx", + ], + [ + "Qualcomm QNN", + "qnn", + "_qnn.onnx", + False, + False, + ["batch", "name", "quantize", "opset", "simplify", "fraction", "data"], + "base", + ], + ["LiteRT", "litert", ".tflite", True, False, ["batch", "quantize", "data", "fraction"], "litert"], + [ + "Hailo", + "hailo", + "_hailo_model", + False, + False, + ["name", "quantize", "data", "fraction", "simplify", "conf", "iou"], + "base", + ], + [ + "Huawei Ascend", + "ascend", + "_ascend_model", + False, + False, + ["batch", "name", "quantize", "opset", "simplify", "nms"], + "base", + ], + [ + "Core AI", + "coreai", + ".aimodel", + True, + False, + ["batch", "quantize"], + "base", + ], + ] + return dict(zip(["Format", "Argument", "Suffix", "CPU", "GPU", "Arguments", "Env"], zip(*x))) + + +EXPORT_ENVS = { + "base": { + "python": None, + "extras": ["export-base", "export-openvino"], + "torch": None, + "requirements": [], + "indexes": [], + "env": {}, + "smoke": [], + }, + "tensorflow": { + "python": "3.12", + "extras": ["export-base", "export-tensorflow"], + "torch": None, + "requirements": [ + "onnx2tf>=1.26.3,<1.29.0", + "tf_keras<=2.19.0", + "sng4onnx>=1.0.1", + "onnx_graphsurgeon>=0.3.26", + "ai-edge-litert>=1.2.0", + "onnxruntime", + "protobuf>=5", + ], + "indexes": [], + "env": {}, + "smoke": ["yolo export format=saved_model model=yolo26n.pt imgsz=32"], + }, + "coreml": { + "python": "3.13", + "extras": ["export-base", "export-coreml"], + "torch": ">=2.12", + "requirements": [], + "indexes": [], + "env": {}, + "smoke": ["yolo export format=coreml model=yolo26n.pt imgsz=32"], + }, + "mnn": { + "python": "3.13", + "extras": ["export-base"], + "torch": None, + "requirements": ["MNN>=2.9.6", "aliyun-log-python-sdk", "protobuf<6.0.0,>=3.20.3"], + "indexes": [], + "env": {}, + "smoke": ["yolo export format=mnn model=yolo26n.pt imgsz=32"], + }, + "ncnn": { + "python": "3.13", + "extras": ["export-base"], + "torch": None, + "requirements": ["ncnn", "pnnx==20260526"], + "indexes": [], + "env": {}, + "smoke": ["yolo export format=ncnn model=yolo26n.pt imgsz=32"], + }, + "executorch": { + "python": "3.13", + "extras": ["export-base", "export-executorch"], + "torch": ">=2.12", + "requirements": [], + "indexes": [], + "env": {}, + "smoke": ["yolo export format=executorch model=yolo26n.pt imgsz=32"], + }, + "isolated-imx": { + "python": "3.11", + "extras": ["export-base"], + "torch": ">=2.9,<2.12", + "requirements": [ + "model-compression-toolkit>=2.4.1", + "edge-mdt-cl<1.1.0", + "edge-mdt-tpc>=1.2.0", + "pydantic<2.12", + "imx500-converter[pt]>=3.17.3", + ], + "indexes": [], + "env": {}, + "smoke": ["yolo export format=imx model=yolo11n.pt imgsz=32 data=coco8.yaml"], + }, + "isolated-rknn": { + "python": "3.11", + "extras": ["export-base"], + "torch": "==2.4", + "requirements": ["rknn-toolkit2>=2.3.2", "onnx>=1.16.1,<1.19.0", "setuptools<82"], + "indexes": [], + "env": {}, + "smoke": ["yolo export format=rknn model=yolo26n.pt imgsz=32 quantize=16"], + }, + "isolated-axelera": { + "python": "3.13", + "extras": ["export-base"], + # Axelera export requires 2.8.0 <= torch < 2.13.0. + "torch": ">=2.8,<2.13", + "requirements": [ + f"axelera-devkit=={AXELERA_SDK}", + f"axelera-rt=={AXELERA_SDK}", + "omnimalloc==0.5.0", + "onnx>=1.12.0,<2.0.0", + "onnxslim>=0.1.71", + ], + "indexes": [ + ("--extra-index-url", "https://software.axelera.ai/artifactory/api/pypi/axelera-pypi/simple"), + ], + # Use the Python protobuf runtime for Axelera compiler compatibility. + "env": {"PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": "python"}, + "smoke": ["yolo export format=axelera model=yolo26n.pt imgsz=64 data=coco8.yaml"], + }, + "isolated-deepx": { + # dx-com 2.3.0 does not provide Python 3.13 wheels. + "python": "3.12", + "extras": ["export-base", "export-deepx"], + "torch": ">=2.8,<2.12", + "requirements": [], + "indexes": [ + ("--find-links", "https://sdk.deepx.ai/release/dxcom/v2.3.0/index.html"), + ], + # DeepX export is only supported on non-aarch64 Linux. + "env": {}, + "smoke": ["yolo export format=deepx model=yolo26n.pt imgsz=32 data=coco8.yaml"], + }, + "litert": { + "python": "3.13", + "extras": ["export-base", "export-litert"], + "torch": None, + "requirements": [], + "indexes": [], + "env": {}, + "smoke": ["yolo export format=litert model=yolo26n.pt imgsz=32"], + }, +} + + +# Export precision support per format. Unset/32 requests are FP32 except for formats listed in FP32_UNSUPPORTED_FORMATS. +FP16_FORMATS = frozenset( + {"torchscript", "onnx", "openvino", "engine", "coreml", "mnn", "ncnn", "rknn", "ascend", "coreai"} +) +INT8_FORMATS = frozenset( + { + "onnx", + "openvino", + "engine", + "coreml", + "saved_model", + "edgetpu", + "mnn", + "imx", + "rknn", + "axelera", + "deepx", + "hailo", + "litert", + } +) +W8A16_FORMATS = frozenset( + {"coreml", "imx", "qnn", "litert"} +) # INT8 weights + 16-bit activations (FP16; INT16 on LiteRT) +W8A32_FORMATS = frozenset({"litert"}) # INT8 weights + FP32 activations (dynamic/weight-only INT8, no calibration) +FP32_UNSUPPORTED_FORMATS = frozenset({"edgetpu", "imx", "rknn", "axelera", "deepx", "qnn", "hailo", "ascend"}) +# (label, supporting formats) per quantize precision, used to list valid options in errors. 32/None (FP32) is universal except FP32_UNSUPPORTED_FORMATS. +QUANTIZE_PRECISIONS = ( + ("16 (FP16)", FP16_FORMATS), + ("8 (INT8)", INT8_FORMATS), + ("'w8a16' (INT8 weights + INT16 activations)", W8A16_FORMATS), + ("'w8a32' (dynamic INT8)", W8A32_FORMATS), +) + + +def validate_args(format, passed_args, valid_args): + """Validate arguments based on the export format. + + Args: + format (str): The export format. + passed_args (SimpleNamespace): The arguments used during export. + valid_args (list): List of valid arguments for the format. + + Raises: + AssertionError: If an unsupported argument is used, or if the format lacks supported argument listings. + """ + # Format-specific args come from the export table; skip inference args and quantize (validated above) + export_args = sorted(set().union(*export_formats()["Arguments"]) - {"conf", "iou", "name", "quantize", "nms"}) + + assert valid_args is not None, f"ERROR ❌️ valid arguments for '{format}' not listed." + custom = {"batch": 1, "data": None, "device": None} # exporter defaults + default_args = get_cfg(DEFAULT_CFG, custom) + if passed_args.quantize is not None: # 32/None (FP32) is universal except FP32_UNSUPPORTED_FORMATS + options = [label for label, formats in QUANTIZE_PRECISIONS if format in formats] + if format not in FP32_UNSUPPORTED_FORMATS: + options.append("32 or None (FP32)") + hint = f"format='{format}' supports quantize={', '.join(options)}. See {QUANTIZE_DOCS_URL}" + if passed_args.quantize == 16: # FP16 + assert format in FP16_FORMATS, f"ERROR ❌️ quantize=16 (FP16) is not supported; {hint}" + elif passed_args.quantize == 8: # INT8 + assert format in INT8_FORMATS, f"ERROR ❌️ quantize=8 (INT8) is not supported; {hint}" + elif passed_args.quantize == "w8a16": # INT8 weights + 16-bit activations (FP16; INT16 on LiteRT) + assert format in W8A16_FORMATS, f"ERROR ❌️ quantize='w8a16' is not supported; {hint}" + elif passed_args.quantize == "w8a32": # INT8 weights + FP32 activations (dynamic/weight-only INT8) + assert format in W8A32_FORMATS, f"ERROR ❌️ quantize='w8a32' is not supported; {hint}" + elif passed_args.quantize == 32: # FP32 + assert format not in FP32_UNSUPPORTED_FORMATS, f"ERROR ❌️ quantize=32 (FP32) is not supported; {hint}" + for arg in export_args: + not_default = getattr(passed_args, arg, getattr(default_args, arg, None)) != getattr(default_args, arg, None) + if not_default: + assert arg in valid_args, f"ERROR ❌️ argument '{arg}' is not supported for format='{format}'" + + +def try_export(inner_func): + """YOLO export decorator, i.e. @try_export.""" + inner_args = get_default_args(inner_func) + + def outer_func(*args, **kwargs): + """Export a model.""" + prefix = inner_args["prefix"] + dt = 0.0 + try: + with Profile() as dt: + f = inner_func(*args, **kwargs) # exported file/dir or tuple of (file/dir, *) + path = f if isinstance(f, (str, Path)) else f[0] + mb = file_size(path) + assert mb > 0.1, f"{mb:.3f} MB output model too small (likely corrupt or unsupported ops)" + LOGGER.info(f"{prefix} export success ✅ {dt.t:.1f}s, saved as '{path}' ({mb:.1f} MB)") + return f + except Exception as e: + LOGGER.error(f"{prefix} export failure {dt.t:.1f}s: {e}") + raise + + return outer_func + + +class Exporter: + """A class for exporting YOLO models to various formats. + + This class provides functionality to export YOLO models to different formats including ONNX, TensorRT, CoreML, + TensorFlow, and others. It handles format validation, device selection, model preparation, and the actual export + process for each supported format. + + Attributes: + args (SimpleNamespace): Configuration arguments for the exporter. + callbacks (dict): Dictionary of callback functions for different export events. + im (torch.Tensor): Input tensor for model inference during export. + model (torch.nn.Module): The YOLO model to be exported. + file (Path): Path to the model file being exported. + output_shape (tuple): Shape of the model output tensor(s). + pretty_name (str): Formatted model name for display purposes. + metadata (dict): Model metadata including description, author, version, etc. + device (torch.device): Device on which the model is loaded. + imgsz (list): Input image size for the model. + + Methods: + __call__: Main export method that handles the export process. + get_int8_calibration_dataloader: Build dataloader for INT8 calibration. + export_torchscript: Export model to TorchScript format. + export_onnx: Export model to ONNX format. + export_openvino: Export model to OpenVINO format. + export_paddle: Export model to PaddlePaddle format. + export_mnn: Export model to MNN format. + export_ncnn: Export model to NCNN format. + export_coreml: Export model to CoreML format. + export_engine: Export model to TensorRT format. + export_saved_model: Export model to TensorFlow SavedModel format. + export_pb: Export model to TensorFlow GraphDef format. + export_edgetpu: Export model to Edge TPU format. + export_rknn: Export model to RKNN format. + export_imx: Export model to IMX format. + export_executorch: Export model to ExecuTorch format. + export_coreai: Export model to Apple Core AI format. + export_axelera: Export model to Axelera format. + export_deepx: Export model to DEEPX format. + + Examples: + Export a YOLO26 model to TorchScript format + >>> from ultralytics import YOLO + >>> from ultralytics.engine.exporter import Exporter + >>> exporter = Exporter() + >>> exporter(model=YOLO("yolo26n.pt").model) # exports to yolo26n.torchscript + + Export with specific arguments + >>> args = {"format": "onnx", "dynamic": True, "quantize": 8, "data": "coco8.yaml"} + >>> exporter = Exporter(overrides=args) + >>> exporter(model=YOLO("yolo26n.pt").model) + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks: dict | None = None): + """Initialize the Exporter class. + + Args: + cfg (str | Path | dict | SimpleNamespace, optional): Configuration file path or configuration object. + overrides (dict, optional): Configuration overrides. + _callbacks (dict, optional): Dictionary of callback functions. + """ + self.args = get_cfg(cfg, overrides) + self.callbacks = _callbacks or callbacks.get_default_callbacks() + callbacks.add_integration_callbacks(self) + + def __call__(self, model=None) -> str: + """Export a model and return the final exported path as a string. + + Returns: + (str): Path to the exported file or directory (the last export artifact). + """ + t = time.time() + fmt = self.args.format.lower() # to lowercase + if fmt in {"tensorrt", "trt"}: # 'engine' aliases + fmt = "engine" + if fmt in {"mlmodel", "mlpackage", "mlprogram", "apple", "ios", "coreml"}: # 'coreml' aliases + fmt = "coreml" + if fmt in {"huawei", "cann", "om"}: # 'ascend' aliases + fmt = self.args.format = "ascend" + if fmt in {"tflite", "tfjs"}: # deprecated formats, replaced by the unified Google LiteRT export + LOGGER.warning( + f"format='{fmt}' is deprecated as of 8.4.83 and has been replaced by the unified Google LiteRT " + f"format. Exporting format='litert' instead. See https://docs.ultralytics.com/integrations/litert" + ) + fmt = self.args.format = "litert" + fmts_dict = export_formats() + fmts = tuple(fmts_dict["Argument"][1:]) # available export formats + if fmt not in fmts: + import difflib + + # Get the closest match if format is invalid + matches = difflib.get_close_matches(fmt, fmts, n=1, cutoff=0.6) # 60% similarity required to match + if not matches: + msg = "Model is already in PyTorch format." if fmt == "pt" else f"Invalid export format='{fmt}'." + raise ValueError(f"{msg} Valid formats are {fmts}") + LOGGER.warning(f"Invalid export format='{fmt}', updating to format='{matches[0]}'") + fmt = matches[0] + is_tf_format = fmt in {"saved_model", "pb", "edgetpu"} + + # Device + self.dla = None + if fmt == "engine" and self.args.device is None: + LOGGER.warning("TensorRT requires GPU export, automatically assigning device=0") + self.args.device = "0" + if fmt == "engine" and "dla" in str(self.args.device): # convert int/list to str first + device_str = str(self.args.device) + self.dla = device_str.rsplit(":", 1)[-1] + self.args.device = "0" # update device to "0" + assert self.dla in {"0", "1"}, f"Expected device 'dla:0' or 'dla:1', but got {device_str}." + if fmt == "imx" and self.args.device is None and torch.cuda.is_available(): + LOGGER.warning("Exporting on CPU while CUDA is available, setting device=0 for faster export on GPU.") + self.args.device = "0" # update device to "0" + self.device = select_device("cpu" if self.args.device is None else self.args.device) + + # Argument compatibility checks + fmt_keys = dict(zip(fmts_dict["Argument"], fmts_dict["Arguments"]))[fmt] + validate_args(fmt, self.args, fmt_keys) + if fmt in {"deepx", "axelera", "imx", "edgetpu", "qnn", "hailo"} and self.args.quantize not in {8, "w8a16"}: + LOGGER.warning(f"{fmt} export requires INT8 quantization, enabling it.") + self.args.quantize = "w8a16" if fmt == "qnn" else 8 + if fmt in {"axelera", "hailo"} and not self.args.data: + self.args.data = TASK2CALIBRATIONDATA.get(model.task) + if fmt == "hailo": + assert LINUX and not ARM64, "Hailo export is only supported on Linux x86_64." + blocks = {str(x[2]) for x in model.yaml.get("backbone", []) + model.yaml.get("head", [])} + family = Path(getattr(model, "yaml_file", None) or model.yaml.get("yaml_file", "")).stem.lower() or ( + "yolov8" if "C2f" in blocks else "yolo11" if {"C3k2", "C2PSA"} <= blocks else "" + ) + task26 = {Segment26: "segmentation", Pose26: "pose", OBB26: "OBB"}.get(type(model.model[-1])) + if task26: + raise ValueError(f"Hailo export does not currently support YOLO26 {task26} models.") + if ( + model.task not in {"detect", "segment", "pose", "obb", "classify", "semantic", "depth"} + or type(model.model[-1]) not in {Detect, Segment, Pose, OBB, Classify, SemanticSegment, Depth} + or not family.startswith(("yolov8", "yolo11", "yolo26")) + ): + raise ValueError( + "Hailo export currently supports YOLOv8/YOLO11/YOLO26 detection and classification models, " + "YOLOv8/YOLO11 segmentation, pose, and OBB models, and YOLO26 semantic segmentation and depth " + "models." + ) + if model.task in {"semantic", "depth"} and not family.startswith("yolo26"): + raise ValueError(f"Hailo export supports {model.task} models only for YOLO26.") + self.args.name = str(self.args.name or "hailo8l").lower() + hailo_archs = ("hailo8", "hailo8l", "hailo10h", "hailo15h", "hailo15l") + if self.args.name not in hailo_archs: + raise ValueError(f"Invalid Hailo architecture '{self.args.name}'. Valid names are {hailo_archs}.") + if fmt == "axelera" and model.task == "segment" and any(isinstance(m, Segment26) for m in model.modules()): + raise ValueError("Axelera export does not currently support YOLO26 segmentation models.") + if fmt == "imx": + if model.task == "depth": + raise ValueError("IMX export is not supported for depth models.") + if not self.args.nms and model.task in {"detect", "pose", "segment"}: + LOGGER.warning("IMX export requires nms=True, setting nms=True.") + self.args.nms = True + if model.task not in {"detect", "pose", "classify", "segment"}: + raise ValueError( + "IMX export only supported for detection, pose estimation, classification, and segmentation models." + ) + memo = {} + if isinstance(model, WorldModel): + LOGGER.warning( + "YOLOWorld (original version) export is not supported to any format. " + "YOLOWorldv2 models (i.e. 'yolov8s-worldv2.pt') only support export to " + "(torchscript, onnx, openvino, engine, coreml) formats. " + "See https://docs.ultralytics.com/models/yolo-world for details." + ) + # Keep a cached CLIP encoder out of the export copy: https://github.com/ultralytics/ultralytics/pull/18445 + memo[id(getattr(model, "clip_model", None))] = None + model = deepcopy(model, memo).to(self.device) # copy before the head and names writes below + if not getattr(model, "names", None): # missing, None or empty on legacy and foreign checkpoints + head = model.model[-1] # name the head's own classes so the metadata matches the output layer + nc = head.linear.out_features if isinstance(head, Classify) else getattr(head, "nc", 999) + model.names = default_class_names(nc=nc) + model.names = check_class_names(model.names) + if hasattr(model, "end2end"): + model.end2end = self.args.nms is False + if getattr(model, "end2end", False): + if fmt in {"rknn", "ncnn", "executorch", "paddle", "imx", "edgetpu", "qnn"}: + # Disable the end2end branch for formats without top-k support + model.end2end = False + LOGGER.warning("This export format does not support end2end models, disabling the end2end branch.") + if fmt == "litert" and self.args.quantize in {8, "w8a16"}: + # Static activation quantization collapses the end2end class-index output; export raw and run NMS later + model.end2end = False + LOGGER.warning("LiteRT INT8 export does not support end2end models, disabling end2end branch.") + if fmt == "engine": + try: + import tensorrt as trt + + if check_version(trt.__version__, "<8.5.0"): + # https://github.com/ultralytics/ultralytics/issues/24607 + model.end2end = False + LOGGER.warning( + "TensorRT versions earlier than 8.5.0 do not support the Mod operator in end-to-end models, disabling the end2end branch. " + "Please upgrade TensorRT to 8.5.0 or later to enable end2end export." + ) + + if ( + self.args.quantize == 8 + and check_version(trt.__version__, ">=10.3.0,<10.4.0") # JetPack 6 builds report 10.3.0.x + and is_jetson(jetpack=6) + ): + # https://github.com/ultralytics/ultralytics/issues/23841 + model.end2end = False + LOGGER.warning( + "TensorRT 10.3.0 on JetPack 6 with INT8 cannot build NMS-free exports; selecting one-to-many outputs. " + "For a fix, see https://docs.ultralytics.com/guides/nvidia-jetson#why-does-my-tensorrt-int8-export-disable-nms-free-inference-on-jetpack-6" + ) + except ImportError: + pass + if self.args.quantize == 16 and fmt == "torchscript" and self.device.type == "cpu": + raise ValueError("FP16 TorchScript export is only supported on GPU, i.e. use device=0.") + self.imgsz = check_imgsz(self.args.imgsz, stride=model.stride, min_dim=2) # check image size + if fmt == "axelera" and min(self.imgsz) < 64: + raise ValueError(f"Axelera export requires imgsz>=64, but got imgsz={self.imgsz}.") + if fmt == "rknn": + if not self.args.name: + LOGGER.warning( + "Rockchip RKNN export requires a missing 'name' arg for processor type. " + "Using default name='rk3588'." + ) + self.args.name = "rk3588" + self.args.name = self.args.name.lower() + assert self.args.name in RKNN_CHIPS, ( + f"Invalid processor name '{self.args.name}' for Rockchip RKNN export. Valid names are {RKNN_CHIPS}." + ) + if self.args.name in {"rv1103", "rv1106", "rv1103b", "rv1106b"} and self.args.quantize != 8: + if self.args.quantize not in {None, 8}: + raise ValueError( + f"Rockchip target '{self.args.name}' only supports INT8, but got quantize={self.args.quantize}. " + f"See {QUANTIZE_DOCS_URL}" + ) + LOGGER.warning(f"Rockchip target '{self.args.name}' requires INT8 quantization, enabling it.") + self.args.quantize = 8 + elif self.args.quantize is None: + self.args.quantize = 16 + if self.args.quantize == 8 and model.task != "detect": + raise ValueError("Rockchip RKNN INT8 export is only supported for detection models.") + if fmt == "ascend": + # No SoC allowlist: valid --soc_version values depend on which Ascend-cann-kernels-* packages are + # installed, so a hardcoded list would reject valid targets. ATC reports an unknown SoC itself. + if not self.args.name: + LOGGER.warning( + "Huawei Ascend export requires a missing 'name' arg for the target SoC. " + "Using default name='Ascend310B4'." + ) + self.args.name = "Ascend310B4" + if not str(self.args.name).startswith("Ascend"): + raise ValueError( + f"Invalid Ascend SoC name='{self.args.name}'. Expected a CANN --soc_version such as " + f"'Ascend310P3' or 'Ascend310B4'. See https://docs.ultralytics.com/integrations/ascend" + ) + if self.args.quantize is None: + self.args.quantize = 16 # Ascend AI Core convolutions accept only FP16/INT8 inputs, never FP32 + if fmt == "qnn": + if not self.args.name: + LOGGER.warning( + "Qualcomm QNN export requires a missing 'name' arg for the target Hexagon HTP architecture. " + "Using default name='73' (Snapdragon 8 Gen 2)." + ) + self.args.name = "73" + self.args.name = str(self.args.name).lower().lstrip("v") # accept '73', 'v73', or a supported SoC + assert self.args.name in QNN_HTP_TARGETS, ( + f"Invalid Qualcomm QNN target '{self.args.name}'. Valid targets are {tuple(QNN_HTP_TARGETS)}." + ) + if self.args.nms and "nms" not in fmt_keys: + LOGGER.warning(f"format={fmt} does not support embedded NMS; exporting native outputs for external NMS.") + self.args.nms = None + if self.args.nms and model.task in {"semantic", "depth"}: + LOGGER.warning(f"'nms=True' is not valid for {model.task} models. Forcing 'nms=None'.") + self.args.nms = None + if fmt == "coreml" and self.args.nms and model.task not in {"detect", "segment", "pose"}: + LOGGER.warning( + "CoreML 'nms=True' is only supported for detect, segment and pose models. Forcing 'nms=None'." + ) + self.args.nms = None + if self.args.nms: + assert not isinstance(model, ClassificationModel), "'nms=True' is not valid for classification models." + assert not is_tf_format or TORCH_1_13, "TensorFlow exports with NMS require torch>=1.13" + assert fmt != "onnx" or TORCH_1_13, "ONNX export with NMS requires torch>=1.13" + # A previously fused checkpoint may only have its one-to-one branch remaining. + if getattr(model, "end2end", False) or isinstance(model.model[-1], RTDETRDecoder): + LOGGER.warning("'nms=True' is not available for end2end models. Forcing 'nms=None'.") + self.args.nms = None + self.args.conf = 0.25 if self.args.conf is None else self.args.conf # set conf default for nms export + if fmt == "mnn" and self.args.nms: + if self.args.dynamic: + raise ValueError("Alibaba MNN export does not support combining 'dynamic=True' with 'nms=True'.") + if model.task not in {"detect", "pose"}: + raise ValueError("Alibaba MNN export with 'nms=True' only supports detect and pose models.") + if fmt == "coreml": + if self.args.nms and model.task != "detect" and self.args.quantize == 32: + # CoreML evaluates NMSModel's data-dependent shapes only on its FP16 path, silently dropping + # detections from an FP32 ML Program. Detect is unaffected, its NMS is an Apple pipeline stage. + LOGGER.warning(f"CoreML 'nms=True' requires FP16 for {model.task} models. Forcing 'quantize=16'.") + self.args.quantize = 16 + if self.args.batch > 1: + assert self.args.dynamic, ( + "batch sizes > 1 are not supported without 'dynamic=True' for CoreML export. Please retry at 'dynamic=True'." + ) + if self.args.dynamic: + assert not self.args.nms, ( + "'nms=True' cannot be used together with 'dynamic=True' for CoreML export. Please disable one of them." + ) + assert model.task != "classify" and not isinstance(model.model[-1], RTDETRDecoder), ( + "'dynamic=True' is not supported for CoreML classification or RT-DETR models." + ) + if (fmt in {"engine", "coreml"} or self.args.nms) and self.args.dynamic and self.args.batch == 1: + LOGGER.warning("'dynamic=True' export requires a maximum batch size, e.g. 'batch=16'.") + if fmt == "edgetpu": + if not LINUX or ARM64: + raise SystemError( + "Edge TPU export only supported on non-aarch64 Linux. See https://coral.ai/docs/edgetpu/compiler" + ) + elif self.args.batch != 1: # see github.com/ultralytics/ultralytics/pull/13420 + LOGGER.warning("Edge TPU export requires batch size 1, setting batch=1.") + self.args.batch = 1 + self.qat = is_qat(model) # quantization-aware trained model: ranges are baked in, calibration is a no-op + if self.qat: + assert fmt in {"onnx", "engine"}, ( + f"format='{fmt}' cannot export a QAT model: its Q/DQ ranges are only read by the 'onnx' and " + f"'engine' backends. Export a non-QAT checkpoint to this format instead." + ) + assert self.args.quantize in {None, 8}, ( + f"a QAT model exports INT8, but got quantize={self.args.quantize}. Export a non-QAT checkpoint for " + f"other precisions." + ) + self.args.quantize = 8 # the graph carries Q/DQ nodes whether or not INT8 was requested + if self.args.quantize in {8, "w8a16"} and not self.args.data and not self.qat: + self.args.data = DEFAULT_CFG.data or TASK2DATA[getattr(model, "task", "detect")] # assign default data + LOGGER.warning( + f"INT8 export requires a missing 'data' arg for calibration. Using default 'data={self.args.data}'." + ) + # Recommend OpenVINO if export and Intel CPU + if SETTINGS.get("openvino_msg"): + if is_intel(): + LOGGER.info( + "💡 ProTip: Export to OpenVINO format for best performance on Intel hardware." + " Learn more at https://docs.ultralytics.com/integrations/openvino" + ) + SETTINGS["openvino_msg"] = False + + # Input + im = torch.zeros(self.args.batch, model.yaml.get("channels", 3), *self.imgsz).to(self.device) + file = Path( + getattr(model, "pt_path", None) or getattr(model, "yaml_file", None) or model.yaml.get("yaml_file", "") + ) + if file.suffix in {".yaml", ".yml"}: + file = Path(file.name) + + # Update model + for p in model.parameters(): + p.requires_grad = False + model.eval() + model.float() + model = model.fuse(imgsz=self.imgsz) + + if fmt == "imx": + from ultralytics.utils.export.imx import FXModel + + model = FXModel(model, self.imgsz) + if fmt == "edgetpu": + from ultralytics.utils.export.tensorflow import tf_wrapper + + model = tf_wrapper(model) + if fmt == "executorch": + from ultralytics.utils.export.executorch import executorch_wrapper + + model = executorch_wrapper(model) + for m in model.modules(): + if isinstance(m, Attention) and fmt == "coreml" and self.args.format.lower() != "mlmodel": + m.format = fmt + if isinstance(m, (Classify, SemanticSegment, Depth)): + m.export = True + m.format = self.args.format + # Semantic argmax bake needs an integer graph output; TensorRT supports uint8 outputs only on TRT>=10 + # (Jetson TRT 8.x rejects them). Read the version from the package name to avoid importing tensorrt here. + if isinstance(m, SemanticSegment) and fmt == "engine": + cuda_major = (torch.version.cuda or "12").split(".")[0] + m.bake_argmax = check_version(f"tensorrt-cu{cuda_major}", ">=10.0.0") or check_version( + "tensorrt", ">=10.0.0" + ) + if isinstance(m, (Detect, RTDETRDecoder)): # includes all Detect subclasses like Segment, Pose, OBB + m.dynamic = self.args.dynamic + m.export = True + m.format = self.args.format + # Clamp max_det to available queries/anchors (required for TensorRT compatibility) + available = ( + m.num_queries + if isinstance(m, RTDETRDecoder) + else sum(int(self.imgsz[0] / s) * int(self.imgsz[1] / s) for s in model.stride.tolist()) + ) + m.max_det = min(self.args.max_det, available) + m.agnostic_nms = self.args.agnostic_nms + # CoreML detect keeps IOSDetectModel's own xywh handling; segment/pose route through + # NMSModel like every other format, which expects xyxy boxes. + m.xyxy = self.args.nms and (fmt != "coreml" or model.task != "detect") + m.shape = None # reset cached shape for new export input size + if hasattr(model, "pe") and hasattr(m, "fuse") and not hasattr(m, "lrpc"): # for YOLOE models + m.fuse(model.pe.to(self.device)) + elif isinstance(m, C2f) and not is_tf_format: + # EdgeTPU does not support FlexSplitV while split provides cleaner ONNX graph + m.forward = m.forward_split + + if model.task == "semantic" and fmt in {"qnn", "coreml", "ascend"}: + # NPU-targeted semantic exports ship a compact uint8 class map instead of float logits: emitting logits + # forces consumers to dequantize and argmax ~20M floats on the CPU every frame (measured erratic + # 123-1065 ms on Hexagon). Not applied to LiteRT, where the GPU delegate cannot compile ArgMax (int64 + # indices) and a whole-graph CPU fallback is slower than GPU logits + consumer-side argmax. Python + # predict/val accept both forms. + model = ClassMapModel(model) + + y = None + for _ in range(2): # dry runs + y = NMSModel(model, self.args)(im) if self.args.nms and fmt not in {"coreml", "imx"} else model(im) + if self.args.quantize == 16 and fmt in {"onnx", "torchscript"} and self.device.type != "cpu": + im, model = im.half(), model.half() # to FP16 + + # Assign + self.im = im + self.model = model + self.file = file + self.output_shape = ( + tuple(y.shape) + if isinstance(y, torch.Tensor) + else tuple(tuple(x.shape if isinstance(x, torch.Tensor) else []) for x in y) + ) + self.pretty_name = Path(self.model.yaml.get("yaml_file", self.file)).stem.replace("yolo", "YOLO") + data = model.args["data"] if hasattr(model, "args") and isinstance(model.args, dict) else "" + description = f"Ultralytics {self.pretty_name} model {f'trained on {data}' if data else ''}" + self.metadata = { + "description": description, + "author": "Ultralytics", + "date": datetime.now().astimezone().isoformat(), + "version": __version__, + "license": "AGPL-3.0 License (https://ultralytics.com/license)", + "docs": "https://docs.ultralytics.com", + "stride": int(max(model.stride)), + "task": model.task, + "head": type(model.model[-1]).__name__, + "batch": self.args.batch, + "imgsz": self.imgsz, + "names": model.names, + "args": {k: str(v) if isinstance(v, Path) else v for k, v in self.args if k in fmt_keys}, + "channels": model.yaml.get("channels", 3), + "end2end": getattr(model, "end2end", False), + } # model metadata + if self.dla is not None: + self.metadata["dla"] = self.dla # make sure `AutoBackend` uses correct dla device if it has one + if model.task == "pose": + self.metadata["kpt_shape"] = model.model[-1].kpt_shape + if hasattr(model, "kpt_names"): + self.metadata["kpt_names"] = model.kpt_names + + LOGGER.info( + f"\n{colorstr('PyTorch:')} starting from '{file}' with input shape {tuple(im.shape)} BCHW and " + f"output shape(s) {self.output_shape} ({file_size(file):.1f} MB)" + ) + self.run_callbacks("on_export_start") + + # Export + if is_tf_format: + f, keras_model = self.export_saved_model() + if fmt == "pb": + f = self.export_pb(keras_model=keras_model) + if fmt == "edgetpu": + f = self.export_edgetpu(tflite_model=Path(f) / f"{self.file.stem}_full_integer_quant.tflite") + else: + f = getattr(self, f"export_{fmt}")() + + # Finish + if f: + square = self.imgsz[0] == self.imgsz[1] + s = ( + "" + if square + else f"WARNING ⚠️ non-PyTorch val requires square images, 'imgsz={self.imgsz}' will not " + f"work. Use export 'imgsz={max(self.imgsz)}' if val is required." + ) + imgsz = self.imgsz[0] if square else str(self.imgsz)[1:-1].replace(" ", "") + q = "quantize=16" if self.args.quantize == 16 else "" # FP16 inference flag for the val/predict hint + inference_commands = ( + f"\nPredict: yolo predict task={model.task} model={f} imgsz={imgsz} {q}" + f"\nValidate: yolo val task={model.task} model={f} imgsz={imgsz} data={data} {q} {s}" + if fmt in AutoBackend._BACKEND_MAP + else "" + ) + LOGGER.info( + f"\nExport complete ({time.time() - t:.1f}s)" + f"\nResults saved to {colorstr('bold', Path(f).resolve())}" + f"{inference_commands}" + f"\nVisualize: https://netron.app" + ) + + self.run_callbacks("on_export_end") + return f # path to final export artifact + + def get_int8_calibration_dataloader(self, prefix=""): + """Build and return a dataloader for calibration of INT8 models.""" + LOGGER.info(f"{prefix} collecting INT8 calibration images from 'data={self.args.data}'") + cfg = deepcopy(self.args) + cfg.imgsz = max(self.imgsz) + split = self.args.split or "val" + if self.model.task == "classify": + import torchvision.transforms as T # scope for faster 'import ultralytics' + + data = check_cls_dataset(self.args.data, split=self.args.split) + if not isinstance(cfg.fraction, list): + cfg.fraction = [cfg.fraction] * 3 + dataset = ClassificationDataset(data[split], args=cfg, augment=False, prefix=split) + # INT8 backends divide images by 255, so emit uint8 [0, 255] center-cropped like classify inference + dataset.torch_transforms = T.Compose([T.Resize(cfg.imgsz), T.CenterCrop(cfg.imgsz), T.PILToTensor()]) + else: + data = check_det_dataset(self.args.data, split=self.args.split) + cfg.fraction = get_split_fraction(cfg.fraction, split) if isinstance(cfg.fraction, list) else cfg.fraction + dataset = build_yolo_dataset( + cfg, + data[split], + self.args.batch, + data, + mode="val", + fraction=cfg.fraction, + ) + if hasattr(dataset, "transforms") and hasattr(dataset.transforms.transforms[0], "new_shape"): + dataset.transforms.transforms[0].new_shape = self.imgsz # LetterBox with non-square imgsz + n = len(dataset) + if n < 1: + raise ValueError(f"The calibration dataset must have at least 1 image, but found {n} images.") + batch = min(self.args.batch, n) + if n < self.args.batch: + LOGGER.warning( + f"{prefix} calibration dataset has only {n} images, reducing calibration batch size to {batch}." + ) + if self.args.format == "axelera" and n < 100: + LOGGER.warning(f"{prefix} >100 images required for Axelera calibration, found {n} images.") + elif self.args.format != "axelera" and n < 300: + LOGGER.warning(f"{prefix} >300 images recommended for INT8 calibration, found {n} images.") + return build_dataloader(dataset, batch=batch, workers=0, drop_last=True) # required for batch loading + + @try_export + def export_torchscript(self, prefix=colorstr("TorchScript:")): # noqa: B008 + """Export YOLO model to TorchScript format.""" + from ultralytics.utils.export.torchscript import torch2torchscript + + return torch2torchscript( + model=NMSModel(self.model, self.args) if self.args.nms else self.model, + im=self.im, + output_file=self.file.with_suffix(".torchscript"), + metadata=self.metadata, + prefix=prefix, + ) + + @try_export + def export_onnx(self, prefix=colorstr("ONNX:")): # noqa: B008 + """Export YOLO model to ONNX format.""" + requirements = ["onnx>=1.16.1,<1.19.0" if self.args.format == "rknn" else "onnx>=1.12.0,<2.0.0"] + if self.args.simplify or (self.args.format == "onnx" and self.args.quantize == 8 and not self.qat): + # Pass onnxruntime variants as interchangeable candidates so AutoUpdate keeps an installed build + # (e.g. onnxruntime-qnn for QNN export) instead of reinstalling stable onnxruntime and breaking its ABI. + ort = "onnxruntime-gpu" if "cuda" in self.device.type else "onnxruntime" + requirements += [(ort, "onnxruntime", "onnxruntime-gpu", "onnxruntime-qnn")] + if self.args.simplify: + requirements += ["onnxslim>=0.1.82"] + check_requirements(requirements) + import onnx + + from ultralytics.utils.export.engine import best_onnx_opset, torch2onnx + + opset = self.args.opset or best_onnx_opset(onnx) + assert not isinstance(self.model.model[-1], RTDETRDecoder) or opset >= 16, "RTDETR export requires opset>=16" + LOGGER.info(f"\n{prefix} starting export with onnx {onnx.__version__} opset {opset}...") + if self.args.nms: + assert TORCH_1_13, f"'nms=True' ONNX export requires torch>=1.13 (found torch=={TORCH_VERSION})" + + f = str(self.file.with_suffix(".onnx")) + output_names = ["output0", "output1"] if self.model.task == "segment" else ["output0"] + dynamic = self.args.dynamic + if dynamic: + dynamic = {"images": {0: "batch", 2: "height", 3: "width"}} # shape(1,3,640,640) + if isinstance(self.model, SegmentationModel): + dynamic["output0"] = {0: "batch", 2: "anchors"} # shape(1, 116, 8400) + dynamic["output1"] = {0: "batch", 2: "mask_height", 3: "mask_width"} # shape(1,32,160,160) + elif isinstance(self.model, DepthModel): + dynamic["output0"] = {0: "batch", 2: "height", 3: "width"} # shape(1,1,640,640) dense map, not anchors + elif isinstance(self.model, DetectionModel): + dynamic["output0"] = {0: "batch", 2: "anchors"} # shape(1, 84, 8400) + if self.args.nms: + dynamic["output0"].pop(2) + if self.args.nms and self.model.task == "obb": + self.args.opset = opset # for NMSModel + self.args.simplify = True # fix OBB runtime error related to topk + + model = NMSModel(self.model, self.args) if self.args.nms else self.model + # Normalize coordinates by input size so RKNN's per-tensor INT8 scale preserves class scores. + if ( + self.args.format == "rknn" + and self.args.quantize == 8 + and self.model.task in {"detect", "segment", "pose", "obb"} + and not self.metadata["end2end"] + ): + from ultralytics.utils.export.engine import _NormalizeCoords + + model = _NormalizeCoords( + model, + int(self.im.shape[2]), + int(self.im.shape[3]), + self.model.task, + len(self.metadata["names"]), + self.metadata.get("kpt_shape"), + ) + + with arange_patch(dynamic=bool(dynamic), quantize=self.args.quantize, fmt=self.args.format): + torch2onnx( + model.cpu() if self.qat else model, + self.im.cpu() if self.qat else self.im, + f, + opset=opset, + input_names=["images"], + output_names=output_names, + dynamic=dynamic or None, + ) + + # Checks + model_onnx = onnx.load(f) # load onnx model + + # Simplify + if self.args.simplify: + try: + import onnxslim + + LOGGER.info(f"{prefix} slimming with onnxslim {onnxslim.__version__}...") + model_onnx = onnxslim.slim(model_onnx) + + except Exception as e: + LOGGER.warning(f"{prefix} simplifier failure: {e}") + + # CANN requires the optional score-threshold input on ONNX NonMaxSuppression nodes. Scores were already + # filtered by args.conf in NMSModel, so zero preserves the graph's semantics. + if self.args.format == "ascend": + for i, node in enumerate(model_onnx.graph.node): + if node.op_type == "NonMaxSuppression" and len(node.input) == 4: + threshold_name = f"ascend_nms_score_threshold_{i}" + node.input.append(threshold_name) + model_onnx.graph.initializer.append( + onnx.helper.make_tensor(threshold_name, onnx.TensorProto.FLOAT, [1], [0.0]) + ) + + # Metadata + for k, v in self.metadata.items(): + meta = model_onnx.metadata_props.add() + meta.key, meta.value = k, str(v) + + # IR version + if getattr(model_onnx, "ir_version", 0) > 10: + LOGGER.info(f"{prefix} limiting IR version {model_onnx.ir_version} to 10 for ONNXRuntime compatibility...") + model_onnx.ir_version = 10 + + # FP16 conversion for CPU export (GPU exports are already FP16 from model.half() during tracing) + if self.args.quantize == 16 and self.args.format == "onnx" and self.device.type == "cpu": + try: + from onnxruntime.transformers import float16 + + LOGGER.info(f"{prefix} converting to FP16...") + model_onnx = float16.convert_float_to_float16(model_onnx, keep_io_types=True) + except Exception as e: + LOGGER.warning(f"{prefix} FP16 conversion failure: {e}") + + onnx.save(model_onnx, f) + del model_onnx + if self.args.quantize == 8 and self.args.format == "onnx" and not self.qat: # QAT exports Q/DQ directly + from ultralytics.utils.export.onnx import onnx_int8_quantize + + source = Path(f) + f_int8 = str(source.with_name(f"{source.stem}_int8{source.suffix}")) + f = onnx_int8_quantize( + source, + f_int8, + self.get_int8_calibration_dataloader(prefix), + self._transform_fn, + batch=0 if self.args.dynamic else self.args.batch, + prefix=prefix, + ) + source.unlink(missing_ok=True) + return f + + @try_export + def export_openvino(self, prefix=colorstr("OpenVINO:")): # noqa: B008 + """Export YOLO model to OpenVINO format.""" + from ultralytics.utils.export.openvino import torch2openvino + + # OpenVINO <= 2025.1.0 error on macOS 15.4+: https://github.com/openvinotoolkit/openvino/issues/30023 + check_requirements("openvino>=2025.2.0" if MACOS and MACOS_VERSION >= "15.4" else "openvino>=2024.0.0") + import openvino as ov + + assert TORCH_2_1, f"OpenVINO export requires torch>=2.1 but torch=={TORCH_VERSION} is installed" + + def serialize(ov_model, file): + """Set RT info, serialize, and save metadata YAML.""" + ov_model.set_rt_info("YOLO", ["model_info", "model_type"]) + ov_model.set_rt_info(True, ["model_info", "reverse_input_channels"]) + ov_model.set_rt_info(114, ["model_info", "pad_value"]) + ov_model.set_rt_info([255.0], ["model_info", "scale_values"]) + ov_model.set_rt_info(self.args.iou, ["model_info", "iou_threshold"]) + ov_model.set_rt_info([v.replace(" ", "_") for v in self.model.names.values()], ["model_info", "labels"]) + if self.model.task != "classify": + ov_model.set_rt_info("fit_to_window_letterbox", ["model_info", "resize_type"]) + + ov.save_model(ov_model, file, compress_to_fp16=self.args.quantize == 16) + YAML.save(Path(file).parent / "metadata.yaml", self.metadata) # add metadata.yaml + + calibration_dataset = None + if self.args.quantize == 8: + check_requirements("packaging>=23.2") # must be installed first to build nncf wheel + check_requirements("nncf>=2.14.0,<3.0.0" if not TORCH_2_3 else "nncf>=2.14.0") + import nncf + + calibration_dataset = nncf.Dataset(self.get_int8_calibration_dataloader(prefix), self._transform_fn) + + ov_model = torch2openvino( + model=NMSModel(self.model, self.args) if self.args.nms else self.model, + im=self.im, + dynamic=self.args.dynamic, + quantize=self.args.quantize, + calibration_dataset=calibration_dataset, + int8_detect=isinstance(self.model.model[-1], (Detect, RTDETRDecoder)), + prefix=prefix, + ) + + suffix = f"_{'int8_' if self.args.quantize == 8 else ''}openvino_model{os.sep}" + f = str(self.file).replace(self.file.suffix, suffix) + f_ov = str(Path(f) / self.file.with_suffix(".xml").name) + + serialize(ov_model, f_ov) + return f + + @try_export + def export_paddle(self, prefix=colorstr("PaddlePaddle:")): # noqa: B008 + """Export YOLO model to PaddlePaddle format.""" + from ultralytics.utils.export.paddle import torch2paddle + + return torch2paddle( + model=self.model, + im=self.im, + output_dir=str(self.file).replace(self.file.suffix, f"_paddle_model{os.sep}"), + metadata=self.metadata, + prefix=prefix, + ) + + @try_export + def export_litert(self, prefix=colorstr("LiteRT:")): # noqa: B008 + """Export YOLO model to LiteRT format using litert_torch with optional INT8 quantization. + + Supports ``quantize=8`` (static INT8, int8 weights + int8 activations, requires calibration ``data``), + ``quantize='w8a16'`` (static, int8 weights + int16 activations, requires calibration ``data``) and + ``quantize='w8a32'`` (dynamic/weight-only INT8, int8 weights + FP32 activations, no calibration needed). + """ + assert MACOS or (LINUX and not ARM64), "LiteRT export only supported on Linux x86 and macOS" + from ultralytics.utils.export.litert import torch2litert + + return torch2litert( + self.model, + self.im, + self.file, + quantize=self.args.quantize, + calibration_dataset=self.get_int8_calibration_dataloader(prefix) + if self.args.quantize in {8, "w8a16"} + else None, + metadata=self.metadata, + prefix=prefix, + ) + + @try_export + def export_mnn(self, prefix=colorstr("MNN:")): # noqa: B008 + """Export YOLO model to MNN format using MNN https://github.com/alibaba/MNN.""" + from ultralytics.utils.export.mnn import onnx2mnn + + return onnx2mnn( + onnx_file=self.export_onnx(), + output_file=self.file.with_suffix(".mnn"), + quantize=self.args.quantize, + metadata=self.metadata, + prefix=prefix, + ) + + @try_export + def export_ncnn(self, prefix=colorstr("NCNN:")): # noqa: B008 + """Export YOLO model to NCNN format using PNNX https://github.com/pnnx/pnnx.""" + from ultralytics.utils.export.ncnn import torch2ncnn + + return torch2ncnn( + model=self.model, + im=self.im, + output_dir=str(self.file).replace(self.file.suffix, "_ncnn_model/"), + quantize=self.args.quantize, + metadata=self.metadata, + device=self.device, + prefix=prefix, + ) + + @try_export + def export_coreml(self, prefix=colorstr("CoreML:")): # noqa: B008 + """Export YOLO model to CoreML format.""" + mlmodel = self.args.format.lower() == "mlmodel" # legacy *.mlmodel export format requested + from ultralytics.utils.export.coreml import IOSDetectModel, pipeline_coreml, torch2coreml + + # numpy 2.4.x breaks coremltools CoreML export https://github.com/apple/coremltools/issues/2633 + check_requirements(["coremltools>=9.0", "numpy>=1.14.5,<=2.3.5"]) + import coremltools as ct + + assert not WINDOWS, "CoreML export is not supported on Windows, please run on macOS or Linux." + assert TORCH_1_11, "CoreML export requires torch>=1.11" + f = self.file.with_suffix(".mlmodel" if mlmodel else ".mlpackage") + if f.is_dir(): + shutil.rmtree(f) + + if self.args.nms and self.model.task == "detect": + model = IOSDetectModel(self.model, self.im, mlprogram=not mlmodel) + elif self.args.nms: # segment, pose: NMS baked into the trace instead of Apple's NMS pipeline, + model = NMSModel(self.model, self.args) # which can't carry masks/keypoints through suppression + else: + model = self.model + + if self.args.dynamic: + h, w = self.imgsz + lb_h = lb_w = 32 + if getattr(self.model, "end2end", False): + # end2end graphs bake TopK k=max_det, so the smallest declared input must still supply >= k anchors + # or CoreML rejects the model at load; shrink the range proportionally from the traced default size + stride = int(self.model.stride.max()) + r = self.model.model[-1].max_det / sum(int(h / s) * int(w / s) for s in self.model.stride.tolist()) + lb_h = max(lb_h, int(np.ceil(h * r**0.5 / stride)) * stride) + lb_w = max(lb_w, int(np.ceil(w * r**0.5 / stride)) * stride) + input_shape = ct.Shape( + shape=( + ct.RangeDim(lower_bound=1, upper_bound=self.args.batch, default=1), + self.im.shape[1], + ct.RangeDim(lower_bound=lb_h, upper_bound=h * 2, default=h), + ct.RangeDim(lower_bound=lb_w, upper_bound=w * 2, default=w), + ) + ) + inputs = [ct.TensorType("image", shape=input_shape)] + else: + inputs = [ct.ImageType("image", shape=self.im.shape, scale=1 / 255, bias=[0.0, 0.0, 0.0])] + + quantize = 16 if self.args.nms and not mlmodel and self.args.quantize is None else self.args.quantize + self.metadata["args"]["quantize"] = quantize + ct_model = torch2coreml( + model=model, + inputs=inputs, + im=self.im, + classifier_names=list(self.model.names.values()) if self.model.task == "classify" else None, + mlmodel=mlmodel, + quantize=quantize, + metadata=self.metadata, + prefix=prefix, + ) + + if self.args.nms and self.model.task == "detect": + ct_model = pipeline_coreml( + ct_model, + self.output_shape, + weights_dir=None if mlmodel else ct_model.weights_dir, + metadata=self.metadata, + mlmodel=mlmodel, + iou=self.args.iou, + conf=self.args.conf, + agnostic_nms=self.args.agnostic_nms, + prefix=prefix, + ) + + if self.model.task == "classify": + ct_model.user_defined_metadata.update({"com.apple.coreml.model.preview.type": "imageClassifier"}) + + try: + ct_model.save(str(f)) # save *.mlpackage + except Exception as e: + LOGGER.warning( + f"{prefix} CoreML export to *.mlpackage failed ({e}), reverting to *.mlmodel export. " + f"Known coremltools Python 3.11 and Windows bugs https://github.com/apple/coremltools/issues/1928." + ) + f = f.with_suffix(".mlmodel") + ct_model.save(str(f)) + return f + + @try_export + def export_engine(self, prefix=colorstr("TensorRT:")): # noqa: B008 + """Export YOLO model to TensorRT format https://developer.nvidia.com/tensorrt.""" + assert self.im.device.type != "cpu", "export running on CPU but must be on GPU, i.e. use 'device=0'" + f_onnx = self.export_onnx() # run before TRT import https://github.com/ultralytics/ultralytics/issues/7016 + from ultralytics.utils.export.engine import onnx2engine + + assert Path(f_onnx).exists(), f"failed to export ONNX file: {f_onnx}" + f = self.file.with_suffix(".engine") # TensorRT engine file + onnx2engine( + f_onnx, + f, + self.args.workspace, + self.args.quantize, + self.args.dynamic, + self.im.shape, + dla=self.dla, + dataset=self.get_int8_calibration_dataloader(prefix) if self.args.quantize == 8 and not self.qat else None, + metadata=self.metadata, + verbose=self.args.verbose, + prefix=prefix, + ) + + return f + + @try_export + def export_saved_model(self, prefix=colorstr("TensorFlow SavedModel:")): # noqa: B008 + """Export YOLO model to TensorFlow SavedModel format.""" + assert not (MACOS and IS_PYTHON_MINIMUM_3_13), ( + "TensorFlow exports not supported on macOS with Python>=3.13: the ai-edge-litert macOS wheel fails to load " + "(missing libpywrap_litert_common.dylib). TensorFlow export works on Linux Python 3.13." + ) + from ultralytics.utils.export.tensorflow import onnx2saved_model + + f = Path(str(self.file).replace(self.file.suffix, "_saved_model")) + if f.is_dir(): + shutil.rmtree(f) # delete output folder + + # Export to ONNX + if isinstance(self.model.model[-1], RTDETRDecoder): + self.args.opset = self.args.opset or 19 + assert self.args.opset <= 19, "RTDETR TensorFlow export requires opset<=19" + self.args.simplify = True + f_onnx = self.export_onnx() # ensure ONNX is available + keras_model = onnx2saved_model( + f_onnx, + f, + quantize=self.args.quantize, + images=( + torch.nn.functional.interpolate( + torch.cat([batch["img"] for batch in self.get_int8_calibration_dataloader(prefix)], 0).float(), + size=self.imgsz, + ) + .permute(0, 2, 3, 1) + .numpy() + if self.args.quantize == 8 and self.args.data + else None + ), + disable_group_convolution=self.args.format == "edgetpu", + cuda=self.device.type == "cuda", + prefix=prefix, + ) + YAML.save(f / "metadata.yaml", self.metadata) # add metadata.yaml + # Add TFLite metadata + for file in f.rglob("*.tflite"): + file.unlink() if "quant_with_int16_act.tflite" in str(file) else self._add_tflite_metadata(file) + + return str(f), keras_model # or keras_model = tf.saved_model.load(f, tags=None, options=None) + + @try_export + def export_pb(self, keras_model, prefix=colorstr("TensorFlow GraphDef:")): # noqa: B008 + """Export YOLO model to TensorFlow GraphDef *.pb format https://github.com/leimao/Frozen-Graph-TensorFlow.""" + from ultralytics.utils.export.tensorflow import keras2pb + + return keras2pb(keras_model, output_file=self.file.with_suffix(".pb"), prefix=prefix) + + @try_export + def export_axelera(self, prefix=colorstr("Axelera:")): # noqa: B008 + """Export YOLO model to Axelera format.""" + assert LINUX and not (ARM64 and IS_DOCKER), ( + "export is only supported on Linux and is not supported on ARM64 Docker." + ) + assert TORCH_2_8, "export requires torch>=2.8.0." + + from ultralytics.utils.export.axelera import torch2axelera + + output_dir = self.file.parent / f"{self.file.stem}_axelera_model" + return torch2axelera( + model=self.model, + output_dir=output_dir, + calibration_dataset=self.get_int8_calibration_dataloader(prefix), + transform_fn=self._transform_fn, + model_name=self.file.stem, + metadata=self.metadata, + prefix=prefix, + ) + + @try_export + def export_executorch(self, prefix=colorstr("ExecuTorch:")): # noqa: B008 + """Export YOLO model to ExecuTorch *.pte format.""" + assert TORCH_2_9, f"ExecuTorch requires torch>=2.9.0 but torch=={TORCH_VERSION} is installed" + from ultralytics.utils.export.executorch import torch2executorch + + return torch2executorch( + model=self.model, + im=self.im, + output_dir=str(self.file).replace(self.file.suffix, "_executorch_model/"), + metadata=self.metadata, + prefix=prefix, + ) + + @try_export + def export_coreai(self, prefix=colorstr("Core AI:")): # noqa: B008 + """Export YOLO model to Apple Core AI *.aimodel format.""" + assert MACOS and ARM64 and MACOS_VERSION >= "26.0", ( + "Core AI export requires macOS>=26 on Apple silicon; coreai-core publishes macosx_26_0_arm64 wheels only." + ) + assert TORCH_2_8, f"Core AI export requires torch>=2.8.0 but torch=={TORCH_VERSION} is installed" + from ultralytics.utils.export.coreai import torch2coreai + + return torch2coreai( + model=self.model, + im=self.im, + output_file=self.file.with_suffix(".aimodel"), + quantize=self.args.quantize, + metadata=self.metadata, + prefix=prefix, + ) + + @try_export + def export_edgetpu(self, tflite_model="", prefix=colorstr("Edge TPU:")): # noqa: B008 + """Export YOLO model to Edge TPU format https://coral.ai/docs/edgetpu/models-intro/.""" + from ultralytics.utils.export.tensorflow import tflite2edgetpu + + output_file = tflite2edgetpu(tflite_file=tflite_model, output_dir=tflite_model.parent, prefix=prefix) + self._add_tflite_metadata(output_file) + return output_file + + @try_export + def export_rknn(self, prefix=colorstr("RKNN:")): # noqa: B008 + """Export YOLO model to RKNN format with optional INT8 quantization.""" + from ultralytics.utils.export.rknn import onnx2rknn + + if self.args.opset and self.args.opset > 19: + LOGGER.warning(f"{prefix} rknn-toolkit2 requires opset<=19, setting opset=19.") + self.args.opset = min(self.args.opset or 19, 19) # rknn-toolkit expects opset<=19 + self.im = self.im[:1] # RKNN Toolkit expands the batch after calibrating the batch-1 ONNX model + f_onnx = self.export_onnx() + output_dir = Path(str(self.file).replace(self.file.suffix, f"_rknn_model{os.sep}")) + rknn_dataset = None + if self.args.quantize == 8: + dataloader = self.get_int8_calibration_dataloader(prefix) + image_paths = getattr(dataloader.dataset, "im_files", None) + if image_paths is None and hasattr(dataloader.dataset, "samples"): + image_paths = [x[0] for x in dataloader.dataset.samples] + if not image_paths: + raise ValueError("RKNN INT8 export requires a calibration dataset with image file paths.") + output_dir.mkdir(parents=True, exist_ok=True) + rknn_dataset = output_dir / "dataset.txt" + rknn_dataset.write_text("\n".join(str(Path(x).resolve()) for x in image_paths) + "\n") + try: + return onnx2rknn( + onnx_file=f_onnx, + output_dir=output_dir, + name=self.args.name, + quantize=self.args.quantize, + batch=self.args.batch, + dataset=rknn_dataset, + metadata=self.metadata, + prefix=prefix, + ) + finally: + if self.args.quantize == 8: # INT8 graphs hold normalized coordinates, so they are not reusable + Path(f_onnx).unlink(missing_ok=True) + + @try_export + def export_ascend(self, prefix=colorstr("Ascend:")): # noqa: B008 + """Export YOLO model to Huawei Ascend offline model (.om) format.""" + from ultralytics.utils.export.ascend import _check_atc, onnx2ascend + + _check_atc() # before the ONNX trace, so a missing toolchain does not cost a full export first + if self.args.opset and self.args.opset > 17: + LOGGER.warning(f"{prefix} the CANN ONNX parser requires opset<=17, setting opset=17.") + self.args.opset = min(self.args.opset or 17, 17) + return onnx2ascend( + onnx_file=self.export_onnx(), + output_dir=self.file.parent / f"{self.file.stem}_ascend_model", + name=self.args.name, + imgsz=self.imgsz, + batch=self.args.batch, + channels=self.im.shape[1], + metadata=self.metadata, + prefix=prefix, + ) + + @try_export + def export_imx(self, prefix=colorstr("IMX:")): # noqa: B008 + """Export YOLO model to IMX format.""" + assert LINUX, ( + "Export only supported on Linux." + "See https://developer.aitrios.sony-semicon.com/en/docs/raspberry-pi-ai-camera/imx500-converter?version=3.17.3&progLang=" + ) + assert IS_PYTHON_MINIMUM_3_9, "IMX export is only supported on Python 3.9 or above." + + from ultralytics.utils.export.imx import torch2imx + + return torch2imx( + model=self.model, + output_dir=str(self.file).replace(self.file.suffix, "_imx_model/"), + conf=self.args.conf, + iou=self.args.iou, + max_det=self.args.max_det, + metadata=self.metadata, + dataset=partial(self.get_int8_calibration_dataloader, prefix), + prefix=prefix, + ) + + @try_export + def export_deepx(self, prefix=colorstr("DEEPX:")): # noqa: B008 + """Export YOLO model to DEEPX format.""" + assert LINUX and not ARM64, "DEEPX export only supported on non-aarch64 Linux" + from ultralytics.utils.export.deepx import onnx2deepx + + f = self.export_onnx() + return onnx2deepx( + onnx_file=f, + imgsz=self.imgsz, + dataset=self.get_int8_calibration_dataloader(prefix), + metadata=self.metadata, + optimize=self.args.optimize, + prefix=prefix, + ) + + @try_export + def export_qnn(self, prefix=colorstr("Qualcomm QNN:")): # noqa: B008 + """Export YOLO model to a Qualcomm QNN context binary using ONNX Runtime QNN.""" + from ultralytics.utils.export.qnn import onnx2qnn + + # Wrap for Hexagon-friendly I/O: channel-last input (the class-map wrap for semantic is format-agnostic) + model, im = self.model, self.im + try: + self.model, self.im = QNNModel(model), im.permute(0, 2, 3, 1) + f_onnx = self.export_onnx() + finally: + self.model, self.im = model, im + return onnx2qnn( + onnx_file=f_onnx, + output_file=str(self.file.with_name(f"{self.file.stem}_qnn.onnx")), + dataset=self.get_int8_calibration_dataloader(prefix), + transform_fn=self._transform_fn, + name=self.args.name, + metadata=self.metadata, + batch=0 if self.args.dynamic else self.args.batch, + prefix=prefix, + ) + + @try_export + def export_hailo(self, prefix=colorstr("Hailo:")): # noqa: B008 + """Export a YOLO model to Hailo Executable Format (HEF).""" + try: + import tensorflow as tf + from hailo_sdk_client import ClientRunner + except ImportError as e: + raise ImportError("Hailo export requires the Hailo Dataflow Compiler.") from e + + calibration_dataloader = self.get_int8_calibration_dataloader(prefix) + calibration_size = len(calibration_dataloader.dataset) + LOGGER.warning( + f"\nHailo level-2 optimization will use {calibration_size} calibration images. " + "Hailo recommends at least 1,024 representative images for best accuracy. " + 'Pass data="path/to/dataset.yaml". ' + "See https://docs.ultralytics.com/integrations/hailo#export-a-hailo-hef-model" + ) + head_index = len(self.model.model) - 1 + head = self.model.model[head_index] + one2one = getattr(self.model, "end2end", False) + task = self.model.task + raw_detect = task == "detect" and head.reg_max == 1 + if task == "classify": + # The Classify head ends in Gemm -> Softmax; cut at the Softmax so the HEF returns the same + # (1, nc) probabilities as the PyTorch model. The DFC translates the softmax to a native layer. + end_nodes = [f"/model.{head_index}/Softmax"] + elif task == "semantic": + # Multi-class Hailo-15/10 (DFC 5.x) heads compile the bilinear upsample and ArgMax on chip. Hailo-8/8L + # (DFC 3.x) cannot compile the Resize, and single-class heads use a threshold instead of ArgMax, so both + # cut at the classifier logits and run the reduction on the host. + head.bake_argmax = head.nc > 1 and self.args.name in {"hailo10h", "hailo15h", "hailo15l"} + end_nodes = [ + f"/model.{head_index}/ArgMax" + if head.bake_argmax + else f"/model.{head_index}/classifier/classifier.1/Conv" + ] + elif task == "depth": + # The Depth head ends in clamp/exp, log-affine calibration, and a 4x upsample. Cut at the final logit + # conv (head.3, the last layer of the dense decoder) so the a16 HEF carries the raw logit and the host + # mirrors Depth.forward. Same string convention as detect's `.2/Conv`; no new head attribute. + end_nodes = [f"/model.{head_index}/head/head.3/Conv"] + else: + scales = range(len(head.one2one_cv2 if one2one else head.cv2)) + if raw_detect: + branch_prefix = "one2one_" if one2one else "" + end_nodes = [ + f"/model.{head_index}/{branch_prefix}cv{branch}.{i}/{branch_prefix}cv{branch}.{i}.2/Conv" + for branch in (2, 3) + for i in scales + ] + elif task in {"segment", "pose", "obb"}: + # reg/cls/extra triple per scale (extra = mask coeffs, keypoints, or angle); segment adds prototypes. + end_nodes = [ + f"/model.{head_index}/cv{branch}.{i}/cv{branch}.{i}.2/Conv" for i in scales for branch in (2, 3, 4) + ] + if task == "segment": + end_nodes.append(f"/model.{head_index}/proto/cv3/act/Mul") + else: + end_nodes = [ + f"/model.{head_index}/cv{branch}.{i}/cv{branch}.{i}.2/Conv" for i in scales for branch in (2, 3) + ] + self.args.opset = 11 + f_onnx = Path(self.export_onnx()) + output_dir = self.file.parent / f"{self.file.stem}_hailo_model" + if output_dir.exists(): + shutil.rmtree(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + try: + runner = ClientRunner(hw_arch=self.args.name) + runner.translate_onnx_model(str(f_onnx), self.file.stem, end_node_names=end_nodes) + model_script = [ + "normalization1 = normalization([0, 0, 0], [255, 255, 255])", + "model_optimization_flavor(optimization_level=2)", + f"post_quantization_optimization(finetune, policy=enabled, dataset_size={calibration_size})", + ] + if raw_detect or task == "depth": + # a16 on the output(s): the DFL-free detect logits and the single dense depth logit both need the + # wider activation to keep their range (a8 collapses the depth map; validated on Hailo-8L). + outputs = ", ".join(f"output_layer{i + 1}" for i in range(len(end_nodes))) + model_script.append(f"quantization_param([{outputs}], precision_mode=a16_w16)") + elif task in {"classify", "semantic"}: + pass # softmax/class-map is already the graph output; no NMS or activation changes needed + else: + outputs = [layer.inputs[0].rsplit("/", 1)[-1] for layer in runner.get_hn_model().get_output_layers()] + if task in {"segment", "pose", "obb"}: + # Bake sigmoid into the class convs only (position 1 of each per-scale reg/cls/extra triple). + # Mask coeffs, prototypes, keypoints and angles stay raw and are decoded on the host. + model_script.extend( + f"change_output_activation({outputs[i]}, sigmoid)" for i in range(1, 3 * len(scales), 3) + ) + else: + nms_config = output_dir / "nms_config.json" + nms_config.write_text( + json.dumps( + { + "nms_scores_th": self.args.conf if self.args.conf is not None else 0.25, + "nms_iou_th": self.args.iou, + "image_dims": self.imgsz, + "max_proposals_per_class": 100, + "classes": len(self.model.names), + "regression_length": 16, + "background_removal": False, + "background_removal_index": 0, + "bbox_decoders": [ + { + "name": f"bbox_decoder_{stride}", + "stride": stride, + "reg_layer": outputs[i * 2], + "cls_layer": outputs[i * 2 + 1], + } + for i, stride in enumerate(int(x) for x in head.stride) + ], + }, + indent=2, + ) + ) + model_script.extend( + f"change_output_activation({outputs[i]}, sigmoid)" for i in range(1, len(outputs), 2) + ) + model_script.append(f'nms_postprocess("{nms_config}", meta_arch=yolov8, engine=cpu)') + model_script.append("allocator_param(width_splitter_defuse=disabled)") + runner.load_model_script("\n".join(model_script)) + + def calibration_dataset(): + for batch in calibration_dataloader: + for image in batch["img"].permute(0, 2, 3, 1).numpy().astype(np.float32): + yield image, {} + + runner.optimize( + lambda: tf.data.Dataset.from_generator( + calibration_dataset, + output_signature=(tf.TensorSpec(shape=(*self.imgsz, 3), dtype=tf.float32), {}), + ) + ) + (output_dir / f"{self.file.stem}.hef").write_bytes(runner.compile()) + YAML.save( + output_dir / "metadata.yaml", + { + **self.metadata, + "hailo_arch": self.args.name, + "nms": task == "detect" and not raw_detect, + "semantic_baked": task == "semantic" and head.bake_argmax, + # Depth's learned log-affine calibration is applied on the host, so it must ride in metadata. + **({"cal_a": float(head.cal_a), "cal_b": float(head.cal_b)} if task == "depth" else {}), + }, + ) + return str(output_dir) + finally: + f_onnx.unlink(missing_ok=True) + + def _add_tflite_metadata(self, file): + """Add metadata to *.tflite models per https://ai.google.dev/edge/litert/models/metadata.""" + import zipfile + + with zipfile.ZipFile(file, "a", zipfile.ZIP_DEFLATED) as zf: + zf.writestr("metadata.json", json.dumps(self.metadata, indent=2)) + + @staticmethod + def _transform_fn(data_item) -> np.ndarray: + """Quantization preprocessing transform for INT8 calibration (Axelera, OpenVINO, ONNX, QNN).""" + data_item: torch.Tensor = data_item["img"] if isinstance(data_item, dict) else data_item + assert data_item.dtype == torch.uint8, "Input image must be uint8 for the quantization preprocessing" + im = data_item.numpy().astype(np.float32) / 255.0 # uint8 to fp16/32 and 0 - 255 to 0.0 - 1.0 + return im[None] if im.ndim == 3 else im + + def add_callback(self, event: str, callback): + """Append the given callback to the specified event.""" + self.callbacks[event].append(callback) + + def run_callbacks(self, event: str): + """Execute all callbacks for a given event.""" + for callback in self.callbacks.get(event, []): + callback(self) + + +class ExportWrapper(torch.nn.Module): + """Base for export-time model wrappers: stores the wrapped model and forwards attribute lookups. + + Subclasses adapt a fused YOLO model's inference I/O for a specific deployment contract (layout, output + reduction) while the exporter keeps interacting with the wrapper as if it were the model itself. + """ + + def __init__(self, model): + """Wrap a fused YOLO `model` prepared for export.""" + super().__init__() + # Stored under a private name so attribute forwarding resolves `wrapper.model` to the wrapped model's own + # `model` (its nn.Sequential), keeping exporter code like `self.model.model[-1]` working unchanged. + self._model = model + self.task = model.task + + def __getattr__(self, name): + """Forward attribute lookups (model, names, stride, yaml, args, ...) to the wrapped model.""" + try: + return super().__getattr__(name) + except AttributeError: + return getattr(self._model, name) + + +class QNNModel(ExportWrapper): + """Wraps a YOLO model with channel-last inference input for Qualcomm QNN export. + + Traced by the standard ONNX export (`export_qnn` swaps it in with a channel-last dummy input). The graph takes `[N, + H, W, C]` images - the Hexagon HTP's native layout and what camera pipelines produce - so ONNX Runtime's layout + transformer folds the wrapper's Transpose into the NPU partition during context generation, and neither the NPU + (boundary transpose) nor the consuming app (CPU-side permute) pays a per-inference layout cost. + + Attributes: + task (str): The wrapped model's task, forwarded for the ONNX export plumbing. + """ + + def forward(self, x): + """Run inference on channel-last `[N, H, W, C]` input normalized to [0, 1].""" + return self._model(x.permute(0, 3, 1, 2)) # the wrapped model is NCHW; the transpose folds into the NPU graph + + +class ClassMapModel(ExportWrapper): + """Reduces semantic-segmentation logits to a compact integer class map for export. + + Applied to QNN, Core ML and Ascend semantic exports, where the argmax runs on the NPU: deployment consumers want + per-pixel class indices, and shipping float logits instead forces a dequantize + argmax over large tensors (~8M + values at the standard 640px mobile input) on the consumer's CPU every frame - measured as both slow and highly + variable on mobile NPUs. The argmax cannot live in the model's own forward because it is non-differentiable + (training needs logits), so it is attached here at export time, mirroring how `NMSModel` adds suppression only for + export. + + Attributes: + task (str): The wrapped model's task ("semantic"). + dtype (torch.dtype): Class-index dtype; uint8 unless the model has more than 256 classes. + """ + + def __init__(self, model): + """Wrap a fused semantic `model` so export emits class indices instead of logits.""" + super().__init__(model) + # uint8 quarters the NPU->CPU output transfer vs int32 and Core ML promotes it to int32 in-spec; + # int32 only when more than 256 classes make uint8 indices ambiguous. + self.dtype = torch.uint8 if len(model.names) <= 256 else torch.int32 + + def forward(self, x): + """Run the wrapped model and return a `[N, H, W]` integer class map instead of float logits.""" + y = self._model(x) + y = y[0] if isinstance(y, (list, tuple)) else y + # Single-channel (binary) models threshold the logit, matching predict/val semantics for nc == 1 + return (y.argmax(1) if y.shape[1] > 1 else y[:, 0].gt(0)).to(self.dtype) + + +class NMSModel(torch.nn.Module): + """Model wrapper with embedded NMS for Detect, Segment, Pose and OBB.""" + + def __init__(self, model, args): + """Initialize the NMSModel. + + Args: + model (torch.nn.Module): The model to wrap with NMS postprocessing. + args (SimpleNamespace): The export arguments. + """ + super().__init__() + self.model = model + self.args = args + self.obb = model.task == "obb" + self.is_tf = self.args.format == "saved_model" + + def forward(self, x): + """Perform inference with NMS post-processing. Supports Detect, Segment, OBB and Pose. + + Args: + x (torch.Tensor): The preprocessed tensor with shape (B, C, H, W). + + Returns: + (torch.Tensor | tuple): Tensor of shape (B, max_det, 4 + 2 + extra_shape) where B is the batch size, or a + tuple of (detections, proto) for segmentation models. + """ + from torchvision.ops import nms + + preds = self.model(x) + pred = preds[0] if isinstance(preds, tuple) else preds + bs = pred.shape[0] + pred = pred.transpose(-1, -2) # shape(1,84,6300) to shape(1,6300,84) + extra_shape = pred.shape[-1] - (4 + len(self.model.names)) # extras from Segment, OBB, Pose + if self.args.dynamic and self.args.batch > 1: # batch size needs to always be same due to loop unroll + pad = pred.new_zeros(torch.max(torch.tensor(self.args.batch - bs), torch.tensor(0)), *pred.shape[1:]) + pred = torch.cat((pred, pad)) + if self.args.dynamic and self.args.format == "onnx" and self.obb: + pred = torch.cat((pred, pred.new_zeros(pred.shape[0], self.args.max_det * 5, pred.shape[2])), dim=1) + boxes, scores, extras = pred.split([4, len(self.model.names), extra_shape], dim=2) + scores, classes = scores.max(dim=-1) + # (N, max_det, 4 coords + 1 class score + 1 class label + extra_shape). + out = pred.new_zeros(pred.shape[0], self.args.max_det, boxes.shape[-1] + 2 + extra_shape) + for i in range(bs): + box, cls, score, extra = boxes[i], classes[i], scores[i], extras[i] + mask = score > self.args.conf + if self.is_tf or (self.args.format == "onnx" and self.obb): + # TFLite GatherND error if mask is empty + score *= mask + # Explicit length otherwise reshape error, hardcoded to `self.args.max_det * 5` + mask = score.topk(min(self.args.max_det * 5, score.shape[0])).indices + box, score, cls, extra = box[mask], score[mask], cls[mask], extra[mask] + nmsbox = box.clone() + # `8` is the minimum value experimented to get correct NMS results for obb + multiplier = 8 if self.obb else 1 / max(len(self.model.names), 1) + # Normalize boxes for NMS since large values for class offset causes issue with int8 quantization + nmsbox = multiplier * (nmsbox / torch._shape_as_tensor(x)[2:].max().to(nmsbox.dtype)) + if not self.args.agnostic_nms: # class-wise NMS + end = 2 if self.obb else 4 + # fully explicit expansion otherwise reshape error + cls_offset = cls.view(cls.shape[0], 1).expand(cls.shape[0], end) + offbox = nmsbox[:, :end] + cls_offset * multiplier + nmsbox = torch.cat((offbox, nmsbox[:, end:]), dim=-1) + nms_fn = ( + partial( + TorchNMS.fast_nms, + use_triu=not ( + self.is_tf + or (self.args.opset or 14) < 14 + or (self.args.format == "openvino" and self.args.quantize == 8) # OpenVINO INT8 error with triu + ), + iou_func=batch_probiou, + exit_early=False, + ) + if self.obb + else nms + ) + keep = nms_fn( + torch.cat([nmsbox, extra], dim=-1) if self.obb else nmsbox, + score, + self.args.iou, + )[: self.args.max_det] + dets = torch.cat( + [box[keep], score[keep].view(-1, 1), cls[keep].view(-1, 1).to(out.dtype), extra[keep]], dim=-1 + ) + # Zero-pad to max_det size to avoid reshape error. Padded on a flattened 1D view (rather than + # dim 0 of the 2D tensor) since CoreML's MIL conversion only supports dynamic padding on rank-1 tensors. + c = dets.shape[-1] + pad = (0, (self.args.max_det - dets.shape[0]) * c) + out[i] = torch.nn.functional.pad(dets.reshape(-1), pad).reshape(self.args.max_det, c) + return (out[:bs], preds[1]) if self.model.task == "segment" else out[:bs] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/model.py b/.venv/lib/python3.12/site-packages/ultralytics/engine/model.py new file mode 100644 index 0000000000000000000000000000000000000000..e1f90d2a4336a5573d946bf9c90e1b0a103cba4f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/engine/model.py @@ -0,0 +1,1257 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import inspect +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import numpy as np +import torch +from PIL import Image + +from ultralytics.cfg import QUANTIZE_ALIASES, TASK2DATA, _handle_deprecation, get_cfg, get_save_dir +from ultralytics.engine.results import Results +from ultralytics.nn.tasks import BaseModel, guess_model_task, load_checkpoint, yaml_model_load +from ultralytics.utils import ( + ARGV, + ASSETS, + DEFAULT_CFG_DICT, + LOGGER, + PLATFORM_URL, + RANK, + SETTINGS, + YAML, + callbacks, + checks, +) +from ultralytics.utils.torch_utils import unwrap_model + + +class Model(torch.nn.Module): + """A base class for implementing YOLO models, unifying APIs across different model types. + + This class provides a common interface for various operations related to YOLO models, such as training, validation, + prediction, exporting, and benchmarking. It handles different types of models, including those loaded from local + files or Triton Server. + + Attributes: + callbacks (dict): A dictionary of callback functions for various events during model operations. + predictor (BasePredictor): The predictor object used for making predictions. + model (torch.nn.Module): The underlying PyTorch model. + trainer (BaseTrainer): The trainer object used for training the model. + ckpt (dict): The checkpoint data of the loaded weights, if any. + cfg (str): The configuration of the model if loaded from a *.yaml file. + ckpt_path (str): The path to the checkpoint file. + overrides (dict): A dictionary of overrides for model configuration. + metrics (ultralytics.utils.metrics.DetMetrics): The latest training/validation metrics. + task (str): The type of task the model is intended for. + model_name (str): The name of the model. + + Methods: + __call__: Alias for the predict method, enabling the model instance to be callable. + _new: Initialize a new model based on a configuration file. + _load: Load a model from a checkpoint file. + _check_is_pytorch_model: Ensure that the model is a PyTorch model. + reset_weights: Reset the model's weights to their initial state. + load: Load model weights from a specified file. + save: Save the current state of the model to a file. + info: Log or return information about the model. + fuse: Fuse Conv2d and BatchNorm2d layers for optimized inference. + predict: Perform predictions on given image sources. + track: Perform object tracking. + val: Validate the model on a dataset. + benchmark: Benchmark the model on various export formats. + export: Export the model to different formats. + train: Train the model on a dataset. + tune: Perform hyperparameter tuning. + _apply: Apply a function to the model's tensors. + add_callback: Add a callback function for an event. + clear_callback: Clear all callbacks for an event. + reset_callbacks: Reset all callbacks to their default functions. + + Examples: + >>> from ultralytics import YOLO + >>> model = YOLO("yolo26n.pt") + >>> results = model.predict("image.jpg") + >>> model.train(data="coco8.yaml", epochs=3) + >>> metrics = model.val() + >>> model.export(format="onnx") + """ + + def __init__( + self, + model: str | Path | Model = "yolo26n.pt", + task: str | None = None, + verbose: bool = False, + ) -> None: + """Initialize a new instance of the YOLO model class. + + This constructor sets up the model based on the provided model path or name. It handles various types of model + sources, including local files and Triton Server models. The method initializes several important attributes of + the model and prepares it for operations like training, prediction, or export. + + Args: + model (str | Path | Model): Path or name of the model to load or create. Can be a local file path, a Triton + Server model, or an already initialized Model instance. + task (str, optional): The specific task for the model. If None, it will be inferred from the config. + verbose (bool): If True, enables verbose output during the model's initialization and subsequent operations. + + Raises: + FileNotFoundError: If the specified model file does not exist or is inaccessible. + ValueError: If the model file or configuration is invalid or unsupported. + """ + if isinstance(model, Model): + self.__dict__ = model.__dict__ # accepts an already initialized Model + return + super().__init__() + self.callbacks = callbacks.get_default_callbacks() + self.predictor = None # reuse predictor + self.model = None # model object + self.trainer = None # trainer object + self.ckpt = {} # if loaded from *.pt + self.cfg = None # if loaded from *.yaml + self.ckpt_path = None + self.overrides = {} # overrides for trainer object + self.metrics = None # validation/training metrics + self.task = task # task type + self.model_name = None # model name + model = str(model).strip() + + # Check if Triton Server model + if self.is_triton_model(model): + self.model_name = self.model = model + self.overrides["task"] = task or "detect" # set `task=detect` if not explicitly set + return + + # Load or create new YOLO model + __import__("os").environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8" # to avoid deterministic warnings + if str(model).endswith((".yaml", ".yml")): + self._new(model, task=task, verbose=verbose) + else: + self._load(model, task=task) + + # Delete super().training for accessing self.model.training + del self.training + + def __call__( + self, + source: str | Path | int | Image.Image | list | tuple | np.ndarray | torch.Tensor = None, + stream: bool = False, + **kwargs: Any, + ) -> Iterator[Results | torch.Tensor] | list[Results] | list[torch.Tensor]: + """Alias for the predict method, enabling the model instance to be callable for predictions. + + This method simplifies the process of making predictions by allowing the model instance to be called directly + with the required arguments. + + Args: + source (str | Path | int | PIL.Image | np.ndarray | torch.Tensor | list | tuple): The source of the image(s) + to make predictions on. Can be a file path, URL, PIL image, numpy array, PyTorch tensor, or a list/tuple + of these. + stream (bool): If True, treat the input source as a continuous stream for predictions. + **kwargs (Any): Additional keyword arguments to configure the prediction process. + + Returns: + (Iterator[ultralytics.engine.results.Results | torch.Tensor] | list[ultralytics.engine.results.Results] | + list[torch.Tensor]): Prediction results or embeddings, streamed when `stream=True`. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> results = model("https://ultralytics.com/images/bus.jpg") + >>> for r in results: + ... print(f"Detected {len(r)} objects in image") + """ + return self.predict(source, stream, **kwargs) + + @staticmethod + def is_triton_model(model: str) -> bool: + """Check if the given model string is a Triton Server URL. + + This static method determines whether the provided model string represents a valid Triton Server URL by parsing + its components using urllib.parse.urlsplit(). + + Args: + model (str): The model string to be checked. + + Returns: + (bool): True if the model string is a valid Triton Server URL, False otherwise. + + Examples: + >>> Model.is_triton_model("http://localhost:8000/v2/models/yolo11n") + True + >>> Model.is_triton_model("yolo26n.pt") + False + """ + from urllib.parse import urlsplit + + url = urlsplit(model) + return url.netloc and url.path and url.scheme in {"http", "grpc"} + + def _new(self, cfg: str, task=None, model=None, verbose=False) -> None: + """Initialize a new model and infer the task type from model definitions. + + Creates a new model instance based on the provided configuration file. Loads the model configuration, infers the + task type if not specified, and initializes the model using the appropriate class from the task map. + + Args: + cfg (str): Path to the model configuration file in YAML format. + task (str, optional): The specific task for the model. If None, it will be inferred from the config. + model (type[torch.nn.Module], optional): A custom model class. If provided, it will be used instead of the + default model class from the task map. + verbose (bool): If True, displays model information during loading. + + Raises: + ValueError: If the configuration file is invalid or the task cannot be inferred. + ImportError: If the required dependencies for the specified task are not installed. + + Examples: + >>> model = Model() + >>> model._new("yolo26n.yaml", task="detect", verbose=True) + """ + cfg_dict = yaml_model_load(cfg) + self.cfg = cfg + self.task = task or guess_model_task(cfg_dict) + self.model = (model or self._smart_load("model"))(cfg_dict, verbose=verbose and RANK == -1) # build model + self.overrides["model"] = self.cfg + self.overrides["task"] = self.task + + # Below added to allow export from YAMLs + self.model.args = {**DEFAULT_CFG_DICT, **self.overrides} # combine default and model args (prefer model args) + self.model.task = self.task + self.model_name = cfg + + def _load(self, weights: str, task=None) -> None: + """Load a model from a checkpoint file or initialize it from a weights file. + + This method handles loading models from either .pt checkpoint files or other weight file formats. It sets up the + model, task, and related attributes based on the loaded weights. + + Args: + weights (str): Path to the model weights file to be loaded. + task (str, optional): The task associated with the model. If None, it will be inferred from the model. + + Raises: + FileNotFoundError: If the specified weights file does not exist or is inaccessible. + ValueError: If the weights file format is unsupported or invalid. + + Examples: + >>> model = Model() + >>> model._load("yolo26n.pt") + >>> model._load("path/to/weights.pth", task="detect") + """ + model_uri = checks.normalize_platform_uri(weights) + if weights.lower().startswith(checks.REMOTE_FILE_PREFIXES): + weights = checks.check_file(weights, download_dir=SETTINGS["weights_dir"]) # download and return local file + weights = checks.check_model_file_from_stem(weights) # add suffix, i.e. yolo26n -> yolo26n.pt + + if str(weights).rpartition(".")[-1] == "pt": + self.model, self.ckpt = load_checkpoint(weights) + self.task = self.model.task + self.overrides = self.model.args = self._reset_ckpt_args(self.model.args) + self.ckpt_path = self.model.pt_path + else: + weights = checks.check_file(weights) # runs in all cases, not redundant with above call + self.model, self.ckpt = weights, None + self.task = task or guess_model_task(weights) + self.ckpt_path = weights + self.overrides["model"] = model_uri if str(model_uri).startswith("ul://") else weights + self.overrides["task"] = self.task + self.model_name = weights + + def _check_is_pytorch_model(self) -> None: + """Check if the model is a PyTorch model and raise TypeError if it's not. + + This method verifies that the model is either a PyTorch module or a .pt file. It's used to ensure that certain + operations that require a PyTorch model are only performed on compatible model types. + + Raises: + TypeError: If the model is not a PyTorch module or a .pt file. The error message provides detailed + information about supported model formats and operations. + + Examples: + >>> model = Model("yolo26n.pt") + >>> model._check_is_pytorch_model() # No error raised + >>> model = Model("yolo26n.onnx") + >>> model._check_is_pytorch_model() # Raises TypeError + """ + pt_str = isinstance(self.model, (str, Path)) and str(self.model).rpartition(".")[-1] == "pt" + pt_module = isinstance(self.model, torch.nn.Module) + if not (pt_module or pt_str): + raise TypeError( + f"model='{self.model}' should be a *.pt PyTorch model to run this method, but is a different format. " + f"PyTorch models can train, val, predict and export, i.e. 'model.train(data=...)', but exported " + f"formats like ONNX, TensorRT etc. only support 'predict' and 'val' modes, " + f"i.e. 'yolo predict model=yolo26n.onnx'.\nTo run CUDA or MPS inference please pass the device " + f"argument directly in your inference command, i.e. 'model.predict(source=..., device=0)'" + ) + + def reset_weights(self) -> Model: + """Reset the model's weights to their initial state. + + This method iterates through all modules in the model and resets their parameters if they have a + 'reset_parameters' method. It also ensures that all parameters have 'requires_grad' set to True, enabling them + to be updated during training. + + Returns: + (Model): The instance of the class with reset weights. + + Raises: + TypeError: If the model is not a PyTorch model. + + Examples: + >>> model = Model("yolo26n.pt") + >>> model.reset_weights() + """ + self._check_is_pytorch_model() + for m in self.model.modules(): + if hasattr(m, "reset_parameters"): + m.reset_parameters() + for p in self.model.parameters(): + p.requires_grad = True + self.overrides["pretrained"] = False # train() builds the seeded model from the architecture + self.predictor = None + return self + + def load(self, weights: str | Path | dict | torch.nn.Module = "yolo26n.pt") -> Model: + """Load parameters from the specified weights file into the model. + + This method supports loading weights from a file or directly from a weights object. It matches parameters by + name and shape and transfers them to the model. + + Args: + weights (str | Path | dict | torch.nn.Module): Path to the weights file, a checkpoint dict or a module. + + Returns: + (Model): The instance of the class with loaded weights. + + Raises: + TypeError: If the model is not a PyTorch model. + + Examples: + >>> model = Model() + >>> model.load("yolo26n.pt") + >>> model.load(Path("path/to/weights.pt")) + """ + self._check_is_pytorch_model() + if isinstance(weights, (str, Path)): + weights, ckpt = load_checkpoint(weights) + ckpt_path = weights.pt_path + else: + ckpt, ckpt_path = {"model": self.model}, None # an object load has no file to resume from + self.overrides.pop("pretrained", None) + self.model.load(weights) + self.ckpt, self.ckpt_path = ckpt, ckpt_path # train() seeds from self.model while ckpt is set + self.predictor = None + return self + + def save(self, filename: str | Path = "saved_model.pt") -> None: + """Save the current model state to a file. + + This method exports the model's checkpoint (ckpt) to the specified filename. It includes metadata such as the + date, Ultralytics version, license information, and a link to the documentation. The module is written as held + in memory: layers folded by ``fuse()`` stay folded, so training from the file transfers less. + + Args: + filename (str | Path): The name of the file to save the model to. + + Raises: + TypeError: If the model is not a PyTorch model. + + Examples: + >>> model = Model("yolo26n.pt") + >>> model.save("my_model.pt") + """ + self._check_is_pytorch_model() + from copy import deepcopy + from datetime import datetime + + from ultralytics import __version__ + from ultralytics.utils.torch_utils import qat_state, strip_qat + + state = qat_state(self.model) if isinstance(self.model, torch.nn.Module) else None + model = ( + deepcopy(self.model).half().to(memory_format=torch.contiguous_format) + if isinstance(self.model, torch.nn.Module) + else self.model + ) + if isinstance(model, torch.nn.Module): + strip_qat(model) + updates = { + "ema": None, + "model": model, + "modelopt": state, + "date": datetime.now().astimezone().isoformat(), + "version": __version__, + "license": "AGPL-3.0 License (https://ultralytics.com/license)", + "docs": "https://docs.ultralytics.com", + } + torch.save({**self.ckpt, **updates}, filename) + + def info(self, detailed: bool = False, verbose: bool = True, imgsz: int | list[int, int] = 640): + """Display model information. + + This method provides an overview or detailed information about the model, depending on the arguments + passed. It can control the verbosity of the output. + + Args: + detailed (bool): If True, shows detailed information about the model layers and parameters. + verbose (bool): If True, prints the information and returns model summary. If False, returns None. + imgsz (int | list[int, int]): Input image size used for FLOPs calculation. + + Returns: + (tuple): A tuple containing the number of layers (int), number of parameters (int), number of gradients + (int), and GFLOPs (float). Returns None if verbose is False. + + Examples: + >>> model = Model("yolo26n.pt") + >>> model.info() # Prints model summary and returns tuple + >>> model.info(detailed=True) # Prints detailed info and returns tuple + """ + self._check_is_pytorch_model() + return self.model.info(detailed=detailed, verbose=verbose, imgsz=imgsz) + + def fuse(self, verbose: bool = True, imgsz: int | list[int, int] = 640) -> Model: + """Fuse Conv2d and BatchNorm2d layers in the model for optimized inference. + + This method iterates through the model's modules and fuses consecutive Conv2d and BatchNorm2d layers into a + single layer. This fusion can significantly improve inference speed by reducing the number of operations and + memory accesses required during forward passes. + + The fusion process typically involves folding the BatchNorm2d parameters (mean, variance, weight, and + bias) into the preceding Conv2d layer's weights and biases. This results in a single Conv2d layer that + performs both convolution and normalization in one step. + + Args: + verbose (bool): Whether to print model information after fusion. + imgsz (int | list[int, int]): Input image size used for FLOPs calculation. + + Examples: + >>> model = Model("yolo26n.pt") + >>> model.fuse() + >>> # Model is now fused and ready for optimized inference + """ + self._check_is_pytorch_model() + # DistillationModel fuses to its student, so adopt the return + self.model = self.model.fuse(verbose=verbose, imgsz=imgsz) + self.predictor = None + return self + + def embed( + self, + source: str | Path | int | list | tuple | np.ndarray | torch.Tensor = None, + stream: bool = False, + **kwargs: Any, + ) -> Iterator[torch.Tensor] | list[torch.Tensor]: + """Generate image embeddings based on the provided source. + + This method is a wrapper around the 'predict()' method, returning feature embeddings from image sources. By + default, embeddings are extracted from the second-to-last model layer. Pass `embed=[layer_index]` in `kwargs` to + select specific layers. + + Args: + source (str | Path | int | list | tuple | np.ndarray | torch.Tensor): The source of the image for generating + embeddings. Can be a file path, URL, numpy array, etc. + stream (bool): If True, predictions are streamed. + **kwargs (Any): Additional keyword arguments for configuring the embedding process. + + Returns: + (Iterator[torch.Tensor] | list[torch.Tensor]): Image embeddings, streamed when `stream=True`. + + Raises: + TypeError: If the model is not an Ultralytics PyTorch model. Exported formats and third-party modules expose + no intermediate layers to embed. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> image = "https://ultralytics.com/images/bus.jpg" + >>> embeddings = model.embed(image) + >>> results = model.predict(image) + >>> print(embeddings[0].shape) + >>> print(results[0].boxes.shape) + """ + self._check_is_pytorch_model() + model = unwrap_model(self.model) + if not isinstance(model, BaseModel): # e.g. a super-gradients YOLO-NAS module, which has no layer list + raise TypeError(f"model='{type(model).__name__}' is not an Ultralytics model and cannot be embedded.") + if not kwargs.get("embed"): + kwargs["embed"] = [len(model.model) - 2] # embed second-to-last layer if no indices passed + return self.predict(source, stream, **kwargs) + + def predict( + self, + source: str | Path | int | Image.Image | list | tuple | np.ndarray | torch.Tensor = None, + stream: bool = False, + predictor=None, + **kwargs: Any, + ) -> Iterator[Results | torch.Tensor] | list[Results] | list[torch.Tensor]: + """Perform predictions on the given image source using the YOLO model. + + This method facilitates the prediction process, allowing various configurations through keyword arguments. It + supports predictions with custom predictors or the default predictor method. The method handles different types + of image sources and can operate in a streaming mode. + + Args: + source (str | Path | int | PIL.Image | np.ndarray | torch.Tensor | list | tuple): The source of the image(s) + to make predictions on. Accepts various types including file paths, URLs, PIL images, numpy arrays, and + torch tensors. + stream (bool): If True, treats the input source as a continuous stream for predictions. + predictor (BasePredictor, optional): An instance of a custom predictor class for making predictions. If + None, the method uses a default predictor. + **kwargs (Any): Additional keyword arguments for configuring the prediction process. These include `embed` + for returning feature embeddings from specified layers. + + Returns: + (Iterator[ultralytics.engine.results.Results | torch.Tensor] | list[ultralytics.engine.results.Results] | + list[torch.Tensor]): Prediction results or embeddings, streamed when `stream=True`. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> results = model.predict(source="path/to/image.jpg", conf=0.25) + >>> for r in results: + ... print(r.boxes.data) # print detection bounding boxes + + Notes: + - If 'source' is not provided, it defaults to the ASSETS constant with a warning. + - The method sets up a new predictor if not already present and updates its arguments with each call. + - For SAM-type models, 'prompts' can be passed as a keyword argument. + """ + if source is None: + source = "https://ultralytics.com/images/boats.jpg" if self.task == "obb" else ASSETS + LOGGER.warning(f"'source' is missing. Using 'source={source}'.") + + is_cli = (ARGV[0].endswith("yolo") or ARGV[0].endswith("ultralytics")) and any( + x in ARGV for x in ("predict", "track", "mode=predict", "mode=track") + ) + + custom = {"conf": 0.25, "batch": 1, "save": is_cli, "mode": "predict", "rect": True, "embed": None} + kwargs = _handle_deprecation(kwargs) + prompts = kwargs.pop("prompts", None) # for SAM-type models + args = {**self.overrides, **custom, **kwargs} # highest priority args on the right + + if ( + not self.predictor + or self.predictor.args.device != args.get("device", self.predictor.args.device) + or self.predictor.args.channels_last != args.get("channels_last", self.predictor.args.channels_last) + or self.predictor.args.nms != args.get("nms", self.predictor.args.nms) + or self.predictor.args.quantize != QUANTIZE_ALIASES.get(str(q := args.get("quantize")).lower(), q) + ): + self.predictor = (predictor or self._smart_load("predictor"))(overrides=args, _callbacks=self.callbacks) + self.predictor.setup_model(model=self.model, verbose=is_cli) + else: # only update args if predictor is already setup + save_keys = ("project", "name", "save_dir", "exist_ok") + prev_save_args = tuple(getattr(self.predictor.args, k, None) for k in save_keys) + setup_keys = ("device", "dnn", "data", "nms", "compile", "channels_last", "quantize") + base_args = { + **DEFAULT_CFG_DICT, + **self.overrides, + **{k: getattr(self.predictor.args, k) for k in setup_keys}, + } + self.predictor.args = get_cfg(base_args, {**custom, **kwargs}) + if self.predictor.args.show: + self.predictor.args.show = checks.check_imshow(warn=True) + if prev_save_args != tuple(getattr(self.predictor.args, k, None) for k in save_keys): + self.predictor.save_dir = get_save_dir(self.predictor.args) + if prompts and hasattr(self.predictor, "set_prompts"): # for SAM-type models + self.predictor.set_prompts(prompts) + return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream) + + def track( + self, + source: str | Path | int | list | tuple | np.ndarray | torch.Tensor = None, + stream: bool = False, + persist: bool = False, + **kwargs: Any, + ) -> list[Results]: + """Conduct object tracking on the specified input source using the registered trackers. + + This method performs object tracking using the model's predictors and optionally registered trackers. It handles + various input sources such as file paths or video streams, and supports customization through keyword arguments. + The method registers or refreshes the tracking callbacks on each call, so a later `persist` takes effect. + + Args: + source (str | Path | int | list | tuple | np.ndarray | torch.Tensor, optional): Input source for object + tracking. Can be a file path, URL, or video stream. + stream (bool): If True, treats the input source as a continuous video stream. + persist (bool): If True, persists trackers between different calls to this method. + **kwargs (Any): Additional keyword arguments for configuring the tracking process. + + Returns: + (list[ultralytics.engine.results.Results]): A list of tracking results, each a Results object. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> results = model.track(source="path/to/video.mp4", show=True) + >>> for r in results: + ... print(r.boxes.id) # print tracking IDs + + Notes: + - This method sets a default confidence threshold of 0.1 so trackers receive low-confidence detections. + - The tracking mode is explicitly set in the keyword arguments. + - Batch size is set to 1 for tracking in videos. + """ + from ultralytics.trackers import register_tracker + + register_tracker(self, persist) + kwargs["conf"] = 0.1 if kwargs.get("conf") is None else kwargs["conf"] # trackers need low-confidence input + kwargs["batch"] = kwargs.get("batch") or 1 # batch-size 1 for tracking in videos + kwargs["mode"] = "track" + return self.predict(source=source, stream=stream, **kwargs) + + def val( + self, + validator=None, + **kwargs: Any, + ): + """Validate the model using a specified dataset and validation configuration. + + This method facilitates the model validation process, allowing for customization through various settings. It + supports validation with a custom validator or the default validation approach. The method combines default + configurations, method-specific defaults, and user-provided arguments to configure the validation process. + + Args: + validator (ultralytics.engine.validator.BaseValidator, optional): An instance of a custom validator class + for validating the model. + **kwargs (Any): Arbitrary keyword arguments for customizing the validation process. + + Returns: + (ultralytics.utils.metrics.DetMetrics): Validation metrics obtained from the validation process. The + specific metrics type depends on the task (e.g., DetMetrics, SegmentMetrics, + PoseMetrics, ClassifyMetrics). + + Raises: + TypeError: If the model is not a PyTorch model. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> results = model.val(data="coco8.yaml", imgsz=640) + >>> print(results.box.map) # Print mAP50-95 + """ + custom = {"rect": True} # method defaults + if kwargs.get("data") is None: + kwargs["data"] = self._val_data() + args = {**self.overrides, **custom, **kwargs, "mode": "val"} # highest priority args on the right + + validator = (validator or self._smart_load("validator"))(args=args, _callbacks=self.callbacks) + validator(model=self.model) + self.metrics = validator.metrics + return validator.metrics + + def calibrate(self, data: str | Path, **kwargs: Any): + """Fit scale-only depth calibration on a small labeled set (depth task only). + + Runs a validation pass, then fits the global log-affine ``d' = exp(a·log d + b)`` against + ground-truth depth via :func:`fit_calibration_selective` — the same "calibrate only if it + helps" policy as trainer auto-calibration (identity / scale-only chosen by held-out δ1) — + which writes ``(a, b)`` into the head's ``cal_a``/``cal_b`` buffers. No gradient training + and the decoder weights are untouched, so it cannot degrade the relative depth structure. + Call ``model.save(...)`` afterwards to persist the calibration. + + Args: + data (str | Path): Dataset YAML providing a labeled split to calibrate against. + **kwargs (Any): Extra validation arguments (e.g. ``imgsz``, ``batch``, ``device``, ``split``). + + Returns: + (tuple | None): The fitted ``(a, b)``, or ``None`` if fewer than 2 images had valid depth pixels. + + Examples: + >>> model = YOLO("yolo26s-depth.pt") + >>> model.calibrate(data="my_depth_dataset.yaml") + >>> model.save("yolo26s-depth-calibrated.pt") + """ + self._check_is_pytorch_model() + if self.task != "depth": + raise ValueError(f"calibrate() is only supported for depth models (task='depth'), got task={self.task!r}.") + from ultralytics.models.yolo.depth.calibrate import _depth_head, fit_calibration_selective + + if _depth_head(self.model) is None: + raise ValueError("Model has no Depth head with calibration buffers (cal_a/cal_b).") + args = {**self.overrides, **kwargs, "data": data, "mode": "val", "task": "depth"} + validator = self._smart_load("validator")(args=args, _callbacks=self.callbacks) + validator(model=self.model) + self.predictor = None # calibration updates the retained model below + res = fit_calibration_selective( + self.model, validator.dataloader, validator.device, max_depth=validator.data.get("max_depth") or 100.0 + ) + if res is None: + return None + LOGGER.info("Call model.save(...) to persist the calibration.") + return res["a"], res["b"] + + def benchmark(self, data=None, format="", verbose=False, **kwargs: Any): + """Benchmark the model across various export formats to evaluate performance. + + This method assesses the model's performance in different export formats, such as ONNX, TorchScript, etc. It + uses the 'benchmark' function from the ultralytics.utils.benchmarks module. The benchmarking is configured using + a combination of default configuration values, model-specific arguments, method-specific defaults, and any + additional user-provided keyword arguments. + + Args: + data (str | None): Path to the dataset for benchmarking. If None, uses default dataset for the task. + format (str): Export format name for specific benchmarking. + verbose (bool): Whether to print detailed benchmark information. + **kwargs (Any): Arbitrary keyword arguments to customize the benchmarking process. Common options include: + - imgsz (int | list[int]): Image size for benchmarking. + - quantize (int | str): Requested precision: 16 (FP16), 8 (INT8), or 32/None (FP32) where + supported; only 16 changes the native PyTorch row. + - device (str): Device to run the benchmark on (e.g., 'cpu', 'cuda'). + + Returns: + (polars.DataFrame): A Polars DataFrame with benchmark results for each format, including file size, metric, + and inference time. + + Raises: + TypeError: If the model is not a PyTorch model. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> results = model.benchmark(data="coco8.yaml", imgsz=640, quantize=16) + >>> print(results) + """ + self._check_is_pytorch_model() + from ultralytics.utils.benchmarks import benchmark + + from .exporter import export_formats + + custom = {"verbose": False, "nms": None} # method defaults + kwargs = _handle_deprecation(kwargs) # forward legacy flags (e.g. half/int8 -> quantize) before merging + args = {**DEFAULT_CFG_DICT, **self.model.args, **custom, **kwargs, "mode": "benchmark"} + fmts = export_formats() + export_args = set(dict(zip(fmts["Argument"], fmts["Arguments"])).get(format.lower(), [])) - { + "batch", + "data", + "quantize", + "nms", + } + export_kwargs = {k: v for k, v in args.items() if k in export_args} # quantize is passed explicitly below + return benchmark( + model=self, + data=data, # if no 'data' argument passed set data=None for default datasets + imgsz=args["imgsz"], + device=args["device"], + verbose=verbose, + format=format, + quantize=args.get("quantize"), + nms=args.get("nms"), + **export_kwargs, + ) + + def export( + self, + **kwargs: Any, + ) -> str: + """Export the model to a different format suitable for deployment. + + This method facilitates the export of the model to various formats (e.g., ONNX, TorchScript) for deployment + purposes. It uses the 'Exporter' class for the export process, combining model-specific overrides, method + defaults, and any additional arguments provided. + + Args: + **kwargs (Any): Arbitrary keyword arguments for export configuration. Common options include: + - format (str): Export format (e.g., 'onnx', 'engine', 'coreml'). + - quantize (int | str): Precision, e.g. 16 (FP16) or 8 (INT8); 32/None is FP32. + - device (str): Device to run the export on. + - workspace (int): Maximum memory workspace size for TensorRT engines. + - nms (bool | None): None for raw output, True to embed NMS, or False for the NMS-free head where available. + - simplify (bool): Simplify ONNX model. + + Returns: + (str): The path to the exported model file. + + Raises: + TypeError: If the model is not a PyTorch model. + ValueError: If an unsupported export format is specified. + RuntimeError: If the export process fails due to errors. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> model.export(format="onnx", dynamic=True, simplify=True) + 'path/to/exported/model.onnx' + """ + self._check_is_pytorch_model() + from .exporter import Exporter, export_formats + + custom = { + "imgsz": self.model.args["imgsz"], + "batch": 1, + "data": None, + "device": None, # reset to avoid multi-GPU errors + "verbose": False, + } # method defaults + args = {**self.overrides, **custom, **kwargs, "mode": "export"} # highest priority args on the right + try: + return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model) + except Exception: + formats = export_formats() + export_format = args.get("format", DEFAULT_CFG_DICT["format"]) + format_name = dict(zip(formats["Argument"], formats["Format"])).get( + str(export_format).lower(), export_format + ) + LOGGER.info(f"Export to {format_name} in the cloud with Ultralytics Platform: {PLATFORM_URL}") + raise + + def train( + self, + trainer=None, + **kwargs: Any, + ): + """Train the model using the specified dataset and training configuration. + + This method facilitates model training with a range of customizable settings. It supports training with a custom + trainer or the default training approach. The method handles scenarios such as resuming training from a + checkpoint and updating model and configuration after training. It checks for pip updates and combines default + configurations, method-specific defaults, and user-provided arguments to configure the training process. + + Args: + trainer (BaseTrainer, optional): Custom trainer instance for model training. If None, uses default. + **kwargs (Any): Arbitrary keyword arguments for training configuration. Common options include: + - data (str): Path to dataset configuration file. + - epochs (int): Number of training epochs. + - batch (int): Batch size for training. + - imgsz (int): Input image size. + - device (str): Device to run training on (e.g., 'cuda', 'cpu'). + - workers (int): Number of worker threads for data loading. + - optimizer (str): Optimizer to use for training. + - lr0 (float): Initial learning rate. + - patience (int): Epochs to wait for no observable improvement for early stopping of training. + - augmentations (list[Callable]): List of augmentation functions to apply during training. + + Returns: + (ultralytics.utils.metrics.DetMetrics | dict | None): Training metrics if available and training is + successful; otherwise, None. The specific metrics type depends on the task. When `data` is a list or + tuple of datasets, the base model is fine-tuned on each in series and a {dataset: metrics} dict is + returned. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> results = model.train(data="coco8.yaml", epochs=3) + >>> multi = model.train(data=["coco8.yaml", "african-wildlife.yaml"], epochs=3) # fine-tune across datasets + """ + self._check_is_pytorch_model() + checks.check_pip_update_available() + + overrides = YAML.load(checks.check_yaml(kwargs["cfg"])) if kwargs.get("cfg") else self.overrides + custom = { + # NOTE: handle the case when 'cfg' includes 'data'. + "data": (overrides.get("data") if kwargs.get("cfg") else None) + or DEFAULT_CFG_DICT["data"] + or ( + None if isinstance(kwargs.get("resume", overrides.get("resume")), (str, Path)) else TASK2DATA[self.task] + ), + "model": self.overrides["model"], + "task": self.task, + } # method defaults + args = {**overrides, **custom, **kwargs, "mode": "train"} # prioritizes rightmost args + pretrained = args.setdefault("pretrained", self.overrides.get("pretrained", True)) + if isinstance(args.get("data"), (list, tuple)): # fine-tune a single base model across multiple datasets + from ultralytics.engine.trainer import MultiTrainer + + use_python_trainer = trainer is not None or self.callbacks != callbacks.get_default_callbacks() + self.trainer = MultiTrainer( + (trainer or self._smart_load("trainer")) if use_python_trainer else None, + args, + self.model, + _callbacks=self.callbacks, + ) + self.metrics = self.trainer.train() + return self.metrics + if args.get("resume") is True: # resume=True (boolean) uses current model as checkpoint + if self.ckpt and self.ckpt.get("epoch", -1) >= 0 and self.ckpt.get("optimizer") is not None: + args["resume"], args["data"] = self.ckpt_path, kwargs.get("data") or overrides.get("data") + else: + LOGGER.warning( + f"model '{self.ckpt_path}' is not a resumable training checkpoint " + f"(missing epoch/optimizer state). Use 'resume' only to continue incomplete training. " + f"Starting new training instead." + ) + args["resume"] = False + + self.trainer = (trainer or self._smart_load("trainer"))(overrides=args, _callbacks=self.callbacks) + if not args.get("resume") and self.ckpt: + # Reuse the already-loaded checkpoint model to avoid re-resolving remote weight sources during trainer setup. + weights = None if pretrained is False else self.model + if isinstance(pretrained, (str, Path)): + weights, _ = load_checkpoint(pretrained) + self.trainer.model = self.trainer.get_model(weights=weights, cfg=self.model.yaml) + self.model = self.trainer.model + self.predictor = None # this module replaced the one the cached predictor wrapped + + self.trainer.train() + # Update model and cfg after training + if RANK in {-1, 0}: + ckpt = self.trainer.best if self.trainer.best.exists() else self.trainer.last + if not ckpt.exists(): + raise FileNotFoundError( + f"Training completed but no checkpoint was saved. Expected {self.trainer.best} or {self.trainer.last}." + ) + self.model, self.ckpt = load_checkpoint(ckpt) + self.predictor = None # the checkpoint replaced the module again; covers resume and YAML runs too + self.overrides = self._reset_ckpt_args(self.model.args) + self.overrides["model"] = str(ckpt) # the reset drops it, train() and tune() read it back + self.metrics = getattr(self.trainer.validator, "metrics", None) + if self.metrics is None and self.ckpt: # recover from checkpoint under DDP (validator runs in subprocess) + self.metrics = self.ckpt.get("train_metrics") + return self.metrics + + def tune( + self, + use_ray=False, + iterations=300, + *args: Any, + **kwargs: Any, + ): + """Conduct hyperparameter tuning for the model, with an option to use Ray Tune. + + This method supports two modes of hyperparameter tuning: using Ray Tune or a custom tuning method. When Ray Tune + is enabled, it leverages the 'run_ray_tune' function from the ultralytics.utils.tuner module. Otherwise, it uses + the internal 'Tuner' class for tuning. The method combines default, overridden, and custom arguments to + configure the tuning process. + + Args: + use_ray (bool): Whether to use Ray Tune for hyperparameter tuning. If False, uses internal tuning method. + iterations (int): Number of tuning iterations to perform. + *args (Any): Additional positional arguments to pass to the tuner. + **kwargs (Any): Additional keyword arguments for tuning configuration. These are combined with model + overrides and defaults to configure the tuning process. + + Returns: + (ray.tune.ResultGrid | None): When use_ray=True, returns a ResultGrid with hyperparameter search results. + When use_ray=False, returns None and saves best hyperparameters to YAML. + + Raises: + TypeError: If the model is not a PyTorch model. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> results = model.tune(data="coco8.yaml", iterations=5) + >>> print(results) + + # Use Ray Tune for more advanced hyperparameter search + >>> results = model.tune(use_ray=True, iterations=20, data="coco8.yaml") + """ + self._check_is_pytorch_model() + if "optimizer" not in (kwargs.get("space") or {}): + kwargs.setdefault("optimizer", "AdamW") + if use_ray: + from ultralytics.utils.tuner import run_ray_tune + + return run_ray_tune(self, *args, iterations=iterations, **kwargs) + else: + from .tuner import Tuner + + custom = {} # method defaults + args = {**self.overrides, **custom, **kwargs, "mode": "train"} # highest priority args on the right + return Tuner(args=args, model=self.model, _callbacks=self.callbacks)(iterations=iterations) + + def _apply(self, fn) -> Model: + """Apply a function to model parameters, buffers, and tensors. + + This method extends the functionality of the parent class's _apply method by additionally updating the device + in the model's overrides and dropping the cached predictor when a model tensor is converted. No-op tensor + conversions preserve the predictor. + + Args: + fn (Callable): A function to be applied to the model's tensors. This is typically a method like to(), cpu(), + cuda(), half(), or float(). + + Returns: + (Model): The model instance with the function applied and updated attributes. + + Raises: + TypeError: If the model is not a PyTorch model. + + Examples: + >>> model = Model("yolo26n.pt") + >>> model = model._apply(lambda t: t.cuda()) # Move model to GPU + """ + self._check_is_pytorch_model() + + def apply(t): + converted = fn(t) + if converted is not t: + self.predictor = None # predictor owns a copy, including buffers and detection-head tensors + return converted + + super()._apply(apply) + self.overrides["device"] = self.device # was str(self.device) i.e. device(type='cuda', index=0) -> 'cuda:0' + return self + + @property + def names(self) -> dict[int, str]: + """Retrieve the class names associated with the loaded model. + + This property returns the class names if they are defined in the model. It checks the class names for validity + using the 'check_class_names' function from the ultralytics.nn.autobackend module. If the predictor is not + initialized, it sets it up before retrieving the names. + + Returns: + (dict[int, str]): A dictionary of class names associated with the model, where keys are class indices and + values are the corresponding class names. + + Raises: + AttributeError: If the model or predictor does not have a 'names' attribute. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> print(model.names) + {0: 'person', 1: 'bicycle', 2: 'car', ...} + """ + from ultralytics.nn.autobackend import check_class_names + + if hasattr(self.model, "names"): + return check_class_names(self.model.names) + if not self.predictor: # export formats will not have predictor defined until predict() is called + predictor = self._smart_load("predictor")(overrides=self.overrides, _callbacks=self.callbacks) + predictor.setup_model(model=self.model, verbose=False) # do not mess with self.predictor.model args + return predictor.model.names + return self.predictor.model.names + + @property + def device(self) -> torch.device: + """Get the device on which the model's parameters are allocated. + + This property determines the device (CPU or GPU) where the model's parameters are currently stored. It is + applicable only to models that are instances of torch.nn.Module. + + Returns: + (torch.device | None): The device (CPU/GPU) of the model, or None if the model is not a torch.nn.Module + instance. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> print(model.device) + device(type='cuda', index=0) # if CUDA is available + >>> model = model.to("cpu") + >>> print(model.device) + device(type='cpu') + """ + return next(self.model.parameters()).device if isinstance(self.model, torch.nn.Module) else None + + @property + def transforms(self): + """Retrieve the transformations applied to the input data of the loaded model. + + This property returns the transformations if they are defined in the model. The transforms typically include + preprocessing steps like resizing, normalization, and data augmentation that are applied to input data before it + is fed into the model. + + Returns: + (object | None): The transform object of the model if available, otherwise None. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> transforms = model.transforms + >>> if transforms: + ... print(f"Model transforms: {transforms}") + ... else: + ... print("No transforms defined for this model.") + """ + return self.model.transforms if hasattr(self.model, "transforms") else None + + def add_callback(self, event: str, func) -> None: + """Add a callback function for a specified event. + + This method allows registering custom callback functions that are triggered on specific events during model + operations such as training or inference. Callbacks provide a way to extend and customize the behavior of the + model at various stages of its lifecycle. + + Args: + event (str): The name of the event to attach the callback to. Must be a valid event name recognized by the + Ultralytics framework. + func (Callable): The callback function to be registered. This function will be called when the specified + event occurs. + + Examples: + >>> def on_train_start(trainer): + ... print("Training is starting!") + >>> model = YOLO("yolo26n.pt") + >>> model.add_callback("on_train_start", on_train_start) + >>> model.train(data="coco8.yaml", epochs=1) + """ + self.callbacks[event].append(func) + + def clear_callback(self, event: str) -> None: + """Clear all callback functions registered for a specified event. + + This method removes all custom and default callback functions associated with the given event. It resets the + callback list for the specified event to an empty list, effectively removing all registered callbacks for that + event. + + Args: + event (str): The name of the event for which to clear the callbacks. This should be a valid event name + recognized by the Ultralytics callback system. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> model.add_callback("on_train_start", lambda: print("Training started")) + >>> model.clear_callback("on_train_start") + >>> # All callbacks for 'on_train_start' are now removed + + Notes: + - This method affects both custom callbacks added by the user and default callbacks + provided by the Ultralytics framework. + - After calling this method, no callbacks will be executed for the specified event + until new ones are added. + - Use with caution as it removes all callbacks, including essential ones that might + be required for proper functioning of certain operations. + """ + self.callbacks[event] = [] + + def reset_callbacks(self) -> None: + """Reset all callbacks to their default functions. + + This method reinstates the default callback functions for all events, removing any custom callbacks that were + previously added. It iterates through all default callback events and replaces the current callbacks with the + default ones. + + The default callbacks are defined in the 'callbacks.default_callbacks' dictionary, which contains predefined + functions for various events in the model's lifecycle, such as on_train_start, on_epoch_end, etc. + + This method is useful when you want to revert to the original set of callbacks after making custom + modifications, ensuring consistent behavior across different runs or experiments. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> model.add_callback("on_train_start", custom_function) + >>> model.reset_callbacks() + # All callbacks are now reset to their default functions + """ + for event in callbacks.default_callbacks: + self.callbacks[event] = [callbacks.default_callbacks[event][0]] + + @staticmethod + def _reset_ckpt_args(args: dict[str, Any]) -> dict[str, Any]: + """Reset specific arguments when loading a PyTorch model checkpoint. + + This method filters the input arguments dictionary to retain only a specific set of keys that are considered + important for model loading. It's used to ensure that only relevant arguments are preserved when loading a model + from a checkpoint, discarding any unnecessary or potentially conflicting settings. + + Args: + args (dict[str, Any]): A dictionary containing various model arguments and settings. + + Returns: + (dict[str, Any]): A new dictionary containing only the specified include keys from the input arguments. + + Examples: + >>> original_args = {"imgsz": 640, "data": "coco.yaml", "task": "detect", "batch": 16, "epochs": 100} + >>> reset_args = Model._reset_ckpt_args(original_args) + >>> print(reset_args) + {'imgsz': 640, 'data': 'coco.yaml', 'task': 'detect'} + """ + include = {"imgsz", "data", "task", "single_cls"} # only remember these arguments when loading a PyTorch model + return {k: v for k, v in args.items() if k in include} + + def _val_data(self) -> str | None: + """Return the checkpoint's dataset when it still resolves, otherwise the task default.""" + data = self.overrides.get("data") + if not isinstance(data, (str, Path)): # absent, or a YOLOE multi-source training dict + data = None + # a bare name (coco8.yaml, imagenet10) is portable; a path recorded on another host, or OS, is not + if data and ( + "://" in str(data) or not any(sep in str(data) for sep in "/\\") or checks.check_file(data, hard=False) + ): + return data + default = TASK2DATA.get(self.task) + LOGGER.warning( + f"Checkpoint dataset '{data}' was not found. Using default 'data={default}'. Pass data=... to validate on " + f"the original dataset." + if data + else f"'data' argument is missing. Using default 'data={default}'." + ) + return default + + def _smart_load(self, key: str): + """Intelligently load the appropriate module based on the model task. + + This method dynamically selects and returns the correct module (model, trainer, validator, or predictor) based + on the current task of the model and the provided key. It uses the task_map dictionary to determine the + appropriate module to load for the specific task. + + Args: + key (str): The type of module to load. Must be one of 'model', 'trainer', 'validator', or 'predictor'. + + Returns: + (object): The loaded module class corresponding to the specified key and current task. + + Raises: + NotImplementedError: If the specified key is not supported for the current task. + + Examples: + >>> model = Model(task="detect") + >>> predictor_class = model._smart_load("predictor") + >>> trainer_class = model._smart_load("trainer") + """ + try: + return self.task_map[self.task][key] + except Exception as e: + name = self.__class__.__name__ + mode = inspect.stack()[1][3] # get the function name. + raise NotImplementedError(f"'{name}' model does not support '{mode}' mode for '{self.task}' task.") from e + + @property + def task_map(self) -> dict: + """Provide a mapping from model tasks to corresponding classes for different modes. + + This property method returns a dictionary that maps each supported task (e.g., detect, segment, semantic, + classify) to a nested dictionary. The nested dictionary contains mappings for different operational modes + (model, trainer, validator, predictor) to their respective class implementations. + + The mapping allows for dynamic loading of appropriate classes based on the model's task and the desired + operational mode. This facilitates a flexible and extensible architecture for handling various tasks and modes + within the Ultralytics framework. + + Returns: + (dict[str, dict[str, Any]]): A dictionary mapping task names to nested dictionaries. Each nested dictionary + contains mappings for 'model', 'trainer', 'validator', and 'predictor' keys to their respective class + implementations for that task. + + Examples: + >>> model = Model("yolo26n.pt") + >>> task_map = model.task_map + >>> detect_predictor = task_map["detect"]["predictor"] + >>> segment_trainer = task_map["segment"]["trainer"] + """ + raise NotImplementedError("Please provide task map for your model!") + + def eval(self): + """Sets the model to evaluation mode. + + This method changes the model's mode to evaluation, which affects layers like dropout and batch normalization + that behave differently during training and evaluation. In evaluation mode, these layers use running statistics + rather than computing batch statistics, and dropout layers are disabled. + + Returns: + (Model): The model instance with evaluation mode set. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> model.eval() + >>> # Model is now in evaluation mode for inference + """ + self.model.eval() + return self + + def __getattr__(self, name): + """Enable accessing model attributes directly through the Model class. + + This method provides a way to access attributes of the underlying model directly through the Model class + instance. It first checks if the requested attribute is 'model', in which case it returns the model from + the module dictionary. Otherwise, it delegates the attribute lookup to the underlying model. + + Args: + name (str): The name of the attribute to retrieve. + + Returns: + (Any): The requested attribute value. + + Raises: + AttributeError: If the requested attribute does not exist in the model. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> print(model.stride) # Access model.stride attribute + >>> print(model.names) # Access model.names attribute + """ + return self._modules["model"] if name == "model" else getattr(self.model, name) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/predictor.py b/.venv/lib/python3.12/site-packages/ultralytics/engine/predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..8021e44adc6235f0fc16a5f6af4b4aeb7688f0ab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/engine/predictor.py @@ -0,0 +1,558 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Run prediction on images, videos, directories, globs, YouTube, webcam, streams, etc. + +Usage - sources: + $ yolo predict model=yolo26n.pt source=0 # webcam + img.jpg # image + vid.mp4 # video + screen # screenshot + path/ # directory + list.txt # list of images + list.streams # list of streams + 'path/*.jpg' # glob + 'https://youtu.be/LNwODJXcvt4' # YouTube + 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP, TCP stream + +Usage - formats: + $ yolo predict model=yolo26n.pt # PyTorch + yolo26n.torchscript # TorchScript + yolo26n.onnx # ONNX Runtime or OpenCV DNN with dnn=True + yolo26n_openvino_model # OpenVINO + yolo26n.engine # TensorRT + yolo26n.mlpackage # CoreML (macOS-only) + yolo26n_saved_model # TensorFlow SavedModel + yolo26n.pb # TensorFlow GraphDef + yolo26n_edgetpu.tflite # TensorFlow Edge TPU + yolo26n_paddle_model # PaddlePaddle + yolo26n.mnn # MNN + yolo26n_ncnn_model # NCNN + yolo26n_imx_model # Sony IMX + yolo26n_rknn_model # Rockchip RKNN + yolo26n_executorch_model # PyTorch ExecuTorch + yolo26n_axelera_model # Axelera AI + yolo26n_deepx_model # DEEPX + yolo26n_qnn.onnx # Qualcomm QNN + yolo26n.tflite # LiteRT + yolo26n_ascend_model # Huawei Ascend +""" + +from __future__ import annotations + +import platform +import re +import threading +from copy import deepcopy +from pathlib import Path +from typing import Any, Callable + +import cv2 +import numpy as np +import torch + +from ultralytics.cfg import get_cfg, get_save_dir +from ultralytics.data import load_inference_source +from ultralytics.data.augment import LetterBox +from ultralytics.nn.autobackend import AutoBackend +from ultralytics.utils import DEFAULT_CFG, LOGGER, MACOS, WINDOWS, callbacks, colorstr, ops +from ultralytics.utils.checks import check_imgsz, check_imshow +from ultralytics.utils.plotting import class_activation_map +from ultralytics.utils.torch_utils import attempt_compile, select_device, smart_inference_mode + +STREAM_WARNING = """ +Inference results will accumulate in RAM unless `stream=True` is passed, which can cause out-of-memory errors for large +sources or long-running streams and videos. See https://docs.ultralytics.com/modes/predict for help. + +Example: + results = model(source=..., stream=True) # generator of Results objects + for r in results: + boxes = r.boxes # Boxes object for bbox outputs + masks = r.masks # Masks object for segment masks outputs + probs = r.probs # Class probabilities for classification outputs +""" + + +class BasePredictor: + """A base class for creating predictors. + + This class provides the foundation for prediction functionality, handling model setup, inference, and result + processing across various input sources. + + Attributes: + args (SimpleNamespace): Configuration for the predictor. + save_dir (Path): Directory to save results. + done_warmup (bool): Whether the predictor has finished setup. + model (torch.nn.Module): Model used for prediction. + data (str | Path | None): Copy of args.data, the dataset YAML AutoBackend falls back to for class names. + device (torch.device): Device used for prediction. + dataset (Dataset): Dataset used for prediction. + vid_writer (dict[Path, cv2.VideoWriter]): Dictionary of {save_path: video_writer} for saving video output. + plotted_img (np.ndarray): Last plotted image. + source_type (SimpleNamespace): Type of input source. + seen (int): Number of images processed. + speed (dict[str, float] | None): Per-image preprocess, inference and postprocess times in ms, once run. + pixels (int | None): Mean per-image inference area in pixels, once a run completes. + windows (list[str]): List of window names for visualization. + batch (tuple): Current batch data. + results (list[Any]): Current batch results. + transforms (Callable): Image transforms for classification. + callbacks (dict[str, list[Callable]]): Callback functions for different events. + txt_path (Path): Path to save text results. + _lock (threading.Lock): Lock for thread-safe inference. + + Methods: + preprocess: Prepare input image before inference. + inference: Run inference on a given image. + postprocess: Process raw predictions into structured results. + predict_cli: Run prediction for command line interface. + setup_source: Set up input source and inference mode. + stream_inference: Stream inference on input source. + setup_model: Initialize and configure the model. + write_results: Write inference results to files. + save_predicted_images: Save prediction visualizations. + show: Display results in a window. + run_callbacks: Execute registered callbacks for an event. + add_callback: Register a new callback function. + """ + + def __init__( + self, + cfg=DEFAULT_CFG, + overrides: dict[str, Any] | None = None, + _callbacks: dict | None = None, + ): + """Initialize the BasePredictor class. + + Args: + cfg (str | Path | dict | SimpleNamespace): Path to a configuration file or a configuration dictionary. + overrides (dict, optional): Configuration overrides. + _callbacks (dict, optional): Dictionary of callback functions. + """ + self.args = get_cfg(cfg, overrides) + self.save_dir = get_save_dir(self.args) + if self.args.conf is None: + self.args.conf = 0.25 # default conf=0.25 + self.done_warmup = False + if self.args.show: + self.args.show = check_imshow(warn=True) + + # Usable if setup is done + self.model = None + self.data = self.args.data + self.imgsz = None + self.device = None + self.dataset = None + self.vid_writer = {} # dict of {save_path: video_writer, ...} + self.plotted_img = None + self.source_type = None + self.seen = 0 + self.speed = None # per-image speeds, set once a run completes + self.pixels = None # mean per-image inference area, set once a run completes + self.windows = [] + self.screen = None # cached screen resolution (width, height) for show=True scaling + self.batch = None + self.results = None + self.transforms = None + self.callbacks = _callbacks or callbacks.get_default_callbacks() + self.txt_path = None + self._lock = threading.Lock() # for automatic thread-safe inference + callbacks.add_integration_callbacks(self) + + def preprocess(self, im: torch.Tensor | list[np.ndarray]) -> torch.Tensor: + """Prepare input image before inference. + + Args: + im (torch.Tensor | list[np.ndarray]): Images of shape (N, 3, H, W) for tensor, already RGB and normalized to + 0.0-1.0, or [(H, W, 3) x N] for list of BGR uint8 arrays. See + ultralytics.data.loaders.LoadTensor._single_check for tensor input requirements. + + Returns: + (torch.Tensor): Preprocessed image tensor of shape (N, 3, H, W). + """ + if not isinstance(im, torch.Tensor): + im = self.pre_transform(im) + # For a single image, add a batch dimension without the copy required by np.stack(). + im = torch.from_numpy(im[0]).unsqueeze(0) if len(im) == 1 else torch.from_numpy(np.stack(im)) + im = im.to(self.device) # transfer as uint8, then reorder on device + im = im.permute(0, 3, 1, 2) # BHWC to BCHW, (n, 3, h, w) + if im.shape[1] == 3: + im = im.flip(1) # BGR to RGB + im = im.contiguous() + im = (im.half() if self.model.fp16 else im.float()).div_(255) # uint8 to fp16/32, 0 - 255 to 0.0 - 1.0 + else: + im = im.to(self.device) + im = im.half() if self.model.fp16 else im.float() # already 0.0 - 1.0, no division + return im + + def inference(self, im: torch.Tensor, *args, **kwargs): + """Run inference on a given image using the specified model and arguments.""" + skip = self.source_type.tensor or self.args.augment or self.args.embed # unsupported with activation maps + if self.args.visualize and getattr(self.model, "base_model", True) and not skip: + return class_activation_map( + self.model, + im, + self.batch[0], + self.save_dir, + *args, + conf=self.args.conf, + classes=self.args.classes, + **kwargs, + ) + return self.model(im, *args, augment=self.args.augment, embed=self.args.embed, **kwargs) + + def pre_transform(self, im: list[np.ndarray]) -> list[np.ndarray]: + """Pre-transform input image before inference. + + Args: + im (list[np.ndarray]): List of images with shape [(H, W, 3) x N]. + + Returns: + (list[np.ndarray]): List of transformed images. + """ + same_shapes = len({x.shape for x in im}) == 1 + letterbox = LetterBox( + self.imgsz, + auto=same_shapes + and self.args.rect + and (self.model.format == "pt" or (getattr(self.model, "dynamic", False) and self.model.format != "imx")), + stride=self.model.stride, + ) + return [letterbox(image=x) for x in im] + + def postprocess(self, preds, img, orig_imgs): + """Post-process predictions for an image and return them.""" + return preds + + def __call__(self, source=None, model=None, stream: bool = False, *args, **kwargs): + """Perform inference on an image or stream. + + Args: + source (str | Path | list[str] | list[Path] | list[np.ndarray] | np.ndarray | torch.Tensor, optional): + Source for inference. + model (str | Path | torch.nn.Module, optional): Model for inference. + stream (bool): Whether to stream the inference results. If True, returns a generator. + *args (Any): Additional arguments for the inference method. + **kwargs (Any): Additional keyword arguments for the inference method. + + Returns: + (list[ultralytics.engine.results.Results] | generator): Results objects or generator of Results objects. + """ + self.stream = stream + if stream: + return self.stream_inference(source, model, *args, **kwargs) + else: + return list(self.stream_inference(source, model, *args, **kwargs)) # merge list of Results into one + + def predict_cli(self, source=None, model=None): + """Method used for Command Line Interface (CLI) prediction. + + This function is designed to run predictions using the CLI. It sets up the source and model, then processes the + inputs in a streaming manner. This method ensures that no outputs accumulate in memory by consuming the + generator without storing results. + + Args: + source (str | Path | list[str] | list[Path] | list[np.ndarray] | np.ndarray | torch.Tensor, optional): + Source for inference. + model (str | Path | torch.nn.Module, optional): Model for inference. + + Notes: + Do not modify this function or remove the generator. The generator ensures that no outputs are + accumulated in memory, which is critical for preventing memory issues during long-running predictions. + """ + gen = self.stream_inference(source, model) + for _ in gen: # sourcery skip: remove-empty-nested-block, noqa + pass + + def setup_source(self, source, stride: int | None = None): + """Set up source and inference mode. + + Args: + source (str | Path | list[str] | list[Path] | list[np.ndarray] | np.ndarray | torch.Tensor): Source for + inference. + stride (int, optional): Model stride for image size checking. + """ + if hasattr(self.model, "imgsz") and not getattr(self.model, "dynamic", False): + self.args.imgsz = self.model.imgsz # every run reuses imgsz from export metadata, not just the first + self.imgsz = check_imgsz(self.args.imgsz, stride=stride or self.model.stride, min_dim=2) # check image size + self.dataset = load_inference_source( + source=source, + batch=self.args.batch, + vid_stride=self.args.vid_stride, + buffer=self.args.stream_buffer, + channels=getattr(self.model, "channels", 3), + ) + self.source_type = self.dataset.source_type + if ( + self.source_type.stream + or self.source_type.screenshot + or len(self.dataset) > 1000 # many images + or any(getattr(self.dataset, "video_flag", [False])) + ): # long sequence + import torchvision # noqa (import here triggers torchvision NMS use in nms.py) + + if not getattr(self, "stream", True): # videos + LOGGER.warning(STREAM_WARNING) + self.vid_writer = {} + + @smart_inference_mode() + def stream_inference(self, source=None, model=None, *args, **kwargs): + """Stream inference on input source and save results to file. + + Args: + source (str | Path | list[str] | list[Path] | list[np.ndarray] | np.ndarray | torch.Tensor, optional): + Source for inference. + model (str | Path | torch.nn.Module, optional): Model for inference. + *args (Any): Additional arguments for the inference method. + **kwargs (Any): Additional keyword arguments for the inference method. + + Yields: + (ultralytics.engine.results.Results): Results objects. + """ + if self.args.verbose: + LOGGER.info("") + + # Setup model + if self.model is None: + self.setup_model(model) + if not getattr(self.model, "base_model", True) and ( + unsupported := [k for k in ("augment", "embed", "visualize") if getattr(self.args, k)] + ): + LOGGER.warning(f"{unsupported} not supported by this model (format='{self.model.format}'), ignoring.") + self.args.augment, self.args.embed, self.args.visualize = False, None, False + + with self._lock: # for thread-safe inference + if self.model.format == "pt" and self.model.end2end: + # Class filtering needs candidates before max_det truncation. + self.model.model.set_head_attr(max_det=max(self.args.max_det, 300), agnostic_nms=self.args.agnostic_nms) + # Setup source every time predict is called + self.setup_source(source if source is not None else self.args.source) + + # Check if save_dir/ label file exists + if self.args.save or self.args.save_txt: + (self.save_dir / "labels" if self.args.save_txt else self.save_dir).mkdir(parents=True, exist_ok=True) + + self.seen, self.speed, self.pixels, self.windows, self.batch = 0, None, None, [], None + px = 0 # inference pixels summed per image, so a mixed-shape source averages rather than reports its last + profilers = ( + ops.Profile(device=self.device), + ops.Profile(device=self.device), + ops.Profile(device=self.device), + ) + self.run_callbacks("on_predict_start") + for batch in self.dataset: + self.batch = batch + self.run_callbacks("on_predict_batch_start") + paths, im0s, s = self.batch + + # Preprocess + with profilers[0]: + im = self.preprocess(im0s) + + if not self.done_warmup: + self.model.warmup(im=im) + self.done_warmup = True + + # Inference + with profilers[1]: + preds = self.inference(im, *args, **kwargs) + if self.args.embed: + yield from [preds] if isinstance(preds, torch.Tensor) else preds # yield embedding tensors + continue + + # Postprocess + with profilers[2]: + self.results = self.postprocess(preds, im, im0s) + self.run_callbacks("on_predict_postprocess_end") + + # Visualize, save, write results + n = len(im0s) + try: + for i in range(n): + self.seen += 1 + px += im.shape[2] * im.shape[3] + self.results[i].speed = { + "preprocess": profilers[0].dt * 1e3 / n, + "inference": profilers[1].dt * 1e3 / n, + "postprocess": profilers[2].dt * 1e3 / n, + } + if ( + self.args.verbose + or self.args.save + or self.args.save_txt + or self.args.save_crop + or self.args.show + ): + s[i] += self.write_results(i, Path(paths[i]), im, s) + except StopIteration: + break + + # Print batch results + if self.args.verbose: + LOGGER.info("\n".join(s)) + + self.run_callbacks("on_predict_batch_end") + yield from self.results + + # Final results, under the lock: seen is reset by every run, so reading it outside could divide this run's + # profilers by a concurrent run's count. px and profilers are locals and are already private to this run. + if seen := self.seen: + t = tuple(x.t / seen * 1e3 for x in profilers) # speeds per image + self.speed = dict(zip(("preprocess", "inference", "postprocess"), t)) + self.pixels = round(px / seen) # mean area, pairing with speeds that are themselves per-image means + if self.args.verbose: + LOGGER.info( + f"Speed: %.1fms preprocess, %.1fms inference, %.1fms postprocess per image at shape " + f"{(min(self.args.batch, seen), getattr(self.model, 'channels', 3), *im.shape[2:])}" % t + ) + + # Release assets + for v in self.vid_writer.values(): + if isinstance(v, cv2.VideoWriter): + v.release() + + if self.args.show: + cv2.destroyAllWindows() # close any open windows + + if self.args.save or self.args.save_txt or self.args.save_crop: + nl = len(list(self.save_dir.glob("labels/*.txt"))) # number of labels + s = f"\n{nl} label{'s' * (nl > 1)} saved to {self.save_dir / 'labels'}" if self.args.save_txt else "" + LOGGER.info(f"Results saved to {colorstr('bold', self.save_dir)}{s}") + self.run_callbacks("on_predict_end") + + @smart_inference_mode(False) + def setup_model(self, model, verbose: bool = True): + """Initialize YOLO model with given parameters and set it to evaluation mode. + + Args: + model (str | Path | torch.nn.Module): Model to load or use. + verbose (bool): Whether to print verbose output. + """ + model = deepcopy(model) + self.model = AutoBackend( + model=model or self.args.model, + device=select_device(self.args.device, verbose=verbose), + dnn=self.args.dnn, + data=self.args.data, + fp16=self.args.quantize == 16, + channels_last=self.args.channels_last, + fuse=True, + verbose=verbose, + end2end=self.args.nms is False, + ) + + self.device = self.model.device # update device + self.model.eval() + self.model = attempt_compile(self.model, device=self.device, mode=self.args.compile) + + def write_results(self, i: int, p: Path, im: torch.Tensor, s: list[str]) -> str: + """Write inference results to a file or directory. + + Args: + i (int): Index of the current image in the batch. + p (Path): Path to the current image. + im (torch.Tensor): Preprocessed image tensor. + s (list[str]): List of result strings. + + Returns: + (str): String with result information. + """ + string = "" # print string + if len(im.shape) == 3: + im = im[None] # expand for batch dim + if self.source_type.stream or self.source_type.from_img or self.source_type.tensor: # batch_size >= 1 + string += f"{i}: " + frame = self.dataset.count + else: + match = re.search(r"frame (\d+)/", s[i]) + frame = int(match[1]) if match else None # None if frame undetermined + + self.txt_path = self.save_dir / "labels" / (p.stem + ("" if self.dataset.mode == "image" else f"_{frame}")) + string += "{:g}x{:g} ".format(*im.shape[2:]) + result = self.results[i] + result.save_dir = self.save_dir.__str__() # used in other locations + string += f"{result.verbose()}{result.speed['inference']:.1f}ms" + + # Add predictions to image + if self.args.save or self.args.show: + self.plotted_img = result.plot( + line_width=self.args.line_width, + boxes=self.args.show_boxes, + conf=self.args.show_conf, + labels=self.args.show_labels, + ) + + # Save results + if self.args.save_txt: + result.save_txt(f"{self.txt_path}.txt", save_conf=self.args.save_conf) + if self.args.save_crop: + result.save_crop(save_dir=self.save_dir / "crops", file_name=self.txt_path.stem) + if self.args.show: + self.show(str(p)) + if self.args.save: + self.save_predicted_images(self.save_dir / p.name, frame) + + return string + + def save_predicted_images(self, save_path: Path, frame: int = 0): + """Save video predictions as mp4/avi or images as jpg at specified path. + + Args: + save_path (Path): Path to save the results. + frame (int): Frame number for video mode. + """ + im = self.plotted_img + + # Save videos and streams + if self.dataset.mode in {"stream", "video"}: + fps = self.dataset.fps if self.dataset.mode == "video" else 30 + frames_path = self.save_dir / f"{save_path.stem}_frames" # save frames to a separate directory + if save_path not in self.vid_writer: # new video + if self.args.save_frames: + Path(frames_path).mkdir(parents=True, exist_ok=True) + suffix, fourcc = (".mp4", "avc1") if MACOS else (".avi", "WMV2") if WINDOWS else (".avi", "MJPG") + self.vid_writer[save_path] = cv2.VideoWriter( + filename=str(Path(save_path).with_suffix(suffix)), + fourcc=cv2.VideoWriter_fourcc(*fourcc), + fps=fps, # integer required, floats produce error in MP4 codec + frameSize=(im.shape[1], im.shape[0]), # (width, height) + ) + + # Save video + self.vid_writer[save_path].write(im) + if self.args.save_frames: + cv2.imwrite(f"{frames_path}/{save_path.stem}_{frame}.jpg", im) + + # Save images + else: + cv2.imwrite(str(save_path.with_suffix(".jpg")), im) # save to JPG for best support + + def show(self, p: str = ""): + """Display an image in a window.""" + im = self.plotted_img + if platform.system() in {"Linux", "Windows"} and p not in self.windows: # macOS scales natively + self.windows.append(p) + name = p.encode("unicode_escape").decode() # match patched cv2.imshow window name + cv2.namedWindow(name, cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize and scaling + h, w = im.shape[:2] + try: # size window to fit screen once on creation if image larger than screen resolution + if self.screen is None: + root = __import__("tkinter").Tk() + root.withdraw() # hide the empty Tk window + self.screen = 0.9 * root.winfo_screenwidth(), 0.9 * root.winfo_screenheight() # 0.9 taskbar margin + root.destroy() + r = min(self.screen[0] / w, self.screen[1] / h, 1.0) + cv2.resizeWindow(name, max(1, int(w * r)), max(1, int(h * r))) # (width, height) + except Exception: + cv2.resizeWindow(name, w, h) + cv2.imshow(p, im) + if cv2.waitKey(300 if self.dataset.mode == "image" else 1) & 0xFF == ord("q"): # 300ms if image; else 1ms + raise StopIteration + + def run_callbacks(self, event: str): + """Run all registered callbacks for a specific event.""" + for callback in self.callbacks.get(event, []): + callback(self) + + def add_callback(self, event: str, func: Callable): + """Add a callback function for a specific event.""" + self.callbacks[event].append(func) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/results.py b/.venv/lib/python3.12/site-packages/ultralytics/engine/results.py new file mode 100644 index 0000000000000000000000000000000000000000..e5aeb10a14195eb2f955a8b6a0badc25b628949e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/engine/results.py @@ -0,0 +1,1629 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Ultralytics Results, Boxes, Masks, SemanticMask, Keypoints, Probs, and OBB classes for handling inference results. + +Usage: See https://docs.ultralytics.com/modes/predict +""" + +from __future__ import annotations + +from copy import deepcopy +from functools import cached_property +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from ultralytics.utils import LOGGER, DataExportMixin, SimpleClass, ops +from ultralytics.utils.plotting import Annotator, colors, save_one_box + + +class BaseTensor(SimpleClass): + """Base tensor class with additional methods for easy manipulation and device handling. + + This class provides a foundation for tensor-like objects with device management capabilities, supporting both + PyTorch tensors and NumPy arrays. It includes methods for moving data between devices and converting between tensor + types. + + Attributes: + data (torch.Tensor | np.ndarray): Prediction data such as bounding boxes, masks, or keypoints. + orig_shape (tuple[int, int]): Original shape of the image, typically in the format (height, width). + + Methods: + cpu: Return a copy of the tensor stored in CPU memory. + numpy: Return a copy of the tensor as a numpy array. + cuda: Move the tensor to GPU memory, returning a new instance if necessary. + to: Return a copy of the tensor with the specified device and dtype. + + Examples: + >>> import torch + >>> data = torch.tensor([[1, 2, 3], [4, 5, 6]]) + >>> orig_shape = (720, 1280) + >>> base_tensor = BaseTensor(data, orig_shape) + >>> cpu_tensor = base_tensor.cpu() + >>> numpy_array = base_tensor.numpy() + >>> gpu_tensor = base_tensor.cuda() + """ + + def __init__(self, data: torch.Tensor | np.ndarray, orig_shape: tuple[int, int]) -> None: + """Initialize BaseTensor with prediction data and the original shape of the image. + + Args: + data (torch.Tensor | np.ndarray): Prediction data such as bounding boxes, masks, or keypoints. + orig_shape (tuple[int, int]): Original shape of the image in (height, width) format. + """ + assert isinstance(data, (torch.Tensor, np.ndarray)), "data must be torch.Tensor or np.ndarray" + self.data = data + self.orig_shape = orig_shape + + @property + def shape(self) -> tuple[int, ...]: + """Return the shape of the underlying data tensor. + + Returns: + (tuple[int, ...]): The shape of the data tensor. + + Examples: + >>> data = torch.rand(100, 4) + >>> base_tensor = BaseTensor(data, orig_shape=(720, 1280)) + >>> print(base_tensor.shape) + torch.Size([100, 4]) + """ + return self.data.shape + + def cpu(self): + """Return a copy of the tensor stored in CPU memory. + + Returns: + (BaseTensor): A new BaseTensor object with the data tensor moved to CPU memory. + + Examples: + >>> data = torch.tensor([[1, 2, 3], [4, 5, 6]]).cuda() + >>> base_tensor = BaseTensor(data, orig_shape=(720, 1280)) + >>> cpu_tensor = base_tensor.cpu() + >>> isinstance(cpu_tensor, BaseTensor) + True + >>> cpu_tensor.data.device + device(type='cpu') + """ + return self if isinstance(self.data, np.ndarray) else self.__class__(self.data.cpu(), self.orig_shape) + + def numpy(self): + """Return a copy of this object with its data converted to a NumPy array. + + Returns: + (BaseTensor): A new instance with `data` as a NumPy array. + + Examples: + >>> data = torch.tensor([[1, 2, 3], [4, 5, 6]]) + >>> orig_shape = (720, 1280) + >>> base_tensor = BaseTensor(data, orig_shape) + >>> numpy_tensor = base_tensor.numpy() + >>> print(type(numpy_tensor.data)) + + """ + return self if isinstance(self.data, np.ndarray) else self.__class__(self.data.cpu().numpy(), self.orig_shape) + + def cuda(self): + """Move the tensor to GPU memory. + + Returns: + (BaseTensor): A new BaseTensor instance with the data moved to GPU memory. + + Examples: + >>> import torch + >>> from ultralytics.engine.results import BaseTensor + >>> data = torch.tensor([[1, 2, 3], [4, 5, 6]]) + >>> base_tensor = BaseTensor(data, orig_shape=(720, 1280)) + >>> gpu_tensor = base_tensor.cuda() + >>> print(gpu_tensor.data.device) + cuda:0 + """ + return self.__class__(torch.as_tensor(self.data).cuda(), self.orig_shape) + + def to(self, *args, **kwargs): + """Return a copy of the tensor with the specified device and dtype. + + Args: + *args (Any): Variable length argument list to be passed to torch.Tensor.to(). + **kwargs (Any): Arbitrary keyword arguments to be passed to torch.Tensor.to(). + + Returns: + (BaseTensor): A new BaseTensor instance with the data moved to the specified device and/or dtype. + + Examples: + >>> base_tensor = BaseTensor(torch.randn(3, 4), orig_shape=(480, 640)) + >>> cuda_tensor = base_tensor.to("cuda") + >>> float16_tensor = base_tensor.to(dtype=torch.float16) + """ + return self.__class__(torch.as_tensor(self.data).to(*args, **kwargs), self.orig_shape) + + def __len__(self) -> int: + """Return the length of the underlying data tensor. + + Returns: + (int): The number of elements in the first dimension of the data tensor. + + Examples: + >>> data = torch.tensor([[1, 2, 3], [4, 5, 6]]) + >>> base_tensor = BaseTensor(data, orig_shape=(720, 1280)) + >>> len(base_tensor) + 2 + """ + return len(self.data) + + def __getitem__(self, idx): + """Return a new BaseTensor instance containing the specified indexed elements of the data tensor. + + Args: + idx (int | list[int] | torch.Tensor): Index or indices to select from the data tensor. + + Returns: + (BaseTensor): A new BaseTensor instance containing the indexed data. + + Examples: + >>> data = torch.tensor([[1, 2, 3], [4, 5, 6]]) + >>> base_tensor = BaseTensor(data, orig_shape=(720, 1280)) + >>> result = base_tensor[0] # Select the first row + >>> print(result.data) + tensor([1, 2, 3]) + """ + return self.__class__(self.data[idx], self.orig_shape) + + +class _DenseResultTensor(BaseTensor): + """A BaseTensor representing zero or one dense per-image result, immune to row-wise indexing.""" + + def __len__(self) -> int: + """Return 1 if the map holds data, 0 if a prior indexing emptied it.""" + return int(self.data.shape[0] > 0) + + def __getitem__(self, idx): + """Return the intact map for any index selecting the one result, or an emptied map for an empty selection.""" + idx = idx.cpu().numpy() if isinstance(idx, torch.Tensor) else idx # NumPy reads a raw bool tensor as an int + empty = np.size(np.arange(len(self))[idx]) == 0 # bounds-checks idx of any type against the logical length + return self.__class__(self.data[:0] if empty else self.data, self.orig_shape) + + +class SemanticMask(_DenseResultTensor): + """Semantic segmentation class map for one image.""" + + +class DepthMap(_DenseResultTensor): + """Per-pixel depth map (meters) for one image, shape (H, W).""" + + +class Results(SimpleClass, DataExportMixin): + """A class for storing and manipulating inference results. + + This class provides comprehensive functionality for handling inference results from various Ultralytics models, + including detection, instance segmentation, semantic segmentation, depth estimation, classification, pose + estimation, and oriented bounding box detection. It supports visualization, data export, and various coordinate + transformations. + + Attributes: + orig_img (np.ndarray): The original image as a numpy array. + orig_shape (tuple[int, int]): Original image shape in (height, width) format. + boxes (Boxes | None): Detected bounding boxes. + masks (Masks | None): Segmentation masks. + probs (Probs | None): Classification probabilities. + keypoints (Keypoints | None): Detected keypoints. + obb (OBB | None): Oriented bounding boxes. + semantic_mask (SemanticMask | None): Semantic segmentation class map. + depth (DepthMap | None): Per-pixel depth map. + speed (dict): Dictionary containing inference speed information. + names (dict): Dictionary mapping class indices to class names. + path (str): Path to the input image file. + save_dir (str | None): Directory to save results. + + Methods: + update: Update the Results object with new detection data. + cpu: Return a copy of the Results object with all tensors moved to CPU memory. + numpy: Convert all tensors in the Results object to numpy arrays. + cuda: Move all tensors in the Results object to GPU memory. + to: Move all tensors to the specified device and dtype. + new: Create a new Results object with the same image, path, names, and speed attributes. + plot: Plot detection results on an input BGR image. + show: Display the image with annotated inference results. + save: Save annotated inference results image to file. + verbose: Return a log string for each task in the results. + save_txt: Save detection results to a text file. + save_crop: Save cropped detection images to specified directory. + summary: Convert inference results to a summarized dictionary. + to_df: Convert detection results to a Polars DataFrame. + to_json: Convert detection results to JSON format. + to_csv: Convert detection results to a CSV format. + + Examples: + >>> results = model("path/to/image.jpg") + >>> result = results[0] # Get the first result + >>> boxes = result.boxes # Get the boxes for the first result + >>> masks = result.masks # Get the masks for the first result + >>> for result in results: + ... result.plot() # Plot detection results + """ + + def __init__( + self, + orig_img: np.ndarray, + path: str, + names: dict[int, str], + boxes: torch.Tensor | None = None, + masks: torch.Tensor | None = None, + probs: torch.Tensor | None = None, + keypoints: torch.Tensor | None = None, + obb: torch.Tensor | None = None, + speed: dict[str, float] | None = None, + semantic_mask: torch.Tensor | None = None, + depth: torch.Tensor | None = None, + ) -> None: + """Initialize the Results class for storing and manipulating inference results. + + Args: + orig_img (np.ndarray): The original image as a numpy array. + path (str): The path to the image file. + names (dict): A dictionary of class names. + boxes (torch.Tensor | None): A 2D tensor of bounding box coordinates for each detection. + masks (torch.Tensor | None): A 3D tensor of detection masks, where each mask is a binary image. + probs (torch.Tensor | None): A 1D tensor of probabilities of each class for classification task. + keypoints (torch.Tensor | None): A 2D tensor of keypoint coordinates for each detection. + obb (torch.Tensor | None): A 2D tensor of oriented bounding box coordinates for each detection. + semantic_mask (torch.Tensor | None): A 2D tensor of class IDs for semantic segmentation results. + depth (torch.Tensor | None): A 2D float tensor of per-pixel depth values (H, W). + speed (dict | None): A dictionary containing preprocess, inference, and postprocess speeds (ms/image). + + Notes: + For the default pose model, keypoint indices for human body pose estimation are: + 0: Nose, 1: Left Eye, 2: Right Eye, 3: Left Ear, 4: Right Ear + 5: Left Shoulder, 6: Right Shoulder, 7: Left Elbow, 8: Right Elbow + 9: Left Wrist, 10: Right Wrist, 11: Left Hip, 12: Right Hip + 13: Left Knee, 14: Right Knee, 15: Left Ankle, 16: Right Ankle + """ + self.orig_img = orig_img + self.orig_shape = orig_img.shape[:2] + self.boxes = Boxes(boxes, self.orig_shape) if boxes is not None else None # native size boxes + self.masks = Masks(masks, self.orig_shape) if masks is not None else None # native size or imgsz masks + self.probs = Probs(probs) if probs is not None else None + self.keypoints = Keypoints(keypoints, self.orig_shape) if keypoints is not None else None + self.obb = OBB(obb, self.orig_shape) if obb is not None else None + self.semantic_mask = SemanticMask(semantic_mask, self.orig_shape) if semantic_mask is not None else None + self.depth = DepthMap(depth, self.orig_shape) if depth is not None else None + self.speed = speed if speed is not None else {"preprocess": None, "inference": None, "postprocess": None} + self.names = names + self.path = path + self.save_dir = None + self._keys = "boxes", "masks", "probs", "keypoints", "obb", "semantic_mask", "depth" + + def __getitem__(self, idx): + """Return a Results object for a specific index of inference results. + + Args: + idx (int | slice): Index or slice to retrieve from the Results object. + + Returns: + (Results): A new Results object containing the specified subset of inference results. + + Examples: + >>> results = model("path/to/image.jpg") # Perform inference + >>> single_result = results[0] # Get the first result + >>> subset_results = results[1:4] # Get a slice of results + """ + return self._apply("__getitem__", idx) + + def __len__(self) -> int: + """Return the number of results in the Results object. + + Returns: + (int): The number of results, determined by the length of the first non-empty attribute in (boxes, masks, + probs, keypoints, obb, semantic_mask, or depth). Empty Results objects return 0. + + Examples: + >>> results = Results(orig_img, path, names, boxes=torch.rand(5, 6)) + >>> len(results) + 5 + """ + for k in self._keys: + v = getattr(self, k) + if v is not None: + return len(v) + return 0 + + def update( + self, + boxes: torch.Tensor | None = None, + masks: torch.Tensor | None = None, + probs: torch.Tensor | None = None, + obb: torch.Tensor | None = None, + keypoints: torch.Tensor | None = None, + semantic_mask: torch.Tensor | None = None, + depth: torch.Tensor | None = None, + ): + """Update the Results object with new detection data. + + This method allows updating the boxes, masks, keypoints, probabilities, and oriented bounding boxes (OBB) of + the Results object. It ensures that boxes are clipped to the original image shape. + + Args: + boxes (torch.Tensor | None): A tensor of shape (N, 6) containing bounding box coordinates and confidence + scores. The format is (x1, y1, x2, y2, conf, class). + masks (torch.Tensor | None): A tensor of shape (N, H, W) containing segmentation masks. + probs (torch.Tensor | None): A tensor of shape (num_classes,) containing class probabilities. + obb (torch.Tensor | None): A tensor of shape (N, 7) or (N, 8) containing oriented bounding box coordinates. + keypoints (torch.Tensor | None): A tensor of shape (N, K, 3) containing keypoints, where K=17 for persons. + semantic_mask (torch.Tensor | None): A tensor of shape (H, W) containing class IDs for semantic + segmentation. + depth (torch.Tensor | None): A tensor of shape (H, W) containing per-pixel depth values. + + Examples: + >>> results = model("image.jpg") + >>> new_boxes = torch.tensor([[100, 100, 200, 200, 0.9, 0]]) + >>> results[0].update(boxes=new_boxes) + """ + if boxes is not None: + self.boxes = Boxes(ops.clip_boxes(boxes, self.orig_shape), self.orig_shape) + if masks is not None: + self.masks = Masks(masks, self.orig_shape) + if probs is not None: + self.probs = Probs(probs) + if obb is not None: + self.obb = OBB(obb, self.orig_shape) + if keypoints is not None: + self.keypoints = Keypoints(keypoints, self.orig_shape) + if semantic_mask is not None: + self.semantic_mask = SemanticMask(semantic_mask, self.orig_shape) + if depth is not None: + self.depth = DepthMap(depth, self.orig_shape) + + def _apply(self, fn: str, *args, **kwargs): + """Apply a function to all non-empty attributes and return a new Results object with modified attributes. + + This method is internally called by methods like .to(), .cuda(), .cpu(), etc. + + Args: + fn (str): The name of the function to apply. + *args (Any): Variable length argument list to pass to the function. + **kwargs (Any): Arbitrary keyword arguments to pass to the function. + + Returns: + (Results): A new Results object with attributes modified by the applied function. + + Examples: + >>> results = model("path/to/image.jpg") + >>> for result in results: + ... result_cuda = result.cuda() + ... result_cpu = result.cpu() + """ + r = self.new() + for k in self._keys: + v = getattr(self, k) + if v is None: + continue + setattr(r, k, getattr(v, fn)(*args, **kwargs)) + return r + + def cpu(self): + """Return a copy of the Results object with all its tensors moved to CPU memory. + + This method creates a new Results object with all tensor attributes (boxes, masks, probs, keypoints, obb) + transferred to CPU memory. It's useful for moving data from GPU to CPU for further processing or saving. + + Returns: + (Results): A new Results object with all tensor attributes on CPU memory. + + Examples: + >>> results = model("path/to/image.jpg") # Perform inference + >>> cpu_result = results[0].cpu() # Move the first result to CPU + >>> print(cpu_result.boxes.device) # Output: cpu + """ + return self._apply("cpu") + + def numpy(self): + """Convert all tensors in the Results object to numpy arrays. + + Returns: + (Results): A new Results object with all tensors converted to numpy arrays. + + Examples: + >>> results = model("path/to/image.jpg") + >>> numpy_result = results[0].numpy() + >>> type(numpy_result.boxes.data) + + + Notes: + This method creates a new Results object, leaving the original unchanged. It's useful for + interoperability with numpy-based libraries or when CPU-based operations are required. + """ + return self._apply("numpy") + + def cuda(self): + """Move all tensors in the Results object to GPU memory. + + Returns: + (Results): A new Results object with all tensors moved to CUDA device. + + Examples: + >>> results = model("path/to/image.jpg") + >>> cuda_results = results[0].cuda() # Move first result to GPU + >>> for result in results: + ... result_cuda = result.cuda() # Move each result to GPU + """ + return self._apply("cuda") + + def to(self, *args, **kwargs): + """Move all tensors in the Results object to the specified device and dtype. + + Args: + *args (Any): Variable length argument list to be passed to torch.Tensor.to(). + **kwargs (Any): Arbitrary keyword arguments to be passed to torch.Tensor.to(). + + Returns: + (Results): A new Results object with all tensors moved to the specified device and dtype. + + Examples: + >>> results = model("path/to/image.jpg") + >>> result_cuda = results[0].to("cuda") # Move first result to GPU + >>> result_cpu = results[0].to("cpu") # Move first result to CPU + >>> result_half = results[0].to(dtype=torch.float16) # Convert first result to half precision + """ + return self._apply("to", *args, **kwargs) + + def new(self): + """Create a new Results object with the same image, path, names, speed, and save directory attributes. + + Returns: + (Results): A new Results object with copied attributes from the original instance. + + Examples: + >>> results = model("path/to/image.jpg") + >>> new_result = results[0].new() + """ + result = Results(orig_img=self.orig_img, path=self.path, names=self.names, speed=self.speed) + result.save_dir = self.save_dir + return result + + def plot( + self, + conf: bool = True, + line_width: float | None = None, + font_size: float | None = None, + font: str = "Arial.ttf", + pil: bool = False, + img: np.ndarray | torch.Tensor | None = None, + kpt_radius: int = 5, + kpt_line: bool = True, + labels: bool = True, + boxes: bool = True, + masks: bool = True, + probs: bool = True, + show: bool = False, + save: bool = False, + filename: str | None = None, + color_mode: str = "class", + txt_color: tuple[int, int, int] = (255, 255, 255), + ) -> np.ndarray: + """Plot detection results on an input BGR image. + + Args: + conf (bool): Whether to plot detection confidence scores. + line_width (float | None): Line width of bounding boxes. If None, scaled to image size. + font_size (float | None): Font size for text. If None, scaled to image size. + font (str): Font to use for text. + pil (bool): Whether to return the image as a PIL Image. + img (np.ndarray | torch.Tensor | None): Image to plot on. Tensor images must be contiguous HWC BGR uint8. If + None, uses the original image. + kpt_radius (int): Radius of drawn keypoints. + kpt_line (bool): Whether to draw lines connecting keypoints. + labels (bool): Whether to plot labels of bounding boxes. + boxes (bool): Whether to plot bounding boxes. + masks (bool): Whether to plot masks. + probs (bool): Whether to plot classification probabilities. + show (bool): Whether to display the annotated image. + save (bool): Whether to save the annotated image. + filename (str | None): Filename to save image if save is True. + color_mode (str): Specify the color mode, e.g., 'instance' or 'class'. + txt_color (tuple[int, int, int]): Text color in BGR format for classification output. + + Returns: + (np.ndarray | PIL.Image.Image): Annotated image as a NumPy array (BGR) or PIL image (RGB) if `pil=True`. + + Examples: + >>> results = model("image.jpg") + >>> for result in results: + ... im = result.plot(pil=True) + ... im.show() + """ + assert color_mode in {"instance", "class"}, f"Expected color_mode='instance' or 'class', not {color_mode}." + if img is None and isinstance(self.orig_img, torch.Tensor): + img = (self.orig_img[0].detach().permute(1, 2, 0).contiguous() * 255).byte().cpu().numpy() + + names = self.names + is_obb = self.obb is not None + pred_boxes, show_boxes = self.obb if is_obb else self.boxes, boxes + pred_masks, show_masks = self.masks, masks + pred_probs, show_probs = self.probs, probs + if pred_boxes is not None and (show_boxes or (pred_masks and show_masks)): + pred_boxes = pred_boxes.cpu() # one host transfer avoids per-box GPU syncs in the color and label loops + annotator = Annotator( + deepcopy(self.orig_img if img is None else img), + line_width, + font_size, + font, + pil or (pred_probs is not None and show_probs), # Classify tasks default to pil=True + example=names, + ) + + # Plot Segment results + if pred_masks and show_masks: + pred_mask_data = torch.as_tensor(pred_masks.data) # no-op for torch, converts a numpy() result + idx = ( + pred_boxes.id + if pred_boxes and pred_boxes.is_track and color_mode == "instance" + else pred_boxes.cls + if pred_boxes and color_mode == "class" + else reversed(range(len(pred_masks))) + ) + annotator.masks(pred_mask_data, colors=[colors(x, True) for x in idx]) + + # Plot Detect results + if pred_boxes is not None and show_boxes: + coords = pred_boxes.xyxyxyxy if is_obb else pred_boxes.xyxy + for i, (d, box) in enumerate(zip(reversed(pred_boxes), reversed(coords))): + c = int(d.cls.item()) # .item() works for torch and numpy alike; int()/float() need 0-d since numpy 2.4 + d_conf, id = float(d.conf.item()) if conf else None, int(d.id.item()) if d.is_track else None + name = ("" if id is None else f"id:{id} ") + names[c] + label = (f"{name} {d_conf:.2f}" if conf else name) if labels else (f"{d_conf:.2f}" if conf else None) + annotator.box_label( + box, + label, + color=colors( + c + if color_mode == "class" + else id + if id is not None + else i + if color_mode == "instance" + else None, + True, + ), + ) + + # Plot Classify results + if pred_probs is not None and show_probs: + text = "\n".join(f"{names[j] if names else j} {pred_probs.data[j]:.2f}" for j in pred_probs.top5) + x = round(self.orig_shape[0] * 0.03) + annotator.text([x, x], text, txt_color=txt_color, box_color=(64, 64, 64, 128)) # RGBA box + + # Plot Semantic Segmentation results + if self.semantic_mask and show_masks: + sem_mask = self.semantic_mask.data + if isinstance(sem_mask, torch.Tensor): + sem_mask = sem_mask.cpu().numpy() + annotator.semantic_mask(sem_mask, alpha=0.5) + + # Plot Depth results — blend colorized depth heatmap over the image + if self.depth and show_masks: + d = self.depth.data + d = d.cpu().numpy() if hasattr(d, "cpu") else np.asarray(d) + annotator.depth_map(d) + + # Plot Pose results + if self.keypoints is not None: + for i, k in enumerate(reversed(self.keypoints.cpu().numpy().data)): # one host transfer, no per-kpt syncs + annotator.kpts( + k, + self.orig_shape, + radius=kpt_radius, + kpt_line=kpt_line, + kpt_color=colors(i, True) if color_mode == "instance" else None, + ) + + # Show results + if show: + annotator.show(self.path) + + # Save results + if save: + annotator.save(filename or f"results_{Path(self.path).name}") + + return annotator.result(pil) + + def show(self, *args, **kwargs): + """Display the image with annotated inference results. + + This method plots the detection results on the original image and displays it. It's a convenient way to + visualize the model's predictions directly. + + Args: + *args (Any): Variable length argument list to be passed to the `plot()` method. + **kwargs (Any): Arbitrary keyword arguments to be passed to the `plot()` method. + + Examples: + >>> results = model("path/to/image.jpg") + >>> results[0].show() # Display the first result + >>> for result in results: + ... result.show() # Display all results + """ + self.plot(*args, show=True, **kwargs) + + def save(self, filename: str | None = None, *args, **kwargs) -> str: + """Save annotated inference results image to file. + + This method plots the detection results on the original image and saves the annotated image to a file. It + utilizes the `plot` method to generate the annotated image and then saves it to the specified filename. + + Args: + filename (str | None): The filename to save the annotated image. If None, a default filename is generated + based on the original image path. + *args (Any): Variable length argument list to be passed to the `plot` method. + **kwargs (Any): Arbitrary keyword arguments to be passed to the `plot` method. + + Returns: + (str): The filename where the image was saved. + + Examples: + >>> results = model("path/to/image.jpg") + >>> for result in results: + ... result.save("annotated_image.jpg") + >>> # Or with custom plot arguments + >>> for result in results: + ... result.save("annotated_image.jpg", conf=False, line_width=2) + >>> # Directory will be created automatically if it does not exist + >>> result.save("path/to/annotated_image.jpg") + """ + if not filename: + filename = f"results_{Path(self.path).name}" + Path(filename).absolute().parent.mkdir(parents=True, exist_ok=True) + self.plot(*args, save=True, filename=filename, **kwargs) + return filename + + def verbose(self) -> str: + """Return a log string for each task in the results, detailing detection and classification outcomes. + + This method generates a human-readable string summarizing the detection and classification results. It includes + the number of detections for each class and the top probabilities for classification tasks. + + Returns: + (str): A formatted string containing a summary of the results. For detection tasks, it includes the number + of detections per class. For classification tasks, it includes the top 5 class probabilities. + + Examples: + >>> results = model("path/to/image.jpg") + >>> for result in results: + ... print(result.verbose()) + 2 persons, 1 car, 3 traffic lights, + dog 0.92, cat 0.78, horse 0.64, + + Notes: + - If there are no detections, the method returns "(no detections), " for detection tasks. + - For classification tasks, it returns the top 5 class probabilities and their corresponding class names. + - The returned string is comma-separated and ends with a comma and a space. + """ + boxes = self.obb if self.obb is not None else self.boxes + if len(self) == 0: + return "" if self.probs is not None else "(no detections), " + if self.probs is not None: + return f"{', '.join(f'{self.names[j]} {self.probs.data[j]:.2f}' for j in self.probs.top5)}, " + if boxes: + counts = torch.as_tensor(boxes.cls, dtype=torch.int64).bincount() # no-op for torch, converts numpy() + return "".join(f"{n} {self.names[i]}{'s' * (n > 1)}, " for i, n in enumerate(counts) if n > 0) + if self.depth is not None: + d = self.depth.data + d = d[d > 0] + return f"depth {float(d.min()):.2f}-{float(d.max()):.2f}m, " if len(d) else "depth (no valid pixels), " + if self.semantic_mask is not None: + return "" + + def save_txt(self, txt_file: str | Path, save_conf: bool = False) -> str: + """Save detection results to a text file. + + Args: + txt_file (str | Path): Path to the output text file. + save_conf (bool): Whether to include confidence scores in the output. + + Returns: + (str): Path to the saved text file. + + Examples: + >>> from ultralytics import YOLO + >>> model = YOLO("yolo26n.pt") + >>> results = model("path/to/image.jpg") + >>> for result in results: + ... result.save_txt("output.txt") + + Notes: + - The file will contain one line per detection or classification with the following structure: + - For detections: `class x_center y_center width height [confidence] [track_id]` + - For classifications: `confidence class_name` + - For masks and keypoints, the specific formats will vary accordingly. + - A detection whose mask contour has fewer than 3 points is omitted, since a shorter row is not a + polygon, and no file is written when no line remains. + - The function will create the output directory if it does not exist. + - If save_conf is False, the confidence scores will be excluded from the output. + - Existing contents of the file will not be overwritten; new results will be appended. + - This method does not support Semantic Segmentation tasks. + """ + if self.semantic_mask is not None: + LOGGER.warning("Semantic Segmentation task does not support `save_txt`.") + return str(txt_file) + is_obb = self.obb is not None + boxes = self.obb if is_obb else self.boxes + masks = self.masks + probs = self.probs + kpts = self.keypoints + texts = [] + if probs is not None: + # Classify + [texts.append(f"{probs.data[j]:.2f} {self.names[j]}") for j in probs.top5] + elif boxes: + # Detect/segment/pose + boxes = boxes.cpu() # one host transfer avoids per-box GPU syncs in the loop below + coords = (boxes.xyxyxyxyn if is_obb else boxes.xywhn).reshape(len(boxes), -1).tolist() + if kpts is not None: + kpts = kpts.cpu() + keypoints = kpts.xyn + if kpts.has_visible: + keypoints = torch.cat((torch.as_tensor(keypoints), torch.as_tensor(kpts.conf)[..., None]), 2) + keypoints = keypoints.reshape(len(kpts), -1).tolist() + segments = masks.xyn if masks else None + for j, d in enumerate(boxes): + c, conf, id = int(d.cls.item()), float(d.conf.item()), int(d.id.item()) if d.is_track else None + line = (c, *coords[j]) + if segments is not None: + seg = segments[j] + if len(seg) < 3: # fewer than 3 points is not a polygon, and writes a row no loader accepts + continue + line = (c, *seg.copy().reshape(-1)) # reversed mask.xyn, (n,2) to (n*2) + if kpts is not None: + line += (*keypoints[j],) + line += (conf,) * save_conf + (() if id is None else (id,)) + texts.append(("%g " * len(line)).rstrip() % line) + + if texts: + Path(txt_file).parent.mkdir(parents=True, exist_ok=True) # make directory + with open(txt_file, "a", encoding="utf-8") as f: + f.writelines(text + "\n" for text in texts) + + return str(txt_file) + + def save_crop(self, save_dir: str | Path, file_name: str | Path = Path("im.jpg")): + """Save cropped detection images to specified directory. + + This method saves cropped images of detected objects to a specified directory. Each crop is saved in a + subdirectory named after the object's class, with the filename based on the input file_name. + + Args: + save_dir (str | Path): Directory path where cropped images will be saved. + file_name (str | Path): Base filename for the saved cropped images. + + Examples: + >>> results = model("path/to/image.jpg") + >>> for result in results: + ... result.save_crop(save_dir="path/to/crops", file_name="detection") + + Notes: + - This method does not support Classify, Oriented Bounding Box (OBB), or Semantic Segmentation tasks. + - Crops are saved as 'save_dir/class_name/file_name.jpg'. + - The method will create necessary subdirectories if they don't exist. + - Original image is copied before cropping to avoid modifying the original. + """ + if self.probs is not None: + LOGGER.warning("Classify task does not support `save_crop`.") + return + if self.obb is not None: + LOGGER.warning("OBB task does not support `save_crop`.") + return + if self.semantic_mask is not None: + LOGGER.warning("Semantic Segmentation task does not support `save_crop`.") + return + if self.depth is not None: + LOGGER.warning("Depth task does not support `save_crop`.") + return + for d in self.boxes.cpu(): # one host transfer avoids per-box GPU syncs in the loop below + save_one_box( + d.xyxy, + self.orig_img.copy(), + file=Path(save_dir) / self.names[int(d.cls.item())] / Path(file_name).with_suffix(".jpg"), + BGR=True, + ) + + def summary(self, normalize: bool = False, decimals: int = 5) -> list[dict[str, Any]]: + """Convert inference results to a summarized dictionary with optional normalization for box coordinates. + + This method creates a list of detection dictionaries, each containing information about a single detection or + classification result. For classification tasks, it returns the top 5 classes and their + confidences. For detection tasks, it includes class information, bounding box coordinates, and + optionally mask segments and keypoints. + + Args: + normalize (bool): Whether to normalize bounding box coordinates by image dimensions. + decimals (int): Number of decimal places to round the output values to. + + Returns: + (list[dict[str, Any]]): A list of dictionaries, each containing summarized information for a single + detection or classification result. The structure of each dictionary varies based on the task type + (classification or detection) and available information (boxes, masks, keypoints). + + Examples: + >>> results = model("image.jpg") + >>> for result in results: + ... summary = result.summary() + ... print(summary) + """ + # Create list of detection dictionaries + results = [] + if self.probs is not None: + # Return top 5 classification results + for class_id, conf in zip(self.probs.top5, self.probs.top5conf.tolist()): + class_id = int(class_id) + results.append( + { + "name": self.names[class_id], + "class": class_id, + "confidence": round(conf, decimals), + } + ) + return results + + if self.semantic_mask is not None: + # Return per-class pixel coverage for semantic segmentation + mask = self.semantic_mask.data + if isinstance(mask, torch.Tensor): + mask = mask.cpu().numpy() + unique, counts = np.unique(mask, return_counts=True) + total = mask.size + for class_id, count in zip(unique.tolist(), counts.tolist()): + if len(self.names) == 1: + if class_id != 1: # skip binary background and ignore label + continue + class_id = 0 + elif class_id not in self.names: # skip ignore label (e.g., 255) + continue + results.append( + { + "name": self.names[class_id], + "class": class_id, + "pixel_ratio": round(count / total, decimals), + } + ) + return results + + if self.depth is not None: + # Depth is a dense per-pixel map, not a per-instance result; excluded from summary. + return results + + is_obb = self.obb is not None + data = self.obb if is_obb else self.boxes + if data: + data = data.cpu() # one host transfer avoids per-row GPU syncs in the loop below + coords = (data.xyxyxyxy if is_obb else data.xyxy).reshape(len(data), -1, 2).tolist() + kpts = self.keypoints + if kpts is not None: + kpts = kpts.cpu() # ditto for the per-row keypoints sync below + h, w = self.orig_shape if normalize else (1, 1) + for i, row in enumerate(data): # xyxy, track_id if tracking, conf, class_id + class_id, conf = int(row.cls.item()), round(row.conf.item(), decimals) + box = coords[i] + xy = {} + for j, b in enumerate(box): + xy[f"x{j + 1}"] = round(b[0] / w, decimals) + xy[f"y{j + 1}"] = round(b[1] / h, decimals) + result = {"name": self.names[class_id], "class": class_id, "confidence": conf, "box": xy} + if data.is_track: + result["track_id"] = int(row.id.item()) # track ID + if self.masks: + result["segments"] = { + "x": (self.masks.xy[i][:, 0] / w).astype(float).round(decimals).tolist(), + "y": (self.masks.xy[i][:, 1] / h).astype(float).round(decimals).tolist(), + } + if kpts is not None: + kpt = kpts[i] + k = kpt.data[0] + k = k.cpu().numpy() if isinstance(k, torch.Tensor) else k + result["keypoints"] = { + "x": (k[:, 0] / w).astype(float).round(decimals).tolist(), + "y": (k[:, 1] / h).astype(float).round(decimals).tolist(), + } + if kpt.has_visible: + result["keypoints"]["visible"] = k[:, 2].astype(float).round(decimals).tolist() + results.append(result) + + return results + + +class Boxes(BaseTensor): + """A class for managing and manipulating detection boxes. + + This class provides comprehensive functionality for handling detection boxes, including their coordinates, + confidence scores, class labels, and optional tracking IDs. It supports various box formats and offers methods for + easy manipulation and conversion between different coordinate systems. + + Attributes: + data (torch.Tensor | np.ndarray): The raw tensor containing detection boxes and associated data. + orig_shape (tuple[int, int]): The original image dimensions (height, width). + is_track (bool): Indicates whether tracking IDs are included in the box data. + xyxy (torch.Tensor | np.ndarray): Boxes in [x1, y1, x2, y2] format. + conf (torch.Tensor | np.ndarray): Confidence scores for each box. + cls (torch.Tensor | np.ndarray): Class labels for each box. + id (torch.Tensor | None): Tracking IDs for each box (if available). + xywh (torch.Tensor | np.ndarray): Boxes in [x, y, width, height] format. + xyxyn (torch.Tensor | np.ndarray): Normalized [x1, y1, x2, y2] boxes relative to orig_shape. + xywhn (torch.Tensor | np.ndarray): Normalized [x, y, width, height] boxes relative to orig_shape. + + Methods: + cpu: Return a copy of the object with all tensors on CPU memory. + numpy: Return a copy of the object with all tensors as numpy arrays. + cuda: Return a copy of the object with all tensors on GPU memory. + to: Return a copy of the object with tensors on specified device and dtype. + + Examples: + >>> import torch + >>> boxes_data = torch.tensor([[100, 50, 150, 100, 0.9, 0], [200, 150, 300, 250, 0.8, 1]]) + >>> orig_shape = (480, 640) # height, width + >>> boxes = Boxes(boxes_data, orig_shape) + >>> print(boxes.xyxy) + >>> print(boxes.conf) + >>> print(boxes.cls) + >>> print(boxes.xywhn) + """ + + def __init__(self, boxes: torch.Tensor | np.ndarray, orig_shape: tuple[int, int]) -> None: + """Initialize the Boxes class with detection box data and the original image shape. + + This class manages detection boxes, providing easy access and manipulation of box coordinates, confidence + scores, class identifiers, and optional tracking IDs. It supports multiple formats for box coordinates, + including both absolute and normalized forms. + + Args: + boxes (torch.Tensor | np.ndarray): A tensor or numpy array with detection boxes of shape (num_boxes, 6) or + (num_boxes, 7). Columns should contain [x1, y1, x2, y2, (optional) track_id, confidence, class]. + orig_shape (tuple[int, int]): The original image shape as (height, width). Used for normalization. + """ + if boxes.ndim == 1: + boxes = boxes[None, :] + n = boxes.shape[-1] + assert n in {6, 7}, f"expected 6 or 7 values but got {n}" # xyxy, track_id, conf, cls + super().__init__(boxes, orig_shape) + self.is_track = n == 7 + self.orig_shape = orig_shape + + @property + def xyxy(self) -> torch.Tensor | np.ndarray: + """Return bounding boxes in [x1, y1, x2, y2] format. + + Returns: + (torch.Tensor | np.ndarray): A tensor or numpy array of shape (n, 4) containing bounding box coordinates in + [x1, y1, x2, y2] format, where n is the number of boxes. + + Examples: + >>> results = model("image.jpg") + >>> boxes = results[0].boxes + >>> xyxy = boxes.xyxy + >>> print(xyxy) + """ + return self.data[:, :4] + + @property + def conf(self) -> torch.Tensor | np.ndarray: + """Return the confidence scores for each detection box. + + Returns: + (torch.Tensor | np.ndarray): A 1D tensor or array containing confidence scores for each detection, with + shape (N,) where N is the number of detections. + + Examples: + >>> boxes = Boxes(torch.tensor([[10, 20, 30, 40, 0.9, 0]]), orig_shape=(100, 100)) + >>> conf_scores = boxes.conf + >>> print(conf_scores) + tensor([0.9000]) + """ + return self.data[:, -2] + + @property + def cls(self) -> torch.Tensor | np.ndarray: + """Return the class ID tensor representing category predictions for each bounding box. + + Returns: + (torch.Tensor | np.ndarray): A tensor or numpy array containing the class IDs for each detection box. The + shape is (N,), where N is the number of boxes. + + Examples: + >>> results = model("image.jpg") + >>> boxes = results[0].boxes + >>> class_ids = boxes.cls + >>> print(class_ids) # tensor([0., 2., 1.]) + """ + return self.data[:, -1] + + @property + def id(self) -> torch.Tensor | np.ndarray | None: + """Return the tracking IDs for each detection box if available. + + Returns: + (torch.Tensor | np.ndarray | None): A tensor or array containing tracking IDs for each box if tracking is + enabled, otherwise None. Shape is (N,) where N is the number of boxes. + + Examples: + >>> results = model.track("path/to/video.mp4") + >>> for result in results: + ... boxes = result.boxes + ... if boxes.is_track: + ... track_ids = boxes.id + ... print(f"Tracking IDs: {track_ids}") + ... else: + ... print("Tracking is not enabled for these boxes.") + + Notes: + - This property is only available when tracking is enabled (i.e., when `is_track` is True). + - The tracking IDs are typically used to associate detections across multiple frames in video analysis. + """ + return self.data[:, -3] if self.is_track else None + + @cached_property + def xywh(self) -> torch.Tensor | np.ndarray: + """Convert bounding boxes from [x1, y1, x2, y2] format to [x, y, width, height] format. + + Returns: + (torch.Tensor | np.ndarray): Boxes in [x_center, y_center, width, height] format, where x_center, y_center + are the coordinates of the center point of the bounding box, width, height are the dimensions of the + bounding box and the shape of the returned tensor is (N, 4), where N is the number of boxes. + + Examples: + >>> boxes = Boxes( + ... torch.tensor([[100, 50, 150, 100, 0.9, 0], [200, 150, 300, 250, 0.8, 1]]), orig_shape=(480, 640) + ... ) + >>> xywh = boxes.xywh + """ + return ops.xyxy2xywh(self.xyxy) + + @cached_property + def xyxyn(self) -> torch.Tensor | np.ndarray: + """Return normalized bounding box coordinates relative to the original image size. + + This property calculates and returns the bounding box coordinates in [x1, y1, x2, y2] format, normalized to the + range [0, 1] based on the original image dimensions. + + Returns: + (torch.Tensor | np.ndarray): Normalized bounding box coordinates with shape (N, 4), where N is the number of + boxes. Each row contains [x1, y1, x2, y2] values normalized to [0, 1]. + + Examples: + >>> boxes = Boxes(torch.tensor([[100, 50, 300, 400, 0.9, 0]]), orig_shape=(480, 640)) + >>> normalized = boxes.xyxyn + >>> print(normalized) + tensor([[0.1562, 0.1042, 0.4688, 0.8333]]) + """ + xyxy = self.xyxy.clone() if isinstance(self.xyxy, torch.Tensor) else np.copy(self.xyxy) + xyxy[..., [0, 2]] /= self.orig_shape[1] + xyxy[..., [1, 3]] /= self.orig_shape[0] + return xyxy + + @cached_property + def xywhn(self) -> torch.Tensor | np.ndarray: + """Return normalized bounding boxes in [x, y, width, height] format. + + This property calculates and returns the normalized bounding box coordinates in the format [x_center, y_center, + width, height], where all values are relative to the original image dimensions. + + Returns: + (torch.Tensor | np.ndarray): Normalized bounding boxes with shape (N, 4), where N is the number of boxes. + Each row contains [x_center, y_center, width, height] values normalized to [0, 1] based on the original + image dimensions. + + Examples: + >>> boxes = Boxes(torch.tensor([[100, 50, 150, 100, 0.9, 0]]), orig_shape=(480, 640)) + >>> normalized = boxes.xywhn + >>> print(normalized) + tensor([[0.1953, 0.1562, 0.0781, 0.1042]]) + """ + xywh = ops.xyxy2xywh(self.xyxy) + xywh[..., [0, 2]] /= self.orig_shape[1] + xywh[..., [1, 3]] /= self.orig_shape[0] + return xywh + + +class Masks(BaseTensor): + """A class for storing and manipulating detection masks. + + This class extends BaseTensor and provides functionality for handling segmentation masks, including methods for + converting between pixel and normalized coordinates. + + Attributes: + data (torch.Tensor | np.ndarray): The raw tensor or array containing mask data. + orig_shape (tuple[int, int]): Original image shape in (height, width) format. + xy (list[np.ndarray]): A list of segments in pixel coordinates. + xyn (list[np.ndarray]): A list of normalized segments. + + Methods: + cpu: Return a copy of the Masks object with the mask tensor on CPU memory. + numpy: Return a copy of the Masks object with the mask tensor as a numpy array. + cuda: Return a copy of the Masks object with the mask tensor on GPU memory. + to: Return a copy of the Masks object with the mask tensor on specified device and dtype. + + Examples: + >>> masks_data = torch.rand(1, 160, 160) + >>> orig_shape = (720, 1280) + >>> masks = Masks(masks_data, orig_shape) + >>> pixel_coords = masks.xy + >>> normalized_coords = masks.xyn + """ + + def __init__(self, masks: torch.Tensor | np.ndarray, orig_shape: tuple[int, int]) -> None: + """Initialize the Masks class with detection mask data and the original image shape. + + Args: + masks (torch.Tensor | np.ndarray): Detection masks with shape (num_masks, height, width). + orig_shape (tuple[int, int]): The original image shape as (height, width). Used for normalization. + """ + if masks.ndim == 2: + masks = masks[None, :] + super().__init__(masks, orig_shape) + + @cached_property + def xyn(self) -> list[np.ndarray]: + """Return normalized xy-coordinates of the segmentation masks. + + This property calculates and caches the normalized xy-coordinates of the segmentation masks. The coordinates are + normalized relative to the original image shape. + + Returns: + (list[np.ndarray]): A list of numpy arrays, where each array contains the normalized xy-coordinates of a + single segmentation mask. Each array has shape (N, 2), where N is the number of points in the + mask contour. + + Examples: + >>> results = model("image.jpg") + >>> masks = results[0].masks + >>> normalized_coords = masks.xyn + >>> print(normalized_coords[0]) # Normalized coordinates of the first mask + """ + return [ + ops.scale_coords(self.data.shape[1:], x, self.orig_shape, normalize=True) + for x in ops.masks2segments(self.data) + ] + + @cached_property + def xy(self) -> list[np.ndarray]: + """Return the [x, y] pixel coordinates for each segment in the mask tensor. + + This property calculates and returns a list of pixel coordinates for each segmentation mask in the Masks object. + The coordinates are scaled to match the original image dimensions. + + Returns: + (list[np.ndarray]): A list of numpy arrays, where each array contains the [x, y] pixel coordinates for a + single segmentation mask. Each array has shape (N, 2), where N is the number of points in the segment. + + Examples: + >>> results = model("image.jpg") + >>> masks = results[0].masks + >>> xy_coords = masks.xy + >>> print(len(xy_coords)) # Number of masks + >>> print(xy_coords[0].shape) # Shape of first mask's coordinates + """ + return [ + ops.scale_coords(self.data.shape[1:], x, self.orig_shape, normalize=False) + for x in ops.masks2segments(self.data) + ] + + +class Keypoints(BaseTensor): + """A class for storing and manipulating detection keypoints. + + This class encapsulates functionality for handling keypoint data, including coordinate manipulation, normalization, + and confidence values. It supports keypoint detection results with optional visibility information. + + Attributes: + data (torch.Tensor): The raw tensor containing keypoint data. + orig_shape (tuple[int, int]): The original image dimensions (height, width). + has_visible (bool): Indicates whether visibility information is available for keypoints. + xy (torch.Tensor): Keypoint coordinates in [x, y] format. + xyn (torch.Tensor): Normalized keypoint coordinates in [x, y] format, relative to orig_shape. + conf (torch.Tensor | None): Confidence values for each keypoint, if available. + + Methods: + cpu: Return a copy of the keypoints tensor on CPU memory. + numpy: Return a copy of the keypoints tensor as a numpy array. + cuda: Return a copy of the keypoints tensor on GPU memory. + to: Return a copy of the keypoints tensor with specified device and dtype. + + Examples: + >>> import torch + >>> from ultralytics.engine.results import Keypoints + >>> keypoints_data = torch.rand(1, 17, 3) # 1 detection, 17 keypoints, (x, y, conf) + >>> orig_shape = (480, 640) # Original image shape (height, width) + >>> keypoints = Keypoints(keypoints_data, orig_shape) + >>> print(keypoints.xy.shape) # Access xy coordinates + >>> print(keypoints.conf) # Access confidence values + >>> keypoints_cpu = keypoints.cpu() # Move keypoints to CPU + """ + + def __init__(self, keypoints: torch.Tensor | np.ndarray, orig_shape: tuple[int, int]) -> None: + """Initialize the Keypoints object with detection keypoints and original image dimensions. + + This method processes the input keypoints tensor, handling both 2D and 3D formats. + + Args: + keypoints (torch.Tensor | np.ndarray): A tensor or array containing keypoint data. Shape can be either: + - (num_objects, num_keypoints, 2) for x, y coordinates only + - (num_objects, num_keypoints, 3) for x, y coordinates and confidence scores + orig_shape (tuple[int, int]): The original image dimensions (height, width). + """ + if keypoints.ndim == 2: + keypoints = keypoints[None, :] + super().__init__(keypoints, orig_shape) + self.has_visible = self.data.shape[-1] == 3 + + @cached_property + def xy(self) -> torch.Tensor | np.ndarray: + """Return x, y coordinates of keypoints. + + Returns: + (torch.Tensor | np.ndarray): A tensor or array containing the x, y coordinates of keypoints with shape (N, + K, 2), where N is the number of detections and K is the number of keypoints per detection. + + Examples: + >>> results = model("image.jpg") + >>> keypoints = results[0].keypoints + >>> xy = keypoints.xy + >>> print(xy.shape) # (N, K, 2) + >>> print(xy[0]) # x, y coordinates of keypoints for first detection + + Notes: + - The returned coordinates are in pixel units relative to the original image dimensions. + - This property uses LRU caching to improve performance on repeated access. + """ + return self.data[..., :2] + + @cached_property + def xyn(self) -> torch.Tensor | np.ndarray: + """Return normalized coordinates (x, y) of keypoints relative to the original image size. + + Returns: + (torch.Tensor | np.ndarray): A tensor or array of shape (N, K, 2) containing normalized keypoint + coordinates, where N is the number of instances, K is the number of keypoints, and the last dimension + contains [x, y] values in the range [0, 1]. + + Examples: + >>> keypoints = Keypoints(torch.rand(1, 17, 2), orig_shape=(480, 640)) + >>> normalized_kpts = keypoints.xyn + >>> print(normalized_kpts.shape) + torch.Size([1, 17, 2]) + """ + xy = self.xy.clone() if isinstance(self.xy, torch.Tensor) else np.copy(self.xy) + xy[..., 0] /= self.orig_shape[1] + xy[..., 1] /= self.orig_shape[0] + return xy + + @cached_property + def conf(self) -> torch.Tensor | np.ndarray | None: + """Return confidence values for each keypoint. + + Returns: + (torch.Tensor | np.ndarray | None): A tensor or array containing confidence scores for each keypoint if + available, otherwise None. Shape is (num_detections, num_keypoints) for batched data or (num_keypoints,) + for single detection. + + Examples: + >>> keypoints = Keypoints(torch.rand(1, 17, 3), orig_shape=(640, 640)) # 1 detection, 17 keypoints + >>> conf = keypoints.conf + >>> print(conf.shape) # torch.Size([1, 17]) + """ + return self.data[..., 2] if self.has_visible else None + + +class Probs(BaseTensor): + """A class for storing and manipulating classification probabilities. + + This class extends BaseTensor and provides methods for accessing and manipulating classification probabilities, + including top-1 and top-5 predictions. + + Attributes: + data (torch.Tensor | np.ndarray): The raw tensor or array containing classification probabilities. + orig_shape (tuple[int, int] | None): The original image shape as (height, width). Not used in this class. + top1 (int): Index of the class with the highest probability. + top5 (list[int]): Indices of the top 5 classes by probability. + top1conf (torch.Tensor | np.ndarray): Confidence score of the top 1 class. + top5conf (torch.Tensor | np.ndarray): Confidence scores of the top 5 classes. + + Methods: + cpu: Return a copy of the probabilities tensor on CPU memory. + numpy: Return a copy of the probabilities tensor as a numpy array. + cuda: Return a copy of the probabilities tensor on GPU memory. + to: Return a copy of the probabilities tensor with specified device and dtype. + + Examples: + >>> probs = torch.tensor([0.1, 0.3, 0.6]) + >>> p = Probs(probs) + >>> print(p.top1) + 2 + >>> print(p.top5) + [2, 1, 0] + >>> print(p.top1conf) + tensor(0.6000) + >>> print(p.top5conf) + tensor([0.6000, 0.3000, 0.1000]) + """ + + def __init__(self, probs: torch.Tensor | np.ndarray, orig_shape: tuple[int, int] | None = None) -> None: + """Initialize the Probs class with classification probabilities. + + This class stores and manages classification probabilities, providing easy access to top predictions and their + confidences. + + Args: + probs (torch.Tensor | np.ndarray): A 1D tensor or array of classification probabilities. + orig_shape (tuple[int, int] | None): The original image shape as (height, width). Not used in this class but + kept for consistency with other result classes. + """ + super().__init__(probs, orig_shape) + + @cached_property + def top1(self) -> int: + """Return the index of the class with the highest probability. + + Returns: + (int): Index of the class with the highest probability. + + Examples: + >>> probs = Probs(torch.tensor([0.1, 0.3, 0.6])) + >>> probs.top1 + 2 + """ + return int(self.data.argmax()) + + @cached_property + def top5(self) -> list[int]: + """Return the indices of the top 5 class probabilities. + + Returns: + (list[int]): A list containing the indices of the top 5 class probabilities, sorted in descending order. + + Examples: + >>> probs = Probs(torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5])) + >>> print(probs.top5) + [4, 3, 2, 1, 0] + """ + return (-self.data).argsort(0)[:5].tolist() # this way works with both torch and numpy. + + @cached_property + def top1conf(self) -> torch.Tensor | np.ndarray: + """Return the confidence score of the highest probability class. + + This property retrieves the confidence score (probability) of the class with the highest predicted probability + from the classification results. + + Returns: + (torch.Tensor | np.ndarray): A tensor containing the confidence score of the top 1 class. + + Examples: + >>> results = model("image.jpg") # classify an image + >>> probs = results[0].probs # get classification probabilities + >>> top1_confidence = probs.top1conf # get confidence of top 1 class + >>> print(f"Top 1 class confidence: {top1_confidence.item():.4f}") + """ + return self.data[self.top1] + + @cached_property + def top5conf(self) -> torch.Tensor | np.ndarray: + """Return confidence scores for the top 5 classification predictions. + + This property retrieves the confidence scores corresponding to the top 5 class probabilities predicted by the + model. It provides a quick way to access the most likely class predictions along with their associated + confidence levels. + + Returns: + (torch.Tensor | np.ndarray): A tensor or array containing the confidence scores for the top 5 predicted + classes, sorted in descending order of probability. + + Examples: + >>> results = model("image.jpg") + >>> probs = results[0].probs + >>> top5_conf = probs.top5conf + >>> print(top5_conf) # Prints confidence scores for top 5 classes + """ + return self.data[self.top5] + + +class OBB(BaseTensor): + """A class for storing and manipulating Oriented Bounding Boxes (OBB). + + This class provides functionality to handle oriented bounding boxes, including conversion between different formats, + normalization, and access to various properties of the boxes. It supports both tracking and non-tracking scenarios. + + Attributes: + data (torch.Tensor): The raw OBB tensor containing box coordinates and associated data. + orig_shape (tuple[int, int]): Original image size as (height, width). + is_track (bool): Indicates whether tracking IDs are included in the box data. + xywhr (torch.Tensor | np.ndarray): Boxes in [x_center, y_center, width, height, rotation] format. + conf (torch.Tensor | np.ndarray): Confidence scores for each box. + cls (torch.Tensor | np.ndarray): Class labels for each box. + id (torch.Tensor | np.ndarray): Tracking IDs for each box, if available. + xyxyxyxy (torch.Tensor | np.ndarray): Boxes in 8-point [x1, y1, x2, y2, x3, y3, x4, y4] format. + xyxyxyxyn (torch.Tensor | np.ndarray): Normalized 8-point coordinates relative to orig_shape. + xyxy (torch.Tensor | np.ndarray): Axis-aligned bounding boxes in [x1, y1, x2, y2] format. + + Methods: + cpu: Return a copy of the OBB object with all tensors on CPU memory. + numpy: Return a copy of the OBB object with all tensors as numpy arrays. + cuda: Return a copy of the OBB object with all tensors on GPU memory. + to: Return a copy of the OBB object with tensors on specified device and dtype. + + Examples: + >>> boxes = torch.tensor([[100, 50, 150, 100, 30, 0.9, 0]]) # xywhr, conf, cls + >>> obb = OBB(boxes, orig_shape=(480, 640)) + >>> print(obb.xyxyxyxy) + >>> print(obb.conf) + >>> print(obb.cls) + """ + + def __init__(self, boxes: torch.Tensor | np.ndarray, orig_shape: tuple[int, int]) -> None: + """Initialize an OBB (Oriented Bounding Box) instance with oriented bounding box data and original image shape. + + This class stores and manipulates Oriented Bounding Boxes (OBB) for object detection tasks. It provides various + properties and methods to access and transform the OBB data. + + Args: + boxes (torch.Tensor | np.ndarray): A tensor or numpy array containing the detection boxes, with shape + (num_boxes, 7) or (num_boxes, 8). The last two columns contain confidence and class values. If present, + the third last column contains track IDs, and the fifth column contains rotation. + orig_shape (tuple[int, int]): Original image size, in the format (height, width). + + Raises: + AssertionError: If the number of values per box is not 7 or 8. + """ + if boxes.ndim == 1: + boxes = boxes[None, :] + n = boxes.shape[-1] + assert n in {7, 8}, f"expected 7 or 8 values but got {n}" # xywh, rotation, track_id, conf, cls + super().__init__(boxes, orig_shape) + self.is_track = n == 8 + self.orig_shape = orig_shape + + @property + def xywhr(self) -> torch.Tensor | np.ndarray: + """Return boxes in [x_center, y_center, width, height, rotation] format. + + Returns: + (torch.Tensor | np.ndarray): A tensor or numpy array containing the oriented bounding boxes with format + [x_center, y_center, width, height, rotation]. The shape is (N, 5) where N is the number of boxes. + + Examples: + >>> results = model("image.jpg") + >>> obb = results[0].obb + >>> xywhr = obb.xywhr + >>> print(xywhr.shape) + torch.Size([3, 5]) + + Notes: + Predictions are not canonicalized to the long-edge convention that training labels use, so width may be + smaller than height with the rotation measured from the short edge. Use `xyxyxyxy` when only the geometry + matters, or `ops.xyxyxyxy2xywhr(obb.xyxyxyxy)` for the canonical form. + """ + return self.data[:, :5] + + @property + def conf(self) -> torch.Tensor | np.ndarray: + """Return the confidence scores for Oriented Bounding Boxes (OBBs). + + This property retrieves the confidence values associated with each OBB detection. The confidence score + represents the model's certainty in the detection. + + Returns: + (torch.Tensor | np.ndarray): A tensor or numpy array of shape (N,) containing confidence scores for N + detections, where each score is in the range [0, 1]. + + Examples: + >>> results = model("image.jpg") + >>> obb_result = results[0].obb + >>> confidence_scores = obb_result.conf + >>> print(confidence_scores) + """ + return self.data[:, -2] + + @property + def cls(self) -> torch.Tensor | np.ndarray: + """Return the class values of the oriented bounding boxes. + + Returns: + (torch.Tensor | np.ndarray): A tensor or numpy array containing the class values for each oriented bounding + box. The shape is (N,), where N is the number of boxes. + + Examples: + >>> results = model("image.jpg") + >>> result = results[0] + >>> obb = result.obb + >>> class_values = obb.cls + >>> print(class_values) + """ + return self.data[:, -1] + + @property + def id(self) -> torch.Tensor | np.ndarray | None: + """Return the tracking IDs of the oriented bounding boxes (if available). + + Returns: + (torch.Tensor | np.ndarray | None): A tensor or numpy array containing the tracking IDs for each oriented + bounding box. Returns None if tracking IDs are not available. + + Examples: + >>> results = model.track("path/to/video.mp4") # Run inference with tracking + >>> for result in results: + ... if result.obb is not None: + ... track_ids = result.obb.id + ... if track_ids is not None: + ... print(f"Tracking IDs: {track_ids}") + """ + return self.data[:, -3] if self.is_track else None + + @cached_property + def xyxyxyxy(self) -> torch.Tensor | np.ndarray: + """Convert OBB format to 8-point (xyxyxyxy) coordinate format for rotated bounding boxes. + + Returns: + (torch.Tensor | np.ndarray): Rotated bounding boxes in xyxyxyxy format with shape (N, 4, 2), where N is the + number of boxes. The 4 points (x, y) are wound counter-clockwise as rendered, starting from the corner + at +w/2, +h/2 in the box frame, so which image corner comes first follows the rotation. + + Examples: + >>> obb = OBB(torch.tensor([[100, 100, 50, 30, 0.5, 0.9, 0]]), orig_shape=(640, 640)) + >>> xyxyxyxy = obb.xyxyxyxy + >>> print(xyxyxyxy.shape) + torch.Size([1, 4, 2]) + """ + return ops.xywhr2xyxyxyxy(self.xywhr) + + @cached_property + def xyxyxyxyn(self) -> torch.Tensor | np.ndarray: + """Convert rotated bounding boxes to normalized xyxyxyxy format. + + Returns: + (torch.Tensor | np.ndarray): Normalized rotated bounding boxes in xyxyxyxy format with shape (N, 4, 2), + where N is the number of boxes. Each box is represented by 4 points (x, y), normalized relative to the + original image dimensions. + + Examples: + >>> obb = OBB(torch.rand(10, 7), orig_shape=(640, 480)) # 10 random OBBs + >>> normalized_boxes = obb.xyxyxyxyn + >>> print(normalized_boxes.shape) + torch.Size([10, 4, 2]) + """ + xyxyxyxyn = self.xyxyxyxy.clone() if isinstance(self.xyxyxyxy, torch.Tensor) else np.copy(self.xyxyxyxy) + xyxyxyxyn[..., 0] /= self.orig_shape[1] + xyxyxyxyn[..., 1] /= self.orig_shape[0] + return xyxyxyxyn + + @cached_property + def xyxy(self) -> torch.Tensor | np.ndarray: + """Convert oriented bounding boxes (OBB) to axis-aligned bounding boxes in xyxy format. + + This property calculates the minimal enclosing rectangle for each oriented bounding box and returns it in xyxy + format (x1, y1, x2, y2). This is useful for operations that require axis-aligned bounding boxes, such as IoU + calculation with non-rotated boxes. + + Returns: + (torch.Tensor | np.ndarray): Axis-aligned bounding boxes in xyxy format with shape (N, 4), where N is the + number of boxes. Each row contains [x1, y1, x2, y2] coordinates. + + Examples: + >>> import torch + >>> from ultralytics import YOLO + >>> model = YOLO("yolo26n-obb.pt") + >>> results = model("path/to/image.jpg") + >>> for result in results: + ... obb = result.obb + ... if obb is not None: + ... xyxy_boxes = obb.xyxy + ... print(xyxy_boxes.shape) # (N, 4) + + Notes: + - This method approximates the OBB by its minimal enclosing rectangle. + - The returned format is compatible with standard object detection metrics and visualization tools. + - The property uses caching to improve performance for repeated access. + """ + x = self.xyxyxyxy[..., 0] + y = self.xyxyxyxy[..., 1] + return ( + torch.stack([x.amin(1), y.amin(1), x.amax(1), y.amax(1)], -1) + if isinstance(x, torch.Tensor) + else np.stack([x.min(1), y.min(1), x.max(1), y.max(1)], -1) + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/trainer.py b/.venv/lib/python3.12/site-packages/ultralytics/engine/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..224b058f5130739533a9b99528b9fda00f8d8b8b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/engine/trainer.py @@ -0,0 +1,1379 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Train a model on a dataset. + +Usage: + $ yolo train model=yolo26n.pt data=coco8.yaml imgsz=640 epochs=100 batch=16 +""" + +from __future__ import annotations + +import gc +import math +import os +import subprocess +import time +import warnings +from copy import copy, deepcopy +from datetime import datetime, timedelta +from functools import partial +from pathlib import Path + +import numpy as np +import torch +from torch import distributed as dist +from torch import nn, optim + +from ultralytics import __version__ +from ultralytics.cfg import _YOLO_CLI_COMMAND, get_cfg, get_save_dir +from ultralytics.data.utils import check_cls_dataset, check_det_dataset, convert_ndjson_to_yolo_if_needed +from ultralytics.nn.distill_model import DistillationModel +from ultralytics.nn.tasks import load_checkpoint +from ultralytics.optim import MuSGD +from ultralytics.utils import ( + DEFAULT_CFG, + GIT, + LOCAL_RANK, + LOGGER, + RANK, + TQDM, + WINDOWS, + YAML, + callbacks, + clean_url, + colorstr, + emojis, +) +from ultralytics.utils.autobatch import check_train_batch_size +from ultralytics.utils.checks import check_amp, check_file, check_imgsz, check_model_file_from_stem, print_args +from ultralytics.utils.dist import ddp_cleanup, generate_ddp_command +from ultralytics.utils.files import get_latest_run +from ultralytics.utils.patches import override_configs +from ultralytics.utils.plotting import plot_results +from ultralytics.utils.torch_utils import ( + TORCH_1_11, + TORCH_2_0, + TORCH_2_4, + TORCH_2_13, + EarlyStopping, + ModelEMA, + attempt_compile, + autocast, + convert_optimizer_state_dict_to_fp16, + get_torch_device_backend, + init_seeds, + one_cycle, + parse_device, + prepare_qat, + qat_state, + restore_qat, + select_device, + strip_optimizer, + strip_qat, + torch_distributed_zero_first, + unset_deterministic, + unwrap_model, +) + + +class BaseTrainer: + """A base class for creating trainers. + + This class provides the foundation for training YOLO models, handling the training loop, validation, checkpointing, + and various training utilities. It supports both single-GPU and multi-GPU distributed training. + + Attributes: + args (SimpleNamespace): Configuration for the trainer. + validator (BaseValidator): Validator instance. + model (nn.Module): Model instance. + callbacks (defaultdict): Dictionary of callbacks. + save_dir (Path): Directory to save results. + wdir (Path): Directory to save weights. + last (Path): Path to the last checkpoint. + best (Path): Path to the best checkpoint. + save_period (int): Save checkpoint every x epochs (disabled if < 1). + batch_size (int): Batch size for training. + epochs (int): Number of epochs to train for. + start_epoch (int): Starting epoch for training. + device (torch.device): Device to use for training. + amp (bool): Whether Automatic Mixed Precision is enabled. + scaler (torch.amp.GradScaler): Gradient scaler for AMP. + data (dict): Dataset dictionary containing paths and metadata. + ema (ModelEMA): EMA (Exponential Moving Average) of the model. + resume (bool): Resume training from a checkpoint. + lf (callable): Learning rate scheduling function. + scheduler (torch.optim.lr_scheduler._LRScheduler): Learning rate scheduler. + best_fitness (float): The best fitness value achieved. + fitness (float): Current fitness value. + loss (torch.Tensor): Current loss value. + tloss (dict): Running mean of loss items. + loss_names (tuple): Names of loss items, derived from the loss dict returned by the criterion on the first + batch. + csv (Path): Path to results CSV file. + metrics (dict): Dictionary of metrics. + plots (dict): Dictionary of plots. + + Methods: + train: Execute the training process. + validate: Run validation on the val set. + save_model: Save model training checkpoints. + get_dataset: Get train and validation datasets. + setup_model: Load, create, or download model. + build_optimizer: Construct an optimizer for the model. + + Examples: + Initialize a trainer and start training + >>> trainer = BaseTrainer(cfg="config.yaml") + >>> trainer.train() + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks: dict | None = None): + """Initialize the BaseTrainer class. + + Args: + cfg (str | dict | SimpleNamespace, optional): Path to a configuration file or configuration object. + overrides (dict, optional): Configuration overrides. + _callbacks (dict, optional): Dictionary of callback functions. + """ + self.args = get_cfg(cfg, overrides) + self.check_resume(overrides or {}) + if getattr(self.args, "augmentations", None) and not isinstance(self.args.augmentations[0], dict): + import albumentations as A + + self.args.augmentations = [A.to_dict(t) for t in self.args.augmentations] # YAML/pickle-safe, DDP-safe + self.args.device = parse_device(self.args.device) # canonical string, resolves '-1' auto-selection once + self.device = select_device(self.args.device) + self.accelerator = get_torch_device_backend(self.device) if self.device.type not in {"cpu", "mps"} else None + self.validator = None + self.metrics = None + self.plots = {} + init_seeds(self.args.seed + 1 + RANK, deterministic=self.args.deterministic) + + # Dirs + self.save_dir = get_save_dir(self.args) + self.args.name = self.save_dir.name # update name for loggers + self.wdir = self.save_dir / "weights" # weights dir + if RANK in {-1, 0}: + self.wdir.mkdir(parents=True, exist_ok=True) # make dir + self.args.save_dir = str(self.save_dir) + YAML.save(self.save_dir / "args.yaml", vars(self.args)) # save run args + self.last, self.best = self.wdir / "last.pt", self.wdir / "best.pt" # checkpoint paths + self.save_period = self.args.save_period + + self.batch_size = self.args.batch + self.epochs = self.args.epochs + self.start_epoch = 0 + if RANK == -1: + print_args(vars(self.args)) + + # Device + if self.device.type in {"cpu", "mps"}: + self.args.workers = 0 # faster CPU training as time dominated by inference, not dataloading + + # Callbacks - initialize early so on_pretrain_routine_start can capture original args.data + self.callbacks = copy(_callbacks) if _callbacks else callbacks.get_default_callbacks() + for k, v in self.callbacks.items(): + self.callbacks[k] = v.copy() + + # Device count in the launching process; distinct from utils.WORLD_SIZE set in spawned DDP workers + if self.device.type in {"cpu", "mps"}: + world_size = 0 + else: # i.e. device='0', '0,1,2,3', 'npu:0', or '' auto-selecting a single GPU + world_size = len(self.args.device.split(",")) if self.args.device else 1 + + self.ddp = world_size > 1 and LOCAL_RANK == -1 # spawn DDP workers unless already one + self.world_size = world_size + # Run on_pretrain_routine_start before get_dataset() to capture original args.data (e.g., ul:// URIs) + if RANK in {-1, 0} and not self.ddp: + callbacks.add_integration_callbacks(self) + self.run_callbacks("on_pretrain_routine_start") + + # Model and Dataset + self.model = check_model_file_from_stem(self.args.model) # add suffix, i.e. yolo26n -> yolo26n.pt + with torch_distributed_zero_first(LOCAL_RANK): # avoid auto-downloading dataset multiple times + self.data = self.get_dataset() + + self.ema = None + + # Optimization utils init + self.lf = None + self.optimizer = None + self.scheduler = None + + # Epoch level metrics + self.best_fitness = None + self.fitness = None + self.loss = None + self.tloss = None + self.loss_names = () + self.csv = self.save_dir / "results.csv" + if self.csv.exists() and not self.args.resume: + self.csv.unlink() + self.plot_idx = [0, 1, 2] + self.nan_recovery_attempts = 0 + + def add_callback(self, event: str, callback): + """Append the given callback to the event's callback list.""" + self.callbacks[event].append(callback) + + def set_callback(self, event: str, callback): + """Override the existing callbacks with the given callback for the specified event.""" + self.callbacks[event] = [callback] + + def run_callbacks(self, event: str): + """Run all existing callbacks associated with a particular event.""" + for callback in self.callbacks.get(event, []): + callback(self) + + def train(self): + """Execute the training process, using DDP subprocess for multi-GPU or direct training for single-GPU.""" + # Run subprocess if DDP training, else train normally + try: + if self.ddp: + # Argument checks + if self.args.rect: + LOGGER.warning("'rect=True' is incompatible with Multi-GPU training, setting 'rect=False'") + self.args.rect = False + if self.args.batch < 1.0: + raise ValueError( + "AutoBatch with batch<1 not supported for Multi-GPU training, " + f"please specify a valid batch size multiple of GPU count {self.world_size}, i.e. batch={self.world_size * 8}." + ) + + # Command + cmd, file = None, None + try: + cmd, file = generate_ddp_command(self) + LOGGER.info(f"{colorstr('DDP:')} debug command {' '.join(cmd)}") + subprocess.run(cmd, check=True) + finally: + if file is not None: + ddp_cleanup(self, str(file)) + + else: + self._do_train() + finally: + unset_deterministic() # never leave deterministic state on, including the DDP parent and failed runs + if not self.ddp: + self.run_callbacks("teardown") + + def _setup_scheduler(self): + """Initialize training learning rate scheduler.""" + if self.args.cos_lr: + self.lf = one_cycle(1, self.args.lrf, self.epochs) # cosine 1->hyp['lrf'] + else: + self.lf = lambda x: max(1 - x / self.epochs, 0) * (1.0 - self.args.lrf) + self.args.lrf # linear + self.scheduler = optim.lr_scheduler.LambdaLR(self.optimizer, lr_lambda=self.lf) + + def _get_warmup_iterations(self, num_batches): + """Return warmup iterations, leaving at least the final epoch for regular training.""" + warmup_epochs = min(self.args.warmup_epochs, max(self.epochs - 1, 0)) + return round(warmup_epochs * num_batches) if warmup_epochs > 0 else 0 + + def _setup_ddp(self): + """Initialize and set the DistributedDataParallel parameters for training.""" + device_type = self.args.device.split(":", 1)[0] + device_type = device_type if device_type in {"npu", "xpu"} else "cuda" + devices = self.args.device.split(":", 1)[-1].split(",") + index = int(devices[LOCAL_RANK]) # world_size > 1 guarantees a multi-device string + self.device = torch.device(device_type, index) + self.accelerator = get_torch_device_backend(self.device) + self.accelerator.set_device(index) + if device_type == "cuda": + os.environ["TORCH_NCCL_BLOCKING_WAIT"] = "1" # set to enforce timeout + elif device_type == "xpu" and not (hasattr(dist, "is_xccl_available") and dist.is_xccl_available()): + raise RuntimeError("Multi-XPU training requires XCCL, which is not available in this PyTorch build.") + dist.init_process_group( + backend={"npu": "hccl", "xpu": "xccl"}.get(device_type, "nccl" if dist.is_nccl_available() else "gloo"), + timeout=timedelta(seconds=10800), # 3 hours + rank=RANK, + world_size=self.world_size, + ) + + def _build_train_pipeline(self): + """Build dataloaders and update optimizer settings for the current batch size.""" + batch_size = self.batch_size // max(self.world_size, 1) + self.train_loader = self.get_dataloader( + self.data["train"], batch_size=batch_size, rank=LOCAL_RANK, mode="train" + ) + final_batch_size = len(self.train_loader.sampler) % self.train_loader.batch_size or self.train_loader.batch_size + if self.args.imgsz < 2 * self.stride and not self.train_loader.drop_last and final_batch_size == 1: + raise ValueError( + f"final batch=1 training at imgsz={self.args.imgsz} gives BatchNorm a single value per channel; " + f"change batch or use imgsz >= {2 * self.stride}" + ) + # Note: When training DOTA dataset, double batch size could get OOM on images with >2000 objects. + self.test_loader = self.get_dataloader( + self.data[self.args.split], + batch_size=batch_size if self.args.task in {"obb", "semantic", "depth"} else batch_size * 2, + rank=LOCAL_RANK, + mode="val", + ) + self.accumulate = max(round(self.args.nbs / self.batch_size), 1) # accumulate loss before optimizing + weight_decay = self.args.weight_decay * self.batch_size * self.accumulate / self.args.nbs # scale weight_decay + if self.optimizer is None: + iterations = math.ceil(len(self.train_loader.dataset) / max(self.batch_size, self.args.nbs)) * self.epochs + self.optimizer = self.build_optimizer( + model=self.model, + name=self.args.optimizer, + lr=self.args.lr0, + momentum=self.args.momentum, + decay=weight_decay, + iterations=iterations, + ) + self._setup_scheduler() + else: + for group in self.optimizer.param_groups: + if group.get("param_group") in {"weight", "muon"}: + group["weight_decay"] = weight_decay + + def _setup_train(self): + """Configure model, optimizer, dataloaders, and training utilities before the training loop.""" + ckpt = self.setup_model() + self.model = self.model.to(self.device) + # channels_last (NHWC) is CUDA-only: lossless and Tensor-Core friendly there, but numerically wrong + # on MPS and no benefit on CPU. Not auto-enabled on Windows, where it measured 3x slower (#26105). + channels_last = self.args.channels_last is True or ( + self.args.channels_last is None and TORCH_1_11 and not WINDOWS + ) + if channels_last and self.device.type == "cuda": + self.model = self.model.to(memory_format=torch.channels_last) + elif self.args.channels_last: + LOGGER.warning(f"'channels_last=True' is only supported on CUDA, ignoring on '{self.device.type}'.") + self.set_model_attributes() + + # Check imgsz + gs = max(int(self.model.stride.max() if hasattr(self.model, "stride") else 32), 32) # grid size (max stride) + self.args.imgsz = check_imgsz(self.args.imgsz, stride=gs, floor=gs, max_dim=1) + self.stride = gs # for multiscale training + + # Prepare the final module structure before compile, DDP, and EMA wrap it. + if self.args.quantize == 8: + if self.resume and ckpt.get("modelopt"): + restore_qat(self.model, ckpt["modelopt"]) + else: + batch = max(self.batch_size // max(self.world_size, 1), 1) if self.batch_size >= 1 else 16 + with torch_distributed_zero_first(LOCAL_RANK), override_configs(self.args, {"cache": False}): + calibration_loader = self.get_dataloader( + self.data["train"], batch_size=batch, rank=-1, mode="train" + ) + self.model = prepare_qat(self.model, calibration_loader, self.preprocess_batch) + del calibration_loader + + # Compile model (knowledge distillation runs the wrapped model eagerly and relies on + # find_unused_parameters under DDP for the frozen teacher, so disable compilation when distilling) + if self.args.distill_model is not None and self.args.compile: + LOGGER.warning("'compile' is not supported with knowledge distillation and will be disabled.") + self.args.compile = False + self.model = attempt_compile(self.model, device=self.device, mode=self.args.compile) + + # Freeze layers + freeze_list = ( + self.args.freeze + if isinstance(self.args.freeze, list) + else range(self.args.freeze) + if isinstance(self.args.freeze, int) + else [] + ) + always_freeze_names = [".dfl"] # always freeze these layers + freeze_layer_names = [f"model.{x}." for x in freeze_list] + always_freeze_names + if isinstance(unwrap_model(self.model), DistillationModel): + freeze_layer_names.append("teacher_model.") + self.freeze_layer_names = freeze_layer_names + for k, v in self.model.named_parameters(): + # v.register_hook(lambda x: torch.nan_to_num(x)) # NaN to 0 (commented for erratic training results) + if any(x in k for x in freeze_layer_names): + LOGGER.info(f"Freezing layer '{k}'") + v.requires_grad = False + elif not v.requires_grad and v.dtype.is_floating_point: # only floating point Tensor can require gradients + LOGGER.warning( + f"setting 'requires_grad=True' for frozen layer '{k}'. " + "See ultralytics.engine.trainer for customization of frozen layers." + ) + v.requires_grad = True + if not any(v.requires_grad for v in self.model.parameters()): + raise RuntimeError( + f"'freeze={self.args.freeze}' froze the entire model with no trainable parameters left. " + f"Reduce 'freeze' or pass a list of specific layer indices." + ) + + # Check AMP + self.amp = self.args.amp not in {False, "fp32"} + self.amp = torch.tensor(self.amp).to(self.device) + if self.amp and self.args.amp != "bf16" and RANK in {-1, 0}: # Single-GPU and DDP + callbacks_backup = callbacks.default_callbacks.copy() # backup callbacks as check_amp() resets them + self.amp = torch.tensor(check_amp(self.model), device=self.device) + callbacks.default_callbacks = callbacks_backup # restore callbacks + if RANK > -1 and self.world_size > 1: # DDP + self.amp = self.amp.int() # gloo errors with boolean + dist.broadcast(self.amp, src=0) # broadcast from rank 0 to all other ranks + self.amp = bool(self.amp) # as boolean + if self.device.type == "npu": + import torch_npu + + self.scaler = torch_npu.npu.amp.GradScaler(enabled=self.amp and self.args.amp != "bf16") + else: + self.scaler = ( + torch.amp.GradScaler( + self.device.type if self.device.type == "xpu" else "cuda", + enabled=self.amp and self.args.amp != "bf16", + ) + if TORCH_2_4 + else torch.cuda.amp.GradScaler(enabled=self.amp and self.args.amp != "bf16") + ) + # resume training would directly load DistillationModel so check here + if self.args.distill_model is not None and not isinstance(unwrap_model(self.model), DistillationModel): + self.model = DistillationModel(student_model=self.model, teacher_model=self.args.distill_model) + if self.world_size > 1: + # static_graph=True permits params used >1 time per forward (e.g. flow_model in + # o2m+o2o pose loss branches) under torch.compile. + ddp_kwargs = {"static_graph": bool(self.args.compile)} if TORCH_1_11 else {} + ddp_kwargs["forward_sync_buffers" if TORCH_2_13 else "broadcast_buffers"] = False + self.model = nn.parallel.DistributedDataParallel( + self.model, + device_ids=[self.device.index], + find_unused_parameters=not bool(self.args.compile), + **ddp_kwargs, + ) + + # Batch size + if self.batch_size < 1 and RANK == -1: # single-GPU only, estimate best batch size + self.args.batch = self.batch_size = self.auto_batch() + self._build_train_pipeline() + self.validator = self.get_validator() + self.set_class_weights() # compute class weights after dataloader is ready + self.ema = ModelEMA(self.model) # after set_class_weights, so the copy carries them at any nesting depth + if RANK in {-1, 0}: + metric_keys = self.validator.metrics.keys + self.label_loss_items(prefix="val") + self.metrics = dict(zip(metric_keys, [0] * len(metric_keys))) + if self.args.plots: + self.plot_training_labels() + + self.stopper, self.stop = EarlyStopping(patience=self.args.patience), False + self.resume_training(ckpt) + self.scheduler.last_epoch = self.start_epoch - 1 # do not move + self.run_callbacks("on_pretrain_routine_end") + + def _do_train(self): + """Perform the full training loop including setup, epoch iteration, validation, and final evaluation.""" + if self.world_size > 1: + self._setup_ddp() + self._setup_train() + + nb = len(self.train_loader) # number of batches + nw = self._get_warmup_iterations(nb) + last_opt_step = -1 + self.epoch_time = None + self.epoch_time_start = time.time() + self.train_time_start = time.time() + self.run_callbacks("on_train_start") + LOGGER.info( + f"Using {len(self.train_loader.dataset)} train, {len(self.test_loader.dataset)} val images for " + f"fraction={self.args.fraction} at imgsz={self.args.imgsz}\n" + f"Using {self.train_loader.num_workers * (self.world_size or 1)} dataloader workers\n" + f"Logging results to {colorstr('bold', self.save_dir)}\n" + f"Starting training for " + (f"{self.args.time} hours..." if self.args.time else f"{self.epochs} epochs...") + ) + if self.args.close_mosaic: + base_idx = (self.epochs - self.args.close_mosaic) * nb + self.plot_idx.extend([base_idx, base_idx + 1, base_idx + 2]) + epoch = self.start_epoch + mosaic_closed = not self.args.close_mosaic # close once when the run enters its final close_mosaic epochs + self.optimizer.zero_grad() # zero any resumed gradients to ensure stability on train start + self._oom_retries = 0 # OOM auto-reduce counter for first epoch + while True: + self.epoch = epoch + self.run_callbacks("on_train_epoch_start") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") # suppress 'Detected lr_scheduler.step() before optimizer.step()' + self.scheduler.step() + + self._model_train() + if RANK != -1: + self.train_loader.sampler.set_epoch(epoch) + pbar = enumerate(self.train_loader) + # Update dataloader attributes (optional) + if not mosaic_closed and epoch >= self.epochs - self.args.close_mosaic: + mosaic_closed = True + self._close_dataloader_mosaic() + self.train_loader.reset() + + if RANK in {-1, 0}: + if self.loss_names: + LOGGER.info(self.progress_string()) + pbar = TQDM(enumerate(self.train_loader), total=nb) + self.tloss = None + for i, batch in pbar: + self.run_callbacks("on_train_batch_start") + # Warmup + ni = i + nb * epoch + if ni < nw: + xi = [0, nw] # x interp + self.accumulate = max(1, int(np.interp(ni, xi, [1, self.args.nbs / self.batch_size]).round())) + for x in self.optimizer.param_groups: + # Bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0 + x["lr"] = float( + np.interp( + ni, + xi, + [ + self.args.warmup_bias_lr if x.get("param_group") == "bias" else 0.0, + x["initial_lr"] * self.lf(epoch), + ], + ) + ) + if "momentum" in x: + x["momentum"] = float(np.interp(ni, xi, [self.args.warmup_momentum, self.args.momentum])) + + # Forward + try: + with autocast(torch.bfloat16 if self.args.amp == "bf16" else self.amp, device=self.device.type): + batch = self.preprocess_batch(batch) + if self.args.compile: + # Decouple inference and loss calculations for improved compile performance + preds = self.model(batch["img"]) + loss, self.loss_items = unwrap_model(self.model).loss(batch, preds) + else: + loss, self.loss_items = self.model(batch) + self.loss = loss.sum() + if RANK != -1: + self.loss *= self.world_size + if not self.loss_names: # derive loss names from the criterion's loss dict on first batch + self.loss_names = tuple(self.loss_items) + if RANK in {-1, 0}: + LOGGER.info(self.progress_string()) + self.metrics.update(dict.fromkeys(self.label_loss_items(prefix="val"), 0.0)) + self.tloss = ( + self.loss_items + if self.tloss is None + else {k: (self.tloss[k] * i + v) / (i + 1) for k, v in self.loss_items.items()} + ) + + # Backward + self.scaler.scale(self.loss).backward() + except RuntimeError as e: + is_oom = "out of memory" in str(e).lower() # torch.cuda.OutOfMemoryError requires torch>=1.13 + if not is_oom and not any( + s in str(e) + for s in ( + "CUBLAS_STATUS_ALLOC_FAILED", + "CUDNN_STATUS_INTERNAL_ERROR", + "unable to find an engine", + ) + ): + raise + if epoch > self.start_epoch or self._oom_retries >= 3 or RANK != -1: + raise # only auto-reduce during first epoch on single GPU, max 3 retries + self._oom_retries += 1 + old_batch = self.batch_size + self.args.batch = self.batch_size = max(self.batch_size // 2, 1) + error = f"{self.device.type.upper()} out of memory" if is_oom else "CUDA backend memory error" + LOGGER.warning( + f"{error} with batch={old_batch}. " + f"Reducing to batch={self.batch_size} and retrying ({self._oom_retries}/3)." + ) + batch = loss = preds = None + self.loss = self.loss_items = self.tloss = None + self._clear_memory() + self._build_train_pipeline() # retain optimizer state across OOM retries + mosaic_closed = not self.args.close_mosaic # the rebuilt loader reopened mosaic, re-arm the gate + self.scheduler.last_epoch = self.start_epoch - 1 + nb = len(self.train_loader) + nw = self._get_warmup_iterations(nb) + last_opt_step = -1 + self.optimizer.zero_grad() + break # restart epoch loop with reduced batch size + if ni - last_opt_step >= self.accumulate: + self.optimizer_step() + last_opt_step = ni + + # Timed stopping + if self.args.time: + self.stop = (time.time() - self.train_time_start) > (self.args.time * 3600) + if RANK != -1: # if DDP training + broadcast_list = [self.stop if RANK == 0 else None] + dist.broadcast_object_list(broadcast_list, 0) # broadcast 'stop' to all ranks + self.stop = broadcast_list[0] + if self.stop: # training time exceeded + break + + # Log + if RANK in {-1, 0}: + loss_length = len(self.tloss) + pbar.set_description( + ("%11s" * 2 + "%11.4g" * (2 + loss_length)) + % ( + f"{epoch + 1}/{self.epochs}", + f"{self._get_memory():.3g}G", # (GB) GPU memory util + *self.tloss.values(), # losses + batch.get("cls", batch["img"]).shape[0], # no. of instances + batch["img"].shape[-1], # imgsz, i.e 640 + ) + ) + self.run_callbacks("on_batch_end") + if self.args.plots and ni in self.plot_idx: + self.plot_training_samples(batch, ni) + + self.run_callbacks("on_train_batch_end") + if self.stop: + break # allow external stop (e.g. platform cancellation) between batches + else: + # for/else: this block runs only when the for loop completes without break (no OOM retry) + self._oom_retries = 0 # reset OOM counter after successful first epoch + + if self._oom_retries and not self.stop: + continue # OOM recovery broke the for loop, restart with reduced batch size + + if hasattr(unwrap_model(self.model).criterion, "update"): + unwrap_model(self.model).criterion.update() + + self.lr = {f"lr/pg{ir}": x["lr"] for ir, x in enumerate(self.optimizer.param_groups)} # for loggers + + self.run_callbacks("on_train_epoch_end") + if RANK in {-1, 0}: + self.ema.update_attr(self.model, include=["yaml", "nc", "args", "names", "stride", "class_weights"]) + + # Validation + final_epoch = epoch + 1 >= self.epochs + if self.args.val or final_epoch or self.stopper.possible_stop or self.stop: + self._clear_memory(None if self.device.type == "mps" else 0.5) # prevent VRAM spike + self.metrics, self.fitness = self.validate() + + # NaN recovery + if self._handle_nan_recovery(epoch): + continue + + self.nan_recovery_attempts = 0 + if RANK in {-1, 0}: + self.save_metrics(metrics={**self.label_loss_items(self.tloss), **self.metrics, **self.lr}) + self.stop |= self.stopper(epoch + 1, self.fitness) or final_epoch + if self.args.time: + self.stop |= (time.time() - self.train_time_start) > (self.args.time * 3600) + + # Save model + if (self.args.save or final_epoch) and self.save_model(): + self.run_callbacks("on_model_save") + + # Scheduler + t = time.time() + self.epoch_time = t - self.epoch_time_start + self.epoch_time_start = t + if self.args.time: + mean_epoch_time = (t - self.train_time_start) / (epoch - self.start_epoch + 1) + self.epochs = self.args.epochs = math.ceil(self.args.time * 3600 / mean_epoch_time) + nw = self._get_warmup_iterations(nb) + self._setup_scheduler() + self.scheduler.last_epoch = self.epoch # do not move + self.stop |= epoch >= self.epochs # stop if exceeded epochs + self.run_callbacks("on_fit_epoch_end") + # clear if memory utilization > 50%; always clear on MPS due to leak https://github.com/ultralytics/ultralytics/issues/22621 + self._clear_memory(None if self.device.type == "mps" else 0.5) + + # Early Stopping + if RANK != -1: # if DDP training + broadcast_list = [self.stop if RANK == 0 else None] + dist.broadcast_object_list(broadcast_list, 0) # broadcast 'stop' to all ranks + self.stop = broadcast_list[0] + if self.stop: + break # must break all DDP ranks + epoch += 1 + + seconds = time.time() - self.train_time_start + LOGGER.info(f"\n{epoch - self.start_epoch + 1} epochs completed in {seconds / 3600:.3f} hours.") + # Do final val with best.pt + self.final_eval() + if RANK in {-1, 0}: + if self.args.plots: + self.plot_metrics() + self.run_callbacks("on_train_end") + self._clear_memory() + for loader in (self.train_loader, self.test_loader): + if hasattr(loader, "close"): + loader.close() # shut down persistent dataloader workers so none survive to interpreter exit + + def auto_batch(self, max_num_obj=0, dataset_size=0): + """Calculate optimal batch size based on model and device memory constraints.""" + # Stride-aligned to match the true multi-scale max size; pyramid heads require stride-multiple inputs + max_imgsz = math.ceil(self.args.imgsz * (1 + self.args.multi_scale) / self.stride) * self.stride + return check_train_batch_size( + model=self.model, + imgsz=max_imgsz, + amp=torch.bfloat16 if self.args.amp == "bf16" else self.amp, + batch=self.batch_size, + max_num_obj=max_num_obj, + dataset_size=dataset_size, + ) # returns batch size + + def _get_memory(self, fraction=False): + """Get accelerator memory utilization in GB or as a fraction of total memory.""" + memory, total = 0, 0 + if self.device.type == "mps": + memory = torch.mps.driver_allocated_memory() + if fraction: + return __import__("psutil").virtual_memory().percent / 100 + elif self.device.type != "cpu": + memory = self.accelerator.memory_reserved() + if fraction: + total = self.accelerator.get_device_properties(self.device).total_memory + return ((memory / total) if total > 0 else 0) if fraction else (memory / 2**30) + + def _clear_memory(self, threshold: float | None = None): + """Clear accelerator memory by calling garbage collector and emptying cache.""" + if threshold: + assert 0 <= threshold <= 1, "Threshold must be between 0 and 1." + if self._get_memory(fraction=True) <= threshold: + return + gc.collect() + if self.device.type == "mps": + torch.mps.empty_cache() + elif self.device.type == "cpu": + return + else: + self.accelerator.empty_cache() + + def read_results_csv(self): + """Read results.csv into a dictionary using polars.""" + import polars as pl # scope for faster 'import ultralytics' + + try: + return pl.read_csv(self.csv, infer_schema_length=None).to_dict(as_series=False) + except Exception: + return {} + + def _model_train(self): + """Set model in training mode.""" + self.model.train() + # Freeze BN stat + for n, m in self.model.named_modules(): + if any(filter(lambda f: f in n, self.freeze_layer_names)) and isinstance(m, nn.BatchNorm2d): + m.eval() + + def save_model(self): + """Save model training checkpoints with additional metadata.""" + import io + + # A transient NaN/Inf permanently poisons the EMA running average (ema = decay*ema + (1-decay)*model), so + # save_model would otherwise skip every epoch and the run would finish with no checkpoint on valid input. + # Resync each poisoned EMA tensor from the live model where finite; any tensor that is non-finite in both is + # left for the nan_to_num_ pass below, so a usable checkpoint is always written. + ema = self.ema.ema + if not all(torch.isfinite(v).all() for v in ema.state_dict().values() if isinstance(v, torch.Tensor)): + model_sd = unwrap_model(self.model).state_dict() + for k, v in ema.state_dict().items(): + if isinstance(v, torch.Tensor) and not torch.isfinite(v).all() and torch.isfinite(model_sd[k]).all(): + v.copy_(model_sd[k]) + # Serialize NCHW regardless of channels_last training: released versions fuse with .view(), which crashes on + # NHWC-strided checkpoint weights, and trainer/predictor re-apply channels_last at setup anyway. + modelopt = qat_state(ema) + ema = deepcopy(ema).half().to(memory_format=torch.contiguous_format) + if hasattr(ema, "criterion"): + ema.criterion = None # strip training-only state from the serialization snapshot + # Clamp fp16 serialization overflow without mutating the live EMA. + for v in ema.state_dict().values(): + if isinstance(v, torch.Tensor) and v.is_floating_point(): + torch.nan_to_num_(v) + + # Serialize ckpt to a byte buffer once (faster than repeated torch.save() calls) + strip_qat(ema) + buffer = io.BytesIO() + torch.save( + { + "epoch": self.epoch, + "best_fitness": self.best_fitness, + "model": None, # resume and final checkpoints derive from EMA + "ema": ema, + "updates": self.ema.updates, + "modelopt": modelopt, # quantization state of a QAT model, restored by load_checkpoint() + "optimizer": convert_optimizer_state_dict_to_fp16(deepcopy(self.optimizer.state_dict())), + "scaler": self.scaler.state_dict(), + "train_args": vars(self.args), # save as dict + "train_metrics": {**self.metrics, "fitness": self.fitness}, + "train_results": self.read_results_csv(), + "date": datetime.now().astimezone().isoformat(), + "version": __version__, + "git": { + "root": str(GIT.root), + "branch": GIT.branch, + "commit": GIT.commit, + "message": GIT.message, + "origin": GIT.origin, + }, + "license": "AGPL-3.0 (https://ultralytics.com/license)", + "docs": "https://docs.ultralytics.com", + }, + buffer, + ) + serialized_ckpt = buffer.getvalue() # get the serialized content to save + + # Save checkpoints + self.wdir.mkdir(parents=True, exist_ok=True) # ensure weights directory exists + self.last.write_bytes(serialized_ckpt) # save last.pt + if self.best_fitness == self.fitness: + self.best.write_bytes(serialized_ckpt) # save best.pt + if (self.save_period > 0) and (self.epoch % self.save_period == 0): + (self.wdir / f"epoch{self.epoch}.pt").write_bytes(serialized_ckpt) # save epoch, i.e. 'epoch3.pt' + return True + + def get_dataset(self): + """Get train and validation datasets from data dictionary. + + Returns: + (dict): A dictionary containing the training/validation/test dataset and category names. + """ + try: + self.args.data = convert_ndjson_to_yolo_if_needed(self.args.data, self.args.fraction, split=self.args.split) + + # Task-specific dataset checking + if self.args.task == "classify": + data = check_cls_dataset(self.args.data, split=self.args.split) + elif str(self.args.data).rsplit(".", 1)[-1] in {"yaml", "yml"} or self.args.task in { + "detect", + "segment", + "pose", + "obb", + "semantic", + "depth", + }: + data = check_det_dataset(self.args.data, split=self.args.split) + if "yaml_file" in data: + self.args.data = data["yaml_file"] # for validating 'yolo train data=url.zip' usage + except Exception as e: + raise RuntimeError(emojis(f"Dataset '{clean_url(self.args.data)}' error ❌ {e}")) from e + if self.args.single_cls: + LOGGER.info("Overriding class names with single class.") + data["names"] = {0: "item"} + data["nc"] = 1 + return data + + def setup_model(self): + """Load, create, or download model for any task. + + Returns: + (dict | None): Checkpoint to resume training from, or None if no checkpoint is loaded. + """ + if isinstance(self.model, torch.nn.Module): # if model is loaded beforehand. No setup needed + return + + cfg, weights = self.model, None + ckpt = None + if str(self.model).endswith(".pt"): + weights, ckpt = load_checkpoint(self.model) + cfg = weights.yaml + if isinstance(self.args.pretrained, (str, Path)) and not self.resume: + weights, _ = load_checkpoint(self.args.pretrained) + elif self.args.pretrained is False and not self.resume: + weights = None + + # rebuild DistillationModel from resuming checkpoint + if isinstance(weights, DistillationModel): + if RANK in {-1, 0}: + LOGGER.info("Resuming training DistillationModel from checkpoint weights") + student_model = self.get_model(cfg=cfg, weights=weights.student_model, verbose=RANK in {-1, 0}) + student_model.args = self.args + # teacher is stripped from the checkpoint to save memory/disk; rebuild it from the distill_model path + teacher_model = weights.teacher_model if weights.teacher_model is not None else self.args.distill_model + model = DistillationModel(student_model=student_model, teacher_model=teacher_model) + if getattr(weights, "projector", None) is not None: + model.projector.load_state_dict(weights.projector.state_dict()) # restore the trained projector + model.criterion = None + self.model = model + else: + self.model = self.get_model(cfg=cfg, weights=weights, verbose=RANK in {-1, 0}) # calls Model(cfg, weights) + return ckpt + + def optimizer_step(self): + """Perform a single step of the training optimizer with gradient clipping and EMA update.""" + self.scaler.unscale_(self.optimizer) # unscale gradients + if self.device.type == "npu" and TORCH_2_0: + torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=10.0, foreach=False) + else: + torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=10.0) + self.scaler.step(self.optimizer) + self.scaler.update() + self.optimizer.zero_grad() + if self.ema: + self.ema.update(self.model) + + def preprocess_batch(self, batch): + """Allow custom preprocessing of model inputs and ground truths depending on task type.""" + return batch + + def validate(self): + """Run validation on val set using self.validator. + + Returns: + (tuple): A tuple containing: + - metrics (dict | None): Dictionary of validation metrics, or None if validation was skipped. + - fitness (float | None): Fitness score for the validation, or None if validation was skipped. + """ + if self.ema and self.world_size > 1: + # Sync EMA buffers from rank 0 to all ranks + for buffer in self.ema.ema.buffers(): + dist.broadcast(buffer, src=0) + metrics = self.validator(self) + if metrics is None: + return None, None + fitness = metrics.pop("fitness", -self.loss.detach().cpu().numpy()) # use loss as fitness measure if not found + if self.best_fitness is None or self.best_fitness < fitness: + self.best_fitness = fitness + return metrics, fitness + + def get_model(self, cfg=None, weights=None, verbose=True): + """Get model and raise NotImplementedError for loading cfg files.""" + raise NotImplementedError("This task trainer doesn't support loading cfg files") + + def get_validator(self): + """Raise NotImplementedError (must be implemented by subclasses).""" + raise NotImplementedError("get_validator function not implemented in trainer") + + def get_dataloader(self, dataset_path, batch_size=16, rank=0, mode="train"): + """Raise NotImplementedError (must return a `torch.utils.data.DataLoader` in subclasses).""" + raise NotImplementedError("get_dataloader function not implemented in trainer") + + def build_dataset(self, img_path, mode="train", batch=None): + """Build dataset.""" + raise NotImplementedError("build_dataset function not implemented in trainer") + + def label_loss_items(self, loss_items=None, prefix="train"): + """Return a loss dict with labeled training loss items, or a list of loss names if loss_items is None.""" + if loss_items is None: + return [f"{prefix}/{x}" for x in self.loss_names] + return {f"{prefix}/{k}": round(float(v), 5) for k, v in loss_items.items()} + + def set_model_attributes(self): + """Set or update model parameters before training.""" + self.model.names = self.data["names"] + + def set_class_weights(self): + """Compute and set class weights for handling class imbalance. Override in subclasses.""" + + def build_targets(self, preds, targets): + """Build target tensors for training YOLO model.""" + + def progress_string(self): + """Return a string describing training progress.""" + return "" + + # TODO: may need to put these following functions into callback + def plot_training_samples(self, batch, ni): + """Plot training samples during YOLO training.""" + + def plot_training_labels(self): + """Plot training labels for YOLO model.""" + + def save_metrics(self, metrics): + """Save training metrics to a CSV file.""" + keys, vals = list(metrics.keys()), list(metrics.values()) + n = len(metrics) + 2 # number of cols + t = time.time() - self.train_time_start + self.csv.parent.mkdir(parents=True, exist_ok=True) # ensure parent directory exists + s = "" if self.csv.exists() else ("%s," * n % ("epoch", "time", *keys)).rstrip(",") + "\n" + with open(self.csv, "a", encoding="utf-8") as f: + f.write(s + ("%.6g," * n % (self.epoch + 1, t, *vals)).rstrip(",") + "\n") + + def plot_metrics(self): + """Plot metrics from a CSV file.""" + plot_results(file=self.csv, on_plot=self.on_plot) # save results.png + + def on_plot(self, name, data=None): + """Register plots (e.g. to be consumed in callbacks).""" + path = Path(name) + self.plots[path] = {"data": data, "timestamp": time.time()} + + def final_eval(self): + """Perform final evaluation and validation for the YOLO model.""" + model = self.best if self.best.exists() else None + with torch_distributed_zero_first(LOCAL_RANK): # strip only on GPU 0; other GPUs should wait + if RANK in {-1, 0}: + ckpt = strip_optimizer(self.last) if self.last.exists() else {} + if model: + # update best.pt train_metrics from last.pt + strip_optimizer(self.best, updates={"train_results": ckpt.get("train_results")}) + if model: + LOGGER.info(f"\nValidating {model}...") + self.validator.args.plots = self.args.plots + self.validator.args.compile = False # disable final val compile as too slow + self.metrics = self.validator(model=model) + self.metrics.pop("fitness", None) + self.epoch += 1 # log best metrics at step epochs+1, not overwriting last epoch + self.run_callbacks("on_fit_epoch_end") + self.epoch -= 1 # restore epoch + + def check_resume(self, overrides): + """Check if resume checkpoint exists and update arguments accordingly.""" + resume = self.args.resume + if resume: + try: + exists = isinstance(resume, (str, Path)) and Path(resume).exists() + last = Path(check_file(resume) if exists else get_latest_run()) + ckpt_args = load_checkpoint(last)[0].args + except Exception as e: + raise FileNotFoundError( + "Resume checkpoint not found. Please pass a valid checkpoint to resume from, " + "i.e. 'yolo train resume model=path/to/last.pt'" + ) from e + if self.args.data or (not isinstance(ckpt_args["data"], dict) and not Path(ckpt_args["data"]).exists()): + ckpt_args["data"] = self.args.data + + resume = True + self.args = get_cfg(ckpt_args) + self.args.model = self.args.resume = str(last) # reinstate model + for k in ( + "imgsz", + "batch", + "device", + "close_mosaic", + "augmentations", + "save_period", + "workers", + "cache", + "patience", + "time", + "freeze", + "val", + "plots", + "channels_last", + "distill_model", + "save_dir", + ): # allow arg updates to reduce memory or update device on resume + if k in overrides: + setattr(self.args, k, overrides[k]) + self.resume = resume + + def _load_checkpoint_state(self, ckpt): + """Load optimizer, scaler, EMA, and best_fitness from checkpoint.""" + if ckpt.get("optimizer") is not None: + self.optimizer.load_state_dict(ckpt["optimizer"]) + if ckpt.get("scaler"): + self.scaler.load_state_dict(ckpt["scaler"]) + if self.ema and ckpt.get("ema"): + self.ema = ModelEMA(self.model) # validation with EMA creates inference tensors that can't be updated + # A QAT checkpoint serializes its EMA without quantizers, but load_checkpoint() re-applied them in place + # to this very module, so the strict load below still matches the QAT-structured EMA built above. + self.ema.ema.load_state_dict(ckpt["ema"].float().state_dict()) + self.ema.updates = ckpt["updates"] + self.best_fitness = ckpt.get("best_fitness") + + def _handle_nan_recovery(self, epoch): + """Detect and recover from NaN/Inf loss by loading last checkpoint.""" + loss_nan = self.loss is not None and not self.loss.isfinite() + fitness_nan = self.fitness is not None and not np.isfinite(self.fitness) + corrupted = RANK in {-1, 0} and (loss_nan or fitness_nan) + reason = "Loss NaN/Inf" if loss_nan else "Fitness NaN/Inf" + if RANK != -1: # DDP: broadcast to all ranks + broadcast_list = [corrupted if RANK == 0 else None] + dist.broadcast_object_list(broadcast_list, 0) + corrupted = broadcast_list[0] + if not corrupted: + return False + if epoch == self.start_epoch: + LOGGER.warning(f"{reason} detected but can not recover from last.pt...") + return False # Cannot recover on first epoch, let training continue + if not self.last.exists(): + raise RuntimeError(f"{reason} detected but no valid last.pt is available for recovery") + self.nan_recovery_attempts += 1 + if self.nan_recovery_attempts > 3: + raise RuntimeError(f"Training failed: NaN persisted for {self.nan_recovery_attempts} epochs") + LOGGER.warning(f"{reason} detected (attempt {self.nan_recovery_attempts}/3), recovering from last.pt...") + self._model_train() # set model to train mode before loading checkpoint to avoid inference tensor errors + _, ckpt = load_checkpoint(self.last) + ema = ckpt["ema"].float() + ema_state = ema.state_dict() + if not all(torch.isfinite(v).all() for v in ema_state.values() if isinstance(v, torch.Tensor)): + raise RuntimeError(f"Checkpoint {self.last} is corrupted with NaN/Inf weights") + model = unwrap_model(self.model) + if hasattr(model, "student_model"): + # Distillation: the EMA is stripped of the teacher (rebuilt from the distill_model path), so only the + # student and projector are restored; loading them separately keeps a strict key match. + model.student_model.load_state_dict(ema.student_model.state_dict()) + model.projector.load_state_dict(ema.projector.state_dict()) + else: + model.load_state_dict(ema_state) # Load EMA weights into model + self._load_checkpoint_state(ckpt) # Load optimizer/scaler/EMA/best_fitness + del ckpt, ema, ema_state + self.scheduler.last_epoch = epoch - 1 + return True + + def resume_training(self, ckpt): + """Resume YOLO training from a given checkpoint.""" + if ckpt is None or not self.resume: + return + start_epoch = ckpt.get("epoch", -1) + 1 + assert 0 < start_epoch < self.epochs, ( + f"{self.args.model} training to {self.epochs} epochs is finished, nothing to resume.\n" + f"Start a new training without resuming, i.e. 'yolo train model={self.args.model}'" + ) + LOGGER.info(f"Resuming training {self.args.model} from epoch {start_epoch + 1} to {self.epochs} total epochs") + self._load_checkpoint_state(ckpt) + model = unwrap_model(self.model) + if getattr(getattr(model, "student_model", model).model[-1], "one2one_cv2", None) is not None: + # Resume both head losses independently of the selected inference head. + model.criterion = model.init_criterion() + model.criterion.updates = start_epoch - 1 + model.criterion.update() + self.start_epoch = start_epoch + + def _close_dataloader_mosaic(self): + """Update dataloaders to stop using mosaic augmentation.""" + if hasattr(self.train_loader.dataset, "mosaic"): + self.train_loader.dataset.mosaic = False + if hasattr(self.train_loader.dataset, "close_mosaic"): + LOGGER.info("Closing dataloader mosaic") + self.train_loader.dataset.close_mosaic(hyp=copy(self.args)) + + def build_optimizer(self, model, name="auto", lr=0.001, momentum=0.9, decay=1e-5, iterations=1e5): + """Construct an optimizer for the given model. + + Args: + model (torch.nn.Module): The model for which to build an optimizer. + name (str, optional): The name of the optimizer to use. If 'auto', the optimizer is selected based on the + number of iterations. + lr (float, optional): The learning rate for the optimizer. + momentum (float, optional): The momentum factor for the optimizer. + decay (float, optional): The weight decay for the optimizer. + iterations (float, optional): The number of iterations, which determines the optimizer if name is 'auto'. + + Returns: + (torch.optim.Optimizer): The constructed optimizer. + """ + g = [{}, {}, {}, {}] # optimizer parameter groups + bn = tuple(v for k, v in nn.__dict__.items() if "Norm" in k) # normalization layers, i.e. BatchNorm2d() + optimizers = {"Adam", "Adamax", "AdamW", "NAdam", "RAdam", "RMSprop", "SGD", "MuSGD", "auto"} + name = {x.lower(): x for x in optimizers}.get(str(name).lower(), str(name)) + if name == "auto": + LOGGER.info( + f"{colorstr('optimizer:')} 'optimizer=auto' found, " + f"ignoring 'lr0={self.args.lr0}' and 'momentum={self.args.momentum}' and " + f"determining best 'optimizer', 'lr0' and 'momentum' automatically... " + ) + nc = self.data.get("nc", 10) # number of classes + lr_fit = round(0.002 * 5 / (4 + nc), 6) # lr0 fit equation to 6 decimal places + name, lr, momentum = ("MuSGD", 0.01, 0.9) if iterations > 10000 else ("AdamW", lr_fit, 0.9) + self.args.warmup_bias_lr = 0.0 # no higher than 0.01 for Adam + + use_muon = name == "MuSGD" + for module_name, module in unwrap_model(model).named_modules(): + for param_name, param in module.named_parameters(recurse=False): + fullname = f"{module_name}.{param_name}" if module_name else param_name + if param.ndim in {2, 4} and use_muon: # muon only orthogonalizes matrices and conv filters + g[3][fullname] = param # muon params + elif "bias" in fullname: # bias (no decay) + g[2][fullname] = param + elif isinstance(module, bn) or "logit_scale" in fullname: # weight (no decay) + # ContrastiveHead and BNContrastiveHead included here with 'logit_scale' + g[1][fullname] = param + else: # weight (with decay) + g[0][fullname] = param + if not use_muon: + g = [x.values() for x in g[:3]] # convert to list of params + + if name in {"Adam", "Adamax", "AdamW", "NAdam", "RAdam"}: + optim_args = {"lr": lr, "betas": (momentum, 0.999), "weight_decay": 0.0} + elif name == "RMSprop": + optim_args = {"lr": lr, "momentum": momentum} + elif name == "SGD" or name == "MuSGD": + optim_args = {"lr": lr, "momentum": momentum, "nesterov": True} + else: + raise NotImplementedError( + f"Optimizer '{name}' not found in list of available optimizers {optimizers}. " + "Request support for additional optimizers at https://github.com/ultralytics/ultralytics." + ) + + num_params = [len(g[0]), len(g[1]), len(g[2])] # number of param groups + g[2] = {"params": g[2], **optim_args, "param_group": "bias"} + g[0] = {"params": g[0], **optim_args, "weight_decay": decay, "param_group": "weight"} + g[1] = {"params": g[1], **optim_args, "weight_decay": 0.0, "param_group": "bn"} + muon, sgd = (0.2, 1.0) + if use_muon: + num_params[0] = len(g[3]) # update number of params + g[3] = {"params": g[3], **optim_args, "weight_decay": decay, "use_muon": True, "param_group": "muon"} + # higher lr for certain parameters in MuSGD when finetuning + target = unwrap_model(model) + head = getattr(target, "student_model", target).model[-1] + heads = (getattr(head, "cv3", None), getattr(head, "one2one_cv3", None)) + boosted = {id(p) for m in heads if m for p in m.parameters()} + g_ = [] # new param groups + for x in g: + p = x.pop("params") + p1, p2 = [], [] + for k, v in p.items(): + (p1 if id(v) in boosted or "proto.semseg" in k or "SemanticSegment" in k else p2).append(v) + g_.extend([{"params": p1, **x, "lr": lr * 3}, {"params": p2, **x}]) + g = g_ + # fused=True must go to the constructor: that is where Adam registers _step_supports_amp_scaling, which lets + # GradScaler pass found_inf to the kernel instead of reading it back on the host + fused = {"fused": True} if name in {"Adam", "AdamW"} and TORCH_2_0 and next(model.parameters()).is_cuda else {} + optimizer = (partial(MuSGD, muon=muon, sgd=sgd) if use_muon else getattr(optim, name))(params=g, **fused) + + LOGGER.info( + f"{colorstr('optimizer:')} {type(optimizer).__name__}(lr={lr}, momentum={momentum}) with parameter groups " + f"{num_params[1]} weight(decay=0.0), {num_params[0]} weight(decay={decay}), {num_params[2]} bias(decay=0.0)" + ) + return optimizer + + +class MultiTrainer: + """Fine-tune a single base model across a collection of datasets and aggregate per-dataset results. + + Used automatically by Model.train() when `data` is a list or tuple, allowing one base model to be benchmarked across + many datasets (such as the RF100 collection) in a single call. The datasets are fine-tuned in series and the same + base weights seed each run, so every run starts from an identical model. All output is grouped under one sweep + directory (e.g. runs/detect/multitrain): each dataset gets its own run subdirectory, and the per-dataset and mean + metrics are written to multitrain_results.json (for post-processing) alongside a multitrain_results.png bar + chart. The base model object is left unchanged; each dataset's fine-tuned weights live in its own run directory. + + Attributes: + trainer (type[BaseTrainer] | None): Task trainer class for Python runs, or None for CLI subprocess runs. + args (dict): Training arguments shared across datasets; its `data` key holds the dataset collection. + model (torch.nn.Module): Base model whose weights seed each per-dataset fine-tune. + callbacks (dict | None): Callbacks forwarded to each per-dataset trainer. + trainers (list[SimpleNamespace]): Completed per-dataset run records. + metrics (dict): Mapping of each run name (e.g. coco8, coco8-2) to its training-metrics dict from the checkpoint. + mean_metrics (dict): Mean training metrics across successful datasets. + save_dir (Path | None): Sweep directory holding the per-dataset runs and the results JSON/plot. + + Examples: + Fine-tune one base model across several datasets and read back per-run metrics: + >>> from ultralytics import YOLO + >>> model = YOLO("yolo26n.pt") + >>> results = model.train(data=["coco8.yaml", "african-wildlife.yaml"], epochs=10) + >>> results["coco8"]["fitness"] # final fitness on the coco8 run + """ + + def __init__(self, trainer, args, model, _callbacks: dict | None = None): + """Initialize MultiTrainer with a task trainer class, shared training arguments, and the base model. + + Args: + trainer (type[BaseTrainer] | None): Task trainer class to run once per dataset. None uses CLI subprocesses. + args (dict): Training arguments; the `data` key holds the list/tuple of datasets to fine-tune on. + model (torch.nn.Module): Base model whose weights seed each per-dataset fine-tune. + _callbacks (dict, optional): Callback functions forwarded to each per-dataset trainer. + """ + self.trainer = trainer + self.args = args + self.model = model + self.callbacks = _callbacks + self.trainers = [] + self.metrics = {} + self.mean_metrics = {} + self.save_dir = None + + def train(self): + """Fine-tune the base model on each dataset in series and return a {dataset: metrics} mapping.""" + from types import SimpleNamespace + + from ultralytics.utils.patches import torch_load, torch_save + + datasets = self.args["data"] + # Group every per-dataset run and the summary plot under one sweep directory, e.g. runs/detect/multitrain + sweep = SimpleNamespace( + project=self.args.get("project"), + task=self.args.get("task"), + mode="train", + exist_ok=self.args.get("exist_ok", False), + ) + self.save_dir = get_save_dir(sweep, name="multitrain") + self.save_dir.mkdir(parents=True, exist_ok=True) + model_name = Path(str(self.args.get("model") or "multitrain_base")).stem + base_model = self.save_dir / f"{model_name}.pt" if self.trainer is None else None + if base_model: + state = qat_state(self.model) + model = deepcopy(self.model).half() + strip_qat(model) + torch_save({"model": model, "modelopt": state, "train_args": getattr(self.model, "args", {})}, base_model) + try: + for i, data in enumerate(datasets): + LOGGER.info( + f"\n{colorstr('blue', 'bold', f'MultiTrainer {i + 1}/{len(datasets)}:')} fine-tuning on {data}" + ) + path = Path(str(data)) + parent = path.parent.name + name = Path(os.path.abspath(path.parent)).name if path.stem == "data" and parent else path.stem + run_name = name + try: + overrides = { + **self.args, + "data": data, + "project": str(self.save_dir), # nest per-dataset runs inside the sweep directory + "name": name, + "resume": False, + } + run = SimpleNamespace( + project=overrides["project"], + name=overrides["name"], + task=overrides.get("task"), + mode="train", + exist_ok=overrides.get("exist_ok", False), + save_dir=None, + ) + save_dir = get_save_dir(run) + save_dir.mkdir(parents=True, exist_ok=True) + run_name = save_dir.name + overrides["save_dir"] = str(save_dir) + if self.trainer is None: + overrides["model"] = str(base_model) + overrides.pop("cfg", None) # already merged here; the CLI would re-apply the file + subprocess.run( + [ + *_YOLO_CLI_COMMAND, + "train", + *(f"{k}={v}" for k, v in overrides.items()), + ], + check=True, + ) + else: + trainer = self.trainer(overrides=overrides, _callbacks=self.callbacks) + pretrained = overrides.get("pretrained", True) + weights = None if pretrained is False else self.model + if isinstance(pretrained, (str, Path)): + weights, _ = load_checkpoint(pretrained) + trainer.model = trainer.get_model(weights=weights, cfg=self.model.yaml) + trainer.train() + best, last = save_dir / "weights" / "best.pt", save_dir / "weights" / "last.pt" + ckpt = best if best.exists() else last + metrics = None + if self.trainer is not None: + metrics = getattr(getattr(trainer, "validator", None), "metrics", None) + if metrics is not None: + metrics = metrics.results_dict + self.metrics[run_name] = metrics or (torch_load(ckpt)["train_metrics"] if ckpt.exists() else None) + self.trainers.append(SimpleNamespace(save_dir=save_dir, best=best, last=last)) + except Exception as e: # one bad dataset should not abort the whole sweep + LOGGER.error(f"MultiTrainer: fine-tuning on {data} failed, skipping: {e}") + self.metrics[run_name] = None + finally: + if base_model: + base_model.unlink(missing_ok=True) + if RANK in {-1, 0} and self.trainers: + self.save_dir.mkdir(parents=True, exist_ok=True) + self.save_results() # JSON of per-dataset + mean metrics for programmatic post-processing + if self.args.get("plots", True): + self.plot_results() + return self.metrics + + def save_results(self): + """Write per-dataset and mean metrics to multitrain_results.json for programmatic post-processing.""" + import json + + results = {run: ({k: float(v) for k, v in m.items()} if m else None) for run, m in self.metrics.items()} + valid = [m for m in results.values() if m] + keys = {k for m in valid for k in m} + self.mean_metrics = {k: sum(m[k] for m in valid if k in m) / sum(k in m for m in valid) for k in keys} + file = self.save_dir / "multitrain_results.json" + with open(file, "w", encoding="utf-8") as f: + json.dump({"results": results, "mean": self.mean_metrics}, f, indent=2) + LOGGER.info(f"MultiTrainer results saved to {colorstr('bold', file)}") + return file + + def plot_results(self): + """Save a cross-dataset bar chart of the per-dataset metric with the mean across all datasets.""" + from ultralytics.cfg import TASK2METRIC + from ultralytics.utils.plotting import plot_multitrain_results + + key = TASK2METRIC.get(self.args.get("task")) + scores = {run: float(m.get(key, m.get("fitness", 0.0))) for run, m in self.metrics.items() if m} + if not scores: + return None + fname = plot_multitrain_results(scores, key=key or "fitness", save_dir=self.save_dir) + LOGGER.info(f"MultiTrainer results saved to {colorstr('bold', fname)}") + return fname diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/tuner.py b/.venv/lib/python3.12/site-packages/ultralytics/engine/tuner.py new file mode 100644 index 0000000000000000000000000000000000000000..69486c5a732be6392f7c2fdbdaffc0227b388a37 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/engine/tuner.py @@ -0,0 +1,614 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Module provides functionalities for hyperparameter tuning of the Ultralytics YOLO models for object detection, instance +segmentation, image classification, and pose estimation. + +Hyperparameter tuning is the process of systematically searching for the optimal set of hyperparameters +that yield the best model performance. This is particularly crucial in deep learning models like YOLO, +where small changes in hyperparameters can lead to significant differences in model accuracy and efficiency. + +Examples: + Tune hyperparameters for YOLO26n on COCO8 at imgsz=640 and epochs=10 for 300 tuning iterations. + >>> from ultralytics import YOLO + >>> model = YOLO("yolo26n.pt") + >>> model.tune(data="coco8.yaml", epochs=10, iterations=300, optimizer="AdamW", plots=False, save=False, val=False) +""" + +from __future__ import annotations + +import json +import shutil +import time +from datetime import datetime + +import numpy as np + +from ultralytics.cfg import CFG_INT_KEYS, TASK2METRIC, get_cfg, get_save_dir +from ultralytics.utils import LOGGER, YAML, callbacks, colorstr, remove_colorstr +from ultralytics.utils.checks import check_requirements +from ultralytics.utils.plotting import plot_tune_results + + +class Tuner: + """A class for hyperparameter tuning of YOLO models. + + The class evolves YOLO model hyperparameters over a given number of iterations by mutating them according to the + search space and retraining the model to evaluate their performance. Supports both local NDJSON storage and + distributed MongoDB Atlas coordination for multi-machine hyperparameter optimization. + + Attributes: + space (dict[str, tuple]): Hyperparameter search space containing bounds and scaling factors for mutation. + tune_dir (Path): Directory where evolution logs and results will be saved. + tune_file (Path): Path to the NDJSON file where evolution logs are saved. + args (SimpleNamespace): Configuration arguments for the tuning process. + model (torch.nn.Module): Base model whose weights seed each iteration. + callbacks (dict): Callback functions to be executed during tuning. + prefix (str): Prefix string for logging messages. + mongodb (MongoClient): Optional MongoDB client for distributed tuning. + collection (Collection): MongoDB collection for storing tuning results. + + Methods: + _mutate: Mutate hyperparameters based on bounds and scaling factors. + __call__: Execute the hyperparameter evolution across multiple iterations. + + Examples: + Tune hyperparameters for YOLO26n on COCO8 at imgsz=640 and epochs=10 for 300 tuning iterations. + >>> from ultralytics import YOLO + >>> model = YOLO("yolo26n.pt") + >>> model.tune( + >>> data="coco8.yaml", + >>> epochs=10, + >>> iterations=300, + >>> plots=False, + >>> save=False, + >>> val=False + >>> ) + + Tune with distributed MongoDB Atlas coordination across multiple machines: + >>> model.tune( + >>> data="coco8.yaml", + >>> epochs=10, + >>> iterations=300, + >>> mongodb_uri="mongodb+srv://user:pass@cluster.mongodb.net/", + >>> mongodb_db="ultralytics", + >>> mongodb_collection="tune_results" + >>> ) + + Tune with custom search space: + >>> model.tune(space={"lr0": (1e-5, 1e-2), "momentum": (0.7, 0.98)}) + """ + + def __init__(self, args, _callbacks: dict | None = None, *, model=None): + """Initialize the Tuner with configurations. + + Args: + args (dict): Configuration for hyperparameter evolution. + _callbacks (dict | None, optional): Callback functions to be executed during tuning. + model (torch.nn.Module, optional): Base model whose weights seed each iteration, built from args if None. + """ + self.space = args.pop("space", None) or { # key: (min, max, gain(optional)) + # 'optimizer': tune.choice(['SGD', 'Adam', 'AdamW', 'NAdam', 'RAdam', 'RMSProp']), + "lr0": (1e-5, 1e-2), # initial learning rate (i.e. SGD=1E-2, Adam=1E-3) + "lrf": (0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf) + "momentum": (0.7, 0.98, 0.3), # SGD momentum/Adam beta1 + "weight_decay": (0.0, 0.001), # optimizer weight decay 5e-4 + "warmup_epochs": (0.0, 5.0), # warmup epochs (fractions ok) + "warmup_momentum": (0.0, 0.95), # warmup initial momentum + "box": (1.0, 20.0), # box loss gain + "cls": (0.1, 4.0), # cls loss gain (scale with pixels) + "cls_pw": (0.0, 1.0), # cls power weight + "dfl": (0.4, 12.0), # dfl loss gain + "hsv_h": (0.0, 0.1), # image HSV-Hue augmentation (fraction) + "hsv_s": (0.0, 0.9), # image HSV-Saturation augmentation (fraction) + "hsv_v": (0.0, 0.9), # image HSV-Value augmentation (fraction) + "degrees": (0.0, 45.0), # image rotation (+/- deg) + "translate": (0.0, 0.9), # image translation (+/- fraction) + "scale": (0.0, 0.95), # image scale (+/- gain) + "shear": (0.0, 10.0), # image shear (+/- deg) + "perspective": (0.0, 0.001), # image perspective (+/- fraction), range 0-0.001 + "flipud": (0.0, 1.0), # image flip up-down (probability) + "fliplr": (0.0, 1.0), # image flip left-right (probability) + "bgr": (0.0, 1.0), # image channel bgr (probability) + "mosaic": (0.0, 1.0), # image mosaic (probability) + "mixup": (0.0, 1.0), # image mixup (probability) + "cutmix": (0.0, 1.0), # image cutmix (probability) + "copy_paste": (0.0, 1.0), # segment/obb copy-paste (object fraction) + "close_mosaic": (0.0, 10.0), # close dataloader mosaic (epochs) + } + mongodb_uri = args.pop("mongodb_uri", None) + mongodb_db = args.pop("mongodb_db", "ultralytics") + mongodb_collection = args.pop("mongodb_collection", "tuner_results") + + self.args = get_cfg(overrides=args) + if model is None: + from ultralytics import YOLO + + model = YOLO(self.args.model).model + self.model = model + self.args.exist_ok = self.args.resume # resume w/ same tune_dir + self.tune_dir = get_save_dir(self.args, name=self.args.name or "tune") + self.args.name, self.args.exist_ok, self.args.resume = (None, False, False) # reset to not affect training + self.tune_file = self.tune_dir / "tune_results.ndjson" + self.callbacks = _callbacks or callbacks.get_default_callbacks() + self.prefix = colorstr("Tuner: ") + callbacks.add_integration_callbacks(self) + + # MongoDB Atlas support (optional) + self.mongodb = None + if mongodb_uri: + self._init_mongodb(mongodb_uri, mongodb_db, mongodb_collection) + + LOGGER.info( + f"{self.prefix}Initialized Tuner instance with 'tune_dir={self.tune_dir}'\n" + f"{self.prefix}💡 Learn about tuning at https://docs.ultralytics.com/guides/hyperparameter-tuning" + ) + + def _connect(self, uri: str = "", max_retries: int = 3): + """Create MongoDB client with exponential backoff retry on connection failures. + + Args: + uri (str): MongoDB connection string with credentials and cluster information. + max_retries (int): Maximum number of connection attempts before giving up. + + Returns: + (MongoClient): Connected MongoDB client instance. + """ + check_requirements("pymongo") + + from pymongo import MongoClient + from pymongo.errors import ConnectionFailure, ServerSelectionTimeoutError + + for attempt in range(max_retries): + try: + client = MongoClient( + uri, + serverSelectionTimeoutMS=30000, + connectTimeoutMS=20000, + socketTimeoutMS=40000, + retryWrites=True, + retryReads=True, + maxPoolSize=30, + minPoolSize=3, + maxIdleTimeMS=60000, + ) + client.admin.command("ping") # Test connection + LOGGER.info(f"{self.prefix}Connected to MongoDB Atlas (attempt {attempt + 1})") + return client + except (ConnectionFailure, ServerSelectionTimeoutError): + if attempt == max_retries - 1: + raise + wait_time = 2**attempt + LOGGER.warning( + f"{self.prefix}MongoDB connection failed (attempt {attempt + 1}), retrying in {wait_time}s..." + ) + time.sleep(wait_time) + + def _init_mongodb(self, mongodb_uri="", mongodb_db="", mongodb_collection=""): + """Initialize MongoDB connection for distributed tuning. + + Connects to MongoDB Atlas for distributed hyperparameter optimization across multiple machines. Each worker + saves results to a shared collection and reads the latest best hyperparameters from all workers for evolution. + + Args: + mongodb_uri (str): MongoDB connection string. + mongodb_db (str, optional): Database name. + mongodb_collection (str, optional): Collection name. + + Notes: + - Creates a fitness index when workers start a new collection + - Falls back to local NDJSON mode if connection fails + - Uses connection pooling and retry logic for production reliability + """ + self.mongodb = self._connect(mongodb_uri) + self.collection = self.mongodb[mongodb_db][mongodb_collection] + LOGGER.info(f"{self.prefix}Using MongoDB Atlas for distributed tuning") + + @staticmethod + def _json_default(x): + """Convert tensor-like values for JSON serialization.""" + return x.item() if hasattr(x, "item") else str(x) + + def _result_record( + self, + iteration: int, + fitness: float, + hyperparameters: dict[str, float], + datasets: dict[str, dict], + save_dirs: dict[str, str] | None = None, + failed_datasets: list[str] | None = None, + ) -> dict: + """Build one local tuning result record.""" + result = { + "iteration": iteration, + "fitness": round(fitness, 5), + "hyperparameters": hyperparameters, + "datasets": datasets, + } + if save_dirs: + result["save_dirs"] = save_dirs + if failed_datasets: + result["failed_datasets"] = failed_datasets + return result + + def _save_to_mongodb( + self, + fitness: float, + hyperparameters: dict[str, float], + metrics: dict, + datasets: dict[str, dict], + save_dirs: dict[str, str], + failed_datasets: list[str], + ): + """Save results to MongoDB with proper type conversion. + + Args: + fitness (float): Fitness score achieved with these hyperparameters. + hyperparameters (dict[str, float]): Dictionary of hyperparameter values. + metrics (dict): Complete training metrics dictionary (mAP, precision, recall, losses, etc.). + datasets (dict[str, dict]): Per-dataset metrics for the iteration. + save_dirs (dict[str, str]): Per-dataset training directories for cleanup. + failed_datasets (list[str]): Dataset runs that did not produce training metrics. + """ + try: + self.collection.insert_one( + { + "fitness": fitness, + "hyperparameters": {k: (v.item() if hasattr(v, "item") else v) for k, v in hyperparameters.items()}, + "metrics": metrics, + "datasets": datasets, + "save_dirs": save_dirs, + "failed_datasets": failed_datasets, + "timestamp": datetime.now().astimezone(), + "iteration": self.collection.find_one_and_update( + {"_id": "defaults"}, {"$inc": {"last_iteration": 1}}, return_document=True + )["last_iteration"], + } + ) + except Exception as e: + LOGGER.warning(f"{self.prefix}MongoDB save failed: {e}") + + def _sync_mongodb_to_file(self): + """Sync MongoDB results to the local NDJSON tuning log. + + Downloads all results from MongoDB and writes them to the local NDJSON file in chronological order. This keeps + resume, mutation, and plotting on the same local source of truth when using distributed tuning. + """ + try: + all_results = list(self.collection.find({"fitness": {"$exists": True}}).sort("iteration", 1)) + if not all_results: + return + last_iteration = max(r["iteration"] for r in all_results) + self.collection.update_one({"_id": "defaults"}, {"$max": {"last_iteration": last_iteration}}, upsert=True) + + with open(self.tune_file, "w", encoding="utf-8") as f: + f.writelines( + json.dumps( + self._result_record( + result["iteration"], + result["fitness"] or 0.0, + result.get("hyperparameters", {}), + result.get("datasets", {}), + result.get("save_dirs"), + result.get("failed_datasets"), + ), + default=self._json_default, + ) + + "\n" + for result in all_results + ) + + except Exception as e: + LOGGER.warning(f"{self.prefix}MongoDB to NDJSON sync failed: {e}") + + def _load_local_results(self) -> list[dict]: + """Load local tuning results from the NDJSON log.""" + if not self.tune_file.exists(): + return [] + with open(self.tune_file, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + def _local_results_to_array(self, results: list[dict]) -> np.ndarray | None: + """Convert local NDJSON records to a fitness-plus-hyperparameters numpy array.""" + if not results: + return None + return np.array( + [ + [r.get("fitness", 0.0)] + + [r.get("hyperparameters", {}).get(k, getattr(self.args, k)) for k in self.space] + for r in results + ], + dtype=float, + ) + + def _save_local_result(self, result: dict): + """Append one tuning result to the local NDJSON log.""" + with open(self.tune_file, "a", encoding="utf-8") as f: + f.write(json.dumps(result, default=self._json_default) + "\n") + + @staticmethod + def _best_metrics(result: dict) -> dict | None: + """Summarize best-result metrics for logging.""" + datasets = result.get("datasets", {}) + if len(datasets) == 1: + return next(iter(datasets.values())) + if len(datasets) > 1: + return {k: round(v.get("fitness") or 0.0, 5) for k, v in datasets.items()} + return None + + @staticmethod + def _has_training_metrics(result: dict, require_all: bool = False) -> bool: + """Return whether a tuning result contains training metrics.""" + datasets = result.get("datasets", {}) + failed = set(result.get("failed_datasets", ())) + trained = [bool(metrics) and dataset not in failed for dataset, metrics in datasets.items()] + return bool(trained) and (all(trained) if require_all else any(trained)) + + @classmethod + def _best_result_index(cls, results: list[dict], fitness: np.ndarray) -> int: + """Return the best result index, preferring rows with training metrics.""" + valid = [i for i, result in enumerate(results) if cls._has_training_metrics(result)] + return valid[int(fitness[valid].argmax())] if valid else int(fitness.argmax()) + + def _mutate( + self, + n: int = 9, + sigma: float = 0.2, + ) -> dict[str, float]: + """Mutate hyperparameters based on bounds and scaling factors specified in `self.space`. + + Args: + n (int): Number of top parents to consider. + sigma (float): Initial normalized mutation standard deviation. + + Returns: + (dict[str, float]): A dictionary containing mutated hyperparameters. + """ + history = None + + # Try MongoDB first if available + if self.mongodb: + if results := list( + self.collection.find({"fitness": {"$exists": True}}, {"fitness": 1, "hyperparameters": 1}).sort( + "_id", 1 + ) + ): + history = np.array( + [ + [r["fitness"]] + [r["hyperparameters"].get(k, self.args.get(k)) for k in self.space] + for r in results + ] + ) + else: + from pymongo.errors import DuplicateKeyError + + default_hyp = self._constrain({k: getattr(self.args, k) for k in self.space}) + try: + self.collection.insert_one({"_id": "defaults", "timestamp": datetime.now().astimezone()}) + except DuplicateKeyError: # Another worker already claimed the default generation + history = np.array([[0.0, *default_hyp.values()]]) + self.collection.create_index([("fitness", -1)], background=True) + if history is None: + return default_hyp + + # Fall back to local NDJSON if MongoDB unavailable or empty + if history is None: + results = self._load_local_results() + history = self._local_results_to_array(results) + + # Mutate if we have data, otherwise use defaults + if history is not None: + rng = np.random.default_rng() + ng = len(self.space) + fitness = np.round(history[:, 0], 5) + stale = len(history) - 1 - int(np.argmax(fitness)) + order = np.argsort(-history[:, 0]) + x = history[order][:n] + bounds = np.array([v[:2] for v in self.space.values()]) + span = np.ptp(bounds, axis=1) + mutable = span > 0 + if mutable.any(): + population = np.divide(x[:, 1:] - bounds[:, 0], span, out=np.zeros_like(x[:, 1:]), where=mutable) + weights = x[:, 0] - x[:, 0].min() + 1e-6 + weights = weights if np.isfinite(weights).all() and weights.sum() else np.ones_like(weights) + gains = np.array([v[2] if len(v) == 3 else 1.0 for v in self.space.values()]) # gains 0-1 + resolution = np.array([1 if k in CFG_INT_KEYS else 1e-5 for k in self.space]) + decay = 1 - 0.2 * min(stale / 25, 1) + scale = sigma * decay * gains + scale = np.maximum(scale, np.divide(resolution, span, out=np.zeros(ng), where=mutable)) + existing = {tuple(row[1:]) for row in history} + covariance = confidence = None + if len(history) >= 30: + n_elite = min(int(np.ceil(len(history) * 0.2)), 30) + confidence = min(n_elite / mutable.sum(), 1) + elite = np.divide( + history[order[:n_elite], 1:] - bounds[:, 0], + span, + out=np.zeros((n_elite, ng)), + where=mutable, + ) + covariance = np.cov(elite, rowvar=False) * decay**2 * confidence + np.diag( + np.square(scale) / mutable.sum() + ) + for attempt in range(200): + if attempt < 100: + genes = population[rng.choice(len(x), p=weights / weights.sum())] + mask = (rng.random(ng) < 0.5) & mutable + if covariance is not None and rng.random() < 0.4 * confidence: + genes = np.where(mask, rng.multivariate_normal(genes, covariance), genes) + genes = 1 - np.abs(genes % 2 - 1) + else: + genes = np.clip(genes + mask * rng.standard_normal(ng) * scale, 0, 1) + else: + genes = population[rng.choice(len(x), p=weights / weights.sum())].copy() + genes[mutable] = rng.random(mutable.sum()) + hyp = {k: float(bounds[i, 0] + genes[i] * span[i]) for i, k in enumerate(self.space)} + hyp = self._constrain(hyp) + if tuple(hyp.values()) not in existing: + return hyp + raise RuntimeError(f"{self.prefix}Unable to generate a unique hyperparameter mutation") + raise RuntimeError(f"{self.prefix}Hyperparameter search space is exhausted") + else: + hyp = {k: getattr(self.args, k) for k in self.space} + + return self._constrain(hyp) + + def _constrain(self, hyp: dict[str, float]) -> dict[str, float]: + """Constrain hyperparameters to their search bounds and configured types.""" + for k, bounds in self.space.items(): + if k in CFG_INT_KEYS: + lower, upper = int(np.ceil(bounds[0])), int(np.floor(bounds[1])) + if lower > upper: + raise ValueError(f"{self.prefix}Search space for '{k}' contains no integer values") + hyp[k] = min(max(round(hyp[k]), lower), upper) + else: + hyp[k] = min(max(round(hyp[k], 5), bounds[0]), bounds[1]) + + return hyp + + def __call__(self, iterations: int = 300, cleanup: bool = True): + """Execute the hyperparameter evolution process when the Tuner instance is called. + + This method iterates through the specified number of iterations, performing the following steps: + 1. Sync MongoDB results to local NDJSON (if using distributed mode) + 2. Mutate hyperparameters using the best previous results or defaults + 3. Train a YOLO model with the mutated hyperparameters + 4. Log fitness scores and hyperparameters to MongoDB and/or NDJSON + 5. Track the best performing configuration across all iterations + + Args: + iterations (int): The number of generations to run the evolution for. + cleanup (bool): Whether to delete iteration weights to reduce storage space during tuning. + """ + from ultralytics.engine.trainer import MultiTrainer + + t0 = time.time() + self.tune_dir.mkdir(parents=True, exist_ok=True) + (self.tune_dir / "weights").mkdir(parents=True, exist_ok=True) + best_save_dirs = {} + n_successful = 0 # iters with real training metrics in this invocation (excludes resumed/MongoDB rows) + + # Sync MongoDB to local NDJSON at startup for proper resume logic + if self.mongodb: + self._sync_mongodb_to_file() + + start = 0 + if self.tune_file.exists(): + start = len(self._load_local_results()) + LOGGER.info(f"{self.prefix}Resuming tuning run {self.tune_dir} from iteration {start + 1}...") + for i in range(start, iterations): + # Mutate hyperparameters + mutated_hyp = self._mutate() + LOGGER.info(f"{self.prefix}Starting iteration {i + 1}/{iterations} with hyperparameters: {mutated_hyp}") + + train_args = {**vars(self.args), **mutated_hyp} + data = train_args.pop("data") + if not isinstance(data, (list, tuple)): + data = [data] + trainer = MultiTrainer(None, {**train_args, "data": data}, self.model) + raw_metrics = trainer.train() + failed_datasets = [dataset for dataset, metrics in raw_metrics.items() if not metrics] + metric = TASK2METRIC[train_args["task"]] + dataset_metrics = { + dataset: metrics or {metric: 0.0, "fitness": 0.0} for dataset, metrics in raw_metrics.items() + } + save_dir = [trainer.save_dir / dataset for dataset in dataset_metrics] + weights_dir = [s / "weights" for s in save_dir] + metrics = trainer.mean_metrics + fitness = sum((metrics or {}).get("fitness") or 0.0 for metrics in dataset_metrics.values()) / len(data) + metrics["fitness"] = fitness + result = self._result_record( + i + 1, + fitness, + mutated_hyp, + dataset_metrics, + {dataset: str(s) for dataset, s in zip(dataset_metrics, save_dir)}, + failed_datasets, + ) + if self._has_training_metrics(result, require_all=True): + n_successful += 1 + stop_after_iteration = False + if self.mongodb: + self._save_to_mongodb( + fitness, mutated_hyp, metrics, dataset_metrics, result["save_dirs"], failed_datasets + ) + self._sync_mongodb_to_file() + total_mongo_iterations = self.collection.count_documents({"fitness": {"$exists": True}}) + if total_mongo_iterations >= iterations: + stop_after_iteration = True + else: + self._save_local_result(result) + + # Get best results + results = self._load_local_results() + x = self._local_results_to_array(results) + fitness = x[:, 0] # first column + best_idx = self._best_result_index(results, fitness) + best_result = results[best_idx] + n_attempted = (i + 1) - start # iters tried in this invocation + current_best_save_dirs = best_result.get("save_dirs", {}) + best_is_current = best_result.get("save_dirs") == result["save_dirs"] + if best_is_current: + if cleanup: + for s in best_save_dirs.values(): + if s not in current_best_save_dirs.values(): + shutil.rmtree(s, ignore_errors=True) + for dataset, weight_dir in zip(dataset_metrics, weights_dir): + best_weights_dir = ( + self.tune_dir / "weights" if len(data) == 1 else self.tune_dir / "weights" / dataset + ) + best_weights_dir.mkdir(parents=True, exist_ok=True) + for ckpt in weight_dir.glob("*.pt"): + shutil.copy2(ckpt, best_weights_dir) + best_save_dirs = current_best_save_dirs + elif cleanup: + for s in save_dir: + shutil.rmtree(s, ignore_errors=True) # remove iteration dirs to reduce storage space + best_save_dirs = current_best_save_dirs + + # Plot tune results + plot_tune_results(str(self.tune_file)) + + # Save and print tune results + if n_successful == n_attempted: + status = "complete ✅" + elif n_successful == 0: + status = "complete (all failed) ❌" + else: + status = f"complete ({n_successful}/{n_attempted} succeeded) ⚠️" + has_valid_best = self._has_training_metrics(best_result) + header_lines = [ + f"{self.prefix}{i + 1}/{iterations} iterations {status} ({time.time() - t0:.2f}s)", + f"{self.prefix}Results saved to {colorstr('bold', self.tune_dir)}", + ] + if has_valid_best: + header_lines.extend( + [ + f"{self.prefix}Best fitness={fitness[best_idx]} observed at iteration {best_idx + 1}", + f"{self.prefix}Best fitness metrics are {self._best_metrics(best_result)}", + ( + f"{self.prefix}Best fitness model is " + f"{self.tune_dir / 'weights' if len(best_result.get('datasets', {})) == 1 else 'not saved for multi-dataset tuning'}" + ), + ] + ) + header = "\n".join(header_lines) + LOGGER.info("\n" + header) + if not has_valid_best: + LOGGER.error( + f"{self.prefix}No iterations produced training metrics; skipping best_hyperparameters.yaml" + ) + else: + data = { + k: int(v) if k in CFG_INT_KEYS else float(v) for k, v in zip(self.space.keys(), x[best_idx, 1:]) + } + YAML.save( + self.tune_dir / "best_hyperparameters.yaml", + data=data, + header=remove_colorstr(header.replace(self.prefix, "# ")) + "\n", + ) + YAML.print(self.tune_dir / "best_hyperparameters.yaml") + if stop_after_iteration: + LOGGER.info( + f"{self.prefix}Target iterations ({iterations}) reached in MongoDB ({total_mongo_iterations}). Stopping." + ) + break diff --git a/.venv/lib/python3.12/site-packages/ultralytics/engine/validator.py b/.venv/lib/python3.12/site-packages/ultralytics/engine/validator.py new file mode 100644 index 0000000000000000000000000000000000000000..bd2be04341508832a47d74710b3c2beba039552b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/engine/validator.py @@ -0,0 +1,427 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Check a model's accuracy on a test or val split of a dataset. + +Usage: + $ yolo val model=yolo26n.pt data=coco8.yaml imgsz=640 + +Usage - formats: + $ yolo val model=yolo26n.pt # PyTorch + yolo26n.torchscript # TorchScript + yolo26n.onnx # ONNX Runtime or OpenCV DNN with dnn=True + yolo26n_openvino_model # OpenVINO + yolo26n.engine # TensorRT + yolo26n.mlpackage # CoreML (macOS-only) + yolo26n_saved_model # TensorFlow SavedModel + yolo26n.pb # TensorFlow GraphDef + yolo26n_edgetpu.tflite # TensorFlow Edge TPU + yolo26n_paddle_model # PaddlePaddle + yolo26n.mnn # MNN + yolo26n_ncnn_model # NCNN + yolo26n_imx_model # Sony IMX + yolo26n_rknn_model # Rockchip RKNN + yolo26n_executorch_model # ExecuTorch + yolo26n_axelera_model # Axelera AI + yolo26n_deepx_model # DEEPX + yolo26n_qnn.onnx # Qualcomm QNN + yolo26n.tflite # LiteRT + yolo26n_ascend_model # Huawei Ascend +""" + +from __future__ import annotations + +import json +import time +from copy import deepcopy +from pathlib import Path + +import numpy as np +import torch +import torch.distributed as dist + +from ultralytics.cfg import get_cfg, get_save_dir +from ultralytics.data.utils import check_cls_dataset, check_det_dataset, convert_ndjson_to_yolo_if_needed +from ultralytics.nn.autobackend import AutoBackend +from ultralytics.utils import LOCAL_RANK, LOGGER, RANK, TQDM, callbacks, colorstr, emojis +from ultralytics.utils.checks import check_imgsz +from ultralytics.utils.ops import Profile, linear_sum_assignment +from ultralytics.utils.torch_utils import ( + attempt_compile, + autocast, + get_torch_device_backend, + select_device, + smart_inference_mode, + torch_distributed_zero_first, + unwrap_model, +) + + +class BaseValidator: + """A base class for creating validators. + + This class provides the foundation for validation processes, including model evaluation, metric computation, and + result visualization. + + Attributes: + args (SimpleNamespace): Configuration for the validator. + dataloader (DataLoader): DataLoader to use for validation. + model (nn.Module): Model to validate. + data (dict): Data dictionary containing dataset information. + device (torch.device): Device to use for validation. + batch_i (int): Current batch index. + training (bool): Whether the model is in training mode. + names (dict): Class names mapping. + seen (int): Number of images seen so far during validation. + stats (dict): Statistics collected during validation. + confusion_matrix: Confusion matrix for classification evaluation. + nc (int): Number of classes. + iouv (torch.Tensor): IoU thresholds from 0.50 to 0.95 in steps of 0.05. + jdict (list): List to store JSON validation results. + speed (dict): Dictionary with keys 'preprocess', 'inference', 'loss', 'postprocess' and their respective batch + processing times in milliseconds. + save_dir (Path): Directory to save results. + plots (dict): Dictionary to store plots for visualization. + callbacks (dict): Dictionary to store various callback functions. + stride (int): Model stride for padding calculations. + loss (dict): Accumulated loss items during training validation. + + Methods: + __call__: Execute validation process, running inference on dataloader and computing performance metrics. + match_predictions: Match predictions to ground truth objects using IoU. + add_callback: Append the given callback to the specified event. + run_callbacks: Run all callbacks associated with a specified event. + get_dataloader: Get data loader from dataset path and batch size. + build_dataset: Build dataset from image path. + preprocess: Preprocess an input batch. + postprocess: Postprocess the predictions. + init_metrics: Initialize performance metrics for the YOLO model. + update_metrics: Update metrics based on predictions and batch. + finalize_metrics: Finalize and return all metrics. + get_stats: Return statistics about the model's performance. + print_results: Print the results of the model's predictions. + get_desc: Get description of the YOLO model. + on_plot: Register plots for visualization. + plot_val_samples: Plot validation samples during training. + plot_predictions: Plot YOLO model predictions on batch images. + pred_to_json: Convert predictions to JSON format. + eval_json: Evaluate and return JSON format of prediction statistics. + """ + + def __init__(self, dataloader=None, save_dir=None, args=None, _callbacks: dict | None = None): + """Initialize a BaseValidator instance. + + Args: + dataloader (torch.utils.data.DataLoader, optional): DataLoader to be used for validation. + save_dir (Path, optional): Directory to save results. + args (SimpleNamespace, optional): Configuration for the validator. + _callbacks (dict, optional): Dictionary to store various callback functions. + """ + import torchvision # noqa (import here so torchvision import time not recorded in postprocess time) + + self.args = get_cfg(overrides=args) + self.dataloader = dataloader + self.stride = None + self.data = None + self.device = None + self.batch_i = None + self.training = True + self.names = None + self.seen = None + self.stats = None + self.confusion_matrix = None + self.nc = None + self.iouv = None + self.jdict = None + self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0} + + self.save_dir = save_dir or get_save_dir(self.args) + (self.save_dir / "labels" if self.args.save_txt else self.save_dir).mkdir(parents=True, exist_ok=True) + if self.args.conf is None: + self.args.conf = 0.01 if self.args.task == "obb" else 0.001 # reduce OBB val memory usage + self.args.imgsz = check_imgsz(self.args.imgsz, max_dim=1) + + self.plots = {} + self.callbacks = _callbacks or callbacks.get_default_callbacks() + + @smart_inference_mode() + def __call__(self, trainer=None, model=None, **kwargs): + """Execute validation process, running inference on dataloader and computing performance metrics. + + Args: + trainer (object, optional): Trainer object that contains the model to validate. + model (nn.Module, optional): Model to validate if not using a trainer. + **kwargs (Any): Task-specific model preparation arguments. + + Returns: + (dict): Dictionary containing validation statistics. + """ + self.training = trainer is not None + model = self.get_model(model, trainer, **kwargs) + augment = self.args.augment and (not self.training) + if self.training: + if hasattr(model, "end2end"): + model.end2end = self.args.nms is False + self.device = trainer.device + self.data = trainer.data + # Keep training validation read-only: inputs may be fp16, but EMA/model weights stay fp32 under autocast. + self.args.quantize = 16 if (self.device.type != "cpu" and trainer.amp) else None + model = model.float() + self.loss = {k: torch.zeros_like(v) for k, v in trainer.loss_items.items()} + self.args.plots &= trainer.stopper.possible_stop or (trainer.epoch == trainer.epochs - 1) + model.eval() + else: + if str(self.args.model).endswith(".yaml") and model is None: + LOGGER.warning("validating an untrained model YAML will result in 0 mAP.") + callbacks.add_integration_callbacks(self) + with torch_distributed_zero_first(LOCAL_RANK): + self.args.data = convert_ndjson_to_yolo_if_needed(self.args.data, self.args.fraction) + device_type = str(self.args.device).split(":", 1)[0] + device_type = device_type if device_type in {"npu", "xpu"} else "cuda" + model = AutoBackend( + model=model or self.args.model, + # DDP ranks reuse the device assigned in trainer._setup_ddp() + device=select_device(self.args.device) + if RANK == -1 + else torch.device(device_type, get_torch_device_backend(device_type).current_device()), + dnn=self.args.dnn, + data=self.args.data, + fp16=self.args.quantize == 16, + channels_last=self.args.channels_last, + end2end=self.args.nms is False, + ) + self.device = model.device # update device + self.args.quantize = 16 if model.fp16 else None # record actual inference precision + stride, fmt = model.stride, model.format + pt = fmt == "pt" + if augment and not model.base_model: + LOGGER.warning(f"'augment' is not supported by this model (format='{fmt}'), ignoring.") + augment = False + imgsz = check_imgsz(self.args.imgsz, stride=stride) + if fmt not in {"pt", "torchscript"} and not getattr(model, "dynamic", False): + if hasattr(model, "imgsz"): + self.args.imgsz = imgsz = max(model.imgsz) # reuse square imgsz from export metadata + self.args.batch = model.metadata.get("batch", 1) # export.py models default to batch-size 1 + LOGGER.info(f"Setting batch={self.args.batch} input of shape ({self.args.batch}, 3, {imgsz}, {imgsz})") + + if self.args.task == "classify": + self.data = check_cls_dataset(self.args.data, split=self.args.split) + elif str(self.args.data).rsplit(".", 1)[-1] in {"yaml", "yml"} or self.args.task in { + "detect", + "segment", + "pose", + "obb", + "semantic", + "depth", + }: + self.data = check_det_dataset(self.args.data, split=self.args.split) + else: + raise FileNotFoundError(emojis(f"Dataset '{self.args.data}' for task={self.args.task} not found ❌")) + + if self.device.type in {"cpu", "mps"}: + self.args.workers = 0 # faster CPU val as time dominated by inference, not dataloading + if not (pt or (getattr(model, "dynamic", False) and fmt != "imx")): + self.args.rect = False + self.stride = model.stride # used in get_dataloader() for padding + self.names = model.names # used in get_dataloader() to filter classification samples + self.dataloader = self.dataloader or self.get_dataloader(self.data.get(self.args.split), self.args.batch) + + model.eval() + if self.args.compile: + model = attempt_compile(model, device=self.device, mode=self.args.compile) + model.warmup(imgsz=(1 if pt else self.args.batch, self.data["channels"], imgsz, imgsz)) # warmup + + self.run_callbacks("on_val_start") + dt = ( + Profile(device=self.device), + Profile(device=self.device), + Profile(device=self.device), + Profile(device=self.device), + ) + bar = TQDM(self.dataloader, desc=self.get_desc(), total=len(self.dataloader)) + self.init_metrics(unwrap_model(model)) + self.jdict = [] # empty before each val + for batch_i, batch in enumerate(bar): + self.run_callbacks("on_val_batch_start") + self.batch_i = batch_i + # Preprocess + with dt[0]: + batch = self.preprocess(batch) + + with autocast(self.training and self.args.quantize == 16, device=self.device.type): + # Inference + with dt[1]: + preds = model(batch["img"], augment=augment) + + # Loss + with dt[2]: + if self.training: + for k, v in model.loss(batch, preds)[1].items(): + self.loss[k] += v + + # Postprocess + with dt[3]: + preds = self.postprocess(preds) + + self.update_metrics(preds, batch) + if self.args.plots and batch_i < 3 and RANK in {-1, 0}: + self.plot_val_samples(batch, batch_i) + self.plot_predictions(batch, preds, batch_i) + + self.run_callbacks("on_val_batch_end") + + stats = {} + self.gather_stats() + if RANK in {-1, 0}: + stats = self.get_stats() + self.speed = dict(zip(self.speed.keys(), (x.t / len(self.dataloader.dataset) * 1e3 for x in dt))) + self.finalize_metrics() + self.print_results() + self.run_callbacks("on_val_end") + + if self.training: + # Reduce loss across all GPUs + loss = {k: v.clone().detach() for k, v in self.loss.items()} + if trainer.world_size > 1: + for v in loss.values(): + dist.reduce(v, dst=0, op=dist.ReduceOp.AVG) + if RANK > 0: + return + loss = {k: v.cpu() / len(self.dataloader) for k, v in loss.items()} + results = {**stats, **trainer.label_loss_items(loss, prefix="val")} + return {k: round(float(v), 5) for k, v in results.items()} # return results as 5 decimal place floats + else: + if RANK > 0: + return stats + LOGGER.info( + "Speed: {:.1f}ms preprocess, {:.1f}ms inference, {:.1f}ms loss, {:.1f}ms postprocess per image".format( + *tuple(self.speed.values()) + ) + ) + if self.args.save_json and self.jdict: + with open(str(self.save_dir / "predictions.json"), "w", encoding="utf-8") as f: + LOGGER.info(f"Saving {f.name}...") + json.dump(self.jdict, f) # flatten and save + stats = self.eval_json(stats) # update stats + if self.args.plots or self.args.save_json: + LOGGER.info(f"Results saved to {colorstr('bold', self.save_dir)}") + return stats + + def match_predictions( + self, pred_classes: torch.Tensor, true_classes: torch.Tensor, iou: torch.Tensor, use_scipy: bool = False + ) -> torch.Tensor: + """Match predictions to ground truth objects using IoU. + + Args: + pred_classes (torch.Tensor): Predicted class indices of shape (N,). + true_classes (torch.Tensor): Target class indices of shape (M,). + iou (torch.Tensor): An NxM tensor containing the pairwise IoU values for predictions and ground truth. + use_scipy (bool, optional): Whether to use Hungarian one-to-one matching (more precise). + + Returns: + (torch.Tensor): Correct tensor of shape (N, 10) for 10 IoU thresholds. + """ + # Dx10 matrix, where D - detections, 10 - IoU thresholds + correct = np.zeros((pred_classes.shape[0], self.iouv.shape[0])).astype(bool) + # LxD matrix where L - labels (rows), D - detections (columns) + correct_class = true_classes[:, None] == pred_classes + iou = iou * correct_class # zero out the wrong classes + iou = iou.cpu().numpy() + for i, threshold in enumerate(self.iouv.cpu().tolist()): + if use_scipy: + cost_matrix = iou * (iou >= threshold) + if cost_matrix.any(): + labels_idx, detections_idx = linear_sum_assignment(-cost_matrix) # negate to maximize IoU + valid = cost_matrix[labels_idx, detections_idx] > 0 + if valid.any(): + correct[detections_idx[valid], i] = True + else: + matches = np.nonzero(iou >= threshold) # IoU > threshold and classes match + matches = np.array(matches).T + if matches.shape[0]: + if matches.shape[0] > 1: + matches = matches[iou[matches[:, 0], matches[:, 1]].argsort()[::-1]] + matches = matches[np.unique(matches[:, 1], return_index=True)[1]] + matches = matches[np.unique(matches[:, 0], return_index=True)[1]] + correct[matches[:, 1].astype(int), i] = True + return torch.from_numpy(correct) + + @smart_inference_mode(False) + def get_model(self, model, trainer=None): + """Return the training EMA or an independent model for standalone validation. + + Args: + model (torch.nn.Module | str | Path | None): Model or checkpoint for standalone validation. + trainer (object, optional): Trainer whose EMA is used during training validation. + + Returns: + (torch.nn.Module | str | Path | None): Model to prepare for inference. + """ + return trainer.ema.ema if trainer is not None else deepcopy(model) + + def add_callback(self, event: str, callback): + """Append the given callback to the specified event.""" + self.callbacks[event].append(callback) + + def run_callbacks(self, event: str): + """Run all callbacks associated with a specified event.""" + for callback in self.callbacks.get(event, []): + callback(self) + + def get_dataloader(self, dataset_path, batch_size): + """Get data loader from dataset path and batch size.""" + raise NotImplementedError("get_dataloader function not implemented for this validator") + + def build_dataset(self, img_path): + """Build dataset from image path.""" + raise NotImplementedError("build_dataset function not implemented in validator") + + def preprocess(self, batch): + """Preprocess an input batch.""" + return batch + + def postprocess(self, preds): + """Postprocess the predictions.""" + return preds + + def init_metrics(self, model): + """Initialize performance metrics for the YOLO model.""" + + def update_metrics(self, preds, batch): + """Update metrics based on predictions and batch.""" + + def finalize_metrics(self): + """Finalize and return all metrics.""" + + def get_stats(self): + """Return statistics about the model's performance.""" + return {} + + def gather_stats(self): + """Gather statistics from all the GPUs during DDP training to GPU 0.""" + + def print_results(self): + """Print the results of the model's predictions.""" + + def get_desc(self): + """Get description of the YOLO model.""" + + @property + def metric_keys(self): + """Return the metric keys used in YOLO training/validation.""" + return [] + + def on_plot(self, name, data=None): + """Register a plot by its unique path for visualization and logging.""" + self.plots[Path(name)] = {"data": data, "timestamp": time.time()} + + def plot_val_samples(self, batch, ni): + """Plot validation samples during training.""" + + def plot_predictions(self, batch, preds, ni): + """Plot YOLO model predictions on batch images.""" + + def pred_to_json(self, preds, batch): + """Convert predictions to JSON format.""" + + def eval_json(self, stats): + """Evaluate and return JSON format of prediction statistics.""" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..87f3163bc37033e587f137348f25f55f02dbfc4c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/__init__.py @@ -0,0 +1,19 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .fastsam import FastSAM +from .llm import LLM +from .nas import NAS +from .rtdetr import RTDETR +from .yolo import YOLO, YOLOE, YOLOWorld + +__all__ = "LLM", "NAS", "RTDETR", "SAM", "YOLO", "YOLOE", "FastSAM", "YOLOWorld" # allow simpler import + + +def __getattr__(name): + """Lazy-import SAM so standard YOLO imports don't load optional torchvision internals.""" + if name == "SAM": + # Scoped for import ultralytics speed: SAM pulls optional torchvision-heavy modules. + from .sam import SAM + + return SAM + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..840d0a70c5779bd11088d9b0320299c407bb3444 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/__pycache__/llm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/__pycache__/llm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..902d625248745b307b45270a0f6bb2298d228815 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/__pycache__/llm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..31395c04f5f8823112ce1eb6b524a8ad776645d2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__init__.py @@ -0,0 +1,7 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .model import FastSAM +from .predict import FastSAMPredictor +from .val import FastSAMValidator + +__all__ = "FastSAM", "FastSAMPredictor", "FastSAMValidator" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1de5fa6fb060ef905ce712dbcc7bf68c80567c91 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/model.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f284034e527d7f21770035dc1d94200180bb76ea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/model.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/predict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/predict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6db01e5e60f3afa837a0bf52f5e8d40f804da0c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/predict.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0389b96fcf1d73f4ed788fce87fc13cb2f3ebef Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/val.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/val.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6501652417151e4882a006ee8733821ec03500f4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/__pycache__/val.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/model.py b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7efd16d43aae5ec4c4212a0f53d67b4ffed0412d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/model.py @@ -0,0 +1,79 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from ultralytics.engine.model import Model + +from .predict import FastSAMPredictor +from .val import FastSAMValidator + + +class FastSAM(Model): + """FastSAM model interface for Segment Anything tasks. + + This class extends the base Model class to provide specific functionality for the FastSAM (Fast Segment Anything + Model) implementation, allowing for efficient and accurate image segmentation with optional prompting support. + + Attributes: + model (str): Path to the pre-trained FastSAM model file. + task (str): The task type, set to "segment" for FastSAM models. + + Methods: + predict: Perform segmentation prediction on image or video source with optional prompts. + task_map: Returns mapping of segment task to predictor and validator classes. + + Examples: + Initialize FastSAM model and run prediction + >>> from ultralytics import FastSAM + >>> model = FastSAM("FastSAM-x.pt") + >>> results = model.predict("ultralytics/assets/bus.jpg") + + Run prediction with bounding box prompts + >>> results = model.predict("image.jpg", bboxes=[[100, 100, 200, 200]]) + """ + + def __init__(self, model: str | Path = "FastSAM-x.pt"): + """Initialize the FastSAM model with the specified pre-trained weights.""" + if str(model) == "FastSAM.pt": + model = "FastSAM-x.pt" + assert Path(model).suffix not in {".yaml", ".yml"}, "FastSAM only supports pre-trained weights." + super().__init__(model=model, task="segment") + + def predict( + self, + source, + stream: bool = False, + bboxes: list | None = None, + points: list | None = None, + labels: list | None = None, + texts: list | None = None, + **kwargs: Any, + ): + """Perform segmentation prediction on image or video source. + + Supports prompted segmentation with bounding boxes, points, labels, and texts. The method packages these prompts + and passes them to the parent class predict method for processing. + + Args: + source (str | PIL.Image | np.ndarray): Input source for prediction, can be a file path, URL, PIL image, or + numpy array. + stream (bool): Whether to enable real-time streaming mode for video inputs. + bboxes (list, optional): Bounding box coordinates for prompted segmentation in format [[x1, y1, x2, y2]]. + points (list, optional): Point coordinates for prompted segmentation in format [[x, y]]. + labels (list, optional): Class labels for prompted segmentation. + texts (list, optional): Text prompts for segmentation guidance. + **kwargs (Any): Additional keyword arguments passed to the predictor. + + Returns: + (list): List of Results objects containing the prediction results. + """ + prompts = {"bboxes": bboxes, "points": points, "labels": labels, "texts": texts} + return super().predict(source, stream, prompts=prompts, **kwargs) + + @property + def task_map(self) -> dict[str, dict[str, Any]]: + """Returns a dictionary mapping segment task to corresponding predictor and validator classes.""" + return {"segment": {"predictor": FastSAMPredictor, "validator": FastSAMValidator}} diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/predict.py b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..9425af10758246dd7640d2ce1e900cd304f70507 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/predict.py @@ -0,0 +1,181 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from multiprocessing.pool import ThreadPool + +import torch +from PIL import Image + +from ultralytics.models.yolo.segment import SegmentationPredictor +from ultralytics.utils import DEFAULT_CFG, NUM_THREADS +from ultralytics.utils.metrics import box_iou +from ultralytics.utils.ops import clip_boxes, clip_coords, scale_masks +from ultralytics.utils.torch_utils import TORCH_1_10 + +from .utils import adjust_bboxes_to_image_border + + +class FastSAMPredictor(SegmentationPredictor): + """FastSAMPredictor is specialized for fast SAM (Segment Anything Model) segmentation prediction tasks. + + This class extends the SegmentationPredictor, customizing the prediction pipeline specifically for fast SAM. It + adjusts post-processing steps to incorporate mask prediction and non-maximum suppression while optimizing for + single-class segmentation. + + Attributes: + prompts (dict): Dictionary containing prompt information for segmentation (bboxes, points, labels, texts). + device (torch.device): Device on which model and tensors are processed. + clip (Any, optional): CLIP model used for text-based prompting, loaded on demand. + + Methods: + postprocess: Apply postprocessing to FastSAM predictions and handle prompts. + prompt: Perform image segmentation inference based on various prompt types. + set_prompts: Set prompts to be used during inference. + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks: dict | None = None): + """Initialize the FastSAMPredictor with configuration and callbacks. + + This initializes a predictor specialized for Fast SAM (Segment Anything Model) segmentation tasks. The predictor + extends SegmentationPredictor with custom post-processing for mask prediction and non-maximum suppression + optimized for single-class segmentation. + + Args: + cfg (dict): Configuration for the predictor. + overrides (dict, optional): Configuration overrides. + _callbacks (dict, optional): Dictionary of callback functions. + """ + super().__init__(cfg, overrides, _callbacks) + self.prompts = {} + + def postprocess(self, preds, img, orig_imgs): + """Apply postprocessing to FastSAM predictions and handle prompts. + + Args: + preds (list[torch.Tensor]): Raw predictions from the model. + img (torch.Tensor): Input image tensor that was fed to the model. + orig_imgs (list[np.ndarray]): Original images before preprocessing. + + Returns: + (list[Results]): Processed results with prompts applied. + """ + bboxes = self.prompts.pop("bboxes", None) + points = self.prompts.pop("points", None) + labels = self.prompts.pop("labels", None) + texts = self.prompts.pop("texts", None) + results = super().postprocess(preds, img, orig_imgs) + for result in results: + full_box = torch.tensor( + [0, 0, result.orig_shape[1], result.orig_shape[0]], device=result.boxes.data.device, dtype=torch.float32 + ) + boxes = adjust_bboxes_to_image_border(result.boxes.xyxy, result.orig_shape) + idx = torch.nonzero(box_iou(full_box[None], boxes)[0] > 0.9).flatten() + if idx.numel() != 0: + result.boxes.xyxy[idx] = full_box + + return self.prompt(results, bboxes=bboxes, points=points, labels=labels, texts=texts) + + def prompt(self, results, bboxes=None, points=None, labels=None, texts=None): + """Perform image segmentation inference based on cues like bounding boxes, points, and text prompts. + + Args: + results (Results | list[Results]): Original inference results from FastSAM models without any prompts. + bboxes (np.ndarray | list, optional): Bounding boxes with shape (N, 4), in XYXY format. + points (np.ndarray | list, optional): Points indicating object locations with shape (N, 2), in pixels. + labels (np.ndarray | list, optional): Labels for point prompts, shape (N, ). 1 = foreground, 0 = background. + texts (str | list[str], optional): Textual prompts, a list containing string objects. + + Returns: + (list[Results]): Output results filtered and determined by the provided prompts. + """ + if bboxes is None and points is None and texts is None: + return results + prompt_results = [] + if not isinstance(results, list): + results = [results] + for result in results: + if len(result) == 0: + prompt_results.append(result) + continue + masks = result.masks.data + if masks.shape[1:] != result.orig_shape: + masks = (scale_masks(masks[None].float(), result.orig_shape)[0] > 0.5).byte() + # bboxes prompt + idx = torch.zeros(len(result), dtype=torch.bool, device=self.device) + if bboxes is not None: + boxes = torch.as_tensor(bboxes, dtype=torch.int32, device=self.device).clone() + boxes = boxes[None] if boxes.ndim == 1 else boxes + boxes = clip_boxes(boxes, result.orig_shape) + bbox_areas = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]) + mask_areas = torch.stack([masks[:, b[1] : b[3], b[0] : b[2]].sum(dim=(1, 2)) for b in boxes]) + full_mask_areas = torch.sum(masks, dim=(1, 2)) + + union = bbox_areas[:, None] + full_mask_areas - mask_areas + idx[torch.argmax(mask_areas / union, dim=1)] = True + if points is not None: + coords = torch.as_tensor(points, dtype=torch.int32, device=self.device).clone() + coords = coords[None] if coords.ndim == 1 else coords + coords = clip_coords(coords, tuple(x - 1 for x in result.orig_shape)) + if labels is None: + labels = torch.ones(coords.shape[0]) + labels = torch.as_tensor(labels, dtype=torch.int32, device=self.device) + assert len(labels) == len(coords), "Labels and points must contain the same number of items." + point_idx = ( + torch.ones(len(result), dtype=torch.bool, device=self.device) + if labels.sum() == 0 # all negative points + else torch.zeros(len(result), dtype=torch.bool, device=self.device) + ) + for point, label in zip(coords, labels): + point_idx[torch.nonzero(masks[:, point[1], point[0]], as_tuple=True)[0]] = bool(label) + idx |= point_idx + if texts is not None: + if isinstance(texts, str): + texts = [texts] + crop_ims, filter_idx = [], [] + for i, b in enumerate(result.boxes.xyxy.tolist()): + x1, y1, x2, y2 = (int(x) for x in b) + if (masks[i].sum() if TORCH_1_10 else masks[i].sum(0).sum()) <= 100: # torch 1.9 bug workaround + filter_idx.append(i) + continue + crop = result.orig_img[y1:y2, x1:x2] * masks[i, y1:y2, x1:x2, None].cpu().numpy() + crop_ims.append(Image.fromarray(crop[:, :, ::-1])) + similarity = self._clip_inference(crop_ims, texts) + text_idx = torch.argmax(similarity, dim=-1) # (M, ) + if len(filter_idx): + # Remap text_idx to its original index before filtering (supports multiple text prompts) + ori_idxs = torch.tensor([i for i in range(len(result)) if i not in filter_idx], device=self.device) + text_idx = ori_idxs[text_idx] + idx[text_idx] = True + + prompt_results.append(result[idx]) + + return prompt_results + + def _clip_inference(self, images, texts): + """Perform CLIP inference to calculate similarity between images and text prompts. + + Args: + images (list[PIL.Image]): List of source images, each should be PIL.Image with RGB channel order. + texts (list[str]): List of prompt texts, each should be a string object. + + Returns: + (torch.Tensor): Similarity matrix between given images and texts with shape (M, N). + """ + from ultralytics.nn.text_model import CLIP + + if not hasattr(self, "clip"): + self.clip = CLIP("ViT-B/32", device=self.device) + if self.device.type == "cuda" and NUM_THREADS > 1 and len(images) >= 2 * NUM_THREADS: + with ThreadPool(NUM_THREADS) as pool: + images = pool.map(self.clip.image_preprocess, images) + images = torch.stack([image.to(self.device) for image in images]) + else: + images = torch.stack([self.clip.image_preprocess(image).to(self.device) for image in images]) + image_features = self.clip.encode_image(images) + text_features = self.clip.encode_text(self.clip.tokenize(texts)) + return text_features @ image_features.T # (M, N) + + def set_prompts(self, prompts): + """Set prompts to be used during inference.""" + self.prompts = prompts diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/utils.py b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0e5844c7f488ab233c8596d7c4470d66f35ed23e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/utils.py @@ -0,0 +1,23 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + + +def adjust_bboxes_to_image_border(boxes, image_shape, threshold=20): + """Adjust bounding boxes to stick to image border if they are within a certain threshold. + + Args: + boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format. + image_shape (tuple): Image dimensions as (height, width). + threshold (int): Pixel threshold for considering a box close to the border. + + Returns: + (torch.Tensor): Adjusted bounding boxes with shape (N, 4). + """ + # Image dimensions + h, w = image_shape + + # Adjust boxes that are close to image borders + boxes[boxes[:, 0] < threshold, 0] = 0 # x1 + boxes[boxes[:, 1] < threshold, 1] = 0 # y1 + boxes[boxes[:, 2] > w - threshold, 2] = w # x2 + boxes[boxes[:, 3] > h - threshold, 3] = h # y2 + return boxes diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/val.py b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/val.py new file mode 100644 index 0000000000000000000000000000000000000000..bc91aeaa334121df8a1c669d36866b134b90c46d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/fastsam/val.py @@ -0,0 +1,40 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from ultralytics.models.yolo.segment import SegmentationValidator + + +class FastSAMValidator(SegmentationValidator): + """Custom validation class for FastSAM (Segment Anything Model) segmentation in the Ultralytics YOLO framework. + + Extends the SegmentationValidator class, customizing the validation process specifically for FastSAM. This class + sets the task to 'segment' and uses the SegmentMetrics for evaluation. Additionally, plotting features are disabled + to avoid errors during validation. + + Attributes: + dataloader (torch.utils.data.DataLoader): The data loader object used for validation. + save_dir (Path): The directory where validation results will be saved. + args (SimpleNamespace): Additional arguments for customization of the validation process. + _callbacks (dict): Dictionary of callback functions to be invoked during validation. + metrics (SegmentMetrics): Segmentation metrics calculator for evaluation. + + Methods: + __init__: Initialize the FastSAMValidator with custom settings for FastSAM. + """ + + def __init__(self, dataloader=None, save_dir=None, args=None, _callbacks: dict | None = None): + """Initialize the FastSAMValidator class, setting the task to 'segment' and metrics to SegmentMetrics. + + Args: + dataloader (torch.utils.data.DataLoader, optional): DataLoader to be used for validation. + save_dir (Path, optional): Directory to save results. + args (SimpleNamespace, optional): Configuration for the validator. + _callbacks (dict, optional): Dictionary of callback functions to be invoked during validation. + + Notes: + Plots for ConfusionMatrix and other related metrics are disabled in this class to avoid errors. + """ + super().__init__(dataloader, save_dir, args, _callbacks) + self.args.task = "segment" + self.args.plots = False # disable ConfusionMatrix and other plots to avoid errors diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/llm.py b/.venv/lib/python3.12/site-packages/ultralytics/models/llm.py new file mode 100644 index 0000000000000000000000000000000000000000..59144427030a1899dafad78a1757df714946c435 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/llm.py @@ -0,0 +1,195 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import base64 +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +from PIL import Image + +from ultralytics.utils.checks import check_requirements + + +class LLM: + """OpenAI-compatible large language model interface. + + Attributes: + model (str): Model name sent with each request. + api (str): API format, either "responses" or "chat.completions". + base_url (str | None): Optional OpenAI-compatible API base URL. + prompt (str | None): Optional instruction prepended to scalar text or image inputs. + overrides (dict): Default arguments passed to each request. + client (OpenAI | None): Lazily initialized synchronous client. + async_client (AsyncOpenAI | None): Lazily initialized asynchronous client. + + Methods: + __call__: Run synchronous inference. + async_call: Run asynchronous inference. + + Examples: + >>> from ultralytics import LLM + >>> model = LLM("gpt-5.6-luna") + >>> response = model("What is YOLO?") + + Analyze an image: + >>> response = model("Describe this image", image="bus.jpg") + + Use the Chat Completions API: + >>> model = LLM("gpt-5.6-luna", api="chat.completions") + >>> response = model("What is YOLO?") + """ + + def __init__( + self, + model: str = "gpt-5.6-luna", + api: str = "responses", + base_url: str | None = None, + api_key: str | None = None, + prompt: str | None = None, + **kwargs: Any, + ) -> None: + """Initialize an OpenAI-compatible LLM. + + Args: + model (str): Model name. + api (str): API format, either "responses" or "chat.completions". + base_url (str, optional): OpenAI-compatible API base URL. + api_key (str, optional): API key. Defaults to the OPENAI_API_KEY environment variable. + prompt (str, optional): Instruction prepended to scalar text or image inputs. + **kwargs (Any): Default arguments passed to each API request. + """ + if api not in {"responses", "chat.completions"}: + raise ValueError(f"Unsupported API format {api!r}. Use 'responses' or 'chat.completions'.") + + self.model = model + self.api = api + self.base_url = base_url + self.prompt = prompt + self.overrides = kwargs + self.client = None + self.async_client = None + self._api_key = api_key + + def __call__(self, source: Any = None, image: Any = None, **kwargs: Any) -> Any: + """Run inference with the configured model.""" + return self._call(self._prepare(source, image), kwargs) + + def _call(self, source: Any, kwargs: dict[str, Any]) -> Any: + """Send prepared input through the synchronous client.""" + request = self._request(source, kwargs) + client = self._get_client() + return ( + client.responses.create(**request) if self.api == "responses" else client.chat.completions.create(**request) + ) + + async def async_call(self, source: Any = None, image: Any = None, **kwargs: Any) -> Any: + """Run asynchronous inference with the configured model.""" + return await self._async_call(self._prepare(source, image), kwargs) + + async def _async_call(self, source: Any, kwargs: dict[str, Any]) -> Any: + """Send prepared input through the asynchronous client.""" + request = self._request(source, kwargs) + client = self._get_async_client() + return ( + await client.responses.create(**request) + if self.api == "responses" + else await client.chat.completions.create(**request) + ) + + def _request(self, source: Any, kwargs: dict[str, Any]) -> dict[str, Any]: + """Build a Responses or Chat Completions request. + + Args: + source (Any, optional): Responses input or chat messages. Strings become a user message for Chat + Completions. + kwargs (dict): Request arguments overriding constructor defaults. + + Returns: + (dict): Native OpenAI SDK request arguments. + """ + request = {"model": self.model, **self.overrides, **kwargs} + if self.api == "responses": + if source is not None: + request["input"] = source + elif source is not None: + request["messages"] = [{"role": "user", "content": source}] if isinstance(source, str) else source + return request + + def _prepare(self, source: Any, image: Any = None) -> Any: + """Normalize scalar text or image input while preserving native message payloads.""" + if image is None: + if source is None: + return self.prompt + if isinstance(source, (list, tuple, dict)): + return source + if isinstance(source, str): + return f"{self.prompt}\n\n{source}" if self.prompt else source + image = source + prompt = self.prompt or "Describe the image." + else: + prompt = source or "Describe the image." + if self.prompt: + prompt = f"{self.prompt}\n\n{source}" if source else self.prompt + image_url = self._image_url(image) + if self.api == "responses": + return [ + { + "role": "user", + "content": [ + {"type": "input_text", "text": prompt}, + {"type": "input_image", "image_url": image_url}, + ], + } + ] + return [ + { + "role": "user", + "content": [ + {"type": "text", "text": prompt}, + {"type": "image_url", "image_url": {"url": image_url}}, + ], + } + ] + + @staticmethod + def _image_url(source: Any) -> str: + """Convert an image URL, path, or array to an OpenAI image URL.""" + if isinstance(source, str) and source.startswith(("http://", "https://", "data:image/")): + return source + if isinstance(source, (str, Path)): + image = cv2.imread(str(source)) + else: + image = ( + cv2.cvtColor(np.asarray(source.convert("RGB")), cv2.COLOR_RGB2BGR) + if isinstance(source, Image.Image) + else np.asarray(source) + ) + if image is None: + raise ValueError(f"Unable to read image source {source!r}.") + success, buffer = cv2.imencode(".jpg", image) + if not success: + raise ValueError("Unable to encode image source as JPEG.") + return f"data:image/jpeg;base64,{base64.b64encode(buffer).decode()}" + + def _get_client(self) -> Any: + """Create the OpenAI client on first inference.""" + if self.client is None: + check_requirements("openai>=2.0.0") + from openai import OpenAI + + kwargs = {k: v for k, v in {"api_key": self._api_key, "base_url": self.base_url}.items() if v is not None} + self.client = OpenAI(**kwargs) + return self.client + + def _get_async_client(self) -> Any: + """Create the asynchronous OpenAI client on first inference.""" + if self.async_client is None: + check_requirements("openai>=2.0.0") + from openai import AsyncOpenAI + + kwargs = {k: v for k, v in {"api_key": self._api_key, "base_url": self.base_url}.items() if v is not None} + self.async_client = AsyncOpenAI(**kwargs) + return self.async_client diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..af82244dc02469a5f86dab65307c02115d370f94 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__init__.py @@ -0,0 +1,7 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .model import NAS +from .predict import NASPredictor +from .val import NASValidator + +__all__ = "NAS", "NASPredictor", "NASValidator" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9f565d6bc58c0473bd07fe6e86a95c8c1b80b40 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__pycache__/model.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__pycache__/model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7dd440da96941204a7d883155cec537788aa8975 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__pycache__/model.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__pycache__/predict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__pycache__/predict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..339787f0bc232734fe352f0032e9257ca8ad5389 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__pycache__/predict.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__pycache__/val.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__pycache__/val.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..348f7aa3356ddbd4a313b594f09737bbb1affddf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/__pycache__/val.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/nas/model.py b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/model.py new file mode 100644 index 0000000000000000000000000000000000000000..ab8e3be5496afb7ae4347a555fc53a04fdf16a51 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/model.py @@ -0,0 +1,90 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import torch + +from ultralytics.engine.model import Model +from ultralytics.utils import DEFAULT_CFG_DICT +from ultralytics.utils.downloads import attempt_download_asset +from ultralytics.utils.patches import torch_load +from ultralytics.utils.torch_utils import model_info + +from .predict import NASPredictor +from .val import NASValidator + + +class NAS(Model): + """YOLO-NAS model for object detection. + + This class provides an interface for the YOLO-NAS models and extends the `Model` class from Ultralytics engine. It + is designed to facilitate the task of object detection using pre-trained or custom-trained YOLO-NAS models. + + Attributes: + model (torch.nn.Module): The loaded YOLO-NAS model. + task (str): The task type for the model, defaults to 'detect'. + predictor (NASPredictor): The predictor instance for making predictions. + validator (NASValidator): The validator instance for model validation. + + Methods: + info: Log model information and return model details. + + Examples: + >>> from ultralytics import NAS + >>> model = NAS("yolo_nas_s") + >>> results = model.predict("ultralytics/assets/bus.jpg") + + Notes: + YOLO-NAS models only support pre-trained models. Do not provide YAML configuration files. + """ + + def __init__(self, model: str = "yolo_nas_s.pt") -> None: + """Initialize the NAS model with the provided or default model.""" + assert Path(model).suffix not in {".yaml", ".yml"}, "YOLO-NAS models only support pre-trained models." + super().__init__(model, task="detect") + + def _load(self, weights: str, task=None) -> None: + """Load an existing NAS model weights or create a new NAS model with pretrained weights. + + Args: + weights (str): Path to the model weights file or model name. + task (str, optional): Task type for the model. + """ + import super_gradients + + suffix = Path(weights).suffix + if suffix == ".pt": + self.model = torch_load(attempt_download_asset(weights)) + elif suffix == "": + self.model = super_gradients.training.models.get(weights, pretrained_weights="coco") + + # Standardize model attributes for compatibility + self.model.fuse = lambda verbose=True, imgsz=640: self.model + self.model.stride = torch.tensor([32]) + self.model.names = dict(enumerate(self.model._class_names)) + self.model.is_fused = lambda: False # for info() + self.model.yaml = {} # for info() + self.model.pt_path = str(weights) # for export() + self.model.task = "detect" # for export() + self.model.args = {**DEFAULT_CFG_DICT, **self.overrides} # for export() + self.model.eval() + + def info(self, detailed: bool = False, verbose: bool = True) -> tuple: + """Log model information. + + Args: + detailed (bool): Show detailed information about model. + verbose (bool): Controls verbosity. + + Returns: + (tuple): Model information as a tuple of (layers, parameters, gradients, GFLOPs). + """ + return model_info(self.model, detailed=detailed, verbose=verbose, imgsz=640) + + @property + def task_map(self) -> dict[str, dict[str, Any]]: + """Return a dictionary mapping tasks to respective predictor and validator classes.""" + return {"detect": {"predictor": NASPredictor, "validator": NASValidator}} diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/nas/predict.py b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..d5b56dcbfa1fc0874a917907e1fac37b30c18037 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/predict.py @@ -0,0 +1,56 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import torch + +from ultralytics.models.yolo.detect.predict import DetectionPredictor +from ultralytics.utils import ops + + +class NASPredictor(DetectionPredictor): + """Ultralytics YOLO NAS Predictor for object detection. + + This class extends the DetectionPredictor from Ultralytics engine and is responsible for post-processing the raw + predictions generated by the YOLO NAS models. It applies operations like non-maximum suppression and scaling the + bounding boxes to fit the original image dimensions. + + Attributes: + args (Namespace): Namespace containing various configurations for post-processing including confidence + threshold, IoU threshold, agnostic NMS flag, maximum detections, and class filtering options. + model (torch.nn.Module): The YOLO NAS model used for inference. + batch (list): Batch of inputs for processing. + + Examples: + >>> from ultralytics import NAS + >>> model = NAS("yolo_nas_s") + >>> predictor = model.predictor + + Assume that raw_preds, img, orig_imgs are available + >>> results = predictor.postprocess(raw_preds, img, orig_imgs) + + Notes: + Typically, this class is not instantiated directly. It is used internally within the NAS class. + """ + + def postprocess(self, preds_in, img, orig_imgs): + """Postprocess NAS model predictions to generate final detection results. + + This method takes raw predictions from a YOLO NAS model, converts bounding box formats, and applies + post-processing operations to generate the final detection results compatible with Ultralytics result + visualization and analysis tools. + + Args: + preds_in (list): Raw predictions from the NAS model, typically containing bounding boxes and class scores. + img (torch.Tensor): Input image tensor that was fed to the model, with shape (B, C, H, W). + orig_imgs (list | torch.Tensor | np.ndarray): Original images before preprocessing, used for scaling + coordinates back to original dimensions. + + Returns: + (list): List of Results objects containing the processed predictions for each image in the batch. + + Examples: + >>> predictor = NAS("yolo_nas_s").predictor + >>> results = predictor.postprocess(raw_preds, img, orig_imgs) + """ + boxes = ops.xyxy2xywh(preds_in[0][0]) # Convert bounding boxes from xyxy to xywh format + preds = torch.cat((boxes, preds_in[0][1]), -1).permute(0, 2, 1) # Concatenate boxes with class scores + return super().postprocess(preds, img, orig_imgs) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/nas/val.py b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/val.py new file mode 100644 index 0000000000000000000000000000000000000000..6e5781136db423c5785fe358f7459e68b5a017f2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/nas/val.py @@ -0,0 +1,38 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import torch + +from ultralytics.models.yolo.detect import DetectionValidator +from ultralytics.utils import ops + +__all__ = ["NASValidator"] + + +class NASValidator(DetectionValidator): + """Ultralytics YOLO NAS Validator for object detection. + + Extends DetectionValidator from the Ultralytics models package and is designed to post-process the raw predictions + generated by YOLO NAS models. It performs non-maximum suppression to remove overlapping and low-confidence boxes, + ultimately producing the final detections. + + Attributes: + args (Namespace): Namespace containing various configurations for post-processing, such as confidence and IoU + thresholds. + lb (torch.Tensor): Optional tensor for multilabel NMS. + + Examples: + >>> from ultralytics import NAS + >>> model = NAS("yolo_nas_s") + >>> validator = model.validator + >>> # Assumes that raw_preds are available + >>> final_preds = validator.postprocess(raw_preds) + + Notes: + This class is generally not instantiated directly but is used internally within the NAS class. + """ + + def postprocess(self, preds_in): + """Apply Non-maximum suppression to prediction outputs.""" + boxes = ops.xyxy2xywh(preds_in[0][0]) # Convert bounding box format from xyxy to xywh + preds = torch.cat((boxes, preds_in[0][1]), -1).permute(0, 2, 1) # Concatenate boxes with scores and permute + return super().postprocess(preds) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2ec9d7bf3031a2f6538d99b721626cf9b99b495a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__init__.py @@ -0,0 +1,7 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .model import RTDETR +from .predict import RTDETRPredictor +from .val import RTDETRValidator + +__all__ = "RTDETR", "RTDETRPredictor", "RTDETRValidator" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a13daa0e967f1b64d61b238fe4079a2dafce5359 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/model.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7319b08c122b7cf13261846fc1a211de0f034b54 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/model.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/predict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/predict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e65b0adfd7a7986ebd71b6717cfa63dd681cceb2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/predict.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/train.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/train.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63c92c15889ad4652d11e33756a3c0ee0d2c64a3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/train.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/val.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/val.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e854275de95ce31af2309743e3ada9bc38f283f0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/__pycache__/val.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/model.py b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/model.py new file mode 100644 index 0000000000000000000000000000000000000000..fe50dfc80a7389c9eefdeda93e7f3e38ff9fcfeb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/model.py @@ -0,0 +1,63 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Interface for Baidu's RT-DETR, a Vision Transformer-based real-time object detector. + +RT-DETR offers real-time performance and high accuracy, excelling in accelerated backends like CUDA with TensorRT. +It features an efficient hybrid encoder and IoU-aware query selection for enhanced detection accuracy. + +References: + https://arxiv.org/pdf/2304.08069.pdf +""" + +from ultralytics.engine.model import Model +from ultralytics.nn.tasks import RTDETRDetectionModel +from ultralytics.utils.torch_utils import TORCH_1_11 + +from .predict import RTDETRPredictor +from .train import RTDETRTrainer +from .val import RTDETRValidator + + +class RTDETR(Model): + """Interface for Baidu's RT-DETR model, a Vision Transformer-based real-time object detector. + + This model provides real-time performance with high accuracy. It supports efficient hybrid encoding, IoU-aware query + selection, and adaptable inference speed. + + Attributes: + model (str): Path to the pre-trained model. + + Methods: + task_map: Return a task map for RT-DETR, associating tasks with corresponding Ultralytics classes. + + Examples: + Initialize RT-DETR with a pre-trained model + >>> from ultralytics import RTDETR + >>> model = RTDETR("rtdetr-l.pt") + >>> results = model("image.jpg") + """ + + def __init__(self, model: str = "rtdetr-l.pt") -> None: + """Initialize the RT-DETR model with the given pre-trained model file. + + Args: + model (str): Path to the pre-trained model. Supports .pt, .yaml, and .yml formats. + """ + assert TORCH_1_11, "RTDETR requires torch>=1.11" + super().__init__(model=model, task="detect") + + @property + def task_map(self) -> dict: + """Return a task map for RT-DETR, associating tasks with corresponding Ultralytics classes. + + Returns: + (dict): A dictionary mapping task names to Ultralytics task classes for the RT-DETR model. + """ + return { + "detect": { + "predictor": RTDETRPredictor, + "validator": RTDETRValidator, + "trainer": RTDETRTrainer, + "model": RTDETRDetectionModel, + } + } diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/predict.py b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..ec61a7271f7a65f0e8d51d12d9c57fe0f7a04fca --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/predict.py @@ -0,0 +1,83 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import torch + +from ultralytics.data.augment import LetterBox +from ultralytics.engine.predictor import BasePredictor +from ultralytics.engine.results import Results +from ultralytics.utils import ops + + +class RTDETRPredictor(BasePredictor): + """RT-DETR (Real-Time Detection Transformer) Predictor extending the BasePredictor class for making predictions. + + This class leverages Vision Transformers to provide real-time object detection while maintaining high accuracy. It + supports key features like efficient hybrid encoding and IoU-aware query selection. + + Attributes: + imgsz (int): Image size for inference (must be square and scale-filled). + args (dict): Argument overrides for the predictor. + model (torch.nn.Module): The loaded RT-DETR model. + batch (list): Current batch of processed inputs. + + Methods: + postprocess: Postprocess raw model predictions to generate bounding boxes and confidence scores. + pre_transform: Pre-transform input images before feeding them into the model for inference. + + Examples: + >>> from ultralytics.utils import ASSETS + >>> from ultralytics.models.rtdetr import RTDETRPredictor + >>> args = dict(model="rtdetr-l.pt", source=ASSETS) + >>> predictor = RTDETRPredictor(overrides=args) + >>> predictor.predict_cli() + """ + + def postprocess(self, preds, img, orig_imgs): + """Postprocess the raw predictions from the model to generate bounding boxes and confidence scores. + + The method filters detections based on confidence and class if specified in `self.args`. It converts model + predictions (already top-k selected by the decoder head) to Results objects containing properly scaled bounding + boxes. + + Args: + preds (list | tuple): List of [predictions, extra] from the model, where predictions have shape (bs, + num_queries, 6) with format [cx, cy, w, h, score, class]. + img (torch.Tensor): Processed input images with shape (N, 3, H, W). + orig_imgs (list | torch.Tensor): Original, unprocessed images. + + Returns: + (list[Results]): A list of Results objects containing the post-processed bounding boxes, confidence scores, + and class labels. + """ + if isinstance(preds, (list, tuple)): + preds = preds[0] + bboxes, scores, labels = preds.split((4, 1, 1), dim=-1) + if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list + orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)[..., ::-1] + + results = [] + for bbox, score, label, orig_img, img_path in zip(bboxes, scores, labels, orig_imgs, self.batch[0]): + bbox = ops.xywh2xyxy(bbox) + idx = score.squeeze(-1) > self.args.conf + if self.args.classes is not None: + idx = (label == torch.tensor(self.args.classes, device=label.device)).any(1) & idx + pred = torch.cat([bbox, score, label], dim=-1)[idx][: self.args.max_det] + oh, ow = orig_img.shape[:2] + pred[..., [0, 2]] *= ow # scale x coordinates to original width + pred[..., [1, 3]] *= oh # scale y coordinates to original height + results.append(Results(orig_img, path=img_path, names=self.model.names, boxes=pred)) + return results + + def pre_transform(self, im): + """Pre-transform input images before feeding them into the model for inference. + + The input images are letterboxed to ensure a square aspect ratio and scale-filled. + + Args: + im (list[np.ndarray]): Input images of shape [(H, W, 3) x N]. + + Returns: + (list): List of pre-transformed images ready for model inference. + """ + letterbox = LetterBox(self.imgsz, auto=False, scale_fill=True) + return [letterbox(image=x) for x in im] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/train.py b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/train.py new file mode 100644 index 0000000000000000000000000000000000000000..994a76f944b75cf1e363a4f80a6afdac49e39c13 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/train.py @@ -0,0 +1,93 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from copy import copy + +from ultralytics.data.utils import get_split_fraction +from ultralytics.models.yolo.detect import DetectionTrainer +from ultralytics.nn.tasks import RTDETRDetectionModel +from ultralytics.utils import RANK, colorstr + +from .val import RTDETRDataset, RTDETRValidator + + +class RTDETRTrainer(DetectionTrainer): + """Trainer class for the RT-DETR model developed by Baidu for real-time object detection. + + This class extends the DetectionTrainer class for YOLO to adapt to the specific features and architecture of + RT-DETR. The model leverages Vision Transformers and has capabilities like IoU-aware query selection and adaptable + inference speed. + + Attributes: + loss_names (tuple): Names of the loss components, derived from the loss dict returned by the criterion. + data (dict): Dataset configuration containing class count and other parameters. + args (dict): Training arguments and hyperparameters. + save_dir (Path): Directory to save training results. + test_loader (DataLoader): DataLoader for validation/testing data. + + Methods: + get_model: Initialize and return an RT-DETR model for object detection tasks. + build_dataset: Build and return an RT-DETR dataset for training or validation. + get_validator: Return a DetectionValidator suitable for RT-DETR model validation. + + Examples: + >>> from ultralytics.models.rtdetr.train import RTDETRTrainer + >>> args = dict(model="rtdetr-l.yaml", data="coco8.yaml", imgsz=640, epochs=3) + >>> trainer = RTDETRTrainer(overrides=args) + >>> trainer.train() + + Notes: + - F.grid_sample used in RT-DETR does not support the `deterministic=True` argument. + - AMP training can lead to NaN outputs and may produce errors during bipartite graph matching. + """ + + def get_model(self, cfg: dict | None = None, weights: str | None = None, verbose: bool = True): + """Initialize and return an RT-DETR model for object detection tasks. + + Args: + cfg (dict, optional): Model configuration. + weights (str, optional): Path to pre-trained model weights. + verbose (bool): Verbose logging if True. + + Returns: + (RTDETRDetectionModel): Initialized model. + """ + model = self.set_model_names_for_load( + RTDETRDetectionModel(cfg, nc=self.data["nc"], ch=self.data["channels"], verbose=verbose and RANK == -1) + ) + if weights: + model.load(weights) + return model + + def build_dataset(self, img_path: str, mode: str = "val", batch: int | None = None): + """Build and return an RT-DETR dataset for training or validation. + + Args: + img_path (str): Path to the folder containing images. + mode (str): Dataset mode, either 'train' or 'val'. + batch (int, optional): Batch size for rectangle training. + + Returns: + (RTDETRDataset): Dataset object for the specific mode. + """ + return RTDETRDataset( + img_path=img_path, + imgsz=self.args.imgsz, + batch_size=batch, + augment=mode == "train", + hyp=self.args, + rect=False, + cache=self.args.cache or None, + single_cls=self.args.single_cls or False, + prefix=colorstr(f"{mode}: "), + classes=self.args.classes, + data=self.data, + fraction=1.0 + if self.data.get("complete") + else get_split_fraction(self.args.fraction, "train" if mode == "train" else self.args.split), + ) + + def get_validator(self): + """Return an RTDETRValidator suitable for RT-DETR model validation.""" + return RTDETRValidator(self.test_loader, save_dir=self.save_dir, args=copy(self.args)) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/val.py b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/val.py new file mode 100644 index 0000000000000000000000000000000000000000..83ba4f28fff41687e5883e1eb9d5f7c320fc37ed --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/val.py @@ -0,0 +1,189 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import torch + +from ultralytics.data import YOLODataset +from ultralytics.data.utils import get_split_fraction +from ultralytics.models.yolo.detect import DetectionValidator +from ultralytics.utils import colorstr, ops + +__all__ = ("RTDETRValidator",) # tuple or list + + +class RTDETRDataset(YOLODataset): + """Real-Time DEtection TRansformer (RT-DETR) dataset class extending the base YOLODataset class. + + This specialized dataset class is designed for use with the RT-DETR object detection model and is optimized for + real-time detection and tracking tasks. + + Attributes: + augment (bool): Whether to apply data augmentation. + rect (bool): Whether to use rectangular training. + use_segments (bool): Whether to use segmentation masks. + use_keypoints (bool): Whether to use keypoint annotations. + imgsz (int): Target image size for training. + + Methods: + load_image: Load one image from dataset index. + build_transforms: Build transformation pipeline for the dataset. + + Examples: + Initialize an RT-DETR dataset + >>> dataset = RTDETRDataset(img_path="path/to/images", imgsz=640) + >>> image, hw0, hw = dataset.load_image(0) + """ + + def __init__(self, *args, data=None, **kwargs): + """Initialize the RTDETRDataset class by inheriting from the YOLODataset class. + + This constructor sets up a dataset specifically optimized for the RT-DETR (Real-Time DEtection TRansformer) + model, building upon the base YOLODataset functionality. + + Args: + *args (Any): Variable length argument list passed to the parent YOLODataset class. + data (dict | None): Dictionary containing dataset information. If None, default values will be used. + **kwargs (Any): Additional keyword arguments passed to the parent YOLODataset class. + """ + super().__init__(*args, data=data, **kwargs) + + def load_image(self, i, rect_mode=False): + """Load one image from dataset index 'i'. + + Args: + i (int): Index of the image to load. + rect_mode (bool, optional): Whether to use rectangular mode for batch inference. + + Returns: + im (np.ndarray): Loaded image as a NumPy array. + hw_original (tuple[int, int]): Original image dimensions in (height, width) format. + hw_resized (tuple[int, int]): Resized image dimensions in (height, width) format. + + Examples: + Load an image from the dataset + >>> dataset = RTDETRDataset(img_path="path/to/images") + >>> image, hw0, hw = dataset.load_image(0) + """ + return super().load_image(i=i, rect_mode=rect_mode) + + +class RTDETRValidator(DetectionValidator): + """RTDETRValidator extends the DetectionValidator class to provide validation capabilities specifically tailored for + the RT-DETR (Real-Time DETR) object detection model. + + The class allows building of an RTDETR-specific dataset for validation, applies confidence thresholding for + post-processing, and updates evaluation metrics accordingly. + + Attributes: + args (Namespace): Configuration arguments for validation. + data (dict): Dataset configuration dictionary. + + Methods: + build_dataset: Build an RTDETR Dataset for validation. + postprocess: Apply confidence thresholding to prediction outputs. + + Examples: + Initialize and run RT-DETR validation + >>> from ultralytics.models.rtdetr import RTDETRValidator + >>> args = dict(model="rtdetr-l.pt", data="coco8.yaml") + >>> validator = RTDETRValidator(args=args) + >>> validator() + + Notes: + For further details on the attributes and methods, refer to the parent DetectionValidator class. + """ + + def build_dataset(self, img_path, mode="val", batch=None): + """Build an RTDETR Dataset. + + Args: + img_path (str): Path to the folder containing images. + mode (str, optional): `train` mode or `val` mode, users are able to customize different augmentations for + each mode. + batch (int, optional): Size of batches, this is for `rect`. + + Returns: + (RTDETRDataset): Dataset configured for RT-DETR validation. + """ + return RTDETRDataset( + img_path=img_path, + imgsz=self.args.imgsz, + batch_size=batch, + augment=False, # no augmentation + hyp=self.args, + rect=False, # no rect + cache=self.args.cache or None, + single_cls=self.args.single_cls or False, + prefix=colorstr(f"{mode}: "), + classes=self.args.classes, + data=self.data, + fraction=1.0 + if self.data.get("complete") + else get_split_fraction(self.args.fraction, self.args.split or "val"), + ) + + def scale_preds(self, predn: dict[str, torch.Tensor], pbatch: dict[str, Any]) -> dict[str, torch.Tensor]: + """Return predictions unchanged as RT-DETR handles scaling in postprocessing.""" + return predn + + def postprocess( + self, preds: torch.Tensor | list[torch.Tensor] | tuple[torch.Tensor] + ) -> list[dict[str, torch.Tensor]]: + """Apply post-processing to prediction outputs. + + Top-k selection is already performed inside the decoder head. This method converts normalized xywh + coordinates to pixel xyxy format. + + Args: + preds (torch.Tensor | list | tuple): Predictions from the model with shape (batch_size, num_queries, 6), + where the last dimension is [cx, cy, w, h, score, class]. + + Returns: + (list[dict[str, torch.Tensor]]): List of dictionaries for each image, each containing: + - 'bboxes': Tensor of shape (N, 4) with bounding box coordinates in xyxy pixel format + - 'conf': Tensor of shape (N,) with confidence scores + - 'cls': Tensor of shape (N,) with class indices + """ + if isinstance(preds, (list, tuple)): + preds = preds[0] + + bboxes, scores, labels = preds.split((4, 1, 1), dim=-1) + bboxes = ops.xywh2xyxy(bboxes) * self.args.imgsz + scores, labels = scores.squeeze(-1), labels.squeeze(-1) + masks = [(score > self.args.conf).nonzero().squeeze(1)[: self.args.max_det] for score in scores] + + return [ + {"bboxes": bbox[m], "conf": score[m], "cls": label[m]} + for bbox, score, label, m in zip(bboxes, scores, labels, masks) + ] + + def pred_to_json(self, predn: dict[str, torch.Tensor], pbatch: dict[str, Any]) -> None: + """Serialize YOLO predictions to COCO json format. + + Args: + predn (dict[str, torch.Tensor]): Predictions dictionary containing 'bboxes', 'conf', and 'cls' keys with + bounding box coordinates, confidence scores, and class predictions. + pbatch (dict[str, Any]): Batch dictionary containing 'imgsz', 'ori_shape', 'ratio_pad', and 'im_file'. + """ + path = Path(pbatch["im_file"]) + stem = path.stem + image_id = int(stem) if stem.isnumeric() else stem + box = predn["bboxes"].clone() + box[..., [0, 2]] *= pbatch["ori_shape"][1] / self.args.imgsz # native-space pred + box[..., [1, 3]] *= pbatch["ori_shape"][0] / self.args.imgsz # native-space pred + box = ops.xyxy2xywh(box) # xywh + box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner + for b, s, c in zip(box.tolist(), predn["conf"].tolist(), predn["cls"].tolist()): + self.jdict.append( + { + "image_id": image_id, + "file_name": path.name, + "category_id": self.class_map[int(c)], + "bbox": [round(x, 3) for x in b], + "score": round(s, 5), + } + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e8723bcd97dace6d9ecafae0893ffc1ecba118b6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__init__.py @@ -0,0 +1,25 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .model import SAM +from .predict import ( + Predictor, + SAM2DynamicInteractivePredictor, + SAM2Predictor, + SAM2VideoPredictor, + SAM3Predictor, + SAM3SemanticPredictor, + SAM3VideoPredictor, + SAM3VideoSemanticPredictor, +) + +__all__ = ( + "SAM", + "Predictor", + "SAM2DynamicInteractivePredictor", + "SAM2Predictor", + "SAM2VideoPredictor", + "SAM3Predictor", + "SAM3SemanticPredictor", + "SAM3VideoPredictor", + "SAM3VideoSemanticPredictor", +) # tuple or list of exportable items diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01e5984d8755633b0aa15e9fc5592b76fed79523 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/amg.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/amg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..083c2ff77cb0aa81913b71421c13edec16f7f6bf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/amg.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/build.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/build.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffaac4f47937221b32449801e4af930c8f642040 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/build.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/build_sam3.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/build_sam3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b5870f988c349c7a8e92b240f1bfc3ac5fb633e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/build_sam3.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/model.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b10be029140f625e0043494f81615dbbe67cb071 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/model.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/predict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/predict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4cfdb391e338c64177c96083bdb70dac4999b0d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/__pycache__/predict.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc99cf55b3be081a168cb4edd712bf653ab240160bd8fa02009f1e0f38fd214d +size 185430 diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/amg.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/amg.py new file mode 100644 index 0000000000000000000000000000000000000000..e72a7f27e14392ab86614e196f871f8f7b46d627 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/amg.py @@ -0,0 +1,275 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import math +from collections.abc import Generator +from itertools import product +from typing import Any + +import numpy as np +import torch + + +def is_box_near_crop_edge( + boxes: torch.Tensor, crop_box: list[int], orig_box: list[int], atol: float = 20.0 +) -> torch.Tensor: + """Determine if bounding boxes are near the edge of a cropped image region using a specified tolerance. + + Args: + boxes (torch.Tensor): Bounding boxes in XYXY format. + crop_box (list[int]): Crop box coordinates in [x0, y0, x1, y1] format. + orig_box (list[int]): Original image box coordinates in [x0, y0, x1, y1] format. + atol (float, optional): Absolute tolerance for edge proximity detection. + + Returns: + (torch.Tensor): Boolean tensor indicating which boxes are near crop edges. + + Examples: + >>> boxes = torch.tensor([[10, 10, 50, 50], [100, 100, 150, 150]]) + >>> crop_box = [0, 0, 200, 200] + >>> orig_box = [0, 0, 300, 300] + >>> near_edge = is_box_near_crop_edge(boxes, crop_box, orig_box, atol=20.0) + """ + crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device) + orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device) + boxes = uncrop_boxes_xyxy(boxes, crop_box).float() + near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0) + near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0) + near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge) + return torch.any(near_crop_edge, dim=1) + + +def batch_iterator(batch_size: int, *args) -> Generator[list[Any]]: + """Yield batches of data from input arguments with specified batch size for efficient processing. + + This function takes a batch size and any number of iterables, then yields batches of elements from those + iterables. All input iterables must have the same length. + + Args: + batch_size (int): Size of each batch to yield. + *args (Any): Variable length input iterables to batch. All iterables must have the same length. + + Yields: + (list[Any]): A list of batched elements from each input iterable. + + Examples: + >>> data = [1, 2, 3, 4, 5] + >>> labels = ["a", "b", "c", "d", "e"] + >>> for batch in batch_iterator(2, data, labels): + ... print(batch) + [[1, 2], ['a', 'b']] + [[3, 4], ['c', 'd']] + [[5], ['e']] + """ + assert args and all(len(a) == len(args[0]) for a in args), "Batched iteration must have same-size inputs." + n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0) + for b in range(n_batches): + yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args] + + +def calculate_stability_score(masks: torch.Tensor, mask_threshold: float, threshold_offset: float) -> torch.Tensor: + """Compute the stability score for a batch of masks. + + The stability score is the IoU between binary masks obtained by thresholding the predicted mask logits at high and + low values. + + Args: + masks (torch.Tensor): Batch of predicted mask logits. + mask_threshold (float): Threshold value for creating binary masks. + threshold_offset (float): Offset applied to the threshold for creating high and low binary masks. + + Returns: + (torch.Tensor): Stability scores for each mask in the batch. + + Examples: + >>> masks = torch.rand(10, 256, 256) # Batch of 10 masks + >>> mask_threshold = 0.5 + >>> threshold_offset = 0.1 + >>> stability_scores = calculate_stability_score(masks, mask_threshold, threshold_offset) + + Notes: + - One mask is always contained inside the other. + - Memory is saved by preventing unnecessary cast to torch.int64. + """ + intersections = (masks > (mask_threshold + threshold_offset)).sum(-1, dtype=torch.int16).sum(-1, dtype=torch.int32) + unions = (masks > (mask_threshold - threshold_offset)).sum(-1, dtype=torch.int16).sum(-1, dtype=torch.int32) + return intersections / unions + + +def build_point_grid(n_per_side: int) -> np.ndarray: + """Generate a 2D grid of evenly spaced points in the range [0,1]x[0,1] for image segmentation tasks.""" + offset = 1 / (2 * n_per_side) + points_one_side = np.linspace(offset, 1 - offset, n_per_side) + points_x = np.tile(points_one_side[None, :], (n_per_side, 1)) + points_y = np.tile(points_one_side[:, None], (1, n_per_side)) + return np.stack([points_x, points_y], axis=-1).reshape(-1, 2) + + +def build_all_layer_point_grids(n_per_side: int, n_layers: int, scale_per_layer: int) -> list[np.ndarray]: + """Generate point grids for multiple crop layers with varying scales and densities.""" + return [build_point_grid(int(n_per_side / (scale_per_layer**i))) for i in range(n_layers + 1)] + + +def generate_crop_boxes( + im_size: tuple[int, ...], n_layers: int, overlap_ratio: float +) -> tuple[list[list[int]], list[int]]: + """Generate crop boxes of varying sizes for multiscale image processing, with layered overlapping regions. + + Args: + im_size (tuple[int, ...]): Height and width of the input image. + n_layers (int): Number of layers to generate crop boxes for. + overlap_ratio (float): Ratio of overlap between adjacent crop boxes. + + Returns: + crop_boxes (list[list[int]]): List of crop boxes in [x0, y0, x1, y1] format. + layer_idxs (list[int]): List of layer indices corresponding to each crop box. + + Examples: + >>> im_size = (800, 1200) # Height, width + >>> n_layers = 3 + >>> overlap_ratio = 0.25 + >>> crop_boxes, layer_idxs = generate_crop_boxes(im_size, n_layers, overlap_ratio) + """ + crop_boxes, layer_idxs = [], [] + im_h, im_w = im_size + short_side = min(im_h, im_w) + + # Original image + crop_boxes.append([0, 0, im_w, im_h]) + layer_idxs.append(0) + + def crop_len(orig_len, n_crops, overlap): + """Calculate the length of each crop given the original length, number of crops, and overlap.""" + return math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops) + + for i_layer in range(n_layers): + n_crops_per_side = 2 ** (i_layer + 1) + overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side)) + + crop_w = crop_len(im_w, n_crops_per_side, overlap) + crop_h = crop_len(im_h, n_crops_per_side, overlap) + + crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)] + crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)] + + # Crops in XYWH format + for x0, y0 in product(crop_box_x0, crop_box_y0): + box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)] + crop_boxes.append(box) + layer_idxs.append(i_layer + 1) + + return crop_boxes, layer_idxs + + +def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: list[int]) -> torch.Tensor: + """Uncrop bounding boxes by adding the crop box offset to their coordinates.""" + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device) + # Check if boxes has a channel dimension + if len(boxes.shape) == 3: + offset = offset.unsqueeze(1) + return boxes + offset + + +def uncrop_points(points: torch.Tensor, crop_box: list[int]) -> torch.Tensor: + """Uncrop points by adding the crop box offset to their coordinates.""" + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0]], device=points.device) + # Check if points has a channel dimension + if len(points.shape) == 3: + offset = offset.unsqueeze(1) + return points + offset + + +def uncrop_masks(masks: torch.Tensor, crop_box: list[int], orig_h: int, orig_w: int) -> torch.Tensor: + """Uncrop masks by padding them to the original image size, handling coordinate transformations.""" + x0, y0, x1, y1 = crop_box + if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h: + return masks + # Coordinate transform masks + pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0) + pad = (x0, pad_x - x0, y0, pad_y - y0) + return torch.nn.functional.pad(masks, pad, value=0) + + +def remove_small_regions(mask: np.ndarray, area_thresh: float, mode: str) -> tuple[np.ndarray, bool]: + """Remove small disconnected regions or holes in a mask based on area threshold and mode. + + Args: + mask (np.ndarray): Binary mask to process. + area_thresh (float): Area threshold below which regions will be removed. + mode (str): Processing mode, either 'holes' to fill small holes or 'islands' to remove small disconnected + regions. + + Returns: + processed_mask (np.ndarray): Processed binary mask with small regions removed. + modified (bool): Whether any regions were modified. + + Examples: + >>> mask = np.zeros((100, 100), dtype=np.bool_) + >>> mask[40:60, 40:60] = True # Create a square + >>> mask[45:55, 45:55] = False # Create a hole + >>> processed_mask, modified = remove_small_regions(mask, 50, "holes") + """ + import cv2 # type: ignore + + assert mode in {"holes", "islands"}, f"Provided mode {mode} is invalid" + correct_holes = mode == "holes" + working_mask = (correct_holes ^ mask).astype(np.uint8) + n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8) + sizes = stats[:, -1][1:] # Row 0 is background label + small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh] + if not small_regions: + return mask, False + fill_labels = [0, *small_regions] + if not correct_holes: + # If every region is below threshold, keep largest + fill_labels = [i for i in range(n_labels) if i not in fill_labels] or [int(np.argmax(sizes)) + 1] + mask = np.isin(regions, fill_labels) + return mask, True + + +def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor: + """Calculate bounding boxes in XYXY format around binary masks. + + Args: + masks (torch.Tensor): Binary masks with shape (B, H, W) or (B, C, H, W). + + Returns: + (torch.Tensor): Bounding boxes in XYXY format with shape (B, 4) or (B, C, 4). + + Notes: + - Handles empty masks by returning zero boxes. + - Preserves input tensor dimensions in the output. + """ + # torch.max below raises an error on empty inputs, just skip in this case + if torch.numel(masks) == 0: + return torch.zeros(*masks.shape[:-2], 4, device=masks.device) + + # Normalize shape to CxHxW + shape = masks.shape + h, w = shape[-2:] + masks = masks.flatten(0, -3) if len(shape) > 2 else masks.unsqueeze(0) + # Get top and bottom edges + in_height, _ = torch.max(masks, dim=-1) + in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :] + bottom_edges, _ = torch.max(in_height_coords, dim=-1) + in_height_coords = in_height_coords + h * (~in_height) + top_edges, _ = torch.min(in_height_coords, dim=-1) + + # Get left and right edges + in_width, _ = torch.max(masks, dim=-2) + in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :] + right_edges, _ = torch.max(in_width_coords, dim=-1) + in_width_coords = in_width_coords + w * (~in_width) + left_edges, _ = torch.min(in_width_coords, dim=-1) + + # If the mask is empty the right edge will be to the left of the left edge. + # Replace these boxes with [0, 0, 0, 0] + empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges) + out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1) + out = out * (~empty_filter).unsqueeze(-1) + + # Return to original shape + return out.reshape(*shape[:-2], 4) if len(shape) > 2 else out[0] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/build.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/build.py new file mode 100644 index 0000000000000000000000000000000000000000..ee7f3d86562dfe49075ae943862ae727dbaece0c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/build.py @@ -0,0 +1,365 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from functools import partial + +import torch + +from ultralytics.utils.downloads import attempt_download_asset +from ultralytics.utils.patches import torch_load + +from .modules.decoders import MaskDecoder +from .modules.encoders import FpnNeck, Hiera, ImageEncoder, ImageEncoderViT, MemoryEncoder, PromptEncoder +from .modules.memory_attention import MemoryAttention, MemoryAttentionLayer +from .modules.sam import SAM2Model, SAMModel +from .modules.tiny_encoder import TinyViT +from .modules.transformer import TwoWayTransformer + + +def _load_checkpoint(model, checkpoint): + """Load checkpoint into model from file path.""" + if checkpoint is None: + return model + + checkpoint = attempt_download_asset(checkpoint) + with open(checkpoint, "rb") as f: + state_dict = torch_load(f) + # Handle nested "model" key + if "model" in state_dict and isinstance(state_dict["model"], dict): + state_dict = state_dict["model"] + model.load_state_dict(state_dict) + return model + + +def build_sam_vit_h(checkpoint=None): + """Build and return a Segment Anything Model (SAM) h-size model with specified encoder parameters.""" + return _build_sam( + encoder_embed_dim=1280, + encoder_depth=32, + encoder_num_heads=16, + encoder_global_attn_indexes=[7, 15, 23, 31], + checkpoint=checkpoint, + ) + + +def build_sam_vit_l(checkpoint=None): + """Build and return a Segment Anything Model (SAM) l-size model with specified encoder parameters.""" + return _build_sam( + encoder_embed_dim=1024, + encoder_depth=24, + encoder_num_heads=16, + encoder_global_attn_indexes=[5, 11, 17, 23], + checkpoint=checkpoint, + ) + + +def build_sam_vit_b(checkpoint=None): + """Build and return a Segment Anything Model (SAM) b-size model with specified encoder parameters.""" + return _build_sam( + encoder_embed_dim=768, + encoder_depth=12, + encoder_num_heads=12, + encoder_global_attn_indexes=[2, 5, 8, 11], + checkpoint=checkpoint, + ) + + +def build_mobile_sam(checkpoint=None): + """Build and return a Mobile Segment Anything Model (Mobile-SAM) for efficient image segmentation.""" + return _build_sam( + encoder_embed_dim=[64, 128, 160, 320], + encoder_depth=[2, 2, 6, 2], + encoder_num_heads=[2, 4, 5, 10], + encoder_global_attn_indexes=None, + mobile_sam=True, + checkpoint=checkpoint, + ) + + +def build_sam2_t(checkpoint=None): + """Build and return a Segment Anything Model 2 (SAM2) tiny-size model with specified architecture parameters.""" + return _build_sam2( + encoder_embed_dim=96, + encoder_stages=[1, 2, 7, 2], + encoder_num_heads=1, + encoder_global_att_blocks=[5, 7, 9], + encoder_window_spec=[8, 4, 14, 7], + encoder_backbone_channel_list=[768, 384, 192, 96], + checkpoint=checkpoint, + ) + + +def build_sam2_s(checkpoint=None): + """Build and return a small-size Segment Anything Model 2 (SAM2) with specified architecture parameters.""" + return _build_sam2( + encoder_embed_dim=96, + encoder_stages=[1, 2, 11, 2], + encoder_num_heads=1, + encoder_global_att_blocks=[7, 10, 13], + encoder_window_spec=[8, 4, 14, 7], + encoder_backbone_channel_list=[768, 384, 192, 96], + checkpoint=checkpoint, + ) + + +def build_sam2_b(checkpoint=None): + """Build and return a Segment Anything Model 2 (SAM2) base-size model with specified architecture parameters.""" + return _build_sam2( + encoder_embed_dim=112, + encoder_stages=[2, 3, 16, 3], + encoder_num_heads=2, + encoder_global_att_blocks=[12, 16, 20], + encoder_window_spec=[8, 4, 14, 7], + encoder_window_spatial_size=[14, 14], + encoder_backbone_channel_list=[896, 448, 224, 112], + checkpoint=checkpoint, + ) + + +def build_sam2_l(checkpoint=None): + """Build and return a large-size Segment Anything Model 2 (SAM2) with specified architecture parameters.""" + return _build_sam2( + encoder_embed_dim=144, + encoder_stages=[2, 6, 36, 4], + encoder_num_heads=2, + encoder_global_att_blocks=[23, 33, 43], + encoder_window_spec=[8, 4, 16, 8], + encoder_backbone_channel_list=[1152, 576, 288, 144], + checkpoint=checkpoint, + ) + + +def _build_sam( + encoder_embed_dim, + encoder_depth, + encoder_num_heads, + encoder_global_attn_indexes, + checkpoint=None, + mobile_sam=False, +): + """Build a Segment Anything Model (SAM) with specified encoder parameters. + + Args: + encoder_embed_dim (int | list[int]): Embedding dimension for the encoder. + encoder_depth (int | list[int]): Depth of the encoder. + encoder_num_heads (int | list[int]): Number of attention heads in the encoder. + encoder_global_attn_indexes (list[int] | None): Indexes for global attention in the encoder. + checkpoint (str | None, optional): Path to the model checkpoint file. + mobile_sam (bool, optional): Whether to build a Mobile-SAM model. + + Returns: + (SAMModel): A Segment Anything Model instance with the specified architecture. + + Examples: + >>> sam = _build_sam(768, 12, 12, [2, 5, 8, 11]) + >>> sam = _build_sam([64, 128, 160, 320], [2, 2, 6, 2], [2, 4, 5, 10], None, mobile_sam=True) + """ + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + image_encoder = ( + TinyViT( + img_size=1024, + in_chans=3, + num_classes=1000, + embed_dims=encoder_embed_dim, + depths=encoder_depth, + num_heads=encoder_num_heads, + window_sizes=[7, 7, 14, 7], + mlp_ratio=4.0, + drop_rate=0.0, + drop_path_rate=0.0, + use_checkpoint=False, + mbconv_expand_ratio=4.0, + local_conv_size=3, + layer_lr_decay=0.8, + ) + if mobile_sam + else ImageEncoderViT( + depth=encoder_depth, + embed_dim=encoder_embed_dim, + img_size=image_size, + mlp_ratio=4, + norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), + num_heads=encoder_num_heads, + patch_size=vit_patch_size, + qkv_bias=True, + use_rel_pos=True, + global_attn_indexes=encoder_global_attn_indexes, + window_size=14, + out_chans=prompt_embed_dim, + ) + ) + sam = SAMModel( + image_encoder=image_encoder, + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + ), + pixel_mean=[123.675, 116.28, 103.53], + pixel_std=[58.395, 57.12, 57.375], + ) + if checkpoint is not None: + sam = _load_checkpoint(sam, checkpoint) + sam.eval() + return sam + + +def _build_sam2( + encoder_embed_dim=1280, + encoder_stages=(2, 6, 36, 4), + encoder_num_heads=2, + encoder_global_att_blocks=(7, 15, 23, 31), + encoder_backbone_channel_list=(1152, 576, 288, 144), + encoder_window_spatial_size=(7, 7), + encoder_window_spec=(8, 4, 16, 8), + checkpoint=None, +): + """Build and return a Segment Anything Model 2 (SAM2) with specified architecture parameters. + + Args: + encoder_embed_dim (int, optional): Embedding dimension for the encoder. + encoder_stages (list[int], optional): Number of blocks in each stage of the encoder. + encoder_num_heads (int, optional): Number of attention heads in the encoder. + encoder_global_att_blocks (list[int], optional): Indices of global attention blocks in the encoder. + encoder_backbone_channel_list (list[int], optional): Channel dimensions for each level of the encoder backbone. + encoder_window_spatial_size (list[int], optional): Spatial size of the window for position embeddings. + encoder_window_spec (list[int], optional): Window specifications for each stage of the encoder. + checkpoint (str | None, optional): Path to the checkpoint file for loading pre-trained weights. + + Returns: + (SAM2Model): A configured and initialized SAM2 model. + + Examples: + >>> sam2_model = _build_sam2(encoder_embed_dim=96, encoder_stages=[1, 2, 7, 2]) + >>> sam2_model.eval() + """ + image_encoder = ImageEncoder( + trunk=Hiera( + embed_dim=encoder_embed_dim, + num_heads=encoder_num_heads, + stages=encoder_stages, + global_att_blocks=encoder_global_att_blocks, + window_pos_embed_bkg_spatial_size=encoder_window_spatial_size, + window_spec=encoder_window_spec, + ), + neck=FpnNeck( + d_model=256, + backbone_channel_list=encoder_backbone_channel_list, + fpn_top_down_levels=[2, 3], + fpn_interp_model="nearest", + ), + scalp=1, + ) + memory_attention = MemoryAttention(d_model=256, pos_enc_at_input=True, num_layers=4, layer=MemoryAttentionLayer()) + memory_encoder = MemoryEncoder(out_dim=64) + + is_sam2_1 = checkpoint is not None and "sam2.1" in checkpoint + sam2 = SAM2Model( + image_encoder=image_encoder, + memory_attention=memory_attention, + memory_encoder=memory_encoder, + num_maskmem=7, + image_size=1024, + sigmoid_scale_for_mem_enc=20.0, + sigmoid_bias_for_mem_enc=-10.0, + use_mask_input_as_output_without_sam=True, + directly_add_no_mem_embed=True, + use_high_res_features_in_sam=True, + multimask_output_in_sam=True, + iou_prediction_use_sigmoid=True, + use_obj_ptrs_in_encoder=True, + add_tpos_enc_to_obj_ptrs=True, + only_obj_ptrs_in_the_past_for_eval=True, + pred_obj_scores=True, + pred_obj_scores_mlp=True, + fixed_no_obj_ptr=True, + multimask_output_for_tracking=True, + use_multimask_token_for_obj_ptr=True, + multimask_min_pt_num=0, + multimask_max_pt_num=1, + use_mlp_for_obj_ptr_proj=True, + compile_image_encoder=False, + no_obj_embed_spatial=is_sam2_1, + proj_tpos_enc_in_obj_ptrs=is_sam2_1, + use_signed_tpos_enc_to_obj_ptrs=is_sam2_1, + sam_mask_decoder_extra_args={ + "dynamic_multimask_via_stability": True, + "dynamic_multimask_stability_delta": 0.05, + "dynamic_multimask_stability_thresh": 0.98, + }, + ) + + if checkpoint is not None: + sam2 = _load_checkpoint(sam2, checkpoint) + sam2.eval() + return sam2 + + +sam_model_map = { + "sam_h.pt": build_sam_vit_h, + "sam_l.pt": build_sam_vit_l, + "sam_b.pt": build_sam_vit_b, + "mobile_sam.pt": build_mobile_sam, + "sam2_t.pt": build_sam2_t, + "sam2_s.pt": build_sam2_s, + "sam2_b.pt": build_sam2_b, + "sam2_l.pt": build_sam2_l, + "sam2.1_t.pt": build_sam2_t, + "sam2.1_s.pt": build_sam2_s, + "sam2.1_b.pt": build_sam2_b, + "sam2.1_l.pt": build_sam2_l, +} + + +def build_sam(ckpt="sam_b.pt"): + """Build and return a Segment Anything Model (SAM) based on the provided checkpoint. + + Args: + ckpt (str | Path, optional): Path to the checkpoint file or name of a pre-defined SAM model. + + Returns: + (SAMModel | SAM2Model): A configured and initialized SAM or SAM2 model instance. + + Raises: + FileNotFoundError: If the provided checkpoint is not a supported SAM model. + + Examples: + >>> sam_model = build_sam("sam_b.pt") + >>> sam_model = build_sam("path/to/custom_checkpoint.pt") + + Notes: + Supported pre-defined models include: + - SAM: 'sam_h.pt', 'sam_l.pt', 'sam_b.pt', 'mobile_sam.pt' + - SAM2: 'sam2_t.pt', 'sam2_s.pt', 'sam2_b.pt', 'sam2_l.pt' + """ + model_builder = None + ckpt = str(ckpt) # to allow Path ckpt types + for k in sam_model_map: + if ckpt.endswith(k): + model_builder = sam_model_map.get(k) + + if not model_builder: + raise FileNotFoundError(f"{ckpt} is not a supported SAM model. Available models are: \n {sam_model_map.keys()}") + + return model_builder(ckpt) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/build_sam3.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/build_sam3.py new file mode 100644 index 0000000000000000000000000000000000000000..da37ff721d9de107449ce99ab1dbf93456594d6c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/build_sam3.py @@ -0,0 +1,390 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved + +from torch import nn + +from ultralytics.nn.modules.transformer import MLP +from ultralytics.utils.patches import torch_load + +from .modules.blocks import PositionEmbeddingSine, RoPEAttention +from .modules.encoders import MemoryEncoder +from .modules.memory_attention import MemoryAttention, MemoryAttentionLayer +from .modules.sam import SAM3Model +from .sam3.decoder import TransformerDecoder, TransformerDecoderLayer +from .sam3.encoder import TransformerEncoderFusion, TransformerEncoderLayer +from .sam3.geometry_encoders import SequenceGeometryEncoder +from .sam3.maskformer_segmentation import PixelDecoder, UniversalSegmentationHead +from .sam3.model_misc import DotProductScoring, TransformerWrapper +from .sam3.necks import Sam3DualViTDetNeck +from .sam3.sam3_image import SAM3SemanticModel +from .sam3.text_encoder_ve import VETextEncoder +from .sam3.vitdet import ViT +from .sam3.vl_combiner import SAM3VLBackbone + + +def _create_vision_backbone(compile_mode=None, enable_inst_interactivity=True) -> Sam3DualViTDetNeck: + """Create SAM3 visual backbone with ViT and neck.""" + # Position encoding + position_encoding = PositionEmbeddingSine( + num_pos_feats=256, + normalize=True, + scale=None, + temperature=10000, + ) + + # ViT backbone + vit_backbone = ViT( + img_size=1008, + pretrain_img_size=336, + patch_size=14, + embed_dim=1024, + depth=32, + num_heads=16, + mlp_ratio=4.625, + norm_layer="LayerNorm", + drop_path_rate=0.1, + qkv_bias=True, + use_abs_pos=True, + tile_abs_pos=True, + global_att_blocks=(7, 15, 23, 31), + rel_pos_blocks=(), + use_rope=True, + use_interp_rope=True, + window_size=24, + pretrain_use_cls_token=True, + retain_cls_token=False, + ln_pre=True, + ln_post=False, + return_interm_layers=False, + bias_patch_embed=False, + compile_mode=compile_mode, + ) + return Sam3DualViTDetNeck( + position_encoding=position_encoding, + d_model=256, + scale_factors=[4.0, 2.0, 1.0, 0.5], + trunk=vit_backbone, + add_sam2_neck=enable_inst_interactivity, + ) + + +def _create_sam3_transformer() -> TransformerWrapper: + """Create SAM3 detector encoder and decoder.""" + encoder: TransformerEncoderFusion = TransformerEncoderFusion( + layer=TransformerEncoderLayer( + d_model=256, + dim_feedforward=2048, + dropout=0.1, + pos_enc_at_attn=True, + pos_enc_at_cross_attn_keys=False, + pos_enc_at_cross_attn_queries=False, + pre_norm=True, + self_attention=nn.MultiheadAttention( + num_heads=8, + dropout=0.1, + embed_dim=256, + batch_first=True, + ), + cross_attention=nn.MultiheadAttention( + num_heads=8, + dropout=0.1, + embed_dim=256, + batch_first=True, + ), + ), + num_layers=6, + d_model=256, + num_feature_levels=1, + frozen=False, + use_act_checkpoint=True, + add_pooled_text_to_img_feat=False, + pool_text_with_mask=True, + ) + decoder: TransformerDecoder = TransformerDecoder( + layer=TransformerDecoderLayer( + d_model=256, + dim_feedforward=2048, + dropout=0.1, + cross_attention=nn.MultiheadAttention( + num_heads=8, + dropout=0.1, + embed_dim=256, + ), + n_heads=8, + use_text_cross_attention=True, + ), + num_layers=6, + num_queries=200, + return_intermediate=True, + box_refine=True, + num_o2m_queries=0, + dac=True, + boxRPB="log", + d_model=256, + frozen=False, + interaction_layer=None, + dac_use_selfatt_ln=True, + use_act_checkpoint=True, + presence_token=True, + ) + + return TransformerWrapper(encoder=encoder, decoder=decoder, d_model=256) + + +def build_sam3_image_model(checkpoint_path: str, enable_segmentation: bool = True, compile: bool = False): + """Build SAM3 image model. + + Args: + checkpoint_path: Optional path to model checkpoint + enable_segmentation: Whether to enable segmentation head + compile: Whether to enable compilation of the model + + Returns: + A SAM3 image model + """ + try: + import clip + except ImportError: + from ultralytics.utils.checks import check_requirements + + check_requirements("git+https://github.com/ultralytics/CLIP.git") + import clip + # Create visual components + compile_mode = "default" if compile else None + vision_encoder = _create_vision_backbone(compile_mode=compile_mode, enable_inst_interactivity=True) + + # Create text components + text_encoder = VETextEncoder( + tokenizer=clip.simple_tokenizer.SimpleTokenizer(), + d_model=256, + width=1024, + heads=16, + layers=24, + ) + + # Create visual-language backbone + backbone = SAM3VLBackbone(visual=vision_encoder, text=text_encoder, scalp=1) + + # Create transformer components + transformer = _create_sam3_transformer() + + # Create dot product scoring + dot_prod_scoring = DotProductScoring( + d_model=256, + d_proj=256, + prompt_mlp=MLP( + input_dim=256, + hidden_dim=2048, + output_dim=256, + num_layers=2, + residual=True, + out_norm=nn.LayerNorm(256), + ), + ) + + # Create segmentation head if enabled + segmentation_head = ( + UniversalSegmentationHead( + hidden_dim=256, + upsampling_stages=3, + aux_masks=False, + presence_head=False, + dot_product_scorer=None, + act_ckpt=True, + cross_attend_prompt=nn.MultiheadAttention( + num_heads=8, + dropout=0, + embed_dim=256, + ), + pixel_decoder=PixelDecoder( + num_upsampling_stages=3, + interpolation_mode="nearest", + hidden_dim=256, + compile_mode=compile_mode, + ), + ) + if enable_segmentation + else None + ) + + # Create geometry encoder + input_geometry_encoder = SequenceGeometryEncoder( + pos_enc=PositionEmbeddingSine( + num_pos_feats=256, + normalize=True, + scale=None, + temperature=10000, + ), + encode_boxes_as_points=False, + boxes_direct_project=True, + boxes_pool=True, + boxes_pos_enc=True, + d_model=256, + num_layers=3, + layer=TransformerEncoderLayer( + d_model=256, + dim_feedforward=2048, + dropout=0.1, + pos_enc_at_attn=False, + pre_norm=True, + pos_enc_at_cross_attn_queries=False, + pos_enc_at_cross_attn_keys=True, + ), + use_act_ckpt=True, + add_cls=True, + add_post_encode_proj=True, + ) + + # Create the SAM3SemanticModel model + model = SAM3SemanticModel( + backbone=backbone, + transformer=transformer, + input_geometry_encoder=input_geometry_encoder, + segmentation_head=segmentation_head, + num_feature_levels=1, + o2m_mask_predict=True, + dot_prod_scoring=dot_prod_scoring, + use_instance_query=False, + multimask_output=True, + ) + + # Load checkpoint + model = _load_checkpoint(model, checkpoint_path) + model.eval() + return model + + +def build_interactive_sam3(checkpoint_path: str, compile=None, with_backbone=True) -> SAM3Model: + """Build the SAM3 Tracker module for video tracking. + + Args: + checkpoint_path (str): Path to model checkpoint. + compile (str | None): Compilation mode for the vision backbone. + with_backbone (bool): Whether to include the vision backbone in the model. + + Returns: + (SAM3Model): A configured and initialized SAM3 model. + """ + # Create model components + memory_encoder = MemoryEncoder(out_dim=64, interpol_size=[1152, 1152]) + memory_attention = MemoryAttention( + batch_first=True, + d_model=256, + pos_enc_at_input=True, + layer=MemoryAttentionLayer( + dim_feedforward=2048, + dropout=0.1, + pos_enc_at_attn=False, + pos_enc_at_cross_attn_keys=True, + pos_enc_at_cross_attn_queries=False, + self_attn=RoPEAttention( + embedding_dim=256, + num_heads=1, + downsample_rate=1, + rope_theta=10000.0, + feat_sizes=[72, 72], + ), + d_model=256, + cross_attn=RoPEAttention( + embedding_dim=256, + num_heads=1, + downsample_rate=1, + kv_in_dim=64, + rope_theta=10000.0, + feat_sizes=[72, 72], + rope_k_repeat=True, + ), + ), + num_layers=4, + ) + + backbone = ( + SAM3VLBackbone(scalp=1, visual=_create_vision_backbone(compile_mode=compile), text=None) + if with_backbone + else None + ) + model = SAM3Model( + image_size=1008, + image_encoder=backbone, + memory_attention=memory_attention, + memory_encoder=memory_encoder, + backbone_stride=14, + num_maskmem=7, + sigmoid_scale_for_mem_enc=20.0, + sigmoid_bias_for_mem_enc=-10.0, + use_mask_input_as_output_without_sam=True, + directly_add_no_mem_embed=True, + use_high_res_features_in_sam=True, + multimask_output_in_sam=True, + iou_prediction_use_sigmoid=True, + use_obj_ptrs_in_encoder=True, + add_tpos_enc_to_obj_ptrs=True, + only_obj_ptrs_in_the_past_for_eval=True, + pred_obj_scores=True, + pred_obj_scores_mlp=True, + fixed_no_obj_ptr=True, + multimask_output_for_tracking=True, + use_multimask_token_for_obj_ptr=True, + multimask_min_pt_num=0, + multimask_max_pt_num=1, + use_mlp_for_obj_ptr_proj=True, + compile_image_encoder=False, + no_obj_embed_spatial=True, + proj_tpos_enc_in_obj_ptrs=True, + use_signed_tpos_enc_to_obj_ptrs=True, + sam_mask_decoder_extra_args={ + "dynamic_multimask_via_stability": True, + "dynamic_multimask_stability_delta": 0.05, + "dynamic_multimask_stability_thresh": 0.98, + }, + ) + + # Load checkpoint if provided + model = _load_checkpoint(model, checkpoint_path, interactive=True) + + # Setup device and mode + model.eval() + return model + + +def _load_checkpoint(model, checkpoint, interactive=False): + """Load SAM3 model checkpoint from file.""" + with open(checkpoint, "rb") as f: + ckpt = torch_load(f) + if "model" in ckpt and isinstance(ckpt["model"], dict): + ckpt = ckpt["model"] + # SAM 3.1 nests its point-prompt head as tracker.model.interactive_* beside the multiplex video tracker and renames + # its neck to interactive_convs, so map both onto the SAM 3 names (no-op for SAM 3 checkpoints) + ckpt = { + k.replace("tracker.model.interactive_", "tracker.") + .replace("tracker.model.interactivity_", "tracker.") + .replace("interactive_convs", "sam2_convs"): v + for k, v in ckpt.items() + } + sam3_image_ckpt = {k.replace("detector.", ""): v for k, v in ckpt.items() if "detector" in k} + if interactive: + sam3_image_ckpt.update( + { + k.replace("backbone.vision_backbone", "image_encoder.vision_backbone"): v + for k, v in sam3_image_ckpt.items() + if "backbone.vision_backbone" in k + } + ) + sam3_image_ckpt.update( + { + k.replace("tracker.transformer.encoder", "memory_attention"): v + for k, v in ckpt.items() + if "tracker.transformer" in k + } + ) + sam3_image_ckpt.update( + { + k.replace("tracker.maskmem_backbone", "memory_encoder"): v + for k, v in ckpt.items() + if "tracker.maskmem_backbone" in k + } + ) + sam3_image_ckpt.update({k.replace("tracker.", ""): v for k, v in ckpt.items() if "tracker." in k}) + model.load_state_dict(sam3_image_ckpt, strict=False) + return model diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/model.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/model.py new file mode 100644 index 0000000000000000000000000000000000000000..be50ee2aa641d09d571461194268384d3caaaf4a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/model.py @@ -0,0 +1,169 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +SAM model interface. + +This module provides an interface to the Segment Anything Model (SAM) from Ultralytics, designed for real-time image +segmentation tasks. The SAM model allows for promptable segmentation with unparalleled versatility in image analysis, +and has been trained on the SA-1B dataset. It features zero-shot performance capabilities, enabling it to adapt to new +image distributions and tasks without prior knowledge. + +Key Features: + - Promptable segmentation + - Real-time performance + - Zero-shot transfer capabilities + - Trained on SA-1B dataset +""" + +from __future__ import annotations + +from pathlib import Path + +from ultralytics.engine.model import Model +from ultralytics.utils.torch_utils import model_info + +from .predict import Predictor, SAM2Predictor, SAM3Predictor + + +class SAM(Model): + """SAM (Segment Anything Model) interface class for real-time image segmentation tasks. + + This class provides an interface to the Segment Anything Model (SAM) from Ultralytics, designed for promptable + segmentation with versatility in image analysis. It supports various prompts such as bounding boxes, points, or + labels, and features zero-shot performance capabilities. + + Attributes: + model (torch.nn.Module): The loaded SAM model. + is_sam2 (bool): Indicates whether the model is SAM2 variant. + task (str): The task type, set to "segment" for SAM models. + + Methods: + predict: Perform segmentation prediction on the given image or video source. + info: Log information about the SAM model. + + Examples: + >>> sam = SAM("sam_b.pt") + >>> results = sam.predict("image.jpg", points=[[500, 375]]) + >>> for r in results: + ... print(f"Detected {len(r.masks)} masks") + """ + + def __init__(self, model: str = "sam_b.pt") -> None: + """Initialize the SAM (Segment Anything Model) instance. + + Args: + model (str): Path to the pre-trained SAM model file. File should have a .pt or .pth extension. + + Raises: + NotImplementedError: If the model file extension is not .pt or .pth. + """ + if model and Path(model).suffix not in {".pt", ".pth"}: + raise NotImplementedError("SAM prediction requires pre-trained *.pt or *.pth model.") + self.is_sam2 = "sam2" in Path(model).stem + self.is_sam3 = "sam3" in Path(model).stem + super().__init__(model=model, task="segment") + + def _load(self, weights: str, task=None): + """Load the specified weights into the SAM model. + + Args: + weights (str): Path to the weights file. Should be a .pt or .pth file containing the model parameters. + task (str | None): Task name. If provided, it specifies the particular task the model is being loaded for. + + Examples: + >>> sam = SAM("sam_b.pt") + >>> sam._load("path/to/custom_weights.pt") + """ + if self.is_sam3: + from .build_sam3 import build_interactive_sam3 + + self.model = build_interactive_sam3(weights) + else: + from .build import build_sam # slow import + + self.model = build_sam(weights) + + def predict(self, source, stream: bool = False, bboxes=None, points=None, labels=None, **kwargs): + """Perform segmentation prediction on the given image or video source. + + Args: + source (str | PIL.Image | np.ndarray): Path to the image or video file, or a PIL.Image object, or a + np.ndarray object. + stream (bool): If True, enables real-time streaming. + bboxes (list[list[float]] | None): List of bounding box coordinates for prompted segmentation. + points (list[list[float]] | None): List of points for prompted segmentation. + labels (list[int] | None): List of labels for prompted segmentation. + **kwargs (Any): Additional keyword arguments for prediction. + + Returns: + (list): The model predictions. + + Examples: + >>> sam = SAM("sam_b.pt") + >>> results = sam.predict("image.jpg", points=[[500, 375]]) + >>> for r in results: + ... print(f"Detected {len(r.masks)} masks") + """ + overrides = {"conf": 0.25, "task": "segment", "mode": "predict", "imgsz": 1024} + kwargs = {**overrides, **kwargs, "retina_masks": True} + prompts = {"bboxes": bboxes, "points": points, "labels": labels} + return super().predict(source, stream, prompts=prompts, **kwargs) + + def __call__(self, source=None, stream: bool = False, bboxes=None, points=None, labels=None, **kwargs): + """Perform segmentation prediction on the given image or video source. + + This method is an alias for the 'predict' method, providing a convenient way to call the SAM model for + segmentation tasks. + + Args: + source (str | PIL.Image | np.ndarray | None): Path to the image or video file, or a PIL.Image object, or a + np.ndarray object. + stream (bool): If True, enables real-time streaming. + bboxes (list[list[float]] | None): List of bounding box coordinates for prompted segmentation. + points (list[list[float]] | None): List of points for prompted segmentation. + labels (list[int] | None): List of labels for prompted segmentation. + **kwargs (Any): Additional keyword arguments to be passed to the predict method. + + Returns: + (list): The model predictions, typically containing segmentation masks and other relevant information. + + Examples: + >>> sam = SAM("sam_b.pt") + >>> results = sam("image.jpg", points=[[500, 375]]) + >>> print(f"Detected {len(results[0].masks)} masks") + """ + return self.predict(source, stream, bboxes, points, labels, **kwargs) + + def info(self, detailed: bool = False, verbose: bool = True): + """Log information about the SAM model. + + Args: + detailed (bool): If True, displays detailed information about the model layers and operations. + verbose (bool): If True, prints the information to the console. + + Returns: + (tuple): A tuple containing the model's information (string representations of the model). + + Examples: + >>> sam = SAM("sam_b.pt") + >>> info = sam.info() + >>> print(info[0]) # Print summary information + """ + return model_info(self.model, detailed=detailed, verbose=verbose) + + @property + def task_map(self) -> dict[str, dict[str, type[Predictor]]]: + """Provide a mapping from the 'segment' task to its corresponding 'Predictor'. + + Returns: + (dict[str, dict[str, type[Predictor]]]): A dictionary mapping the 'segment' task to its corresponding + Predictor class. For SAM2 models, it maps to SAM2Predictor, otherwise to the standard Predictor. + + Examples: + >>> sam = SAM("sam_b.pt") + >>> task_map = sam.task_map + >>> print(task_map) + {'segment': {'predictor': }} + """ + return { + "segment": {"predictor": SAM2Predictor if self.is_sam2 else SAM3Predictor if self.is_sam3 else Predictor} + } diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..77a19dcf0f8093de419453747db2e7e719f96349 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__init__.py @@ -0,0 +1 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b7215bbeb7eacc70317c799974d4ab93ed3cf25 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/blocks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/blocks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e82282fe10f2d9acfa1cb0cd9a0ef20e1cba90a0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/blocks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/decoders.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/decoders.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1842f5780e727e806dd7281ce867eeafa0c2f61 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/decoders.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/encoders.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/encoders.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c203302b967a08e04398a6f83c5ed2f5c0ef70e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/encoders.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/memory_attention.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/memory_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d63e2cf374584c41f43415821c04488f740b10d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/memory_attention.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/sam.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/sam.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..450deeb557e15c70c7267983668c7e53cf53c3a6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/sam.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/tiny_encoder.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/tiny_encoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..643749093eee69318698daea7716e79e62aeb63a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/tiny_encoder.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/transformer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/transformer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99bbaf049e2701697e16cb21610ff640807f38df Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/transformer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bef02868b701d8c6e1a331d1d5c06d9b88cf1c23 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/blocks.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..67d6451bdb51f189643c0e190906e17a0ef3f846 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/blocks.py @@ -0,0 +1,1056 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import copy +import math +from functools import partial + +import numpy as np +import torch +import torch.nn.functional as F +from torch import Tensor, nn + +from ultralytics.nn.modules import MLP, LayerNorm2d, MLPBlock + +from .transformer import Attention, TwoWayAttentionBlock, TwoWayTransformer +from .utils import add_decomposed_rel_pos, apply_rotary_enc, compute_axial_cis, window_partition, window_unpartition + + +class DropPath(nn.Module): + """Implements stochastic depth regularization for neural networks during training. + + Attributes: + drop_prob (float): Probability of dropping a path during training. + scale_by_keep (bool): Whether to scale the output by the keep probability. + + Methods: + forward: Applies stochastic depth to input tensor during training, with optional scaling. + + Examples: + >>> drop_path = DropPath(drop_prob=0.2, scale_by_keep=True) + >>> x = torch.randn(32, 64, 224, 224) + >>> output = drop_path(x) + """ + + def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True): + """Initialize DropPath module for stochastic depth regularization during training.""" + super().__init__() + self.drop_prob = drop_prob + self.scale_by_keep = scale_by_keep + + def forward(self, x: Tensor) -> Tensor: + """Apply stochastic depth to input tensor during training, with optional scaling.""" + if self.drop_prob == 0.0 or not self.training: + return x + keep_prob = 1 - self.drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0 and self.scale_by_keep: + random_tensor.div_(keep_prob) + return x * random_tensor + + +class MaskDownSampler(nn.Module): + """A mask downsampling and embedding module for efficient processing of input masks. + + This class implements a mask downsampler that progressively reduces the spatial dimensions of input masks while + expanding their channel dimensions using convolutional layers, layer normalization, and activation functions. + + Attributes: + encoder (nn.Sequential): A sequential container of convolutional layers, layer normalization, and activation + functions for downsampling and embedding masks. + + Methods: + forward: Downsamples and encodes input mask to embed_dim channels. + + Examples: + >>> mask_downsampler = MaskDownSampler(embed_dim=256, kernel_size=4, stride=4, padding=0, total_stride=16) + >>> input_mask = torch.randn(1, 1, 256, 256) + >>> output = mask_downsampler(input_mask) + >>> print(output.shape) + torch.Size([1, 256, 16, 16]) + """ + + def __init__( + self, + embed_dim: int = 256, + kernel_size: int = 4, + stride: int = 4, + padding: int = 0, + total_stride: int = 16, + activation: type[nn.Module] = nn.GELU, + interpol_size: tuple[int, int] | None = None, + ): + """Initialize a mask downsampler module for progressive downsampling and channel expansion.""" + super().__init__() + num_layers = int(math.log2(total_stride) // math.log2(stride)) + assert stride**num_layers == total_stride + self.encoder = nn.Sequential() + mask_in_chans, mask_out_chans = 1, 1 + for _ in range(num_layers): + mask_out_chans = mask_in_chans * (stride**2) + self.encoder.append( + nn.Conv2d( + mask_in_chans, + mask_out_chans, + kernel_size=kernel_size, + stride=stride, + padding=padding, + ) + ) + self.encoder.append(LayerNorm2d(mask_out_chans)) + self.encoder.append(activation()) + mask_in_chans = mask_out_chans + + self.encoder.append(nn.Conv2d(mask_out_chans, embed_dim, kernel_size=1)) + self.interpol_size = interpol_size + if self.interpol_size is not None: + assert isinstance(self.interpol_size, (list, tuple)), ( + f"Unsupported type {type(self.interpol_size)}. Should be a list or tuple." + ) + self.interpol_size = list(interpol_size) + assert len(self.interpol_size) == 2 + + def forward(self, x: Tensor) -> Tensor: + """Downsample and encode input mask to embed_dim channels using convolutional layers and LayerNorm2d.""" + if self.interpol_size is not None and self.interpol_size != list(x.shape[-2:]): + x = F.interpolate( + x.float(), + size=self.interpol_size, + align_corners=False, + mode="bilinear", + antialias=True, + ).to(x.dtype) + return self.encoder(x) + + +class CXBlock(nn.Module): + """ConvNeXt Block for efficient feature extraction in convolutional neural networks. + + This block implements a modified version of the ConvNeXt architecture, offering improved performance and flexibility + in feature extraction. + + Attributes: + dwconv (nn.Conv2d): Depthwise or standard 2D convolution layer. + norm (LayerNorm2d): Layer normalization applied to channels. + pwconv1 (nn.Linear): First pointwise convolution implemented as a linear layer. + act (nn.GELU): GELU activation function. + pwconv2 (nn.Linear): Second pointwise convolution implemented as a linear layer. + gamma (nn.Parameter | None): Learnable scale parameter for layer scaling. + drop_path (nn.Module): DropPath layer for stochastic depth regularization. + + Methods: + forward: Processes the input tensor through the ConvNeXt block. + + Examples: + >>> import torch + >>> x = torch.randn(1, 64, 56, 56) + >>> block = CXBlock(dim=64, kernel_size=7, padding=3) + >>> output = block(x) + >>> print(output.shape) + torch.Size([1, 64, 56, 56]) + """ + + def __init__( + self, + dim: int, + kernel_size: int = 7, + padding: int = 3, + drop_path: float = 0.0, + layer_scale_init_value: float = 1e-6, + use_dwconv: bool = True, + ): + """Initialize a ConvNeXt Block for efficient feature extraction in convolutional neural networks. + + This block implements a modified version of the ConvNeXt architecture, offering improved performance and + flexibility in feature extraction. + + Args: + dim (int): Number of input channels. + kernel_size (int): Size of the convolutional kernel. + padding (int): Padding size for the convolution. + drop_path (float): Stochastic depth rate. + layer_scale_init_value (float): Initial value for Layer Scale. + use_dwconv (bool): Whether to use depthwise convolution. + """ + super().__init__() + self.dwconv = nn.Conv2d( + dim, + dim, + kernel_size=kernel_size, + padding=padding, + groups=dim if use_dwconv else 1, + ) # depthwise conv + self.norm = LayerNorm2d(dim, eps=1e-6) + self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers + self.act = nn.GELU() + self.pwconv2 = nn.Linear(4 * dim, dim) + self.gamma = ( + nn.Parameter(layer_scale_init_value * torch.ones(dim), requires_grad=True) + if layer_scale_init_value > 0 + else None + ) + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + def forward(self, x: Tensor) -> Tensor: + """Apply ConvNeXt block operations to input tensor, including convolutions and residual connection.""" + input = x + x = self.dwconv(x) + x = self.norm(x) + x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C) + x = self.pwconv1(x) + x = self.act(x) + x = self.pwconv2(x) + if self.gamma is not None: + x = self.gamma * x + x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W) + + x = input + self.drop_path(x) + return x + + +class Fuser(nn.Module): + """A module for fusing features through multiple layers of a neural network. + + This class applies a series of identical layers to an input tensor, optionally projecting the input first. + + Attributes: + proj (nn.Module): An optional input projection layer. Identity if no projection is needed. + layers (nn.ModuleList): A list of identical layers to be applied sequentially. + + Methods: + forward: Applies the fuser to an input tensor. + + Examples: + >>> layer = CXBlock(dim=256) + >>> fuser = Fuser(layer, num_layers=3, dim=256, input_projection=True) + >>> x = torch.randn(1, 256, 32, 32) + >>> output = fuser(x) + >>> print(output.shape) + torch.Size([1, 256, 32, 32]) + """ + + def __init__(self, layer: nn.Module, num_layers: int, dim: int | None = None, input_projection: bool = False): + """Initialize the Fuser module for feature fusion through multiple layers. + + This module creates a sequence of identical layers and optionally applies an input projection. + + Args: + layer (nn.Module): The layer to be replicated in the fuser. + num_layers (int): The number of times to replicate the layer. + dim (int | None): The dimension for input projection, if used. + input_projection (bool): Whether to use input projection. + """ + super().__init__() + self.proj = nn.Identity() + self.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(num_layers)]) + + if input_projection: + assert dim is not None + self.proj = nn.Conv2d(dim, dim, kernel_size=1) + + def forward(self, x: Tensor) -> Tensor: + """Apply a series of layers to the input tensor, optionally projecting it first.""" + x = self.proj(x) + for layer in self.layers: + x = layer(x) + return x + + +class SAM2TwoWayAttentionBlock(TwoWayAttentionBlock): + """A two-way attention block for performing self-attention and cross-attention in both directions. + + This block extends the TwoWayAttentionBlock and consists of four main components: self-attention on sparse inputs, + cross-attention from sparse to dense inputs, an MLP block on sparse inputs, and cross-attention from dense to sparse + inputs. + + Attributes: + self_attn (Attention): Self-attention layer for queries. + norm1 (nn.LayerNorm): Layer normalization after the first attention block. + cross_attn_token_to_image (Attention): Cross-attention layer from queries to keys. + norm2 (nn.LayerNorm): Layer normalization after the second attention block. + mlp (MLP): MLP block for transforming query embeddings. + norm3 (nn.LayerNorm): Layer normalization after the MLP block. + norm4 (nn.LayerNorm): Layer normalization after the third attention block. + cross_attn_image_to_token (Attention): Cross-attention layer from keys to queries. + skip_first_layer_pe (bool): Flag to skip positional encoding in the first layer. + + Methods: + forward: Processes input through the attention blocks and MLP. + + Examples: + >>> block = SAM2TwoWayAttentionBlock(embedding_dim=256, num_heads=8) + >>> sparse_input = torch.randn(1, 100, 256) + >>> dense_input = torch.randn(1, 256, 16, 16) + >>> sparse_output, dense_output = block(sparse_input, dense_input) + """ + + def __init__( + self, + embedding_dim: int, + num_heads: int, + mlp_dim: int = 2048, + activation: type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + skip_first_layer_pe: bool = False, + ) -> None: + """Initialize a SAM2TwoWayAttentionBlock for performing self-attention and cross-attention in two directions. + + This block extends the TwoWayAttentionBlock and consists of four main components: self-attention on sparse + inputs, cross-attention from sparse to dense inputs, an MLP block on sparse inputs, and cross-attention from + dense to sparse inputs. + + Args: + embedding_dim (int): The channel dimension of the embeddings. + num_heads (int): The number of heads in the attention layers. + mlp_dim (int): The hidden dimension of the MLP block. + activation (type[nn.Module]): The activation function of the MLP block. + attention_downsample_rate (int): The downsample rate for attention computations. + skip_first_layer_pe (bool): Whether to skip the positional encoding in the first layer. + """ + super().__init__(embedding_dim, num_heads, mlp_dim, activation, attention_downsample_rate, skip_first_layer_pe) + self.mlp = MLP(embedding_dim, mlp_dim, embedding_dim, num_layers=2, act=activation) + + +class SAM2TwoWayTransformer(TwoWayTransformer): + """A Two-Way Transformer module for simultaneous attention to image and query points. + + This class extends the TwoWayTransformer, implementing a specialized transformer decoder that attends to an input + image using queries with supplied positional embeddings. It is particularly useful for tasks like object detection, + image segmentation, and point cloud processing. + + Attributes: + depth (int): Number of layers in the transformer. + embedding_dim (int): Channel dimension for input embeddings. + num_heads (int): Number of heads for multihead attention. + mlp_dim (int): Internal channel dimension for the MLP block. + layers (nn.ModuleList): List of SAM2TwoWayAttentionBlock layers comprising the transformer. + final_attn_token_to_image (Attention): Final attention layer from queries to image. + norm_final_attn (nn.LayerNorm): Layer normalization applied to final queries. + + Methods: + forward: Processes input image embeddings and query embeddings through the transformer. + + Examples: + >>> transformer = SAM2TwoWayTransformer(depth=5, embedding_dim=256, num_heads=8, mlp_dim=2048) + >>> image_embedding = torch.randn(1, 256, 64, 64) + >>> query_embedding = torch.randn(1, 100, 256) + >>> output = transformer(image_embedding, query_embedding) + >>> print(output[0].shape, output[1].shape) + torch.Size([1, 100, 256]) torch.Size([1, 256, 64, 64]) + """ + + def __init__( + self, + depth: int, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + ) -> None: + """Initialize a SAM2TwoWayTransformer instance. + + This transformer decoder attends to an input image using queries with supplied positional embeddings. It is + designed for tasks like object detection, image segmentation, and point cloud processing. + + Args: + depth (int): Number of layers in the transformer. + embedding_dim (int): Channel dimension for the input embeddings. + num_heads (int): Number of heads for multihead attention. Must divide embedding_dim. + mlp_dim (int): Channel dimension internal to the MLP block. + activation (type[nn.Module]): Activation function to use in the MLP block. + attention_downsample_rate (int): Downsampling rate for attention computations. + """ + super().__init__(depth, embedding_dim, num_heads, mlp_dim, activation, attention_downsample_rate) + self.layers = nn.ModuleList() + for i in range(depth): + self.layers.append( + SAM2TwoWayAttentionBlock( + embedding_dim=embedding_dim, + num_heads=num_heads, + mlp_dim=mlp_dim, + activation=activation, + attention_downsample_rate=attention_downsample_rate, + skip_first_layer_pe=(i == 0), + ) + ) + + +class RoPEAttention(Attention): + """Implements rotary position encoding for attention mechanisms in transformer architectures. + + This class extends the base Attention class by incorporating Rotary Position Encoding (RoPE) to enhance the + positional awareness of the attention mechanism. + + Attributes: + compute_cis (Callable): Function to compute axial complex numbers for rotary encoding. + freqs_cis (torch.Tensor): Precomputed frequency tensor for rotary encoding. + rope_k_repeat (bool): Flag to repeat query RoPE to match key length for cross-attention to memories. + + Methods: + forward: Applies rotary position encoding and computes attention between query, key, and value tensors. + + Examples: + >>> rope_attn = RoPEAttention(embedding_dim=256, num_heads=8, rope_theta=10000.0, feat_sizes=(32, 32)) + >>> q = torch.randn(1, 1024, 256) + >>> k = torch.randn(1, 1024, 256) + >>> v = torch.randn(1, 1024, 256) + >>> output = rope_attn(q, k, v) + >>> print(output.shape) + torch.Size([1, 1024, 256]) + """ + + def __init__( + self, + *args, + rope_theta: float = 10000.0, + rope_k_repeat: bool = False, + feat_sizes: tuple[int, int] = (32, 32), # [w, h] for stride 16 feats at 512 resolution + **kwargs, + ): + """Initialize RoPEAttention with rotary position encoding for enhanced positional awareness.""" + super().__init__(*args, **kwargs) + + self.compute_cis = partial(compute_axial_cis, dim=self.internal_dim // self.num_heads, theta=rope_theta) + freqs_cis = self.compute_cis(end_x=feat_sizes[0], end_y=feat_sizes[1]) + self.freqs_cis = freqs_cis + self.rope_k_repeat = rope_k_repeat # repeat q rope to match k length, needed for cross-attention to memories + + def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, num_k_exclude_rope: int = 0) -> torch.Tensor: + """Apply rotary position encoding and compute attention between query, key, and value tensors.""" + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + # Apply rotary position encoding + w = h = math.sqrt(q.shape[-2]) + self.freqs_cis = self.freqs_cis.to(q.device) + if self.freqs_cis.shape[0] != q.shape[-2]: + self.freqs_cis = self.compute_cis(end_x=w, end_y=h).to(q.device) + if q.shape[-2] != k.shape[-2]: + assert self.rope_k_repeat + + num_k_rope = k.size(-2) - num_k_exclude_rope + q, k[:, :, :num_k_rope] = apply_rotary_enc( + q, + k[:, :, :num_k_rope], + freqs_cis=self.freqs_cis, + repeat_freqs_k=self.rope_k_repeat, + ) + + # Attention + out = F.scaled_dot_product_attention(q, k, v) + + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out + + +def do_pool(x: torch.Tensor, pool: nn.Module, norm: nn.Module = None) -> torch.Tensor: + """Apply pooling and optional normalization to a tensor, handling spatial dimension permutations.""" + if pool is None: + return x + # (B, H, W, C) -> (B, C, H, W) + x = x.permute(0, 3, 1, 2) + x = pool(x) + # (B, C, H', W') -> (B, H', W', C) + x = x.permute(0, 2, 3, 1) + if norm: + x = norm(x) + + return x + + +class MultiScaleAttention(nn.Module): + """Implements multiscale self-attention with optional query pooling for efficient feature extraction. + + This class provides a flexible implementation of multiscale attention, allowing for optional downsampling of query + features through pooling. It's designed to enhance the model's ability to capture multiscale information in visual + tasks. + + Attributes: + dim (int): Input dimension of the feature map. + dim_out (int): Output dimension of the attention module. + num_heads (int): Number of attention heads. + scale (float): Scaling factor for dot-product attention. + q_pool (nn.Module | None): Optional pooling module for query features. + qkv (nn.Linear): Linear projection for query, key, and value. + proj (nn.Linear): Output projection. + + Methods: + forward: Applies multiscale attention to the input tensor. + + Examples: + >>> import torch + >>> from torch import nn + >>> x = torch.randn(1, 64, 64, 256) + >>> msa = MultiScaleAttention(dim=256, dim_out=256, num_heads=8) + >>> output = msa(x) + >>> print(output.shape) + torch.Size([1, 64, 64, 256]) + """ + + def __init__( + self, + dim: int, + dim_out: int, + num_heads: int, + q_pool: nn.Module = None, + ): + """Initialize multiscale attention with optional query pooling for efficient feature extraction.""" + super().__init__() + + self.dim = dim + self.dim_out = dim_out + + self.num_heads = num_heads + head_dim = dim_out // num_heads + self.scale = head_dim**-0.5 + + self.q_pool = q_pool + self.qkv = nn.Linear(dim, dim_out * 3) + self.proj = nn.Linear(dim_out, dim_out) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply multiscale attention with optional query pooling to extract multiscale features.""" + B, H, W, _ = x.shape + # qkv with shape (B, H * W, 3, nHead, C) + qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1) + # q, k, v with shape (B, H * W, nheads, C) + q, k, v = torch.unbind(qkv, 2) + + # Q pooling (for downsample at stage changes) + if self.q_pool: + q = do_pool(q.reshape(B, H, W, -1), self.q_pool) + H, W = q.shape[1:3] # downsampled shape + q = q.reshape(B, H * W, self.num_heads, -1) + + # Torch's SDPA expects [B, nheads, H*W, C] so we transpose + x = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + ) + # Transpose back + x = x.transpose(1, 2) + x = x.reshape(B, H, W, -1) + + x = self.proj(x) + + return x + + +class MultiScaleBlock(nn.Module): + """A multiscale attention block with window partitioning and query pooling for efficient vision transformers. + + This class implements a multiscale attention mechanism with optional window partitioning and downsampling, designed + for use in vision transformer architectures. + + Attributes: + dim (int): Input dimension of the block. + dim_out (int): Output dimension of the block. + norm1 (nn.Module): First normalization layer. + window_size (int): Size of the window for partitioning. + pool (nn.Module | None): Pooling layer for query downsampling. + q_stride (tuple[int, int] | None): Stride for query pooling. + attn (MultiScaleAttention): Multi-scale attention module. + drop_path (nn.Module): Drop path layer for regularization. + norm2 (nn.Module): Second normalization layer. + mlp (MLP): Multi-layer perceptron module. + proj (nn.Linear | None): Projection layer for dimension mismatch. + + Methods: + forward: Processes input tensor through the multiscale block. + + Examples: + >>> block = MultiScaleBlock(dim=256, dim_out=512, num_heads=8, window_size=7) + >>> x = torch.randn(1, 56, 56, 256) + >>> output = block(x) + >>> print(output.shape) + torch.Size([1, 56, 56, 512]) + """ + + def __init__( + self, + dim: int, + dim_out: int, + num_heads: int, + mlp_ratio: float = 4.0, + drop_path: float = 0.0, + norm_layer: nn.Module | str = "LayerNorm", + q_stride: tuple[int, int] | None = None, + act_layer: type[nn.Module] = nn.GELU, + window_size: int = 0, + ): + """Initialize a multiscale attention block with window partitioning and optional query pooling.""" + super().__init__() + + if isinstance(norm_layer, str): + norm_layer = partial(getattr(nn, norm_layer), eps=1e-6) + + self.dim = dim + self.dim_out = dim_out + self.norm1 = norm_layer(dim) + + self.window_size = window_size + + self.pool, self.q_stride = None, q_stride + if self.q_stride: + self.pool = nn.MaxPool2d(kernel_size=q_stride, stride=q_stride, ceil_mode=False) + + self.attn = MultiScaleAttention( + dim, + dim_out, + num_heads=num_heads, + q_pool=self.pool, + ) + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.norm2 = norm_layer(dim_out) + self.mlp = MLP( + dim_out, + int(dim_out * mlp_ratio), + dim_out, + num_layers=2, + act=act_layer, + ) + + if dim != dim_out: + self.proj = nn.Linear(dim, dim_out) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Process input through multiscale attention and MLP, with optional windowing and downsampling.""" + shortcut = x # B, H, W, C + x = self.norm1(x) + + # Skip connection + if self.dim != self.dim_out: + shortcut = do_pool(self.proj(x), self.pool) + + # Window partition + window_size = self.window_size + if window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, window_size) + + # Window Attention + Q Pooling (if stage change) + x = self.attn(x) + if self.q_stride: + # Shapes have changed due to Q pooling + window_size = self.window_size // self.q_stride[0] + H, W = shortcut.shape[1:3] + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + pad_hw = (H + pad_h, W + pad_w) + + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, window_size, pad_hw, (H, W)) + + x = shortcut + self.drop_path(x) + # MLP + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x + + +class PositionEmbeddingSine(nn.Module): + """A module for generating sinusoidal positional embeddings for 2D inputs like images. + + This class implements sinusoidal position encoding for 2D spatial positions, which can be used in transformer-based + models for computer vision tasks. + + Attributes: + num_pos_feats (int): Number of positional features (half of the embedding dimension). + temperature (int): Temperature parameter for the sinusoidal functions. + normalize (bool): Whether to normalize the positional embeddings. + scale (float): Scaling factor for the embeddings when normalize is True. + cache (dict): Cache for storing precomputed embeddings. + + Methods: + _encode_xy: Encodes 2D positions using sine and cosine functions. + encode_boxes: Encodes box coordinates and dimensions into positional embeddings. + encode_points: Encodes 2D point coordinates with sinusoidal positional embeddings. + forward: Generates sinusoidal position embeddings for 2D inputs. + + Examples: + >>> pos_emb = PositionEmbeddingSine(num_pos_feats=128) + >>> x = torch.randn(1, 3, 224, 224) + >>> embeddings = pos_emb(x) + >>> print(embeddings.shape) + torch.Size([1, 128, 224, 224]) + """ + + def __init__( + self, + num_pos_feats: int, + temperature: int = 10000, + normalize: bool = True, + scale: float | None = None, + ): + """Initialize sinusoidal position embeddings for 2D image inputs.""" + super().__init__() + assert num_pos_feats % 2 == 0, "Expecting even model width" + self.num_pos_feats = num_pos_feats // 2 + self.temperature = temperature + self.normalize = normalize + if scale is not None and not normalize: + raise ValueError("normalize should be True if scale is passed") + if scale is None: + scale = 2 * math.pi + self.scale = scale + + self.cache = {} + + def _encode_xy(self, x: torch.Tensor, y: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Encode 2D positions using sine/cosine functions for transformer positional embeddings.""" + assert len(x) == len(y) and x.ndim == y.ndim == 1 + x_embed = x * self.scale + y_embed = y * self.scale + + dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) + + pos_x = x_embed[:, None] / dim_t + pos_y = y_embed[:, None] / dim_t + pos_x = torch.stack((pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2).flatten(1) + pos_y = torch.stack((pos_y[:, 0::2].sin(), pos_y[:, 1::2].cos()), dim=2).flatten(1) + return pos_x, pos_y + + @torch.no_grad() + def encode_boxes(self, x: torch.Tensor, y: torch.Tensor, w: torch.Tensor, h: torch.Tensor) -> torch.Tensor: + """Encode box coordinates and dimensions into positional embeddings for detection.""" + pos_x, pos_y = self._encode_xy(x, y) + return torch.cat((pos_y, pos_x, h[:, None], w[:, None]), dim=1) + + encode = encode_boxes # Backwards compatibility + + @torch.no_grad() + def encode_points(self, x: torch.Tensor, y: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: + """Encode 2D points with sinusoidal embeddings and append labels.""" + (bx, nx), (by, ny), (bl, nl) = x.shape, y.shape, labels.shape + assert bx == by and nx == ny and bx == bl and nx == nl + pos_x, pos_y = self._encode_xy(x.flatten(), y.flatten()) + pos_x, pos_y = pos_x.reshape(bx, nx, -1), pos_y.reshape(by, ny, -1) + return torch.cat((pos_y, pos_x, labels[:, :, None]), dim=2) + + @torch.no_grad() + def forward(self, x: torch.Tensor) -> Tensor: + """Generate sinusoidal position embeddings for 2D inputs like images.""" + cache_key = (x.shape[-2], x.shape[-1]) + if cache_key in self.cache: + return self.cache[cache_key][None].repeat(x.shape[0], 1, 1, 1) + y_embed = ( + torch.arange(1, x.shape[-2] + 1, dtype=torch.float32, device=x.device) + .view(1, -1, 1) + .repeat(x.shape[0], 1, x.shape[-1]) + ) + x_embed = ( + torch.arange(1, x.shape[-1] + 1, dtype=torch.float32, device=x.device) + .view(1, 1, -1) + .repeat(x.shape[0], x.shape[-2], 1) + ) + + if self.normalize: + eps = 1e-6 + y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale + x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale + + dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) + + pos_x = x_embed[:, :, :, None] / dim_t + pos_y = y_embed[:, :, :, None] / dim_t + pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3) + pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3) + pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) + self.cache[cache_key] = pos[0] + return pos + + +class PositionEmbeddingRandom(nn.Module): + """Positional encoding using random spatial frequencies. + + This class generates positional embeddings for input coordinates using random spatial frequencies. It is + particularly useful for transformer-based models that require position information. + + Attributes: + positional_encoding_gaussian_matrix (torch.Tensor): A buffer containing random values for encoding. + + Methods: + _pe_encoding: Positionally encodes points that are normalized to [0,1]. + forward: Generates positional encoding for a grid of the specified size. + forward_with_coords: Positionally encodes points that are not normalized to [0,1]. + + Examples: + >>> pe = PositionEmbeddingRandom(num_pos_feats=64) + >>> size = (32, 32) + >>> encoding = pe(size) + >>> print(encoding.shape) + torch.Size([128, 32, 32]) + """ + + def __init__(self, num_pos_feats: int = 64, scale: float | None = None) -> None: + """Initialize random spatial frequency position embedding for transformers.""" + super().__init__() + if scale is None or scale <= 0.0: + scale = 1.0 + self.register_buffer("positional_encoding_gaussian_matrix", scale * torch.randn((2, num_pos_feats))) + + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: + """Encode normalized [0,1] coordinates using random spatial frequencies.""" + # Assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * np.pi * coords + # Outputs d_1 x ... x d_n x C shape + return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) + + def forward(self, size: tuple[int, int]) -> torch.Tensor: + """Generate positional encoding for a grid using random spatial frequencies.""" + h, w = size + m = self.positional_encoding_gaussian_matrix + y_embed = (torch.arange(h, device=m.device, dtype=m.dtype) + 0.5) / h # pixel centers + x_embed = (torch.arange(w, device=m.device, dtype=m.dtype) + 0.5) / w + pe = self._pe_encoding(torch.stack([x_embed[None].expand(h, w), y_embed[:, None].expand(h, w)], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords(self, coords_input: torch.Tensor, image_size: tuple[int, int]) -> torch.Tensor: + """Positionally encode input coordinates, normalizing them to [0,1] based on the given image size.""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + return self._pe_encoding(coords) # B x N x C + + +class Block(nn.Module): + """Transformer block with support for window attention and residual propagation. + + This class implements a transformer block that can use either global or windowed self-attention, followed by a + feed-forward network. It supports relative positional embeddings and is designed for use in vision transformer + architectures. + + Attributes: + norm1 (nn.Module): First normalization layer. + attn (REAttention): Self-attention layer with optional relative positional encoding. + norm2 (nn.Module): Second normalization layer. + mlp (MLPBlock): Multi-layer perceptron block. + window_size (int): Size of attention window. If 0, global attention is used. + + Methods: + forward: Processes input through the transformer block. + + Examples: + >>> import torch + >>> block = Block(dim=256, num_heads=8, window_size=7) + >>> x = torch.randn(1, 56, 56, 256) + >>> output = block(x) + >>> print(output.shape) + torch.Size([1, 56, 56, 256]) + """ + + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + norm_layer: type[nn.Module] = nn.LayerNorm, + act_layer: type[nn.Module] = nn.GELU, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + input_size: tuple[int, int] | None = None, + ) -> None: + """Initialize a transformer block with optional window attention and relative positional embeddings. + + This constructor sets up a transformer block that can use either global or windowed self-attention, followed by + a feed-forward network. It supports relative positional embeddings and is designed for use in vision transformer + architectures. + + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads in the self-attention layer. + mlp_ratio (float): Ratio of mlp hidden dimension to embedding dimension. + qkv_bias (bool): If True, adds a learnable bias to query, key, value projections. + norm_layer (type[nn.Module]): Type of normalization layer to use. + act_layer (type[nn.Module]): Type of activation function to use in the MLP block. + use_rel_pos (bool): If True, uses relative positional embeddings in attention. + rel_pos_zero_init (bool): If True, initializes relative positional parameters to zero. + window_size (int): Size of attention window. If 0, uses global attention. + input_size (tuple[int, int] | None): Input resolution for calculating relative positional parameter size. + """ + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = REAttention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + input_size=input_size if window_size == 0 else (window_size, window_size), + ) + + self.norm2 = norm_layer(dim) + self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer) + + self.window_size = window_size + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Process input through transformer block with optional windowed self-attention and residual connection.""" + shortcut = x + x = self.norm1(x) + # Window partition + if self.window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, self.window_size) + + x = self.attn(x) + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, self.window_size, pad_hw, (H, W)) + + x = shortcut + x + return x + self.mlp(self.norm2(x)) + + +class REAttention(nn.Module): + """Relative Position Attention module for efficient self-attention in transformer architectures. + + This class implements a multi-head attention mechanism with relative positional embeddings, designed for use in + vision transformer models. + + Attributes: + num_heads (int): Number of attention heads. + scale (float): Scaling factor for attention computation. + qkv (nn.Linear): Linear projection for query, key, and value. + proj (nn.Linear): Output projection layer. + use_rel_pos (bool): Whether to use relative positional embeddings. + rel_pos_h (nn.Parameter): Relative positional embeddings for height dimension. + rel_pos_w (nn.Parameter): Relative positional embeddings for width dimension. + + Methods: + forward: Applies multi-head attention with optional relative positional encoding to input tensor. + + Examples: + >>> attention = REAttention(dim=256, num_heads=8, input_size=(32, 32)) + >>> x = torch.randn(1, 32, 32, 256) + >>> output = attention(x) + >>> print(output.shape) + torch.Size([1, 32, 32, 256]) + """ + + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + input_size: tuple[int, int] | None = None, + ) -> None: + """Initialize a Relative Position Attention module for transformer-based architectures. + + This module implements multi-head attention with optional relative positional encodings, designed specifically + for vision tasks in transformer models. + + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + qkv_bias (bool): If True, adds a learnable bias to query, key, value projections. + use_rel_pos (bool): If True, uses relative positional encodings. + rel_pos_zero_init (bool): If True, initializes relative positional parameters to zero. + input_size (tuple[int, int] | None): Input resolution for calculating relative positional parameter size. + Required if use_rel_pos is True. + """ + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim) + + self.use_rel_pos = use_rel_pos + if self.use_rel_pos: + assert input_size is not None, "Input size must be provided if using relative positional encoding." + # Initialize relative positional embeddings + self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim)) + self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply multi-head attention with optional relative positional encoding to input tensor.""" + B, H, W, _ = x.shape + # qkv with shape (3, B, nHead, H * W, C) + qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) + # q, k, v with shape (B * nHead, H * W, C) + q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) + + attn = (q * self.scale) @ k.transpose(-2, -1) + + if self.use_rel_pos: + attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)) + + attn = attn.softmax(dim=-1) + x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1) + return self.proj(x) + + +class PatchEmbed(nn.Module): + """Image to Patch Embedding module for vision transformer architectures. + + This module converts an input image into a sequence of patch embeddings using a convolutional layer. It is commonly + used as the first layer in vision transformer architectures to transform image data into a suitable format for + subsequent transformer blocks. + + Attributes: + proj (nn.Conv2d): Convolutional layer for projecting image patches to embeddings. + + Methods: + forward: Applies patch embedding to the input tensor. + + Examples: + >>> patch_embed = PatchEmbed(kernel_size=(16, 16), stride=(16, 16), in_chans=3, embed_dim=768) + >>> x = torch.randn(1, 3, 224, 224) + >>> output = patch_embed(x) + >>> print(output.shape) + torch.Size([1, 14, 14, 768]) + """ + + def __init__( + self, + kernel_size: tuple[int, int] = (16, 16), + stride: tuple[int, int] = (16, 16), + padding: tuple[int, int] = (0, 0), + in_chans: int = 3, + embed_dim: int = 768, + bias: bool = True, + ) -> None: + """Initialize the PatchEmbed module for converting image patches to embeddings. + + This module is typically used as the first layer in vision transformer architectures to transform image data + into a suitable format for subsequent transformer blocks. + + Args: + kernel_size (tuple[int, int]): Size of the convolutional kernel for patch extraction. + stride (tuple[int, int]): Stride of the convolutional operation. + padding (tuple[int, int]): Padding applied to the input before convolution. + in_chans (int): Number of input image channels. + embed_dim (int): Dimensionality of the output patch embeddings. + bias (bool): Whether to include a bias term in the convolutional layer. + """ + super().__init__() + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Compute patch embedding by applying convolution and transposing resulting tensor.""" + return self.proj(x).permute(0, 2, 3, 1) # B C H W -> B H W C diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/decoders.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/decoders.py new file mode 100644 index 0000000000000000000000000000000000000000..d9a12d763cca17a843d2a6edd61e1f6e556947a2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/decoders.py @@ -0,0 +1,495 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import torch +from torch import nn + +from ultralytics.nn.modules import MLP, LayerNorm2d + + +class MaskDecoder(nn.Module): + """Decoder module for generating masks and their associated quality scores using a transformer architecture. + + This class predicts masks given image and prompt embeddings, utilizing a transformer to process the inputs and + generate mask predictions along with their quality scores. + + Attributes: + transformer_dim (int): Channel dimension for the transformer module. + transformer (nn.Module): Transformer module used for mask prediction. + num_multimask_outputs (int): Number of masks to predict for disambiguating masks. + iou_token (nn.Embedding): Embedding for the IoU token. + num_mask_tokens (int): Number of mask tokens. + mask_tokens (nn.Embedding): Embedding for the mask tokens. + output_upscaling (nn.Sequential): Neural network sequence for upscaling the output. + output_hypernetworks_mlps (nn.ModuleList): Hypernetwork MLPs for generating masks. + iou_prediction_head (nn.Module): MLP for predicting mask quality. + + Methods: + forward: Predict masks given image and prompt embeddings. + predict_masks: Internal method for mask prediction. + + Examples: + >>> decoder = MaskDecoder(transformer_dim=256, transformer=transformer_module) + >>> masks, iou_pred = decoder( + ... image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, multimask_output=True + ... ) + >>> print(f"Predicted masks shape: {masks.shape}, IoU predictions shape: {iou_pred.shape}") + """ + + def __init__( + self, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + ) -> None: + """Initialize the MaskDecoder module for generating masks and their associated quality scores. + + Args: + transformer_dim (int): Channel dimension for the transformer module. + transformer (nn.Module): Transformer module used for mask prediction. + num_multimask_outputs (int): Number of masks to predict for disambiguating masks. + activation (type[nn.Module]): Type of activation to use when upscaling masks. + iou_head_depth (int): Depth of the MLP used to predict mask quality. + iou_head_hidden_dim (int): Hidden dimension of the MLP used to predict mask quality. + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2), + activation(), + ) + self.output_hypernetworks_mlps = nn.ModuleList( + [MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) for _ in range(self.num_mask_tokens)] + ) + + self.iou_prediction_head = MLP(transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth) + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Predict masks given image and prompt embeddings. + + Args: + image_embeddings (torch.Tensor): Embeddings from the image encoder. + image_pe (torch.Tensor): Positional encoding with the shape of image_embeddings. + sparse_prompt_embeddings (torch.Tensor): Embeddings of the points and boxes. + dense_prompt_embeddings (torch.Tensor): Embeddings of the mask inputs. + multimask_output (bool): Whether to return multiple masks or a single mask. + + Returns: + masks (torch.Tensor): Batched predicted masks. + iou_pred (torch.Tensor): Batched predictions of mask quality. + + Examples: + >>> decoder = MaskDecoder(transformer_dim=256, transformer=transformer_module) + >>> image_emb = torch.rand(1, 256, 64, 64) + >>> image_pe = torch.rand(1, 256, 64, 64) + >>> sparse_emb = torch.rand(1, 2, 256) + >>> dense_emb = torch.rand(1, 256, 64, 64) + >>> masks, iou_pred = decoder(image_emb, image_pe, sparse_emb, dense_emb, multimask_output=True) + >>> print(f"Masks shape: {masks.shape}, IoU predictions shape: {iou_pred.shape}") + """ + masks, iou_pred = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + ) + + # Select the correct mask or masks for output + mask_slice = slice(1, None) if multimask_output else slice(0, 1) + masks = masks[:, mask_slice, :, :] + iou_pred = iou_pred[:, mask_slice] + + return masks, iou_pred + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Predict masks and quality scores using image and prompt embeddings via transformer architecture.""" + # Concatenate output tokens + output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0) + output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.shape[0], -1, -1) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + # Expand per-image data in batch direction to be per-mask + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + src = src + dense_prompt_embeddings + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, 0, :] + mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + upscaled_embedding = self.output_upscaling(src) + hyper_in_list: list[torch.Tensor] = [ + self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]) for i in range(self.num_mask_tokens) + ] + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding.shape + masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w) + + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + + return masks, iou_pred + + +class SAM2MaskDecoder(nn.Module): + """Transformer-based decoder for predicting instance segmentation masks from image and prompt embeddings. + + This class extends the functionality of the MaskDecoder, incorporating additional features such as high-resolution + feature processing, dynamic multimask output, and object score prediction. + + Attributes: + transformer_dim (int): Channel dimension of the transformer. + transformer (nn.Module): Transformer used to predict masks. + num_multimask_outputs (int): Number of masks to predict when disambiguating masks. + iou_token (nn.Embedding): Embedding for IOU token. + num_mask_tokens (int): Total number of mask tokens. + mask_tokens (nn.Embedding): Embedding for mask tokens. + pred_obj_scores (bool): Whether to predict object scores. + obj_score_token (nn.Embedding): Embedding for object score token. + use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer. + output_upscaling (nn.Sequential): Upscaling layers for output. + use_high_res_features (bool): Whether to use high-resolution features. + conv_s0 (nn.Conv2d): Convolutional layer for high-resolution features (s0). + conv_s1 (nn.Conv2d): Convolutional layer for high-resolution features (s1). + output_hypernetworks_mlps (nn.ModuleList): List of MLPs for output hypernetworks. + iou_prediction_head (MLP): MLP for IOU prediction. + pred_obj_score_head (nn.Linear | MLP): Linear layer or MLP for object score prediction. + dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability. + dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability. + dynamic_multimask_stability_thresh (float): Threshold for dynamic multimask stability. + + Methods: + forward: Predict masks given image and prompt embeddings. + predict_masks: Predict instance segmentation masks from image and prompt embeddings. + _get_stability_scores: Compute mask stability scores based on IoU between thresholds. + _dynamic_multimask_via_stability: Dynamically select the most stable mask output. + + Examples: + >>> image_embeddings = torch.rand(1, 256, 64, 64) + >>> image_pe = torch.rand(1, 256, 64, 64) + >>> sparse_prompt_embeddings = torch.rand(1, 2, 256) + >>> dense_prompt_embeddings = torch.rand(1, 256, 64, 64) + >>> decoder = SAM2MaskDecoder(256, transformer) + >>> masks, iou_pred, sam_tokens_out, obj_score_logits = decoder.forward( + ... image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, True, False + ... ) + """ + + def __init__( + self, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + use_high_res_features: bool = False, + iou_prediction_use_sigmoid=False, + dynamic_multimask_via_stability=False, + dynamic_multimask_stability_delta=0.05, + dynamic_multimask_stability_thresh=0.98, + pred_obj_scores: bool = False, + pred_obj_scores_mlp: bool = False, + use_multimask_token_for_obj_ptr: bool = False, + ) -> None: + """Initialize the SAM2MaskDecoder module for predicting instance segmentation masks. + + This decoder extends the functionality of MaskDecoder, incorporating additional features such as high-resolution + feature processing, dynamic multimask output, and object score prediction. + + Args: + transformer_dim (int): Channel dimension of the transformer. + transformer (nn.Module): Transformer used to predict masks. + num_multimask_outputs (int): Number of masks to predict when disambiguating masks. + activation (type[nn.Module]): Type of activation to use when upscaling masks. + iou_head_depth (int): Depth of the MLP used to predict mask quality. + iou_head_hidden_dim (int): Hidden dimension of the MLP used to predict mask quality. + use_high_res_features (bool): Whether to use high-resolution features. + iou_prediction_use_sigmoid (bool): Whether to use sigmoid for IOU prediction. + dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability. + dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability. + dynamic_multimask_stability_thresh (float): Threshold for dynamic multimask stability. + pred_obj_scores (bool): Whether to predict object scores. + pred_obj_scores_mlp (bool): Whether to use MLP for object score prediction. + use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer. + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.pred_obj_scores = pred_obj_scores + if self.pred_obj_scores: + self.obj_score_token = nn.Embedding(1, transformer_dim) + self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2), + activation(), + ) + self.use_high_res_features = use_high_res_features + if use_high_res_features: + self.conv_s0 = nn.Conv2d(transformer_dim, transformer_dim // 8, kernel_size=1, stride=1) + self.conv_s1 = nn.Conv2d(transformer_dim, transformer_dim // 4, kernel_size=1, stride=1) + + self.output_hypernetworks_mlps = nn.ModuleList( + [MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) for _ in range(self.num_mask_tokens)] + ) + + self.iou_prediction_head = MLP( + transformer_dim, + iou_head_hidden_dim, + self.num_mask_tokens, + iou_head_depth, + sigmoid=iou_prediction_use_sigmoid, + ) + if self.pred_obj_scores: + self.pred_obj_score_head = nn.Linear(transformer_dim, 1) + if pred_obj_scores_mlp: + self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3) + + # When outputting a single mask, optionally we can dynamically fall back to the best + # multimask output token if the single mask output token gives low stability scores. + self.dynamic_multimask_via_stability = dynamic_multimask_via_stability + self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta + self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + repeat_image: bool, + high_res_features: list[torch.Tensor] | None = None, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Predict masks given image and prompt embeddings. + + Args: + image_embeddings (torch.Tensor): Embeddings from the image encoder with shape (B, C, H, W). + image_pe (torch.Tensor): Positional encoding with the shape of image_embeddings (B, C, H, W). + sparse_prompt_embeddings (torch.Tensor): Embeddings of the points and boxes with shape (B, N, C). + dense_prompt_embeddings (torch.Tensor): Embeddings of the mask inputs with shape (B, C, H, W). + multimask_output (bool): Whether to return multiple masks or a single mask. + repeat_image (bool): Flag to repeat the image embeddings. + high_res_features (list[torch.Tensor] | None, optional): Optional high-resolution features. + + Returns: + masks (torch.Tensor): Batched predicted masks with shape (B, N, H, W). + iou_pred (torch.Tensor): Batched predictions of mask quality with shape (B, N). + sam_tokens_out (torch.Tensor): Batched SAM token for mask output with shape (B, N, C). + object_score_logits (torch.Tensor): Batched object score logits with shape (B, 1). + + Examples: + >>> image_embeddings = torch.rand(1, 256, 64, 64) + >>> image_pe = torch.rand(1, 256, 64, 64) + >>> sparse_prompt_embeddings = torch.rand(1, 2, 256) + >>> dense_prompt_embeddings = torch.rand(1, 256, 64, 64) + >>> decoder = SAM2MaskDecoder(256, transformer) + >>> masks, iou_pred, sam_tokens_out, obj_score_logits = decoder.forward( + ... image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, True, False + ... ) + """ + masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + repeat_image=repeat_image, + high_res_features=high_res_features, + ) + + # Select the correct mask or masks for output + if multimask_output: + masks = masks[:, 1:, :, :] + iou_pred = iou_pred[:, 1:] + elif self.dynamic_multimask_via_stability and not self.training: + masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred) + else: + masks = masks[:, 0:1, :, :] + iou_pred = iou_pred[:, 0:1] + + if multimask_output and self.use_multimask_token_for_obj_ptr: + sam_tokens_out = mask_tokens_out[:, 1:] # [b, 3, c] shape + else: + # Take the mask output token. Here we *always* use the token for single mask output. + # At test time, even if we track after 1-click (and using multimask_output=True), + # we still take the single mask token here. The rationale is that we always track + # after multiple clicks during training, so the past tokens seen during training + # are always the single mask token (and we'll let it be the object-memory token). + sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape + + return masks, iou_pred, sam_tokens_out, object_score_logits + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + repeat_image: bool, + high_res_features: list[torch.Tensor] | None = None, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Predict instance segmentation masks from image and prompt embeddings using a transformer.""" + # Concatenate output tokens + s = 0 + if self.pred_obj_scores: + output_tokens = torch.cat( + [ + self.obj_score_token.weight, + self.iou_token.weight, + self.mask_tokens.weight, + ], + dim=0, + ) + s = 1 + else: + output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0) + output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.shape[0], -1, -1) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + # Expand per-image data in batch direction to be per-mask + if repeat_image: + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + else: + assert image_embeddings.shape[0] == tokens.shape[0] + src = image_embeddings + src = src + dense_prompt_embeddings + assert image_pe.shape[0] == 1, "image_pe should have size 1 in batch dim (from `get_dense_pe()`)" + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, s, :] + mask_tokens_out = hs[:, s + 1 : (s + 1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + if not self.use_high_res_features or high_res_features is None: + upscaled_embedding = self.output_upscaling(src) + else: + dc1, ln1, act1, dc2, act2 = self.output_upscaling + feat_s0, feat_s1 = high_res_features + upscaled_embedding = act1(ln1(dc1(src) + feat_s1)) + upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0) + + hyper_in_list: list[torch.Tensor] = [ + self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]) for i in range(self.num_mask_tokens) + ] + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding.shape + masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w) + + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + if self.pred_obj_scores: + assert s == 1 + object_score_logits = self.pred_obj_score_head(hs[:, 0, :]) + else: + # Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1 + object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1) + + return masks, iou_pred, mask_tokens_out, object_score_logits + + def _get_stability_scores(self, mask_logits): + """Compute mask stability scores based on IoU between upper and lower thresholds.""" + mask_logits = mask_logits.flatten(-2) + area_i = torch.sum(mask_logits > self.dynamic_multimask_stability_delta, dim=-1).float() + area_u = torch.sum(mask_logits > -self.dynamic_multimask_stability_delta, dim=-1).float() + return torch.where(area_u > 0, area_i / area_u, 1.0) + + def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores): + """Dynamically select the most stable mask output based on stability scores and IoU predictions. + + This method is used when outputting a single mask. If the stability score from the current single-mask output + (based on output token 0) falls below a threshold, it instead selects from multi-mask outputs (based on output + tokens 1-3) the mask with the highest predicted IoU score. This ensures a valid mask for both clicking and + tracking scenarios. + + Args: + all_mask_logits (torch.Tensor): Logits for all predicted masks, shape (B, N, H, W) where B is batch size, N + is number of masks (typically 4), and H, W are mask dimensions. + all_iou_scores (torch.Tensor): Predicted IoU scores for all masks, shape (B, N). + + Returns: + mask_logits_out (torch.Tensor): Selected mask logits, shape (B, 1, H, W). + iou_scores_out (torch.Tensor): Selected IoU scores, shape (B, 1). + + Examples: + >>> decoder = SAM2MaskDecoder(...) + >>> all_mask_logits = torch.rand(2, 4, 256, 256) # 2 images, 4 masks each + >>> all_iou_scores = torch.rand(2, 4) + >>> mask_logits, iou_scores = decoder._dynamic_multimask_via_stability(all_mask_logits, all_iou_scores) + >>> print(mask_logits.shape, iou_scores.shape) + torch.Size([2, 1, 256, 256]) torch.Size([2, 1]) + """ + # The best mask from multimask output tokens (1~3) + multimask_logits = all_mask_logits[:, 1:, :, :] + multimask_iou_scores = all_iou_scores[:, 1:] + best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1) + batch_inds = torch.arange(multimask_iou_scores.shape[0], device=all_iou_scores.device) + best_multimask_logits = multimask_logits[batch_inds, best_scores_inds] + best_multimask_logits = best_multimask_logits.unsqueeze(1) + best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds] + best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1) + + # The mask from singlemask output token 0 and its stability score + singlemask_logits = all_mask_logits[:, 0:1, :, :] + singlemask_iou_scores = all_iou_scores[:, 0:1] + stability_scores = self._get_stability_scores(singlemask_logits) + is_stable = stability_scores >= self.dynamic_multimask_stability_thresh + + # Dynamically fall back to best multimask output upon low stability scores. + mask_logits_out = torch.where( + is_stable[..., None, None].expand_as(singlemask_logits), + singlemask_logits, + best_multimask_logits, + ) + iou_scores_out = torch.where( + is_stable.expand_as(singlemask_iou_scores), + singlemask_iou_scores, + best_multimask_iou_scores, + ) + return mask_logits_out, iou_scores_out diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/encoders.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/encoders.py new file mode 100644 index 0000000000000000000000000000000000000000..ff692f0cd0f6eddd4b3617352fdd70350530f247 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/encoders.py @@ -0,0 +1,794 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + +from ultralytics.nn.modules import LayerNorm2d + +from .blocks import ( + Block, + CXBlock, + Fuser, + MaskDownSampler, + MultiScaleBlock, + PatchEmbed, + PositionEmbeddingRandom, + PositionEmbeddingSine, +) + + +class ImageEncoderViT(nn.Module): + """An image encoder using Vision Transformer (ViT) architecture for encoding images into a compact latent space. + + This class processes images by splitting them into patches, applying transformer blocks, and generating a final + encoded representation through a neck module. + + Attributes: + img_size (int): Dimension of input images, assumed to be square. + patch_embed (PatchEmbed): Module for patch embedding. + pos_embed (nn.Parameter | None): Absolute positional embedding for patches. + blocks (nn.ModuleList): List of transformer blocks for processing patch embeddings. + neck (nn.Sequential): Neck module to further process the output. + + Methods: + forward: Process input through patch embedding, positional embedding, blocks, and neck. + + Examples: + >>> import torch + >>> encoder = ImageEncoderViT(img_size=224, patch_size=16, embed_dim=768, depth=12, num_heads=12) + >>> input_image = torch.randn(1, 3, 224, 224) + >>> output = encoder(input_image) + >>> print(output.shape) + """ + + def __init__( + self, + img_size: int = 1024, + patch_size: int = 16, + in_chans: int = 3, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + mlp_ratio: float = 4.0, + out_chans: int = 256, + qkv_bias: bool = True, + norm_layer: type[nn.Module] = nn.LayerNorm, + act_layer: type[nn.Module] = nn.GELU, + use_abs_pos: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + global_attn_indexes: tuple[int, ...] = (), + ) -> None: + """Initialize an ImageEncoderViT instance for encoding images using Vision Transformer architecture. + + Args: + img_size (int): Input image size, assumed to be square. + patch_size (int): Size of image patches. + in_chans (int): Number of input image channels. + embed_dim (int): Dimension of patch embeddings. + depth (int): Number of transformer blocks. + num_heads (int): Number of attention heads in each block. + mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension. + out_chans (int): Number of output channels from the neck module. + qkv_bias (bool): If True, adds learnable bias to query, key, value projections. + norm_layer (type[nn.Module]): Type of normalization layer to use. + act_layer (type[nn.Module]): Type of activation layer to use. + use_abs_pos (bool): If True, uses absolute positional embeddings. + use_rel_pos (bool): If True, adds relative positional embeddings to attention maps. + rel_pos_zero_init (bool): If True, initializes relative positional parameters to zero. + window_size (int): Size of attention window for windowed attention blocks. + global_attn_indexes (tuple[int, ...]): Indices of blocks that use global attention. + """ + super().__init__() + self.img_size = img_size + + self.patch_embed = PatchEmbed( + kernel_size=(patch_size, patch_size), + stride=(patch_size, patch_size), + in_chans=in_chans, + embed_dim=embed_dim, + ) + + self.pos_embed: nn.Parameter | None = None + if use_abs_pos: + # Initialize absolute positional embedding with pretrain image size + self.pos_embed = nn.Parameter(torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim)) + + self.blocks = nn.ModuleList() + for i in range(depth): + block = Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + norm_layer=norm_layer, + act_layer=act_layer, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + window_size=window_size if i not in global_attn_indexes else 0, + input_size=(img_size // patch_size, img_size // patch_size), + ) + self.blocks.append(block) + + self.neck = nn.Sequential( + nn.Conv2d( + embed_dim, + out_chans, + kernel_size=1, + bias=False, + ), + LayerNorm2d(out_chans), + nn.Conv2d( + out_chans, + out_chans, + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(out_chans), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Process input through patch embedding, positional embedding, transformer blocks, and neck module.""" + x = self.patch_embed(x) + if self.pos_embed is not None: + pos_embed = ( + F.interpolate(self.pos_embed.permute(0, 3, 1, 2), scale_factor=self.img_size / 1024).permute(0, 2, 3, 1) + if self.img_size != 1024 + else self.pos_embed + ) + x = x + pos_embed + for blk in self.blocks: + x = blk(x) + return self.neck(x.permute(0, 3, 1, 2)) + + +class PromptEncoder(nn.Module): + """Encode different types of prompts for input to SAM's mask decoder, producing sparse and dense embeddings. + + Attributes: + embed_dim (int): Dimension of the embeddings. + input_image_size (tuple[int, int]): Size of the input image as (H, W). + image_embedding_size (tuple[int, int]): Spatial size of the image embedding as (H, W). + pe_layer (PositionEmbeddingRandom): Module for random position embedding. + num_point_embeddings (int): Number of point embeddings for different types of points. + point_embeddings (nn.ModuleList): List of point embeddings. + not_a_point_embed (nn.Embedding): Embedding for points that are not part of any label. + mask_input_size (tuple[int, int]): Size of the input mask. + mask_downscaling (nn.Sequential): Neural network for downscaling the mask. + no_mask_embed (nn.Embedding): Embedding for cases where no mask is provided. + + Methods: + get_dense_pe: Return the positional encoding used to encode point prompts. + forward: Embed different types of prompts, returning both sparse and dense embeddings. + + Examples: + >>> prompt_encoder = PromptEncoder(256, (64, 64), (1024, 1024), 16) + >>> points = (torch.rand(1, 5, 2), torch.randint(0, 4, (1, 5))) + >>> boxes = torch.rand(1, 2, 2) + >>> masks = torch.rand(1, 1, 256, 256) + >>> sparse_embeddings, dense_embeddings = prompt_encoder(points, boxes, masks) + >>> print(sparse_embeddings.shape, dense_embeddings.shape) + torch.Size([1, 7, 256]) torch.Size([1, 256, 64, 64]) + """ + + def __init__( + self, + embed_dim: int, + image_embedding_size: tuple[int, int], + input_image_size: tuple[int, int], + mask_in_chans: int, + activation: type[nn.Module] = nn.GELU, + ) -> None: + """Initialize the PromptEncoder module for encoding various types of prompts. + + Args: + embed_dim (int): The dimension of the embeddings. + image_embedding_size (tuple[int, int]): The spatial size of the image embedding as (H, W). + input_image_size (tuple[int, int]): The padded size of the input image as (H, W). + mask_in_chans (int): The number of hidden channels used for encoding input masks. + activation (type[nn.Module]): The activation function to use when encoding input masks. + """ + super().__init__() + self.embed_dim = embed_dim + self.input_image_size = input_image_size + self.image_embedding_size = image_embedding_size + self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) + + self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners + point_embeddings = [nn.Embedding(1, embed_dim) for _ in range(self.num_point_embeddings)] + self.point_embeddings = nn.ModuleList(point_embeddings) + self.not_a_point_embed = nn.Embedding(1, embed_dim) + + self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1]) + self.mask_downscaling = nn.Sequential( + nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans // 4), + activation(), + nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans), + activation(), + nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), + ) + self.no_mask_embed = nn.Embedding(1, embed_dim) + + def get_dense_pe(self) -> torch.Tensor: + """Return the dense positional encoding used for encoding point prompts. + + Generate a positional encoding for a dense set of points matching the shape of the image + encoding. The encoding is used to provide spatial information to the model when processing point prompts. + + Returns: + (torch.Tensor): Positional encoding tensor with shape (1, embed_dim, H, W), where H and W are the height and + width of the image embedding size, respectively. + + Examples: + >>> prompt_encoder = PromptEncoder(256, (64, 64), (1024, 1024), 16) + >>> dense_pe = prompt_encoder.get_dense_pe() + >>> print(dense_pe.shape) + torch.Size([1, 256, 64, 64]) + """ + return self.pe_layer(self.image_embedding_size).unsqueeze(0) + + def _embed_points(self, points: torch.Tensor, labels: torch.Tensor, pad: bool) -> torch.Tensor: + """Embed point prompts by applying positional encoding and label-specific embeddings.""" + points = points + 0.5 # Shift to center of pixel + if pad: + padding_point = torch.zeros((points.shape[0], 1, 2), dtype=points.dtype, device=points.device) + padding_label = -torch.ones((labels.shape[0], 1), dtype=labels.dtype, device=labels.device) + points = torch.cat([points, padding_point], dim=1) + labels = torch.cat([labels, padding_label], dim=1) + point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size) + point_embedding[labels == -1] = 0.0 + point_embedding[labels == -1] += self.not_a_point_embed.weight + point_embedding[labels == 0] += self.point_embeddings[0].weight + point_embedding[labels == 1] += self.point_embeddings[1].weight + point_embedding[labels == 2] += self.point_embeddings[2].weight + point_embedding[labels == 3] += self.point_embeddings[3].weight + return point_embedding + + def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor: + """Embed box prompts by applying positional encoding and adding corner embeddings.""" + boxes = boxes + 0.5 # Shift to center of pixel + coords = boxes.reshape(-1, 2, 2) + corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size) + corner_embedding[:, 0, :] += self.point_embeddings[2].weight + corner_embedding[:, 1, :] += self.point_embeddings[3].weight + return corner_embedding + + def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor: + """Embed mask inputs by downscaling and processing through convolutional layers.""" + return self.mask_downscaling(masks) + + @staticmethod + def _get_batch_size( + points: tuple[torch.Tensor, torch.Tensor] | None, + boxes: torch.Tensor | None, + masks: torch.Tensor | None, + ) -> int: + """Get the batch size of the output given the batch size of the input prompts.""" + if points is not None: + return points[0].shape[0] + elif boxes is not None: + return boxes.shape[0] + elif masks is not None: + return masks.shape[0] + else: + return 1 + + def forward( + self, + points: tuple[torch.Tensor, torch.Tensor] | None, + boxes: torch.Tensor | None, + masks: torch.Tensor | None, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Embed different types of prompts, returning both sparse and dense embeddings. + + Args: + points (tuple[torch.Tensor, torch.Tensor] | None): Point coordinates and labels to embed. The first tensor + contains coordinates of shape (B, N, 2), and the second tensor contains labels of shape (B, N). + boxes (torch.Tensor | None): Boxes to embed with shape (B, M, 2, 2), where M is the number of boxes. + masks (torch.Tensor | None): Masks to embed with shape (B, 1, H, W). + + Returns: + sparse_embeddings (torch.Tensor): Sparse embeddings for points and boxes with shape (B, N, embed_dim). + dense_embeddings (torch.Tensor): Dense embeddings for masks of shape (B, embed_dim, embed_H, embed_W). + + Examples: + >>> encoder = PromptEncoder(256, (64, 64), (1024, 1024), 16) + >>> points = (torch.rand(1, 5, 2), torch.randint(0, 4, (1, 5))) + >>> boxes = torch.rand(1, 2, 2, 2) + >>> masks = torch.rand(1, 1, 256, 256) + >>> sparse_emb, dense_emb = encoder(points, boxes, masks) + >>> print(sparse_emb.shape, dense_emb.shape) + torch.Size([1, 7, 256]) torch.Size([1, 256, 64, 64]) + """ + bs = self._get_batch_size(points, boxes, masks) + sparse_embeddings = torch.empty( + (bs, 0, self.embed_dim), + dtype=self.point_embeddings[0].weight.dtype, + device=self.point_embeddings[0].weight.device, + ) + if points is not None: + coords, labels = points + point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) + sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1) + if boxes is not None: + box_embeddings = self._embed_boxes(boxes) + sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1) + + if masks is not None: + dense_embeddings = self._embed_masks(masks) + else: + dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( + bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] + ) + + return sparse_embeddings, dense_embeddings + + +class MemoryEncoder(nn.Module): + """Encode pixel features and masks into a memory representation for efficient image segmentation. + + This class processes pixel-level features and masks, fusing them to generate encoded memory representations suitable + for downstream tasks in image segmentation models like SAM (Segment Anything Model). + + Attributes: + mask_downsampler (MaskDownSampler): Module for downsampling input masks. + pix_feat_proj (nn.Conv2d): Convolutional layer for projecting pixel features. + fuser (Fuser): Module for fusing pixel features and masks. + position_encoding (PositionEmbeddingSine): Module for adding positional encoding to features. + out_proj (nn.Module): Output projection layer, either nn.Identity or nn.Conv2d. + + Methods: + forward: Process input pixel features and masks to generate encoded memory representations. + + Examples: + >>> import torch + >>> encoder = MemoryEncoder(out_dim=256, in_dim=256) + >>> pix_feat = torch.randn(1, 256, 64, 64) + >>> masks = torch.randn(1, 1, 1024, 1024) + >>> out = encoder(pix_feat, masks) + >>> print(out["vision_features"].shape, out["vision_pos_enc"][0].shape) + torch.Size([1, 256, 64, 64]) torch.Size([1, 64, 64, 64]) + """ + + def __init__( + self, + out_dim, + in_dim=256, # in_dim of pix_feats + interpol_size: tuple[int, int] | None = None, + ): + """Initialize the MemoryEncoder for encoding pixel features and masks into memory representations. + + This encoder processes pixel-level features and masks, fusing them to generate encoded memory representations + suitable for downstream tasks in image segmentation models like SAM (Segment Anything Model). + + Args: + out_dim (int): Output dimension of the encoded features. + in_dim (int): Input dimension of the pixel features. + interpol_size (tuple[int, int] | None): Size to interpolate masks to. If None, uses the size of pixel + features. + """ + super().__init__() + + self.mask_downsampler = MaskDownSampler(kernel_size=3, stride=2, padding=1, interpol_size=interpol_size) + + self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1) + self.fuser = Fuser(CXBlock(dim=256), num_layers=2) + self.position_encoding = PositionEmbeddingSine(num_pos_feats=64) + self.out_proj = nn.Identity() + if out_dim != in_dim: + self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1) + + def forward( + self, + pix_feat: torch.Tensor, + masks: torch.Tensor, + skip_mask_sigmoid: bool = False, + ) -> dict: + """Process pixel features and masks to generate encoded memory representations for segmentation.""" + if not skip_mask_sigmoid: + masks = F.sigmoid(masks) + masks = self.mask_downsampler(masks) + + # Fuse pix_feats and downsampled masks, in case the visual features are on CPU, cast them to CUDA + pix_feat = pix_feat.to(masks.device) + + x = self.pix_feat_proj(pix_feat) + x = x + masks + x = self.fuser(x) + x = self.out_proj(x) + + pos = self.position_encoding(x).to(x.dtype) + + return {"vision_features": x, "vision_pos_enc": [pos]} + + +class ImageEncoder(nn.Module): + """Encode images using a trunk-neck architecture, producing multiscale features and positional encodings. + + This class combines a trunk network for feature extraction with a neck network for feature refinement and positional + encoding generation. It can optionally discard the lowest resolution features. + + Attributes: + trunk (nn.Module): The trunk network for initial feature extraction. + neck (nn.Module): The neck network for feature refinement and positional encoding generation. + scalp (int): Number of lowest resolution feature levels to discard. + + Methods: + forward: Process the input image through the trunk and neck networks. + + Examples: + >>> trunk = SomeTrunkNetwork() + >>> neck = SomeNeckNetwork() + >>> encoder = ImageEncoder(trunk, neck, scalp=1) + >>> image = torch.randn(1, 3, 224, 224) + >>> output = encoder(image) + >>> print(output.keys()) + dict_keys(['vision_features', 'vision_pos_enc', 'backbone_fpn']) + """ + + def __init__( + self, + trunk: nn.Module, + neck: nn.Module, + scalp: int = 0, + ): + """Initialize the ImageEncoder with trunk and neck networks for feature extraction and refinement. + + This encoder combines a trunk network for feature extraction with a neck network for feature refinement and + positional encoding generation. It can optionally discard the lowest resolution features. + + Args: + trunk (nn.Module): The trunk network for initial feature extraction. + neck (nn.Module): The neck network for feature refinement and positional encoding generation. + scalp (int): Number of lowest resolution feature levels to discard. + """ + super().__init__() + self.trunk = trunk + self.neck = neck + self.scalp = scalp + assert self.trunk.channel_list == self.neck.backbone_channel_list, ( + f"Channel dims of trunk {self.trunk.channel_list} and neck {self.neck.backbone_channel_list} do not match." + ) + + def forward(self, sample: torch.Tensor): + """Encode input through trunk and neck networks, returning multiscale features and positional encodings.""" + features, pos = self.neck(self.trunk(sample)) + if self.scalp > 0: + # Discard the lowest resolution features + features, pos = features[: -self.scalp], pos[: -self.scalp] + + src = features[-1] + return { + "vision_features": src, + "vision_pos_enc": pos, + "backbone_fpn": features, + } + + +class FpnNeck(nn.Module): + """A Feature Pyramid Network (FPN) neck variant for multiscale feature fusion in object detection models. + + This FPN variant removes the output convolution and uses configurable interpolation (default bilinear) for feature + resizing, similar to ViT positional embedding interpolation. + + Attributes: + position_encoding (PositionEmbeddingSine): Sinusoidal positional encoding module. + convs (nn.ModuleList): List of convolutional layers for each backbone level. + backbone_channel_list (list[int]): List of channel dimensions from the backbone. + fpn_interp_model (str): Interpolation mode for FPN feature resizing. + fuse_type (str): Type of feature fusion, either 'sum' or 'avg'. + fpn_top_down_levels (list[int]): Levels to have top-down features in outputs. + + Methods: + forward: Perform forward pass through the FPN neck. + + Examples: + >>> backbone_channels = [64, 128, 256, 512] + >>> fpn_neck = FpnNeck(256, backbone_channels) + >>> inputs = [torch.rand(1, c, 32, 32) for c in backbone_channels] + >>> outputs, positions = fpn_neck(inputs) + >>> print(len(outputs), len(positions)) + 4 4 + """ + + def __init__( + self, + d_model: int, + backbone_channel_list: list[int], + kernel_size: int = 1, + stride: int = 1, + padding: int = 0, + fpn_interp_model: str = "bilinear", + fuse_type: str = "sum", + fpn_top_down_levels: list[int] | None = None, + ): + """Initialize a modified Feature Pyramid Network (FPN) neck. + + This FPN variant removes the output convolution and uses configurable interpolation (default bilinear) for + feature resizing, similar to ViT positional embedding interpolation. + + Args: + d_model (int): Dimension of the model. + backbone_channel_list (list[int]): List of channel dimensions from the backbone. + kernel_size (int): Kernel size for the convolutional layers. + stride (int): Stride for the convolutional layers. + padding (int): Padding for the convolutional layers. + fpn_interp_model (str): Interpolation mode for FPN feature resizing. + fuse_type (str): Type of feature fusion, either 'sum' or 'avg'. + fpn_top_down_levels (list[int] | None): Levels to have top-down features in outputs. + """ + super().__init__() + self.position_encoding = PositionEmbeddingSine(num_pos_feats=256) + self.convs = nn.ModuleList() + self.backbone_channel_list = backbone_channel_list + for dim in backbone_channel_list: + current = nn.Sequential() + current.add_module( + "conv", + nn.Conv2d( + in_channels=dim, + out_channels=d_model, + kernel_size=kernel_size, + stride=stride, + padding=padding, + ), + ) + + self.convs.append(current) + self.fpn_interp_model = fpn_interp_model + assert fuse_type in {"sum", "avg"} + self.fuse_type = fuse_type + + # Levels to have top-down features in its outputs + # e.g. if fpn_top_down_levels is [2, 3], then only outputs of level 2 and 3 + # have top-down propagation, while outputs of level 0 and level 1 have only + # lateral features from the same backbone level + if fpn_top_down_levels is None: + # Default is to have top-down features on all levels + fpn_top_down_levels = range(len(self.convs)) + self.fpn_top_down_levels = list(fpn_top_down_levels) + + def forward(self, xs: list[torch.Tensor]): + """Perform forward pass through the Feature Pyramid Network (FPN) neck. + + This method processes a list of input tensors from the backbone through the FPN, applying lateral connections + and top-down feature fusion. It generates output feature maps and corresponding positional encodings. + + Args: + xs (list[torch.Tensor]): List of input tensors from the backbone, each with shape (B, C, H, W). + + Returns: + out (list[torch.Tensor]): List of output feature maps after FPN processing, each with shape (B, d_model, H, + W). + pos (list[torch.Tensor]): List of positional encodings corresponding to each output feature map. + + Examples: + >>> fpn_neck = FpnNeck(d_model=256, backbone_channel_list=[64, 128, 256, 512]) + >>> inputs = [torch.rand(1, c, 32, 32) for c in [64, 128, 256, 512]] + >>> outputs, positions = fpn_neck(inputs) + >>> print(len(outputs), len(positions)) + 4 4 + """ + out = [None] * len(self.convs) + pos = [None] * len(self.convs) + assert len(xs) == len(self.convs) + # FPN forward pass + # see https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/fpn.py + prev_features = None + # Forward in top-down order (from low to high resolution) + n = len(self.convs) - 1 + for i in range(n, -1, -1): + x = xs[i] + lateral_features = self.convs[n - i](x) + if i in self.fpn_top_down_levels and prev_features is not None: + top_down_features = F.interpolate( + prev_features.to(dtype=x.dtype), + scale_factor=2.0, + mode=self.fpn_interp_model, + align_corners=(None if self.fpn_interp_model == "nearest" else False), + antialias=False, + ) + prev_features = lateral_features + top_down_features + if self.fuse_type == "avg": + prev_features /= 2 + else: + prev_features = lateral_features + x_out = prev_features + out[i] = x_out + pos[i] = self.position_encoding(x_out).to(x_out.dtype) + + return out, pos + + +class Hiera(nn.Module): + """Hierarchical vision transformer for efficient multiscale feature extraction in image processing tasks. + + This class implements a Hiera model, which is a hierarchical vision transformer architecture designed for efficient + multiscale feature extraction. It uses a series of transformer blocks organized into stages, with optional pooling + and global attention mechanisms. + + Attributes: + window_spec (tuple[int, ...]): Window sizes for each stage. + q_stride (tuple[int, int]): Downsampling stride between stages. + stage_ends (list[int]): Indices of the last block in each stage. + q_pool_blocks (list[int]): Indices of blocks where pooling is applied. + return_interm_layers (bool): Whether to return intermediate layer outputs. + patch_embed (PatchEmbed): Module for patch embedding. + global_att_blocks (tuple[int, ...]): Indices of blocks with global attention. + window_pos_embed_bkg_spatial_size (tuple[int, int]): Spatial size for window positional embedding background. + pos_embed (nn.Parameter): Positional embedding for the background. + pos_embed_window (nn.Parameter): Positional embedding for the window. + blocks (nn.ModuleList): List of MultiScaleBlock modules. + channel_list (list[int]): List of output channel dimensions for each stage. + + Methods: + _get_pos_embed: Generate positional embeddings by interpolating and combining window and background embeddings. + forward: Perform the forward pass through the Hiera model. + + Examples: + >>> model = Hiera(embed_dim=96, num_heads=1, stages=(2, 3, 16, 3)) + >>> input_tensor = torch.randn(1, 3, 224, 224) + >>> output_features = model(input_tensor) + >>> for feat in output_features: + ... print(feat.shape) + """ + + def __init__( + self, + embed_dim: int = 96, # initial embed dim + num_heads: int = 1, # initial number of heads + drop_path_rate: float = 0.0, # stochastic depth + q_pool: int = 3, # number of q_pool stages + q_stride: tuple[int, int] = (2, 2), # downsample stride bet. stages + stages: tuple[int, ...] = (2, 3, 16, 3), # blocks per stage + dim_mul: float = 2.0, # dim_mul factor at stage shift + head_mul: float = 2.0, # head_mul factor at stage shift + window_pos_embed_bkg_spatial_size: tuple[int, int] = (14, 14), + # window size per stage, when not using global att. + window_spec: tuple[int, ...] = ( + 8, + 4, + 14, + 7, + ), + # global attn in these blocks + global_att_blocks: tuple[int, ...] = ( + 12, + 16, + 20, + ), + return_interm_layers=True, # return feats from every stage + ): + """Initialize a Hiera model, a hierarchical vision transformer for efficient multiscale feature extraction. + + Hiera is a hierarchical vision transformer architecture designed for efficient multiscale feature extraction in + image processing tasks. It uses a series of transformer blocks organized into stages, with optional pooling and + global attention mechanisms. + + Args: + embed_dim (int): Initial embedding dimension for the model. + num_heads (int): Initial number of attention heads. + drop_path_rate (float): Stochastic depth rate. + q_pool (int): Number of query pooling stages. + q_stride (tuple[int, int]): Downsampling stride between stages. + stages (tuple[int, ...]): Number of blocks per stage. + dim_mul (float): Dimension multiplier factor at stage transitions. + head_mul (float): Head multiplier factor at stage transitions. + window_pos_embed_bkg_spatial_size (tuple[int, int]): Spatial size for window positional embedding + background. + window_spec (tuple[int, ...]): Window sizes for each stage when not using global attention. + global_att_blocks (tuple[int, ...]): Indices of blocks that use global attention. + return_interm_layers (bool): Whether to return intermediate layer outputs. + """ + super().__init__() + + assert len(stages) == len(window_spec) + self.window_spec = window_spec + + depth = sum(stages) + self.q_stride = q_stride + self.stage_ends = [sum(stages[:i]) - 1 for i in range(1, len(stages) + 1)] + assert 0 <= q_pool <= len(self.stage_ends[:-1]) + self.q_pool_blocks = [x + 1 for x in self.stage_ends[:-1]][:q_pool] + self.return_interm_layers = return_interm_layers + + self.patch_embed = PatchEmbed( + embed_dim=embed_dim, + kernel_size=(7, 7), + stride=(4, 4), + padding=(3, 3), + ) + # Which blocks have global attention? + self.global_att_blocks = global_att_blocks + + # Windowed positional embedding (https://arxiv.org/abs/2311.05613) + self.window_pos_embed_bkg_spatial_size = window_pos_embed_bkg_spatial_size + self.pos_embed = nn.Parameter(torch.zeros(1, embed_dim, *self.window_pos_embed_bkg_spatial_size)) + self.pos_embed_window = nn.Parameter(torch.zeros(1, embed_dim, self.window_spec[0], self.window_spec[0])) + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + + cur_stage = 1 + self.blocks = nn.ModuleList() + + for i in range(depth): + dim_out = embed_dim + # Lags by a block, so first block of next stage uses an initial window size + # of previous stage and final window size of current stage + window_size = self.window_spec[cur_stage - 1] + + if self.global_att_blocks is not None: + window_size = 0 if i in self.global_att_blocks else window_size + + if i - 1 in self.stage_ends: + dim_out = int(embed_dim * dim_mul) + num_heads = int(num_heads * head_mul) + cur_stage += 1 + + block = MultiScaleBlock( + dim=embed_dim, + dim_out=dim_out, + num_heads=num_heads, + drop_path=dpr[i], + q_stride=self.q_stride if i in self.q_pool_blocks else None, + window_size=window_size, + ) + + embed_dim = dim_out + self.blocks.append(block) + + self.channel_list = ( + [self.blocks[i].dim_out for i in self.stage_ends[::-1]] + if return_interm_layers + else [self.blocks[-1].dim_out] + ) + + def _get_pos_embed(self, hw: tuple[int, int]) -> torch.Tensor: + """Generate positional embeddings by interpolating and combining window and background embeddings.""" + h, w = hw + window_embed = self.pos_embed_window + pos_embed = F.interpolate(self.pos_embed, size=(h, w), mode="bicubic") + pos_embed = pos_embed + window_embed.tile([x // y for x, y in zip(pos_embed.shape, window_embed.shape)]) + pos_embed = pos_embed.permute(0, 2, 3, 1) + return pos_embed + + def forward(self, x: torch.Tensor) -> list[torch.Tensor]: + """Perform forward pass through Hiera model, extracting multiscale features from input images. + + Args: + x (torch.Tensor): Input tensor with shape (B, C, H, W) representing a batch of images. + + Returns: + (list[torch.Tensor]): List of feature maps at different scales, each with shape (B, C_i, H_i, W_i), where + C_i is the channel dimension and H_i, W_i are the spatial dimensions at scale i. The list is ordered + from highest resolution (fine features) to lowest resolution (coarse features) if return_interm_layers + is True, otherwise contains only the final output. + + Examples: + >>> model = Hiera(embed_dim=96, num_heads=1, stages=(2, 3, 16, 3)) + >>> input_tensor = torch.randn(1, 3, 224, 224) + >>> output_features = model(input_tensor) + >>> for feat in output_features: + ... print(feat.shape) + """ + x = self.patch_embed(x) + # x: (B, H, W, C) + + # Add positional embedding + x = x + self._get_pos_embed(x.shape[1:3]) + + outputs = [] + for i, blk in enumerate(self.blocks): + x = blk(x) + if (i == self.stage_ends[-1]) or (i in self.stage_ends and self.return_interm_layers): + feats = x.permute(0, 3, 1, 2) + outputs.append(feats) + + return outputs diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/memory_attention.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/memory_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..0e232e0f5b504212d4a366172262e33d8be80d97 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/memory_attention.py @@ -0,0 +1,298 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import copy + +import torch +from torch import nn + +from .blocks import RoPEAttention + + +class MemoryAttentionLayer(nn.Module): + """Implements a memory attention layer with self-attention and cross-attention mechanisms for neural networks. + + This class combines self-attention, cross-attention, and feedforward components to process input tensors and + generate memory-based attention outputs. + + Attributes: + d_model (int): Dimensionality of the model. + dim_feedforward (int): Dimensionality of the feedforward network. + dropout_value (float): Dropout rate for regularization. + self_attn (RoPEAttention): Self-attention mechanism using RoPE (Rotary Position Embedding). + cross_attn_image (RoPEAttention): Cross-attention mechanism for image processing. + linear1 (nn.Linear): First linear layer of the feedforward network. + linear2 (nn.Linear): Second linear layer of the feedforward network. + norm1 (nn.LayerNorm): Layer normalization for self-attention output. + norm2 (nn.LayerNorm): Layer normalization for cross-attention output. + norm3 (nn.LayerNorm): Layer normalization for feedforward network output. + dropout1 (nn.Dropout): Dropout layer after self-attention. + dropout2 (nn.Dropout): Dropout layer after cross-attention. + dropout3 (nn.Dropout): Dropout layer after feedforward network. + activation (nn.ReLU): Activation function for the feedforward network. + pos_enc_at_attn (bool): Flag to add positional encoding at attention. + pos_enc_at_cross_attn_queries (bool): Flag to add positional encoding to cross-attention queries. + pos_enc_at_cross_attn_keys (bool): Flag to add positional encoding to cross-attention keys. + + Methods: + forward: Performs the full memory attention operation on input tensors. + _forward_sa: Performs self-attention on input tensor. + _forward_ca: Performs cross-attention between target and memory tensors. + + Examples: + >>> layer = MemoryAttentionLayer(d_model=256, dim_feedforward=2048, dropout=0.1) + >>> tgt = torch.randn(1, 100, 256) + >>> memory = torch.randn(1, 100, 64) + >>> pos = torch.randn(1, 100, 256) + >>> query_pos = torch.randn(1, 100, 256) + >>> output = layer(tgt, memory, pos, query_pos) + >>> print(output.shape) + torch.Size([1, 100, 256]) + """ + + def __init__( + self, + d_model: int = 256, + dim_feedforward: int = 2048, + dropout: float = 0.1, + pos_enc_at_attn: bool = False, + pos_enc_at_cross_attn_keys: bool = True, + pos_enc_at_cross_attn_queries: bool = False, + self_attn: nn.Module | None = None, + cross_attn: nn.Module | None = None, + ): + """Initialize a memory attention layer with self-attention, cross-attention, and feedforward components. + + Args: + d_model (int): Dimensionality of the model. + dim_feedforward (int): Dimensionality of the feedforward network. + dropout (float): Dropout rate for regularization. + pos_enc_at_attn (bool): Whether to add positional encoding at attention. + pos_enc_at_cross_attn_keys (bool): Whether to add positional encoding to cross-attention keys. + pos_enc_at_cross_attn_queries (bool): Whether to add positional encoding to cross-attention queries. + self_attn (nn.Module | None): Custom self-attention module. If None, a default RoPEAttention is used. + cross_attn (nn.Module | None): Custom cross-attention module. If None, a default RoPEAttention is used. + """ + super().__init__() + self.d_model = d_model + self.dim_feedforward = dim_feedforward + self.dropout_value = dropout + self.self_attn = self_attn or RoPEAttention(embedding_dim=256, num_heads=1, downsample_rate=1) + self.cross_attn_image = cross_attn or RoPEAttention( + rope_k_repeat=True, + embedding_dim=256, + num_heads=1, + downsample_rate=1, + kv_in_dim=64, + ) + + # Implementation of Feedforward model + self.linear1 = nn.Linear(d_model, dim_feedforward) + self.dropout = nn.Dropout(dropout) + self.linear2 = nn.Linear(dim_feedforward, d_model) + + self.norm1 = nn.LayerNorm(d_model) + self.norm2 = nn.LayerNorm(d_model) + self.norm3 = nn.LayerNorm(d_model) + self.dropout1 = nn.Dropout(dropout) + self.dropout2 = nn.Dropout(dropout) + self.dropout3 = nn.Dropout(dropout) + + self.activation = nn.ReLU() + + # Where to add pos enc + self.pos_enc_at_attn = pos_enc_at_attn + self.pos_enc_at_cross_attn_queries = pos_enc_at_cross_attn_queries + self.pos_enc_at_cross_attn_keys = pos_enc_at_cross_attn_keys + + def _forward_sa(self, tgt: torch.Tensor, query_pos: torch.Tensor | None) -> torch.Tensor: + """Perform self-attention on input tensor using positional encoding and RoPE attention mechanism.""" + tgt2 = self.norm1(tgt) + q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2 + tgt2 = self.self_attn(q, k, v=tgt2) + tgt = tgt + self.dropout1(tgt2) + return tgt + + def _forward_ca( + self, + tgt: torch.Tensor, + memory: torch.Tensor, + query_pos: torch.Tensor | None, + pos: torch.Tensor | None, + num_k_exclude_rope: int = 0, + ) -> torch.Tensor: + """Perform cross-attention between target and memory tensors using RoPEAttention mechanism.""" + kwds = {} + if num_k_exclude_rope > 0: + assert isinstance(self.cross_attn_image, RoPEAttention) + kwds = {"num_k_exclude_rope": num_k_exclude_rope} + + # Cross-Attention + tgt2 = self.norm2(tgt) + tgt2 = self.cross_attn_image( + q=tgt2 + query_pos if self.pos_enc_at_cross_attn_queries else tgt2, + k=memory + pos if self.pos_enc_at_cross_attn_keys else memory, + v=memory, + **kwds, + ) + tgt = tgt + self.dropout2(tgt2) + return tgt + + def forward( + self, + tgt: torch.Tensor, + memory: torch.Tensor, + pos: torch.Tensor | None = None, + query_pos: torch.Tensor | None = None, + num_k_exclude_rope: int = 0, + ) -> torch.Tensor: + """Process input tensors through self-attention, cross-attention, and feedforward network layers. + + Args: + tgt (torch.Tensor): Target tensor for self-attention with shape (N, L, D). + memory (torch.Tensor): Memory tensor for cross-attention with shape (N, S, D). + pos (torch.Tensor | None): Positional encoding for memory tensor. + query_pos (torch.Tensor | None): Positional encoding for target tensor. + num_k_exclude_rope (int): Number of keys to exclude from rotary position embedding. + + Returns: + (torch.Tensor): Processed tensor after attention and feedforward layers with shape (N, L, D). + """ + tgt = self._forward_sa(tgt, query_pos) + tgt = self._forward_ca(tgt, memory, query_pos, pos, num_k_exclude_rope) + # MLP + tgt2 = self.norm3(tgt) + tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) + tgt = tgt + self.dropout3(tgt2) + return tgt + + +class MemoryAttention(nn.Module): + """Memory attention module for processing sequential data with self and cross-attention mechanisms. + + This class implements a multi-layer attention mechanism that combines self-attention and cross-attention for + processing sequential data, particularly useful in transformer-like architectures. + + Attributes: + d_model (int): The dimension of the model's hidden state. + layers (nn.ModuleList): A list of MemoryAttentionLayer modules. + num_layers (int): The number of attention layers. + norm (nn.LayerNorm): Layer normalization applied to the output. + pos_enc_at_input (bool): Whether to apply positional encoding at the input. + batch_first (bool): Whether the input tensors are in batch-first format. + + Methods: + forward: Processes input tensors through the attention layers. + + Examples: + >>> d_model = 256 + >>> layer = MemoryAttentionLayer(d_model) + >>> attention = MemoryAttention(d_model, pos_enc_at_input=True, layer=layer, num_layers=3) + >>> curr = torch.randn(10, 32, d_model) # (seq_len, batch_size, d_model) + >>> memory = torch.randn(20, 32, d_model) # (mem_len, batch_size, d_model) + >>> curr_pos = torch.randn(10, 32, d_model) + >>> memory_pos = torch.randn(20, 32, d_model) + >>> output = attention(curr, memory, curr_pos, memory_pos) + >>> print(output.shape) + torch.Size([10, 32, 256]) + """ + + def __init__( + self, + d_model: int, + pos_enc_at_input: bool, + layer: nn.Module, + num_layers: int, + batch_first: bool = True, # Do layers expect batch first input? + ): + """Initialize MemoryAttention with specified layers and normalization for sequential data processing. + + This class implements a multi-layer attention mechanism that combines self-attention and cross-attention for + processing sequential data, particularly useful in transformer-like architectures. + + Args: + d_model (int): The dimension of the model's hidden state. + pos_enc_at_input (bool): Whether to apply positional encoding at the input. + layer (nn.Module): The attention layer to be used in the module. + num_layers (int): The number of attention layers. + batch_first (bool): Whether the input tensors are in batch-first format. + """ + super().__init__() + self.d_model = d_model + self.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(num_layers)]) + self.num_layers = num_layers + self.norm = nn.LayerNorm(d_model) + self.pos_enc_at_input = pos_enc_at_input + self.batch_first = batch_first + + def forward( + self, + curr: torch.Tensor, # self-attention inputs + memory: torch.Tensor, # cross-attention inputs + curr_pos: torch.Tensor | None = None, # pos_enc for self-attention inputs + memory_pos: torch.Tensor | None = None, # pos_enc for cross-attention inputs + num_obj_ptr_tokens: int = 0, # number of object pointer *tokens* + ) -> torch.Tensor: + """Process inputs through attention layers, applying self and cross-attention with positional encoding. + + Args: + curr (torch.Tensor): Self-attention input tensor, representing the current state. + memory (torch.Tensor): Cross-attention input tensor, representing memory information. + curr_pos (torch.Tensor | None): Positional encoding for self-attention inputs. + memory_pos (torch.Tensor | None): Positional encoding for cross-attention inputs. + num_obj_ptr_tokens (int): Number of object pointer tokens to exclude from rotary position embedding. + + Returns: + (torch.Tensor): Processed output tensor after applying attention layers and normalization. + + Examples: + >>> d_model = 256 + >>> layer = MemoryAttentionLayer(d_model) + >>> attention = MemoryAttention(d_model, pos_enc_at_input=True, layer=layer, num_layers=3) + >>> curr = torch.randn(10, 32, d_model) # (seq_len, batch_size, d_model) + >>> memory = torch.randn(20, 32, d_model) # (mem_len, batch_size, d_model) + >>> curr_pos = torch.randn(10, 32, d_model) + >>> memory_pos = torch.randn(20, 32, d_model) + >>> output = attention(curr, memory, curr_pos, memory_pos) + >>> print(output.shape) + torch.Size([10, 32, 256]) + """ + if isinstance(curr, list): + assert isinstance(curr_pos, list) + assert len(curr) == len(curr_pos) == 1 + curr, curr_pos = curr[0], curr_pos[0] + + assert curr.shape[1] == memory.shape[1], "Batch size must be the same for curr and memory" + + output = curr + if self.pos_enc_at_input and curr_pos is not None: + output = output + 0.1 * curr_pos + + if self.batch_first: + # Convert to batch first + output = output.transpose(0, 1) + curr_pos = curr_pos.transpose(0, 1) + memory = memory.transpose(0, 1) + memory_pos = memory_pos.transpose(0, 1) + + for layer in self.layers: + kwds = {} + if isinstance(layer.cross_attn_image, RoPEAttention): + kwds = {"num_k_exclude_rope": num_obj_ptr_tokens} + + output = layer( + tgt=output, + memory=memory, + pos=memory_pos, + query_pos=curr_pos, + **kwds, + ) + normed_output = self.norm(output) + + if self.batch_first: + # Convert back to seq first + normed_output = normed_output.transpose(0, 1) + curr_pos = curr_pos.transpose(0, 1) + + return normed_output diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/sam.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/sam.py new file mode 100644 index 0000000000000000000000000000000000000000..eac90809423b99f1a6d27c30bc1a4c17e76f1be6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/sam.py @@ -0,0 +1,1159 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn +from torch.nn.init import trunc_normal_ + +from ultralytics.nn.modules import MLP +from ultralytics.utils import LOGGER + +from .blocks import SAM2TwoWayTransformer, TwoWayTransformer +from .decoders import MaskDecoder, SAM2MaskDecoder +from .encoders import ImageEncoderViT, PromptEncoder +from .utils import get_1d_sine_pe, select_closest_cond_frames + +# a large negative value as a placeholder score for missing objects +NO_OBJ_SCORE = -1024.0 + + +class SAMModel(nn.Module): + """Segment Anything Model (SAM) for object segmentation tasks. + + This class combines image encoders, prompt encoders, and mask decoders to predict object masks from images and input + prompts. + + Attributes: + mask_threshold (float): Threshold value for mask prediction. + image_encoder (ImageEncoderViT): Backbone for encoding images into embeddings. + prompt_encoder (PromptEncoder): Encoder for various types of input prompts. + mask_decoder (MaskDecoder): Predicts object masks from image and prompt embeddings. + pixel_mean (torch.Tensor): Mean values for normalizing pixels in the input image. + pixel_std (torch.Tensor): Standard deviation values for normalizing pixels in the input image. + + Methods: + set_imgsz: Set image size to make model compatible with different image sizes. + + Examples: + >>> image_encoder = ImageEncoderViT(...) + >>> prompt_encoder = PromptEncoder(...) + >>> mask_decoder = MaskDecoder(...) + >>> sam_model = SAMModel(image_encoder, prompt_encoder, mask_decoder) + >>> # Further usage depends on SAMPredictor class + + Notes: + All forward() operations are implemented in the SAMPredictor class. + """ + + mask_threshold: float = 0.0 + + def __init__( + self, + image_encoder: ImageEncoderViT, + prompt_encoder: PromptEncoder, + mask_decoder: MaskDecoder, + pixel_mean: list[float] = (123.675, 116.28, 103.53), + pixel_std: list[float] = (58.395, 57.12, 57.375), + ) -> None: + """Initialize the SAMModel class to predict object masks from an image and input prompts. + + Args: + image_encoder (ImageEncoderViT): The backbone used to encode the image into image embeddings. + prompt_encoder (PromptEncoder): Encodes various types of input prompts. + mask_decoder (MaskDecoder): Predicts masks from the image embeddings and encoded prompts. + pixel_mean (list[float]): Mean values for normalizing pixels in the input image. + pixel_std (list[float]): Standard deviation values for normalizing pixels in the input image. + + Notes: + All forward() operations moved to SAMPredictor. + """ + super().__init__() + self.image_encoder = image_encoder + self.prompt_encoder = prompt_encoder + self.mask_decoder = mask_decoder + self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) + self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) + + def set_imgsz(self, imgsz): + """Set image size to make model compatible with different image sizes.""" + if hasattr(self.image_encoder, "set_imgsz"): + self.image_encoder.set_imgsz(imgsz) + self.prompt_encoder.input_image_size = imgsz + self.prompt_encoder.image_embedding_size = [x // 16 for x in imgsz] # 16 is fixed as patch size of ViT model + self.image_encoder.img_size = imgsz[0] + + +class SAM2Model(torch.nn.Module): + """SAM2Model class for Segment Anything Model 2 with memory-based video object segmentation capabilities. + + This class extends the functionality of SAM to handle video sequences, incorporating memory mechanisms for temporal + consistency and efficient tracking of objects across frames. + + Attributes: + mask_threshold (float): Threshold value for mask prediction. + image_encoder (ImageEncoderViT): Visual encoder for extracting image features. + memory_attention (nn.Module): Module for attending to memory features. + memory_encoder (nn.Module): Encoder for generating memory representations. + num_maskmem (int): Number of accessible memory frames. + image_size (int): Size of input images. + backbone_stride (int): Stride of the backbone network output. + sam_prompt_embed_dim (int): Dimension of SAM prompt embeddings. + sam_image_embedding_size (int): Size of SAM image embeddings. + sam_prompt_encoder (PromptEncoder): Encoder for processing input prompts. + sam_mask_decoder (SAM2MaskDecoder): Decoder for generating object masks. + obj_ptr_proj (nn.Module): Projection layer for object pointers. + obj_ptr_tpos_proj (nn.Module): Projection for temporal positional encoding in object pointers. + hidden_dim (int): Hidden dimension of the model. + mem_dim (int): Memory dimension for encoding features. + use_high_res_features_in_sam (bool): Whether to use high-resolution feature maps in the SAM mask decoder. + use_obj_ptrs_in_encoder (bool): Whether to cross-attend to object pointers from other frames in the encoder. + max_obj_ptrs_in_encoder (int): Maximum number of object pointers from other frames in encoder cross-attention. + add_tpos_enc_to_obj_ptrs (bool): Whether to add temporal positional encoding to object pointers. + proj_tpos_enc_in_obj_ptrs (bool): Whether to add an extra linear projection layer for temporal positional + encoding in object pointers. + use_signed_tpos_enc_to_obj_ptrs (bool): Whether to use signed distance in temporal positional encoding. + only_obj_ptrs_in_the_past_for_eval (bool): Whether to only attend to object pointers in the past during + evaluation. + pred_obj_scores (bool): Whether to predict if there is an object in the frame. + pred_obj_scores_mlp (bool): Whether to use an MLP to predict object scores. + fixed_no_obj_ptr (bool): Whether to have a fixed no-object pointer when there is no object present. + soft_no_obj_ptr (bool): Whether to mix in no-object pointer softly for easier recovery and error mitigation. + use_mlp_for_obj_ptr_proj (bool): Whether to use MLP for object pointer projection. + no_obj_embed_spatial (torch.Tensor | None): No-object embedding for spatial frames. + max_cond_frames_in_attn (int): Maximum number of conditioning frames to participate in memory attention. + directly_add_no_mem_embed (bool): Whether to directly add no-memory embedding to image feature on the first + frame. + multimask_output_in_sam (bool): Whether to output multiple masks for the first click on initial conditioning + frames. + multimask_min_pt_num (int): Minimum number of clicks to use multimask output in SAM. + multimask_max_pt_num (int): Maximum number of clicks to use multimask output in SAM. + multimask_output_for_tracking (bool): Whether to use multimask output for tracking. + use_multimask_token_for_obj_ptr (bool): Whether to use multimask tokens for object pointers. + iou_prediction_use_sigmoid (bool): Whether to use sigmoid to restrict IoU prediction to [0-1]. + memory_temporal_stride_for_eval (int): Memory bank's temporal stride during evaluation. + non_overlap_masks_for_mem_enc (bool): Whether to apply non-overlapping constraints on object masks in memory + encoder during evaluation. + sigmoid_scale_for_mem_enc (float): Scale factor for mask sigmoid probability. + sigmoid_bias_for_mem_enc (float): Bias factor for mask sigmoid probability. + binarize_mask_from_pts_for_mem_enc (bool): Whether to binarize sigmoid mask logits on interacted frames with + clicks during evaluation. + use_mask_input_as_output_without_sam (bool): Whether to directly output the input mask without using SAM prompt + encoder and mask decoder on frames with mask input. + + Methods: + forward_image: Process image batch through encoder to extract multi-level features. + track_step: Perform a single tracking step, updating object masks and memory features. + set_binarize: Set binarize for VideoPredictor. + set_imgsz: Set image size to make model compatible with different image sizes. + + Examples: + >>> model = SAM2Model(image_encoder, memory_attention, memory_encoder) + >>> image_batch = torch.rand(1, 3, 512, 512) + >>> features = model.forward_image(image_batch) + >>> track_results = model.track_step(0, True, features, None, None, None, {}) + """ + + mask_threshold: float = 0.0 + + def __init__( + self, + image_encoder, + memory_attention, + memory_encoder, + num_maskmem=7, + image_size=512, + backbone_stride=16, + sigmoid_scale_for_mem_enc=1.0, + sigmoid_bias_for_mem_enc=0.0, + binarize_mask_from_pts_for_mem_enc=False, + use_mask_input_as_output_without_sam=False, + max_cond_frames_in_attn=-1, + directly_add_no_mem_embed=False, + use_high_res_features_in_sam=False, + multimask_output_in_sam=False, + multimask_min_pt_num=1, + multimask_max_pt_num=1, + multimask_output_for_tracking=False, + use_multimask_token_for_obj_ptr: bool = False, + iou_prediction_use_sigmoid=False, + memory_temporal_stride_for_eval=1, + non_overlap_masks_for_mem_enc=False, + use_obj_ptrs_in_encoder=False, + max_obj_ptrs_in_encoder=16, + add_tpos_enc_to_obj_ptrs=True, + proj_tpos_enc_in_obj_ptrs=False, + use_signed_tpos_enc_to_obj_ptrs=False, + only_obj_ptrs_in_the_past_for_eval=False, + pred_obj_scores: bool = False, + pred_obj_scores_mlp: bool = False, + fixed_no_obj_ptr: bool = False, + soft_no_obj_ptr: bool = False, + use_mlp_for_obj_ptr_proj: bool = False, + no_obj_embed_spatial: bool = False, + sam_mask_decoder_extra_args=None, + compile_image_encoder: bool = False, + ): + """Initialize the SAM2Model for video object segmentation with memory-based tracking. + + Args: + image_encoder (nn.Module): Visual encoder for extracting image features. + memory_attention (nn.Module): Module for attending to memory features. + memory_encoder (nn.Module): Encoder for generating memory representations. + num_maskmem (int): Number of accessible memory frames. + image_size (int): Size of input images. + backbone_stride (int): Stride of the image backbone output. + sigmoid_scale_for_mem_enc (float): Scale factor for mask sigmoid probability. + sigmoid_bias_for_mem_enc (float): Bias factor for mask sigmoid probability. + binarize_mask_from_pts_for_mem_enc (bool): Whether to binarize sigmoid mask logits on interacted frames with + clicks during evaluation. + use_mask_input_as_output_without_sam (bool): Whether to directly output the input mask without using SAM + prompt encoder and mask decoder on frames with mask input. + max_cond_frames_in_attn (int): Maximum number of conditioning frames to participate in memory attention. + directly_add_no_mem_embed (bool): Whether to directly add no-memory embedding to image feature on the first + frame. + use_high_res_features_in_sam (bool): Whether to use high-resolution feature maps in the SAM mask decoder. + multimask_output_in_sam (bool): Whether to output multiple masks for the first click on initial conditioning + frames. + multimask_min_pt_num (int): Minimum number of clicks to use multimask output in SAM. + multimask_max_pt_num (int): Maximum number of clicks to use multimask output in SAM. + multimask_output_for_tracking (bool): Whether to use multimask output for tracking. + use_multimask_token_for_obj_ptr (bool): Whether to use multimask tokens for object pointers. + iou_prediction_use_sigmoid (bool): Whether to use sigmoid to restrict IoU prediction to [0-1]. + memory_temporal_stride_for_eval (int): Memory bank's temporal stride during evaluation. + non_overlap_masks_for_mem_enc (bool): Whether to apply non-overlapping constraints on object masks in memory + encoder during evaluation. + use_obj_ptrs_in_encoder (bool): Whether to cross-attend to object pointers from other frames in the encoder. + max_obj_ptrs_in_encoder (int): Maximum number of object pointers from other frames in encoder + cross-attention. + add_tpos_enc_to_obj_ptrs (bool): Whether to add temporal positional encoding to object pointers in the + encoder. + proj_tpos_enc_in_obj_ptrs (bool): Whether to add an extra linear projection layer for temporal positional + encoding in object pointers. + use_signed_tpos_enc_to_obj_ptrs (bool): Whether to use signed distance in the temporal positional encoding + in the object pointers. + only_obj_ptrs_in_the_past_for_eval (bool): Whether to only attend to object pointers in the past during + evaluation. + pred_obj_scores (bool): Whether to predict if there is an object in the frame. + pred_obj_scores_mlp (bool): Whether to use an MLP to predict object scores. + fixed_no_obj_ptr (bool): Whether to have a fixed no-object pointer when there is no object present. + soft_no_obj_ptr (bool): Whether to mix in no-object pointer softly for easier recovery and error mitigation. + use_mlp_for_obj_ptr_proj (bool): Whether to use MLP for object pointer projection. + no_obj_embed_spatial (bool): Whether to add no-object embedding to spatial frames. + sam_mask_decoder_extra_args (dict | None): Extra arguments for constructing the SAM mask decoder. + compile_image_encoder (bool): Whether to compile the image encoder for faster inference. + """ + super().__init__() + + # Part 1: the image backbone + self.image_encoder = image_encoder + # Use level 0, 1, 2 for high-res setting, or just level 2 for the default setting + self.use_high_res_features_in_sam = use_high_res_features_in_sam + self.num_feature_levels = 3 if use_high_res_features_in_sam else 1 + self.use_obj_ptrs_in_encoder = use_obj_ptrs_in_encoder + self.max_obj_ptrs_in_encoder = max_obj_ptrs_in_encoder + if use_obj_ptrs_in_encoder: + # A conv layer to downsample the mask prompt to stride 4 (the same stride as + # low-res SAM mask logits) and to change its scales from 0~1 to SAM logit scale, + # so that it can be fed into the SAM mask decoder to generate a pointer. + self.mask_downsample = torch.nn.Conv2d(1, 1, kernel_size=4, stride=4) + self.add_tpos_enc_to_obj_ptrs = add_tpos_enc_to_obj_ptrs + if proj_tpos_enc_in_obj_ptrs: + assert add_tpos_enc_to_obj_ptrs # these options need to be used together + self.proj_tpos_enc_in_obj_ptrs = proj_tpos_enc_in_obj_ptrs + self.use_signed_tpos_enc_to_obj_ptrs = use_signed_tpos_enc_to_obj_ptrs + self.only_obj_ptrs_in_the_past_for_eval = only_obj_ptrs_in_the_past_for_eval + + # Part 2: memory attention to condition current frame's visual features + # with memories (and obj ptrs) from past frames + self.memory_attention = memory_attention + self.hidden_dim = memory_attention.d_model + + # Part 3: memory encoder for the previous frame's outputs + self.memory_encoder = memory_encoder + self.mem_dim = self.hidden_dim + if hasattr(self.memory_encoder, "out_proj") and hasattr(self.memory_encoder.out_proj, "weight"): + # if there is compression of memories along channel dim + self.mem_dim = self.memory_encoder.out_proj.weight.shape[0] + self.num_maskmem = num_maskmem # Number of memories accessible + # Temporal encoding of the memories + self.maskmem_tpos_enc = torch.nn.Parameter(torch.zeros(num_maskmem, 1, 1, self.mem_dim)) + trunc_normal_(self.maskmem_tpos_enc, std=0.02) + # a single token to indicate no memory embedding from previous frames + self.no_mem_embed = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim)) + self.no_mem_pos_enc = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim)) + trunc_normal_(self.no_mem_embed, std=0.02) + trunc_normal_(self.no_mem_pos_enc, std=0.02) + self.directly_add_no_mem_embed = directly_add_no_mem_embed + # Apply sigmoid to the output raw mask logits (to turn them from + # range (-inf, +inf) to range (0, 1)) before feeding them into the memory encoder + self.sigmoid_scale_for_mem_enc = sigmoid_scale_for_mem_enc + self.sigmoid_bias_for_mem_enc = sigmoid_bias_for_mem_enc + self.binarize_mask_from_pts_for_mem_enc = binarize_mask_from_pts_for_mem_enc + self.non_overlap_masks_for_mem_enc = non_overlap_masks_for_mem_enc + self.memory_temporal_stride_for_eval = memory_temporal_stride_for_eval + # On frames with mask input, whether to directly output the input mask without + # using a SAM prompt encoder + mask decoder + self.use_mask_input_as_output_without_sam = use_mask_input_as_output_without_sam + self.multimask_output_in_sam = multimask_output_in_sam + self.multimask_min_pt_num = multimask_min_pt_num + self.multimask_max_pt_num = multimask_max_pt_num + self.multimask_output_for_tracking = multimask_output_for_tracking + self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr + self.iou_prediction_use_sigmoid = iou_prediction_use_sigmoid + + # Part 4: SAM-style prompt encoder (for both mask and point inputs) + # and SAM-style mask decoder for the final mask output + self.image_size = image_size + self.backbone_stride = backbone_stride + self.sam_mask_decoder_extra_args = sam_mask_decoder_extra_args + self.pred_obj_scores = pred_obj_scores + self.pred_obj_scores_mlp = pred_obj_scores_mlp + self.fixed_no_obj_ptr = fixed_no_obj_ptr + self.soft_no_obj_ptr = soft_no_obj_ptr + if self.fixed_no_obj_ptr: + assert self.pred_obj_scores + assert self.use_obj_ptrs_in_encoder + if self.pred_obj_scores and self.use_obj_ptrs_in_encoder: + self.no_obj_ptr = torch.nn.Parameter(torch.zeros(1, self.hidden_dim)) + trunc_normal_(self.no_obj_ptr, std=0.02) + self.use_mlp_for_obj_ptr_proj = use_mlp_for_obj_ptr_proj + self.no_obj_embed_spatial = None + if no_obj_embed_spatial: + self.no_obj_embed_spatial = torch.nn.Parameter(torch.zeros(1, self.mem_dim)) + trunc_normal_(self.no_obj_embed_spatial, std=0.02) + + self._build_sam_heads() + self.max_cond_frames_in_attn = max_cond_frames_in_attn + self.add_all_frames_to_correct_as_cond = True + + # Model compilation + if compile_image_encoder: + # Compile the forward function (not the full module) to allow loading checkpoints. + LOGGER.info("Image encoder compilation is enabled. First forward pass will be slow.") + self.image_encoder.forward = torch.compile( + self.image_encoder.forward, + mode="max-autotune", + fullgraph=True, + dynamic=False, + ) + + @property + def device(self): + """Return the device on which the model's parameters are stored.""" + return next(self.parameters()).device + + def forward(self, *args, **kwargs): + """Process image and prompt inputs to generate object masks and scores in video sequences.""" + raise NotImplementedError( + "Please use the corresponding methods in SAM2VideoPredictor for inference." + "See notebooks/video_predictor_example.ipynb for an example." + ) + + def _build_sam_heads(self): + """Build SAM-style prompt encoder and mask decoder for image segmentation tasks.""" + self.sam_prompt_embed_dim = self.hidden_dim + self.sam_image_embedding_size = self.image_size // self.backbone_stride + + # Build PromptEncoder and MaskDecoder from SAM (hyperparameters like `mask_in_chans=16` are from SAM code) + self.sam_prompt_encoder = PromptEncoder( + embed_dim=self.sam_prompt_embed_dim, + image_embedding_size=( + self.sam_image_embedding_size, + self.sam_image_embedding_size, + ), + input_image_size=(self.image_size, self.image_size), + mask_in_chans=16, + ) + self.sam_mask_decoder = SAM2MaskDecoder( + num_multimask_outputs=3, + transformer=SAM2TwoWayTransformer( + depth=2, + embedding_dim=self.sam_prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=self.sam_prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + use_high_res_features=self.use_high_res_features_in_sam, + iou_prediction_use_sigmoid=self.iou_prediction_use_sigmoid, + pred_obj_scores=self.pred_obj_scores, + pred_obj_scores_mlp=self.pred_obj_scores_mlp, + use_multimask_token_for_obj_ptr=self.use_multimask_token_for_obj_ptr, + **(self.sam_mask_decoder_extra_args or {}), + ) + if self.use_obj_ptrs_in_encoder: + # a linear projection on SAM output tokens to turn them into object pointers + self.obj_ptr_proj = torch.nn.Linear(self.hidden_dim, self.hidden_dim) + if self.use_mlp_for_obj_ptr_proj: + self.obj_ptr_proj = MLP(self.hidden_dim, self.hidden_dim, self.hidden_dim, 3) + else: + self.obj_ptr_proj = torch.nn.Identity() + if self.proj_tpos_enc_in_obj_ptrs: + # a linear projection on temporal positional encoding in object pointers to + # avoid potential interference with spatial positional encoding + self.obj_ptr_tpos_proj = torch.nn.Linear(self.hidden_dim, self.mem_dim) + else: + self.obj_ptr_tpos_proj = torch.nn.Identity() + + def _forward_sam_heads( + self, + backbone_features, + point_inputs=None, + mask_inputs=None, + high_res_features=None, + multimask_output=False, + ): + """Forward pass through SAM prompt encoders and mask heads. + + This method processes image features and optional point/mask inputs to generate object masks and scores. + + Args: + backbone_features (torch.Tensor): Image features with shape (B, C, H, W). + point_inputs (dict[str, torch.Tensor] | None): Dictionary containing point prompts with keys 'point_coords' + (Tensor of shape (B, P, 2) with float32 dtype, containing absolute pixel-unit coordinates in (x, y) + format for P input points) and 'point_labels' (Tensor of shape (B, P) with int32 dtype, where 1 means + positive clicks, 0 means negative clicks, and -1 means padding). + mask_inputs (torch.Tensor | None): Mask of shape (B, 1, H*16, W*16), float or bool, with the same spatial + size as the image. + high_res_features (list[torch.Tensor] | None): List of two feature maps with shapes (B, C, 4*H, 4*W) and (B, + C, 2*H, 2*W) respectively, used as high-resolution feature maps for SAM decoder. + multimask_output (bool): If True, output 3 candidate masks and their IoU estimates; if False, output only 1 + mask and its IoU estimate. + + Returns: + low_res_multimasks (torch.Tensor): Tensor of shape (B, M, H*4, W*4) with SAM output mask logits. + high_res_multimasks (torch.Tensor): Tensor of shape (B, M, H*16, W*16) with upsampled mask logits. + ious (torch.Tensor): Tensor of shape (B, M) with estimated IoU for each output mask. + low_res_masks (torch.Tensor): Tensor of shape (B, 1, H*4, W*4) with the best low-resolution mask. + high_res_masks (torch.Tensor): Tensor of shape (B, 1, H*16, W*16) with the best high-resolution mask. + obj_ptr (torch.Tensor): Tensor of shape (B, C) with object pointer vector for the output mask. + object_score_logits (torch.Tensor): Tensor of shape (B, 1) with object score logits. + + Examples: + >>> backbone_features = torch.rand(1, 256, 32, 32) + >>> point_inputs = {"point_coords": torch.rand(1, 2, 2), "point_labels": torch.tensor([[1, 0]])} + >>> mask_inputs = torch.rand(1, 1, 512, 512) + >>> results = model._forward_sam_heads(backbone_features, point_inputs, mask_inputs) + >>> ( + ... low_res_multimasks, + ... high_res_multimasks, + ... ious, + ... low_res_masks, + ... high_res_masks, + ... obj_ptr, + ... object_score_logits, + ... ) = results + """ + B = backbone_features.shape[0] + device = backbone_features.device + assert backbone_features.size(1) == self.sam_prompt_embed_dim + assert backbone_features.size(2) == self.sam_image_embedding_size + assert backbone_features.size(3) == self.sam_image_embedding_size + + # a) Handle point prompts + if point_inputs is not None: + sam_point_coords = point_inputs["point_coords"] + sam_point_labels = point_inputs["point_labels"] + assert sam_point_coords.shape[0] == B and sam_point_labels.shape[0] == B + else: + # If no points are provide, pad with an empty point (with label -1) + sam_point_coords = torch.zeros(B, 1, 2, device=device, dtype=backbone_features.dtype) + sam_point_labels = -torch.ones(B, 1, dtype=torch.int32, device=device) + + # b) Handle mask prompts + if mask_inputs is not None: + # If mask_inputs is provided, downsize it into low-res mask input if needed + # and feed it as a dense mask prompt into the SAM mask encoder + assert len(mask_inputs.shape) == 4 and mask_inputs.shape[:2] == (B, 1) + if mask_inputs.shape[-2:] != self.sam_prompt_encoder.mask_input_size: + sam_mask_prompt = F.interpolate( + mask_inputs.to(backbone_features.dtype), + size=self.sam_prompt_encoder.mask_input_size, + align_corners=False, + mode="bilinear", + antialias=True, # use antialias for downsampling + ) + else: + sam_mask_prompt = mask_inputs + else: + # Otherwise, simply feed None (and SAM's prompt encoder will add + # a learned `no_mask_embed` to indicate no mask input in this case). + sam_mask_prompt = None + + sparse_embeddings, dense_embeddings = self.sam_prompt_encoder( + points=(sam_point_coords, sam_point_labels), + boxes=None, + masks=sam_mask_prompt, + ) + low_res_multimasks, ious, sam_output_tokens, object_score_logits = self.sam_mask_decoder( + image_embeddings=backbone_features, + image_pe=self.sam_prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + repeat_image=False, # the image is already batched + high_res_features=high_res_features, + ) + if self.pred_obj_scores: + is_obj_appearing = object_score_logits > 0 + + # Spatial memory mask is a *hard* choice between obj and no obj, consistent with actual mask prediction + low_res_multimasks = torch.where(is_obj_appearing[:, None, None], low_res_multimasks, NO_OBJ_SCORE) + + # convert masks from possibly bfloat16 (or float16) to float32 + # (older PyTorch versions before 2.1 don't support `interpolate` on bf16) + high_res_multimasks = F.interpolate( + low_res_multimasks, + size=(self.image_size, self.image_size), + mode="bilinear", + align_corners=False, + ) + + sam_output_token = sam_output_tokens[:, 0] + if multimask_output: + # take the best mask prediction (with the highest IoU estimation) + best_iou_inds = torch.argmax(ious, dim=-1) + batch_inds = torch.arange(B, device=device) + low_res_masks = low_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1) + high_res_masks = high_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1) + if sam_output_tokens.size(1) > 1: + sam_output_token = sam_output_tokens[batch_inds, best_iou_inds] + else: + low_res_masks, high_res_masks = low_res_multimasks, high_res_multimasks + + # Extract object pointer from the SAM output token (with occlusion handling) + obj_ptr = self.obj_ptr_proj(sam_output_token) + if self.pred_obj_scores: + # Allow *soft* no obj ptr, unlike for masks + if self.soft_no_obj_ptr: + lambda_is_obj_appearing = object_score_logits.sigmoid() + else: + lambda_is_obj_appearing = is_obj_appearing.to(obj_ptr.dtype) + + if self.fixed_no_obj_ptr: + obj_ptr = lambda_is_obj_appearing * obj_ptr + obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr + return ( + low_res_multimasks, + high_res_multimasks, + ious, + low_res_masks, + high_res_masks, + obj_ptr, + object_score_logits, + ) + + def _use_mask_as_output(self, mask_inputs, backbone_features=None, high_res_features=None): + """Process mask inputs directly as output, bypassing SAM encoder/decoder.""" + # Use -10/+10 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid). + out_scale, out_bias = 20.0, -10.0 # sigmoid(-10.0)=4.5398e-05 + mask_inputs_float = mask_inputs.float() + high_res_masks = mask_inputs_float * out_scale + out_bias + low_res_masks = F.interpolate( + high_res_masks, + size=(high_res_masks.size(-2) // 4, high_res_masks.size(-1) // 4), + align_corners=False, + mode="bilinear", + antialias=True, # use antialias for downsampling + ) + # a dummy IoU prediction of all 1's under mask input + ious = mask_inputs.new_ones(mask_inputs.shape[0], 1).float() + if not self.use_obj_ptrs_in_encoder or backbone_features is None or high_res_features is None: + # all zeros as a dummy object pointer (of shape [B, C]) + obj_ptr = torch.zeros(mask_inputs.shape[0], self.hidden_dim, device=mask_inputs.device) + else: + # produce an object pointer using the SAM decoder from the mask input + _, _, _, _, _, obj_ptr, _ = self._forward_sam_heads( + backbone_features=backbone_features, + mask_inputs=self.mask_downsample(mask_inputs_float.to(backbone_features.dtype)), + high_res_features=high_res_features, + ) + # In this method, we are treating mask_input as output, e.g. using it directly to create spatial mem; + # Below, we follow the same design axiom to use mask_input to decide if obj appears or not instead of relying + # on the object_scores from the SAM decoder. + is_obj_appearing = torch.any(mask_inputs.flatten(1).float() > 0.0, dim=1) + is_obj_appearing = is_obj_appearing[..., None] + lambda_is_obj_appearing = is_obj_appearing.float() + object_score_logits = out_scale * lambda_is_obj_appearing + out_bias + if self.pred_obj_scores: + if self.fixed_no_obj_ptr: + obj_ptr = lambda_is_obj_appearing * obj_ptr + obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr + + return ( + low_res_masks, + high_res_masks, + ious, + low_res_masks, + high_res_masks, + obj_ptr, + object_score_logits, + ) + + def forward_image(self, img_batch: torch.Tensor): + """Process image batch through encoder to extract multi-level features for SAM model.""" + backbone_out = self.image_encoder(img_batch) + if self.use_high_res_features_in_sam: + # precompute projected level 0 and level 1 features in SAM decoder + # to avoid running it again on every SAM click + backbone_out["backbone_fpn"][0] = self.sam_mask_decoder.conv_s0(backbone_out["backbone_fpn"][0]) + backbone_out["backbone_fpn"][1] = self.sam_mask_decoder.conv_s1(backbone_out["backbone_fpn"][1]) + return backbone_out + + def _prepare_backbone_features(self, backbone_out, batch=1): + """Prepare and flatten visual features from the image backbone output for further processing.""" + if batch > 1: # expand features if there's more than one prompt + backbone_out = { + **backbone_out, + "backbone_fpn": [feat.expand(batch, -1, -1, -1) for feat in backbone_out["backbone_fpn"]], + "vision_pos_enc": [pos.expand(batch, -1, -1, -1) for pos in backbone_out["vision_pos_enc"]], + } + assert len(backbone_out["backbone_fpn"]) == len(backbone_out["vision_pos_enc"]) + assert len(backbone_out["backbone_fpn"]) >= self.num_feature_levels + + feature_maps = backbone_out["backbone_fpn"][-self.num_feature_levels :] + vision_pos_embeds = backbone_out["vision_pos_enc"][-self.num_feature_levels :] + + feat_sizes = [(x.shape[-2], x.shape[-1]) for x in vision_pos_embeds] + # flatten NxCxHxW to HWxNxC + vision_feats = [x.flatten(2).permute(2, 0, 1) for x in feature_maps] + vision_pos_embeds = [x.flatten(2).permute(2, 0, 1) for x in vision_pos_embeds] + return backbone_out, vision_feats, vision_pos_embeds, feat_sizes + + def _prepare_memory_conditioned_features( + self, + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + output_dict, + num_frames, + track_in_reverse=False, # tracking in reverse time order (for demo usage) + ): + """Prepare memory-conditioned features by fusing current frame's visual features with previous memories.""" + B = current_vision_feats[-1].size(1) # batch size on this frame + C = self.hidden_dim + H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size + device = current_vision_feats[-1].device + # The case of `self.num_maskmem == 0` below is primarily used for reproducing SAM on images. + # In this case, we skip the fusion with any memory. + if self.num_maskmem == 0: # Disable memory and skip fusion + return current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W) + num_obj_ptr_tokens = 0 + tpos_sign_mul = -1 if track_in_reverse else 1 + # Step 1: condition the visual features of the current frame on previous memories + if not is_init_cond_frame: + # Retrieve the memories encoded with the maskmem backbone + to_cat_memory, to_cat_memory_pos_embed = [], [] + # Add conditioning frame's output first (all cond frames have t_pos=0 for + # when getting temporal positional embedding below) + assert len(output_dict["cond_frame_outputs"]) > 0 + # Select a maximum number of temporally closest cond frames for cross attention + cond_outputs = output_dict["cond_frame_outputs"] + selected_cond_outputs, unselected_cond_outputs = select_closest_cond_frames( + frame_idx, cond_outputs, self.max_cond_frames_in_attn + ) + t_pos_and_prevs = [(0, out) for out in selected_cond_outputs.values()] + # Add last (self.num_maskmem - 1) frames before current frame for non-conditioning memory + # the earliest one has t_pos=1 and the latest one has t_pos=self.num_maskmem-1 + # We also allow taking the memory frame non-consecutively (with r>1), in which case + # we take (self.num_maskmem - 2) frames among every r-th frames plus the last frame. + r = 1 if self.training else self.memory_temporal_stride_for_eval + for t_pos in range(1, self.num_maskmem): + t_rel = self.num_maskmem - t_pos # how many frames before current frame + if t_rel == 1: + # for t_rel == 1, we take the last frame (regardless of r) + prev_frame_idx = frame_idx + t_rel if track_in_reverse else frame_idx - t_rel + elif not track_in_reverse: + # first find the nearest frame among every r-th frames before this frame + # for r=1, this would be (frame_idx - 2) + prev_frame_idx = ((frame_idx - 2) // r) * r + # then seek further among every r-th frames + prev_frame_idx = prev_frame_idx - (t_rel - 2) * r + else: + # first find the nearest frame among every r-th frames after this frame + # for r=1, this would be (frame_idx + 2) + prev_frame_idx = -(-(frame_idx + 2) // r) * r + # then seek further among every r-th frames + prev_frame_idx = prev_frame_idx + (t_rel - 2) * r + out = output_dict["non_cond_frame_outputs"].get(prev_frame_idx, None) + if out is None: + # If an unselected conditioning frame is among the last (self.num_maskmem - 1) + # frames, we still attend to it as if it's a non-conditioning frame. + out = unselected_cond_outputs.get(prev_frame_idx, None) + t_pos_and_prevs.append((t_pos, out)) + + for t_pos, prev in t_pos_and_prevs: + if prev is None: + continue # skip padding frames + # "maskmem_features" might have been offloaded to CPU in demo use cases, + # so we load it back to inference device (it's a no-op if it's already on device). + feats = prev["maskmem_features"].to(device=device, non_blocking=device.type == "cuda") + to_cat_memory.append(feats.flatten(2).permute(2, 0, 1)) + # Spatial positional encoding (it might have been offloaded to CPU in eval) + maskmem_enc = prev["maskmem_pos_enc"][-1].to(device=device) + maskmem_enc = maskmem_enc.flatten(2).permute(2, 0, 1) + # Temporal positional encoding + maskmem_enc = maskmem_enc + self.maskmem_tpos_enc[self.num_maskmem - t_pos - 1] + to_cat_memory_pos_embed.append(maskmem_enc) + + # Construct the list of past object pointers + if self.use_obj_ptrs_in_encoder: + max_obj_ptrs_in_encoder = min(num_frames, self.max_obj_ptrs_in_encoder) + # First add those object pointers from selected conditioning frames + # (optionally, only include object pointers in the past during evaluation) + if not self.training and self.only_obj_ptrs_in_the_past_for_eval: + ptr_cond_outputs = { + t: out + for t, out in selected_cond_outputs.items() + if (t >= frame_idx if track_in_reverse else t <= frame_idx) + } + else: + ptr_cond_outputs = selected_cond_outputs + pos_and_ptrs = [ + # Temporal pos encoding contains how far away each pointer is from current frame + ( + ( + (frame_idx - t) * tpos_sign_mul + if self.use_signed_tpos_enc_to_obj_ptrs + else abs(frame_idx - t) + ), + out["obj_ptr"], + ) + for t, out in ptr_cond_outputs.items() + ] + # Add up to (max_obj_ptrs_in_encoder - 1) non-conditioning frames before current frame + for t_diff in range(1, max_obj_ptrs_in_encoder): + t = frame_idx + t_diff if track_in_reverse else frame_idx - t_diff + if t < 0 or (num_frames is not None and t >= num_frames): + break + out = output_dict["non_cond_frame_outputs"].get(t, unselected_cond_outputs.get(t, None)) + if out is not None: + pos_and_ptrs.append((t_diff, out["obj_ptr"])) + # If we have at least one object pointer, add them to the across attention + if pos_and_ptrs: + pos_list, ptrs_list = zip(*pos_and_ptrs) + # stack object pointers along dim=0 into [ptr_seq_len, B, C] shape + obj_ptrs = torch.stack(ptrs_list, dim=0) + # a temporal positional embedding based on how far each object pointer is from + # the current frame (sine embedding normalized by the max pointer num). + if self.add_tpos_enc_to_obj_ptrs: + t_diff_max = max_obj_ptrs_in_encoder - 1 + tpos_dim = C if self.proj_tpos_enc_in_obj_ptrs else self.mem_dim + obj_pos = torch.tensor(pos_list, device=device, dtype=current_vision_feats[-1].dtype) + obj_pos = get_1d_sine_pe(obj_pos / t_diff_max, dim=tpos_dim) + obj_pos = self.obj_ptr_tpos_proj(obj_pos) + obj_pos = obj_pos.unsqueeze(1).expand(-1, B, self.mem_dim) + else: + obj_pos = obj_ptrs.new_zeros(len(pos_list), B, self.mem_dim) + if self.mem_dim < C: + # split a pointer into (C // self.mem_dim) tokens for self.mem_dim < C + obj_ptrs = obj_ptrs.reshape(-1, B, C // self.mem_dim, self.mem_dim) + obj_ptrs = obj_ptrs.permute(0, 2, 1, 3).flatten(0, 1) + obj_pos = obj_pos.repeat_interleave(C // self.mem_dim, dim=0) + to_cat_memory.append(obj_ptrs) + to_cat_memory_pos_embed.append(obj_pos) + num_obj_ptr_tokens = obj_ptrs.shape[0] + else: + num_obj_ptr_tokens = 0 + else: + # for initial conditioning frames, encode them without using any previous memory + if self.directly_add_no_mem_embed: + # directly add no-mem embedding (instead of using the transformer encoder) + pix_feat_with_mem = current_vision_feats[-1] + self.no_mem_embed + pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W) + return pix_feat_with_mem + + # Use a dummy token on the first frame (to avoid empty memory input to transformer encoder) + to_cat_memory = [self.no_mem_embed.expand(1, B, self.mem_dim)] + to_cat_memory_pos_embed = [self.no_mem_pos_enc.expand(1, B, self.mem_dim)] + + # Step 2: Concatenate the memories and forward through the transformer encoder + memory = torch.cat(to_cat_memory, dim=0) + memory_pos_embed = torch.cat(to_cat_memory_pos_embed, dim=0) + + pix_feat_with_mem = self.memory_attention( + curr=current_vision_feats, + curr_pos=current_vision_pos_embeds, + memory=memory, + memory_pos=memory_pos_embed, + num_obj_ptr_tokens=num_obj_ptr_tokens, + ) + # Reshape output (HW)BC => BCHW + pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W) + return pix_feat_with_mem + + def _encode_new_memory( + self, + current_vision_feats, + feat_sizes, + pred_masks_high_res, + object_score_logits, + is_mask_from_pts, + ): + """Encode frame features and masks into a new memory representation for video segmentation.""" + B = current_vision_feats[-1].size(1) # batch size on this frame + C = self.hidden_dim + H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size + # top-level feature, (HW)BC => BCHW + pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W) + if self.non_overlap_masks_for_mem_enc and not self.training: + # optionally, apply non-overlapping constraints to the masks (it's applied + # in the batch dimension and should only be used during eval, where all + # the objects come from the same video under batch size 1). + pred_masks_high_res = self._apply_non_overlapping_constraints(pred_masks_high_res) + # scale the raw mask logits with a temperature before applying sigmoid + binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts + if binarize and not self.training: + mask_for_mem = (pred_masks_high_res > 0).to(pix_feat.dtype) + else: + # apply sigmoid on the raw mask logits to turn them into range (0, 1) + mask_for_mem = torch.sigmoid(pred_masks_high_res) + # apply scale and bias terms to the sigmoid probabilities + if self.sigmoid_scale_for_mem_enc != 1.0: + mask_for_mem = mask_for_mem * self.sigmoid_scale_for_mem_enc + if self.sigmoid_bias_for_mem_enc != 0.0: + mask_for_mem = mask_for_mem + self.sigmoid_bias_for_mem_enc + maskmem_out = self.memory_encoder(pix_feat, mask_for_mem, skip_mask_sigmoid=True) # sigmoid already applied + maskmem_features = maskmem_out["vision_features"] + # add a no-object embedding to the spatial memory to indicate that the frame + # is predicted to be occluded (i.e. no object is appearing in the frame) + if self.no_obj_embed_spatial is not None: + is_obj_appearing = (object_score_logits > 0).float() + maskmem_features += (1 - is_obj_appearing[..., None, None]) * self.no_obj_embed_spatial[ + ..., None, None + ].expand(*maskmem_features.shape) + + return maskmem_features, maskmem_out["vision_pos_enc"] + + def _track_step( + self, + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + point_inputs, + mask_inputs, + output_dict, + num_frames, + track_in_reverse, + prev_sam_mask_logits, + ): + """Perform a single tracking step, updating object masks and memory features based on current frame inputs.""" + # High-resolution feature maps for the SAM head, reshape (HW)BC => BCHW + if len(current_vision_feats) > 1: + high_res_features = [ + x.permute(1, 2, 0).view(x.size(1), x.size(2), *s) + for x, s in zip(current_vision_feats[:-1], feat_sizes[:-1]) + ] + else: + high_res_features = None + if mask_inputs is not None and self.use_mask_input_as_output_without_sam: + # When use_mask_input_as_output_without_sam=True, we directly output the mask input + # (see it as a GT mask) without using a SAM prompt encoder + mask decoder. + pix_feat = current_vision_feats[-1].permute(1, 2, 0) + pix_feat = pix_feat.view(-1, self.hidden_dim, *feat_sizes[-1]) + sam_outputs = self._use_mask_as_output(mask_inputs, pix_feat, high_res_features) + else: + # Fuse visual features with previous memory features in the memory bank + pix_feat = self._prepare_memory_conditioned_features( + frame_idx=frame_idx, + is_init_cond_frame=is_init_cond_frame, + current_vision_feats=current_vision_feats[-1:], + current_vision_pos_embeds=current_vision_pos_embeds[-1:], + feat_sizes=feat_sizes[-1:], + output_dict=output_dict, + num_frames=num_frames, + track_in_reverse=track_in_reverse, + ) + # apply SAM-style segmentation head + # here we might feed previously predicted low-res SAM mask logits into the SAM mask decoder, + # e.g. in demo where such logits come from earlier interaction instead of correction sampling + # (in this case, any `mask_inputs` shouldn't reach here as they are sent to _use_mask_as_output instead) + if prev_sam_mask_logits is not None: + assert point_inputs is not None and mask_inputs is None + mask_inputs = prev_sam_mask_logits + multimask_output = self._use_multimask(is_init_cond_frame, point_inputs) + sam_outputs = self._forward_sam_heads( + backbone_features=pix_feat, + point_inputs=point_inputs, + mask_inputs=mask_inputs, + high_res_features=high_res_features, + multimask_output=multimask_output, + ) + return sam_outputs, high_res_features, pix_feat + + def _encode_memory_in_output( + self, + current_vision_feats, + feat_sizes, + point_inputs, + run_mem_encoder, + high_res_masks, + object_score_logits, + current_out, + ): + """Run memory encoder on predicted mask to encode it into a new memory feature for future frames.""" + if run_mem_encoder and self.num_maskmem > 0: + maskmem_features, maskmem_pos_enc = self._encode_new_memory( + current_vision_feats=current_vision_feats, + feat_sizes=feat_sizes, + pred_masks_high_res=high_res_masks, + object_score_logits=object_score_logits, + is_mask_from_pts=(point_inputs is not None), + ) + current_out["maskmem_features"] = maskmem_features + current_out["maskmem_pos_enc"] = maskmem_pos_enc + else: + current_out["maskmem_features"] = None + current_out["maskmem_pos_enc"] = None + + def track_step( + self, + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + point_inputs, + mask_inputs, + output_dict, + num_frames, + track_in_reverse=False, # tracking in reverse time order (for demo usage) + # Whether to run the memory encoder on the predicted masks. Sometimes we might want + # to skip the memory encoder with `run_mem_encoder=False`. For example, + # in demo we might call `track_step` multiple times for each user click, + # and only encode the memory when the user finalizes their clicks. And in ablation + # settings like SAM training on static images, we don't need the memory encoder. + run_mem_encoder=True, + # The previously predicted SAM mask logits (which can be fed together with new clicks in demo). + prev_sam_mask_logits=None, + ): + """Perform a single tracking step, updating object masks and memory features based on current frame inputs.""" + sam_outputs, _, _ = self._track_step( + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + point_inputs, + mask_inputs, + output_dict, + num_frames, + track_in_reverse, + prev_sam_mask_logits, + ) + _, _, _, low_res_masks, high_res_masks, obj_ptr, object_score_logits = sam_outputs + + current_out = { + "pred_masks": low_res_masks, + "pred_masks_high_res": high_res_masks, + "obj_ptr": obj_ptr, + } + if not self.training: + # Only add this in inference (to avoid unused param in activation checkpointing; + # it's mainly used in the demo to encode spatial memories w/ consolidated masks) + current_out["object_score_logits"] = object_score_logits + + # Run memory encoder on the predicted mask to encode it into a new memory feature (for use in future frames) + self._encode_memory_in_output( + current_vision_feats, + feat_sizes, + point_inputs, + run_mem_encoder, + high_res_masks, + object_score_logits, + current_out, + ) + + return current_out + + def _use_multimask(self, is_init_cond_frame, point_inputs): + """Determine whether to use multiple mask outputs in the SAM head based on configuration and inputs.""" + num_pts = 0 if point_inputs is None else point_inputs["point_labels"].size(1) + return ( + self.multimask_output_in_sam + and (is_init_cond_frame or self.multimask_output_for_tracking) + and (self.multimask_min_pt_num <= num_pts <= self.multimask_max_pt_num) + ) + + @staticmethod + def _apply_non_overlapping_constraints(pred_masks): + """Apply non-overlapping constraints to masks, keeping the highest scoring object per location.""" + batch_size = pred_masks.shape[0] + if batch_size < 2: + return pred_masks + + device = pred_masks.device + # "max_obj_inds": object index of the object with the highest score at each location + max_obj_inds = pred_masks.max(dim=0, keepdim=True).indices + # "batch_obj_inds": object index of each object slice (along dim 0) in `pred_masks` + batch_obj_inds = torch.arange(batch_size, device=device)[:, None, None, None] + keep = max_obj_inds == batch_obj_inds + # suppress overlapping regions' scores below -10.0 so that the foreground regions + # don't overlap (here sigmoid(-10.0)=4.5398e-05) + pred_masks = torch.where(keep, pred_masks, torch.clamp(pred_masks, max=-10.0)) + return pred_masks + + def set_binarize(self, binarize=False): + """Set binarize for VideoPredictor.""" + self.binarize_mask_from_pts_for_mem_enc = binarize + + def set_imgsz(self, imgsz): + """Set image size to make model compatible with different image sizes.""" + if hasattr(self.image_encoder, "set_imgsz"): + self.image_encoder.set_imgsz(imgsz) + self.image_size = imgsz[0] + self.sam_prompt_encoder.input_image_size = imgsz + self.sam_prompt_encoder.image_embedding_size = [ + x // self.backbone_stride for x in imgsz + ] # fixed ViT patch size of 16 + self.sam_prompt_encoder.mask_input_size = [ + x // self.backbone_stride * 4 for x in imgsz + ] # fixed ViT patch size of 16 + self.sam_image_embedding_size = self.image_size // self.backbone_stride # update image embedding size + + +class SAM3Model(SAM2Model): + """SAM3Model class for Segment Anything Model 3 with memory-based video object segmentation capabilities.""" + + def __init__( + self, + image_encoder, + memory_attention, + memory_encoder, + num_maskmem=7, + image_size=1008, + backbone_stride=14, + sigmoid_scale_for_mem_enc=1, + sigmoid_bias_for_mem_enc=0, + binarize_mask_from_pts_for_mem_enc=False, + use_mask_input_as_output_without_sam=False, + max_cond_frames_in_attn=-1, + directly_add_no_mem_embed=False, + use_high_res_features_in_sam=False, + multimask_output_in_sam=False, + multimask_min_pt_num=1, + multimask_max_pt_num=1, + multimask_output_for_tracking=False, + use_multimask_token_for_obj_ptr: bool = False, + iou_prediction_use_sigmoid=False, + memory_temporal_stride_for_eval=1, + non_overlap_masks_for_mem_enc=False, + use_obj_ptrs_in_encoder=False, + max_obj_ptrs_in_encoder=16, + add_tpos_enc_to_obj_ptrs=True, + proj_tpos_enc_in_obj_ptrs=False, + use_signed_tpos_enc_to_obj_ptrs=False, + only_obj_ptrs_in_the_past_for_eval=False, + pred_obj_scores: bool = False, + pred_obj_scores_mlp: bool = False, + fixed_no_obj_ptr: bool = False, + soft_no_obj_ptr: bool = False, + use_mlp_for_obj_ptr_proj: bool = False, + no_obj_embed_spatial: bool = False, + sam_mask_decoder_extra_args=None, + compile_image_encoder: bool = False, + ): + """SAM3Model class for Segment Anything Model 3 with memory-based video object segmentation capabilities.""" + super().__init__( + image_encoder, + memory_attention, + memory_encoder, + num_maskmem, + image_size, + backbone_stride, + sigmoid_scale_for_mem_enc, + sigmoid_bias_for_mem_enc, + binarize_mask_from_pts_for_mem_enc, + use_mask_input_as_output_without_sam, + max_cond_frames_in_attn, + directly_add_no_mem_embed, + use_high_res_features_in_sam, + multimask_output_in_sam, + multimask_min_pt_num, + multimask_max_pt_num, + multimask_output_for_tracking, + use_multimask_token_for_obj_ptr, + iou_prediction_use_sigmoid, + memory_temporal_stride_for_eval, + non_overlap_masks_for_mem_enc, + use_obj_ptrs_in_encoder, + max_obj_ptrs_in_encoder, + add_tpos_enc_to_obj_ptrs, + proj_tpos_enc_in_obj_ptrs, + use_signed_tpos_enc_to_obj_ptrs, + only_obj_ptrs_in_the_past_for_eval, + pred_obj_scores, + pred_obj_scores_mlp, + fixed_no_obj_ptr, + soft_no_obj_ptr, + use_mlp_for_obj_ptr_proj, + no_obj_embed_spatial, + sam_mask_decoder_extra_args, + compile_image_encoder, + ) + self.sam_mask_decoder = SAM2MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=self.sam_prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=self.sam_prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + use_high_res_features=self.use_high_res_features_in_sam, + iou_prediction_use_sigmoid=self.iou_prediction_use_sigmoid, + pred_obj_scores=self.pred_obj_scores, + pred_obj_scores_mlp=self.pred_obj_scores_mlp, + use_multimask_token_for_obj_ptr=self.use_multimask_token_for_obj_ptr, + **(self.sam_mask_decoder_extra_args or {}), + ) + + def forward_image(self, img_batch: torch.Tensor): + """Process image batch through encoder to extract multi-level features for SAM model.""" + backbone_out = self.image_encoder.forward_image_sam2(img_batch) + if self.use_high_res_features_in_sam: + # precompute projected level 0 and level 1 features in SAM decoder + # to avoid running it again on every SAM click + backbone_out["backbone_fpn"][0] = self.sam_mask_decoder.conv_s0(backbone_out["backbone_fpn"][0]) + backbone_out["backbone_fpn"][1] = self.sam_mask_decoder.conv_s1(backbone_out["backbone_fpn"][1]) + return backbone_out + + def set_imgsz(self, imgsz: tuple[int, int]): + """Set the image size for the model and mask downsampler.""" + super().set_imgsz(imgsz) + self.memory_encoder.mask_downsampler.interpol_size = [size // 14 * 16 for size in imgsz] + + @staticmethod + def _suppress_shrinked_masks(pred_masks, new_pred_masks, shrink_threshold=0.3): + """Suppress masks that shrink in area after applying pixelwise non-overlapping constraints.""" + area_before = (pred_masks > 0).sum(dim=(-1, -2)) + area_after = (new_pred_masks > 0).sum(dim=(-1, -2)) + area_before = torch.clamp(area_before, min=1.0) + area_ratio = area_after / area_before + keep = area_ratio >= shrink_threshold + keep_mask = keep[..., None, None].expand_as(pred_masks) + pred_masks_after = torch.where(keep_mask, pred_masks, torch.clamp(pred_masks, max=-10.0)) + return pred_masks_after + + def _suppress_object_pw_area_shrinkage(self, pred_masks): + """This function suppresses masks that shrink in area after applying pixelwise non-overlapping constraints. Note + that the final output can still be overlapping. + """ + # Apply pixel-wise non-overlapping constraint based on mask scores + pixel_level_non_overlapping_masks = self._apply_non_overlapping_constraints(pred_masks) + # Fully suppress masks with high shrinkage (probably noisy) based on the pixel wise non-overlapping constraints + # NOTE: The output of this function can be a no op if none of the masks shrink by a large factor. + pred_masks = self._suppress_shrinked_masks(pred_masks, pixel_level_non_overlapping_masks) + return pred_masks diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/tiny_encoder.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/tiny_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..6dd108fdce9abc66ba11b6caac3e7d7aff089819 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/tiny_encoder.py @@ -0,0 +1,985 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# -------------------------------------------------------- +# TinyViT Model Architecture +# Copyright (c) 2022 Microsoft +# Adapted from LeViT and Swin Transformer +# LeViT: (https://github.com/facebookresearch/levit) +# Swin: (https://github.com/microsoft/swin-transformer) +# Build the TinyViT Model +# -------------------------------------------------------- + +from __future__ import annotations + +import itertools + +import torch +import torch.nn.functional as F +from torch import nn + +from ultralytics.nn.modules import LayerNorm2d +from ultralytics.utils.instance import to_2tuple +from ultralytics.utils.torch_utils import TORCH_1_11 + +CKPT_KWARGS = {"use_reentrant": False} if TORCH_1_11 else {} # use_reentrant added in torch 1.11, required in 2.9 + + +class Conv2d_BN(torch.nn.Sequential): + """A sequential container that performs 2D convolution followed by batch normalization. + + This module combines a 2D convolution layer with batch normalization, providing a common building block for + convolutional neural networks. The batch normalization weights and biases are initialized to specific values for + optimal training performance. + + Attributes: + c (torch.nn.Conv2d): 2D convolution layer. + bn (torch.nn.BatchNorm2d): Batch normalization layer. + + Examples: + >>> conv_bn = Conv2d_BN(3, 64, ks=3, stride=1, pad=1) + >>> input_tensor = torch.randn(1, 3, 224, 224) + >>> output = conv_bn(input_tensor) + >>> print(output.shape) + torch.Size([1, 64, 224, 224]) + """ + + def __init__( + self, + a: int, + b: int, + ks: int = 1, + stride: int = 1, + pad: int = 0, + dilation: int = 1, + groups: int = 1, + bn_weight_init: float = 1, + ): + """Initialize a sequential container with 2D convolution followed by batch normalization. + + Args: + a (int): Number of input channels. + b (int): Number of output channels. + ks (int, optional): Kernel size for the convolution. + stride (int, optional): Stride for the convolution. + pad (int, optional): Padding for the convolution. + dilation (int, optional): Dilation factor for the convolution. + groups (int, optional): Number of groups for the convolution. + bn_weight_init (float, optional): Initial value for batch normalization weight. + """ + super().__init__() + self.add_module("c", torch.nn.Conv2d(a, b, ks, stride, pad, dilation, groups, bias=False)) + bn = torch.nn.BatchNorm2d(b) + torch.nn.init.constant_(bn.weight, bn_weight_init) + torch.nn.init.constant_(bn.bias, 0) + self.add_module("bn", bn) + + +class PatchEmbed(nn.Module): + """Embed images into patches and project them into a specified embedding dimension. + + This module converts input images into patch embeddings using a sequence of convolutional layers, effectively + downsampling the spatial dimensions while increasing the channel dimension. + + Attributes: + patches_resolution (tuple[int, int]): Resolution of the patches after embedding. + num_patches (int): Total number of patches. + in_chans (int): Number of input channels. + embed_dim (int): Dimension of the embedding. + seq (nn.Sequential): Sequence of convolutional and activation layers for patch embedding. + + Examples: + >>> import torch + >>> patch_embed = PatchEmbed(in_chans=3, embed_dim=96, resolution=224, activation=nn.GELU) + >>> x = torch.randn(1, 3, 224, 224) + >>> output = patch_embed(x) + >>> print(output.shape) + torch.Size([1, 96, 56, 56]) + """ + + def __init__(self, in_chans: int, embed_dim: int, resolution: int, activation): + """Initialize patch embedding with convolutional layers for image-to-patch conversion and projection. + + Args: + in_chans (int): Number of input channels. + embed_dim (int): Dimension of the embedding. + resolution (int): Input image resolution. + activation (nn.Module): Activation function to use between convolutions. + """ + super().__init__() + img_size: tuple[int, int] = to_2tuple(resolution) + self.patches_resolution = (img_size[0] // 4, img_size[1] // 4) + self.num_patches = self.patches_resolution[0] * self.patches_resolution[1] + self.in_chans = in_chans + self.embed_dim = embed_dim + n = embed_dim + self.seq = nn.Sequential( + Conv2d_BN(in_chans, n // 2, 3, 2, 1), + activation(), + Conv2d_BN(n // 2, n, 3, 2, 1), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Process input tensor through patch embedding sequence, converting images to patch embeddings.""" + return self.seq(x) + + +class MBConv(nn.Module): + """Mobile Inverted Bottleneck Conv (MBConv) layer, part of the EfficientNet architecture. + + This module implements the mobile inverted bottleneck convolution with expansion, depthwise convolution, and + projection phases, along with residual connections for improved gradient flow. + + Attributes: + in_chans (int): Number of input channels. + hidden_chans (int): Number of hidden channels after expansion. + out_chans (int): Number of output channels. + conv1 (Conv2d_BN): First convolutional layer for channel expansion. + act1 (nn.Module): First activation function. + conv2 (Conv2d_BN): Depthwise convolutional layer. + act2 (nn.Module): Second activation function. + conv3 (Conv2d_BN): Final convolutional layer for projection. + act3 (nn.Module): Third activation function. + drop_path (nn.Module): Drop path layer (Identity for inference). + + Examples: + >>> in_chans, out_chans = 64, 64 + >>> mbconv = MBConv(in_chans, out_chans, expand_ratio=4, activation=nn.ReLU, drop_path=0.1) + >>> x = torch.randn(1, in_chans, 56, 56) + >>> output = mbconv(x) + >>> print(output.shape) + torch.Size([1, 64, 56, 56]) + """ + + def __init__(self, in_chans: int, out_chans: int, expand_ratio: float, activation, drop_path: float): + """Initialize the MBConv layer with specified input/output channels, expansion ratio, and activation. + + Args: + in_chans (int): Number of input channels. + out_chans (int): Number of output channels. + expand_ratio (float): Channel expansion ratio for the hidden layer. + activation (nn.Module): Activation function to use. + drop_path (float): Drop path rate for stochastic depth. + """ + super().__init__() + self.in_chans = in_chans + self.hidden_chans = int(in_chans * expand_ratio) + self.out_chans = out_chans + + self.conv1 = Conv2d_BN(in_chans, self.hidden_chans, ks=1) + self.act1 = activation() + + self.conv2 = Conv2d_BN(self.hidden_chans, self.hidden_chans, ks=3, stride=1, pad=1, groups=self.hidden_chans) + self.act2 = activation() + + self.conv3 = Conv2d_BN(self.hidden_chans, out_chans, ks=1, bn_weight_init=0.0) + self.act3 = activation() + + # NOTE: `DropPath` is needed only for training. + # self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.drop_path = nn.Identity() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Implement the forward pass of MBConv, applying convolutions and skip connection.""" + shortcut = x + x = self.conv1(x) + x = self.act1(x) + x = self.conv2(x) + x = self.act2(x) + x = self.conv3(x) + x = self.drop_path(x) + x += shortcut + return self.act3(x) + + +class PatchMerging(nn.Module): + """Merge neighboring patches in the feature map and project to a new dimension. + + This class implements a patch merging operation that combines spatial information and adjusts the feature dimension + using a series of convolutional layers with batch normalization. It effectively reduces spatial resolution while + potentially increasing channel dimensions. + + Attributes: + input_resolution (tuple[int, int]): The input resolution (height, width) of the feature map. + dim (int): The input dimension of the feature map. + out_dim (int): The output dimension after merging and projection. + act (nn.Module): The activation function used between convolutions. + conv1 (Conv2d_BN): The first convolutional layer for dimension projection. + conv2 (Conv2d_BN): The second convolutional layer for spatial merging. + conv3 (Conv2d_BN): The third convolutional layer for final projection. + + Examples: + >>> input_resolution = (56, 56) + >>> patch_merging = PatchMerging(input_resolution, dim=64, out_dim=128, activation=nn.ReLU) + >>> x = torch.randn(4, 64, 56, 56) + >>> output = patch_merging(x) + >>> print(output.shape) + torch.Size([4, 784, 128]) + """ + + def __init__(self, input_resolution: tuple[int, int], dim: int, out_dim: int, activation): + """Initialize the PatchMerging module for merging and projecting neighboring patches in feature maps. + + Args: + input_resolution (tuple[int, int]): The input resolution (height, width) of the feature map. + dim (int): The input dimension of the feature map. + out_dim (int): The output dimension after merging and projection. + activation (nn.Module): The activation function used between convolutions. + """ + super().__init__() + + self.input_resolution = input_resolution + self.dim = dim + self.out_dim = out_dim + self.act = activation() + self.conv1 = Conv2d_BN(dim, out_dim, 1, 1, 0) + stride_c = 1 if out_dim in {320, 448, 576} else 2 + self.conv2 = Conv2d_BN(out_dim, out_dim, 3, stride_c, 1, groups=out_dim) + self.conv3 = Conv2d_BN(out_dim, out_dim, 1, 1, 0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply patch merging and dimension projection to the input feature map.""" + if x.ndim == 3: + H, W = self.input_resolution + B = len(x) + # (B, C, H, W) + x = x.view(B, H, W, -1).permute(0, 3, 1, 2) + + x = self.conv1(x) + x = self.act(x) + + x = self.conv2(x) + x = self.act(x) + x = self.conv3(x) + return x.flatten(2).transpose(1, 2) + + +class ConvLayer(nn.Module): + """Convolutional Layer featuring multiple MobileNetV3-style inverted bottleneck convolutions (MBConv). + + This layer optionally applies downsample operations to the output and supports gradient checkpointing for memory + efficiency during training. + + Attributes: + dim (int): Dimensionality of the input and output. + input_resolution (tuple[int, int]): Resolution of the input image. + depth (int): Number of MBConv layers in the block. + use_checkpoint (bool): Whether to use gradient checkpointing to save memory. + blocks (nn.ModuleList): List of MBConv layers. + downsample (nn.Module | None): Function for downsampling the output. + + Examples: + >>> input_tensor = torch.randn(1, 64, 56, 56) + >>> conv_layer = ConvLayer(64, (56, 56), depth=3, activation=nn.ReLU) + >>> output = conv_layer(input_tensor) + >>> print(output.shape) + torch.Size([1, 64, 56, 56]) + """ + + def __init__( + self, + dim: int, + input_resolution: tuple[int, int], + depth: int, + activation, + drop_path: float | list[float] = 0.0, + downsample: nn.Module | None = None, + use_checkpoint: bool = False, + out_dim: int | None = None, + conv_expand_ratio: float = 4.0, + ): + """Initialize the ConvLayer with the given dimensions and settings. + + This layer consists of multiple MobileNetV3-style inverted bottleneck convolutions (MBConv) and optionally + applies downsampling to the output. + + Args: + dim (int): The dimensionality of the input and output. + input_resolution (tuple[int, int]): The resolution of the input image. + depth (int): The number of MBConv layers in the block. + activation (nn.Module): Activation function applied after each convolution. + drop_path (float | list[float], optional): Drop path rate. Single float or a list of floats for each MBConv. + downsample (nn.Module | None, optional): Function for downsampling the output. None to skip downsampling. + use_checkpoint (bool, optional): Whether to use gradient checkpointing to save memory. + out_dim (int | None, optional): Output dimensions. None means it will be the same as `dim`. + conv_expand_ratio (float, optional): Expansion ratio for the MBConv layers. + """ + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.depth = depth + self.use_checkpoint = use_checkpoint + + # Build blocks + self.blocks = nn.ModuleList( + [ + MBConv( + dim, + dim, + conv_expand_ratio, + activation, + drop_path[i] if isinstance(drop_path, list) else drop_path, + ) + for i in range(depth) + ] + ) + + # Patch merging layer + self.downsample = ( + None + if downsample is None + else downsample(input_resolution, dim=dim, out_dim=out_dim, activation=activation) + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Process input through convolutional layers, applying MBConv blocks and optional downsampling.""" + for blk in self.blocks: + x = torch.utils.checkpoint.checkpoint(blk, x, **CKPT_KWARGS) if self.use_checkpoint else blk(x) + return x if self.downsample is None else self.downsample(x) + + +class MLP(nn.Module): + """Multi-layer Perceptron (MLP) module for transformer architectures. + + This module applies layer normalization, two fully-connected layers with an activation function in between, and + dropout. It is commonly used in transformer-based architectures for processing token embeddings. + + Attributes: + norm (nn.LayerNorm): Layer normalization applied to the input. + fc1 (nn.Linear): First fully-connected layer. + fc2 (nn.Linear): Second fully-connected layer. + act (nn.Module): Activation function applied after the first fully-connected layer. + drop (nn.Dropout): Dropout layer applied after the activation function. + + Examples: + >>> import torch + >>> from torch import nn + >>> mlp = MLP(in_features=256, hidden_features=512, out_features=256, activation=nn.GELU, drop=0.1) + >>> x = torch.randn(32, 100, 256) + >>> output = mlp(x) + >>> print(output.shape) + torch.Size([32, 100, 256]) + """ + + def __init__( + self, + in_features: int, + hidden_features: int | None = None, + out_features: int | None = None, + activation=nn.GELU, + drop: float = 0.0, + ): + """Initialize a multi-layer perceptron with configurable input, hidden, and output dimensions. + + Args: + in_features (int): Number of input features. + hidden_features (int | None, optional): Number of hidden features. + out_features (int | None, optional): Number of output features. + activation (nn.Module): Activation function applied after the first fully-connected layer. + drop (float, optional): Dropout probability. + """ + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.norm = nn.LayerNorm(in_features) + self.fc1 = nn.Linear(in_features, hidden_features) + self.fc2 = nn.Linear(hidden_features, out_features) + self.act = activation() + self.drop = nn.Dropout(drop) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply MLP operations: layer norm, FC layers, activation, and dropout to the input tensor.""" + x = self.norm(x) + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + return self.drop(x) + + +class Attention(torch.nn.Module): + """Multi-head attention module with spatial awareness and trainable attention biases. + + This module implements a multi-head attention mechanism with support for spatial awareness, applying attention + biases based on spatial resolution. It includes trainable attention biases for each unique offset between spatial + positions in the resolution grid. + + Attributes: + num_heads (int): Number of attention heads. + scale (float): Scaling factor for attention scores. + key_dim (int): Dimensionality of the keys and queries. + nh_kd (int): Product of num_heads and key_dim. + d (int): Dimensionality of the value vectors. + dh (int): Product of d and num_heads. + attn_ratio (float): Attention ratio affecting the dimensions of the value vectors. + norm (nn.LayerNorm): Layer normalization applied to input. + qkv (nn.Linear): Linear layer for computing query, key, and value projections. + proj (nn.Linear): Linear layer for final projection. + attention_biases (nn.Parameter): Learnable attention biases. + attention_bias_idxs (torch.Tensor): Indices for attention biases. + ab (torch.Tensor): Cached attention biases for inference, deleted during training. + + Examples: + >>> attn = Attention(dim=256, key_dim=64, num_heads=8, resolution=(14, 14)) + >>> x = torch.randn(1, 196, 256) + >>> output = attn(x) + >>> print(output.shape) + torch.Size([1, 196, 256]) + """ + + def __init__( + self, + dim: int, + key_dim: int, + num_heads: int = 8, + attn_ratio: float = 4, + resolution: tuple[int, int] = (14, 14), + ): + """Initialize the Attention module for multi-head attention with spatial awareness. + + This module implements a multi-head attention mechanism with support for spatial awareness, applying attention + biases based on spatial resolution. It includes trainable attention biases for each unique offset between + spatial positions in the resolution grid. + + Args: + dim (int): The dimensionality of the input and output. + key_dim (int): The dimensionality of the keys and queries. + num_heads (int, optional): Number of attention heads. + attn_ratio (float, optional): Attention ratio, affecting the dimensions of the value vectors. + resolution (tuple[int, int], optional): Spatial resolution of the input feature map. + """ + super().__init__() + + assert isinstance(resolution, tuple) and len(resolution) == 2, "'resolution' argument not tuple of length 2" + self.num_heads = num_heads + self.scale = key_dim**-0.5 + self.key_dim = key_dim + self.nh_kd = nh_kd = key_dim * num_heads + self.d = int(attn_ratio * key_dim) + self.dh = int(attn_ratio * key_dim) * num_heads + self.attn_ratio = attn_ratio + h = self.dh + nh_kd * 2 + + self.norm = nn.LayerNorm(dim) + self.qkv = nn.Linear(dim, h) + self.proj = nn.Linear(self.dh, dim) + + points = list(itertools.product(range(resolution[0]), range(resolution[1]))) + N = len(points) + attention_offsets = {} + idxs = [] + for p1 in points: + for p2 in points: + offset = (abs(p1[0] - p2[0]), abs(p1[1] - p2[1])) + if offset not in attention_offsets: + attention_offsets[offset] = len(attention_offsets) + idxs.append(attention_offsets[offset]) + self.attention_biases = torch.nn.Parameter(torch.zeros(num_heads, len(attention_offsets))) + self.register_buffer("attention_bias_idxs", torch.LongTensor(idxs).view(N, N), persistent=False) + + @torch.no_grad() + def train(self, mode: bool = True): + """Set the module in training mode and handle the 'ab' attribute for cached attention biases.""" + super().train(mode) + if mode and hasattr(self, "ab"): + del self.ab + else: + self.ab = self.attention_biases[:, self.attention_bias_idxs] + return self + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply multi-head attention with spatial awareness and trainable attention biases.""" + B, N, _ = x.shape # B, N, C + + # Normalization + x = self.norm(x) + + qkv = self.qkv(x) + # (B, N, num_heads, d) + q, k, v = qkv.view(B, N, self.num_heads, -1).split([self.key_dim, self.key_dim, self.d], dim=3) + # (B, num_heads, N, d) + q = q.permute(0, 2, 1, 3) + k = k.permute(0, 2, 1, 3) + v = v.permute(0, 2, 1, 3) + if not self.training: + self.ab = self.ab.to(self.attention_biases.device) + + attn = (q @ k.transpose(-2, -1)) * self.scale + ( + self.attention_biases[:, self.attention_bias_idxs] if self.training else self.ab + ) + attn = attn.softmax(dim=-1) + x = (attn @ v).transpose(1, 2).reshape(B, N, self.dh) + return self.proj(x) + + +class TinyViTBlock(nn.Module): + """TinyViT Block that applies self-attention and a local convolution to the input. + + This block is a key component of the TinyViT architecture, combining self-attention mechanisms with local + convolutions to process input features efficiently. It supports windowed attention for computational efficiency and + includes residual connections. + + Attributes: + dim (int): The dimensionality of the input and output. + input_resolution (tuple[int, int]): Spatial resolution of the input feature map. + num_heads (int): Number of attention heads. + window_size (int): Size of the attention window. + mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension. + drop_path (nn.Module): Stochastic depth layer, identity function during inference. + attn (Attention): Self-attention module. + mlp (MLP): Multi-layer perceptron module. + local_conv (Conv2d_BN): Depth-wise local convolution layer. + + Examples: + >>> input_tensor = torch.randn(1, 196, 192) + >>> block = TinyViTBlock(dim=192, input_resolution=(14, 14), num_heads=3) + >>> output = block(input_tensor) + >>> print(output.shape) + torch.Size([1, 196, 192]) + """ + + def __init__( + self, + dim: int, + input_resolution: tuple[int, int], + num_heads: int, + window_size: int = 7, + mlp_ratio: float = 4.0, + drop: float = 0.0, + drop_path: float = 0.0, + local_conv_size: int = 3, + activation=nn.GELU, + ): + """Initialize a TinyViT block with self-attention and local convolution. + + This block is a key component of the TinyViT architecture, combining self-attention mechanisms with local + convolutions to process input features efficiently. + + Args: + dim (int): Dimensionality of the input and output features. + input_resolution (tuple[int, int]): Spatial resolution of the input feature map (height, width). + num_heads (int): Number of attention heads. + window_size (int, optional): Size of the attention window. Must be greater than 0. + mlp_ratio (float, optional): Ratio of MLP hidden dimension to embedding dimension. + drop (float, optional): Dropout rate. + drop_path (float, optional): Stochastic depth rate. + local_conv_size (int, optional): Kernel size of the local convolution. + activation (nn.Module): Activation function for MLP. + """ + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.num_heads = num_heads + assert window_size > 0, "window_size must be greater than 0" + self.window_size = window_size + self.mlp_ratio = mlp_ratio + + # NOTE: `DropPath` is needed only for training. + # self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.drop_path = nn.Identity() + + assert dim % num_heads == 0, "dim must be divisible by num_heads" + head_dim = dim // num_heads + + window_resolution = (window_size, window_size) + self.attn = Attention(dim, head_dim, num_heads, attn_ratio=1, resolution=window_resolution) + + mlp_hidden_dim = int(dim * mlp_ratio) + mlp_activation = activation + self.mlp = MLP(in_features=dim, hidden_features=mlp_hidden_dim, activation=mlp_activation, drop=drop) + + pad = local_conv_size // 2 + self.local_conv = Conv2d_BN(dim, dim, ks=local_conv_size, stride=1, pad=pad, groups=dim) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply self-attention, local convolution, and MLP operations to the input tensor.""" + h, w = self.input_resolution + b, hw, c = x.shape # batch, height*width, channels + assert hw == h * w, "input feature has wrong size" + res_x = x + if h == self.window_size and w == self.window_size: + x = self.attn(x) + else: + x = x.view(b, h, w, c) + pad_b = (self.window_size - h % self.window_size) % self.window_size + pad_r = (self.window_size - w % self.window_size) % self.window_size + padding = pad_b > 0 or pad_r > 0 + if padding: + x = F.pad(x, (0, 0, 0, pad_r, 0, pad_b)) + + pH, pW = h + pad_b, w + pad_r + nH = pH // self.window_size + nW = pW // self.window_size + + # Window partition + x = ( + x.view(b, nH, self.window_size, nW, self.window_size, c) + .transpose(2, 3) + .reshape(b * nH * nW, self.window_size * self.window_size, c) + ) + x = self.attn(x) + + # Window reverse + x = x.view(b, nH, nW, self.window_size, self.window_size, c).transpose(2, 3).reshape(b, pH, pW, c) + if padding: + x = x[:, :h, :w].contiguous() + + x = x.view(b, hw, c) + + x = res_x + self.drop_path(x) + x = x.transpose(1, 2).reshape(b, c, h, w) + x = self.local_conv(x) + x = x.view(b, c, hw).transpose(1, 2) + + return x + self.drop_path(self.mlp(x)) + + def extra_repr(self) -> str: + """Return a string representation of the TinyViTBlock's parameters. + + This method provides a formatted string containing key information about the TinyViTBlock, including its + dimension, input resolution, number of attention heads, window size, and MLP ratio. + + Returns: + (str): A formatted string containing the block's parameters. + + Examples: + >>> block = TinyViTBlock(dim=192, input_resolution=(14, 14), num_heads=3, window_size=7, mlp_ratio=4.0) + >>> print(block.extra_repr()) + dim=192, input_resolution=(14, 14), num_heads=3, window_size=7, mlp_ratio=4.0 + """ + return ( + f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " + f"window_size={self.window_size}, mlp_ratio={self.mlp_ratio}" + ) + + +class BasicLayer(nn.Module): + """A basic TinyViT layer for one stage in a TinyViT architecture. + + This class represents a single layer in the TinyViT model, consisting of multiple TinyViT blocks and an optional + downsampling operation. It processes features at a specific resolution and dimensionality within the overall + architecture. + + Attributes: + dim (int): The dimensionality of the input and output features. + input_resolution (tuple[int, int]): Spatial resolution of the input feature map. + depth (int): Number of TinyViT blocks in this layer. + use_checkpoint (bool): Whether to use gradient checkpointing to save memory. + blocks (nn.ModuleList): List of TinyViT blocks that make up this layer. + downsample (nn.Module | None): Downsample layer at the end of the layer, if specified. + + Examples: + >>> input_tensor = torch.randn(1, 3136, 192) + >>> layer = BasicLayer(dim=192, input_resolution=(56, 56), depth=2, num_heads=3, window_size=7) + >>> output = layer(input_tensor) + >>> print(output.shape) + torch.Size([1, 3136, 192]) + """ + + def __init__( + self, + dim: int, + input_resolution: tuple[int, int], + depth: int, + num_heads: int, + window_size: int, + mlp_ratio: float = 4.0, + drop: float = 0.0, + drop_path: float | list[float] = 0.0, + downsample: nn.Module | None = None, + use_checkpoint: bool = False, + local_conv_size: int = 3, + activation=nn.GELU, + out_dim: int | None = None, + ): + """Initialize a BasicLayer in the TinyViT architecture. + + This layer consists of multiple TinyViT blocks and an optional downsampling operation. It is designed to process + feature maps at a specific resolution and dimensionality within the TinyViT model. + + Args: + dim (int): Dimensionality of the input and output features. + input_resolution (tuple[int, int]): Spatial resolution of the input feature map (height, width). + depth (int): Number of TinyViT blocks in this layer. + num_heads (int): Number of attention heads in each TinyViT block. + window_size (int): Size of the local window for attention computation. + mlp_ratio (float, optional): Ratio of MLP hidden dimension to embedding dimension. + drop (float, optional): Dropout rate. + drop_path (float | list[float], optional): Stochastic depth rate. Can be a float or a list of floats for + each block. + downsample (nn.Module | None, optional): Downsampling layer at the end of the layer. None to skip + downsampling. + use_checkpoint (bool, optional): Whether to use gradient checkpointing to save memory. + local_conv_size (int, optional): Kernel size for the local convolution in each TinyViT block. + activation (nn.Module): Activation function used in the MLP. + out_dim (int | None, optional): Output dimension after downsampling. None means it will be the same as dim. + """ + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.depth = depth + self.use_checkpoint = use_checkpoint + + # Build blocks + self.blocks = nn.ModuleList( + [ + TinyViTBlock( + dim=dim, + input_resolution=input_resolution, + num_heads=num_heads, + window_size=window_size, + mlp_ratio=mlp_ratio, + drop=drop, + drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, + local_conv_size=local_conv_size, + activation=activation, + ) + for i in range(depth) + ] + ) + + # Patch merging layer + self.downsample = ( + None + if downsample is None + else downsample(input_resolution, dim=dim, out_dim=out_dim, activation=activation) + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Process input through TinyViT blocks and optional downsampling.""" + for blk in self.blocks: + x = torch.utils.checkpoint.checkpoint(blk, x, **CKPT_KWARGS) if self.use_checkpoint else blk(x) + return x if self.downsample is None else self.downsample(x) + + def extra_repr(self) -> str: + """Return a string with the layer's parameters for printing.""" + return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}" + + +class TinyViT(nn.Module): + """TinyViT: A compact vision transformer architecture for efficient image classification and feature extraction. + + This class implements the TinyViT model, which combines elements of vision transformers and convolutional neural + networks for improved efficiency and performance on vision tasks. It features hierarchical processing with patch + embedding, multiple stages of attention and convolution blocks, and a feature refinement neck. + + Attributes: + img_size (int): Input image size. + num_classes (int): Number of classification classes. + depths (tuple[int, int, int, int]): Number of blocks in each stage. + num_layers (int): Total number of layers in the network. + mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension. + patch_embed (PatchEmbed): Module for patch embedding. + patches_resolution (tuple[int, int]): Resolution of embedded patches. + layers (nn.ModuleList): List of network layers. + norm_head (nn.LayerNorm): Layer normalization for the classifier head. + head (nn.Linear): Linear layer for final classification. + neck (nn.Sequential): Neck module for feature refinement. + + Examples: + >>> model = TinyViT(img_size=224, embed_dims=(64, 128, 160, 320), num_heads=(2, 4, 5, 10)) + >>> x = torch.randn(1, 3, 224, 224) + >>> features = model.forward_features(x) + >>> print(features.shape) + torch.Size([1, 256, 14, 14]) + """ + + def __init__( + self, + img_size: int = 224, + in_chans: int = 3, + num_classes: int = 1000, + embed_dims: tuple[int, int, int, int] = (96, 192, 384, 768), + depths: tuple[int, int, int, int] = (2, 2, 6, 2), + num_heads: tuple[int, int, int, int] = (3, 6, 12, 24), + window_sizes: tuple[int, int, int, int] = (7, 7, 14, 7), + mlp_ratio: float = 4.0, + drop_rate: float = 0.0, + drop_path_rate: float = 0.1, + use_checkpoint: bool = False, + mbconv_expand_ratio: float = 4.0, + local_conv_size: int = 3, + layer_lr_decay: float = 1.0, + ): + """Initialize the TinyViT model. + + This constructor sets up the TinyViT architecture, including patch embedding, multiple layers of attention and + convolution blocks, and a classification head. + + Args: + img_size (int, optional): Size of the input image. + in_chans (int, optional): Number of input channels. + num_classes (int, optional): Number of classes for classification. + embed_dims (tuple[int, int, int, int], optional): Embedding dimensions for each stage. + depths (tuple[int, int, int, int], optional): Number of blocks in each stage. + num_heads (tuple[int, int, int, int], optional): Number of attention heads in each stage. + window_sizes (tuple[int, int, int, int], optional): Window sizes for each stage. + mlp_ratio (float, optional): Ratio of MLP hidden dim to embedding dim. + drop_rate (float, optional): Dropout rate. + drop_path_rate (float, optional): Stochastic depth rate. + use_checkpoint (bool, optional): Whether to use checkpointing to save memory. + mbconv_expand_ratio (float, optional): Expansion ratio for MBConv layer. + local_conv_size (int, optional): Kernel size for local convolutions. + layer_lr_decay (float, optional): Layer-wise learning rate decay factor. + """ + super().__init__() + self.img_size = img_size + self.num_classes = num_classes + self.depths = depths + self.num_layers = len(depths) + self.mlp_ratio = mlp_ratio + + activation = nn.GELU + + self.patch_embed = PatchEmbed( + in_chans=in_chans, embed_dim=embed_dims[0], resolution=img_size, activation=activation + ) + + patches_resolution = self.patch_embed.patches_resolution + self.patches_resolution = patches_resolution + + # Stochastic depth + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule + + # Build layers + self.layers = nn.ModuleList() + for i_layer in range(self.num_layers): + kwargs = { + "dim": embed_dims[i_layer], + "input_resolution": ( + patches_resolution[0] // (2 ** (i_layer - 1 if i_layer == 3 else i_layer)), + patches_resolution[1] // (2 ** (i_layer - 1 if i_layer == 3 else i_layer)), + ), + # input_resolution=(patches_resolution[0] // (2 ** i_layer), + # patches_resolution[1] // (2 ** i_layer)), + "depth": depths[i_layer], + "drop_path": dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])], + "downsample": PatchMerging if (i_layer < self.num_layers - 1) else None, + "use_checkpoint": use_checkpoint, + "out_dim": embed_dims[min(i_layer + 1, len(embed_dims) - 1)], + "activation": activation, + } + if i_layer == 0: + layer = ConvLayer(conv_expand_ratio=mbconv_expand_ratio, **kwargs) + else: + layer = BasicLayer( + num_heads=num_heads[i_layer], + window_size=window_sizes[i_layer], + mlp_ratio=self.mlp_ratio, + drop=drop_rate, + local_conv_size=local_conv_size, + **kwargs, + ) + self.layers.append(layer) + + # Classifier head + self.norm_head = nn.LayerNorm(embed_dims[-1]) + self.head = nn.Linear(embed_dims[-1], num_classes) if num_classes > 0 else torch.nn.Identity() + + # Init weights + self.apply(self._init_weights) + self.set_layer_lr_decay(layer_lr_decay) + self.neck = nn.Sequential( + nn.Conv2d( + embed_dims[-1], + 256, + kernel_size=1, + bias=False, + ), + LayerNorm2d(256), + nn.Conv2d( + 256, + 256, + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(256), + ) + + def set_layer_lr_decay(self, layer_lr_decay: float): + """Set layer-wise learning rate decay for the TinyViT model based on depth.""" + decay_rate = layer_lr_decay + + # Layers -> blocks (depth) + depth = sum(self.depths) + lr_scales = [decay_rate ** (depth - i - 1) for i in range(depth)] + + def _set_lr_scale(m, scale): + """Set the learning rate scale for each layer in the model based on the layer's depth.""" + for p in m.parameters(): + p.lr_scale = scale + + self.patch_embed.apply(lambda x: _set_lr_scale(x, lr_scales[0])) + i = 0 + for layer in self.layers: + for block in layer.blocks: + block.apply(lambda x, scale=lr_scales[i]: _set_lr_scale(x, scale)) + i += 1 + if layer.downsample is not None: + layer.downsample.apply(lambda x, scale=lr_scales[i - 1]: _set_lr_scale(x, scale)) + assert i == depth + for m in {self.norm_head, self.head}: + m.apply(lambda x: _set_lr_scale(x, lr_scales[-1])) + + for k, p in self.named_parameters(): + p.param_name = k + + def _check_lr_scale(m): + """Check if the learning rate scale attribute is present in module's parameters.""" + for p in m.parameters(): + assert hasattr(p, "lr_scale"), p.param_name + + self.apply(_check_lr_scale) + + @staticmethod + def _init_weights(m): + """Initialize weights for linear and normalization layers in the TinyViT model.""" + if isinstance(m, nn.Linear): + # NOTE: This initialization is needed only for training. + # trunc_normal_(m.weight, std=.02) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + @torch.jit.ignore + def no_weight_decay_keywords(self): + """Return a set of keywords for parameters that should not use weight decay.""" + return {"attention_biases"} + + def forward_features(self, x: torch.Tensor) -> torch.Tensor: + """Process input through feature extraction layers, returning spatial features.""" + x = self.patch_embed(x) # x input is (N, C, H, W) + + x = self.layers[0](x) + start_i = 1 + + for i in range(start_i, len(self.layers)): + layer = self.layers[i] + x = layer(x) + batch, _, channel = x.shape + x = x.view(batch, self.patches_resolution[0] // 4, self.patches_resolution[1] // 4, channel) + x = x.permute(0, 3, 1, 2) + return self.neck(x) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Perform the forward pass through the TinyViT model, extracting features from the input image.""" + return self.forward_features(x) + + def set_imgsz(self, imgsz: list[int] | None = None): + """Set image size to make model compatible with different image sizes.""" + imgsz = imgsz if imgsz is not None else [1024, 1024] + imgsz = [s // 4 for s in imgsz] + self.patches_resolution = imgsz + for i, layer in enumerate(self.layers): + input_resolution = ( + imgsz[0] // (2 ** (i - 1 if i == 3 else i)), + imgsz[1] // (2 ** (i - 1 if i == 3 else i)), + ) + layer.input_resolution = input_resolution + if layer.downsample is not None: + layer.downsample.input_resolution = input_resolution + if isinstance(layer, BasicLayer): + for b in layer.blocks: + b.input_resolution = input_resolution diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/transformer.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..019d96e8a3769c47dfe12503744eb6aa82f8420a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/transformer.py @@ -0,0 +1,344 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import math + +import torch +from torch import Tensor, nn + +from ultralytics.nn.modules import MLPBlock + + +class TwoWayTransformer(nn.Module): + """A Two-Way Transformer module for simultaneous attention to image and query points. + + This class implements a specialized transformer decoder that attends to an input image using queries with supplied + positional embeddings. It's useful for tasks like object detection, image segmentation, and point cloud processing. + + Attributes: + depth (int): Number of layers in the transformer. + embedding_dim (int): Channel dimension for input embeddings. + num_heads (int): Number of heads for multihead attention. + mlp_dim (int): Internal channel dimension for the MLP block. + layers (nn.ModuleList): List of TwoWayAttentionBlock layers composing the transformer. + final_attn_token_to_image (Attention): Final attention layer from queries to image. + norm_final_attn (nn.LayerNorm): Layer normalization applied to final queries. + + Methods: + forward: Process image and point embeddings through the transformer. + + Examples: + >>> transformer = TwoWayTransformer(depth=6, embedding_dim=256, num_heads=8, mlp_dim=2048) + >>> image_embedding = torch.randn(1, 256, 32, 32) + >>> image_pe = torch.randn(1, 256, 32, 32) + >>> point_embedding = torch.randn(1, 100, 256) + >>> output_queries, output_image = transformer(image_embedding, image_pe, point_embedding) + >>> print(output_queries.shape, output_image.shape) + """ + + def __init__( + self, + depth: int, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + ) -> None: + """Initialize a Two-Way Transformer for simultaneous attention to image and query points. + + Args: + depth (int): Number of layers in the transformer. + embedding_dim (int): Channel dimension for input embeddings. + num_heads (int): Number of heads for multihead attention. Must divide embedding_dim. + mlp_dim (int): Internal channel dimension for the MLP block. + activation (type[nn.Module], optional): Activation function to use in the MLP block. + attention_downsample_rate (int, optional): Downsampling rate for attention mechanism. + """ + super().__init__() + self.depth = depth + self.embedding_dim = embedding_dim + self.num_heads = num_heads + self.mlp_dim = mlp_dim + self.layers = nn.ModuleList() + + for i in range(depth): + self.layers.append( + TwoWayAttentionBlock( + embedding_dim=embedding_dim, + num_heads=num_heads, + mlp_dim=mlp_dim, + activation=activation, + attention_downsample_rate=attention_downsample_rate, + skip_first_layer_pe=(i == 0), + ) + ) + + self.final_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate) + self.norm_final_attn = nn.LayerNorm(embedding_dim) + + def forward( + self, + image_embedding: torch.Tensor, + image_pe: torch.Tensor, + point_embedding: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Process image and point embeddings through the Two-Way Transformer. + + Args: + image_embedding (torch.Tensor): Image to attend to, with shape (B, embedding_dim, H, W). + image_pe (torch.Tensor): Positional encoding to add to the image, with same shape as image_embedding. + point_embedding (torch.Tensor): Embedding to add to query points, with shape (B, N_points, embedding_dim). + + Returns: + queries (torch.Tensor): Processed point embeddings with shape (B, N_points, embedding_dim). + keys (torch.Tensor): Processed image embeddings with shape (B, H*W, embedding_dim). + """ + # BxCxHxW -> BxHWxC == B x N_image_tokens x C + image_embedding = image_embedding.flatten(2).permute(0, 2, 1) + image_pe = image_pe.flatten(2).permute(0, 2, 1) + + # Prepare queries + queries = point_embedding + keys = image_embedding + + # Apply transformer blocks and final layernorm + for layer in self.layers: + queries, keys = layer( + queries=queries, + keys=keys, + query_pe=point_embedding, + key_pe=image_pe, + ) + + # Apply the final attention layer from the points to the image + q = queries + point_embedding + k = keys + image_pe + attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm_final_attn(queries) + + return queries, keys + + +class TwoWayAttentionBlock(nn.Module): + """A two-way attention block for simultaneous attention to image and query points. + + This class implements a specialized transformer block with four main layers: self-attention on sparse inputs, + cross-attention of sparse inputs to dense inputs, MLP block on sparse inputs, and cross-attention of dense inputs to + sparse inputs. + + Attributes: + self_attn (Attention): Self-attention layer for queries. + norm1 (nn.LayerNorm): Layer normalization after self-attention. + cross_attn_token_to_image (Attention): Cross-attention layer from queries to keys. + norm2 (nn.LayerNorm): Layer normalization after token-to-image attention. + mlp (MLPBlock): MLP block for transforming query embeddings. + norm3 (nn.LayerNorm): Layer normalization after MLP block. + norm4 (nn.LayerNorm): Layer normalization after image-to-token attention. + cross_attn_image_to_token (Attention): Cross-attention layer from keys to queries. + skip_first_layer_pe (bool): Whether to skip positional encoding in the first layer. + + Methods: + forward: Apply self-attention and cross-attention to queries and keys. + + Examples: + >>> embedding_dim, num_heads = 256, 8 + >>> block = TwoWayAttentionBlock(embedding_dim, num_heads) + >>> queries = torch.randn(1, 100, embedding_dim) + >>> keys = torch.randn(1, 1000, embedding_dim) + >>> query_pe = torch.randn(1, 100, embedding_dim) + >>> key_pe = torch.randn(1, 1000, embedding_dim) + >>> processed_queries, processed_keys = block(queries, keys, query_pe, key_pe) + """ + + def __init__( + self, + embedding_dim: int, + num_heads: int, + mlp_dim: int = 2048, + activation: type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + skip_first_layer_pe: bool = False, + ) -> None: + """Initialize a TwoWayAttentionBlock for simultaneous attention to image and query points. + + This block implements a specialized transformer layer with four main components: self-attention on sparse + inputs, cross-attention of sparse inputs to dense inputs, MLP block on sparse inputs, and cross-attention of + dense inputs to sparse inputs. + + Args: + embedding_dim (int): Channel dimension of the embeddings. + num_heads (int): Number of attention heads in the attention layers. + mlp_dim (int, optional): Hidden dimension of the MLP block. + activation (type[nn.Module], optional): Activation function for the MLP block. + attention_downsample_rate (int, optional): Downsampling rate for the attention mechanism. + skip_first_layer_pe (bool, optional): Whether to skip positional encoding in the first layer. + """ + super().__init__() + self.self_attn = Attention(embedding_dim, num_heads) + self.norm1 = nn.LayerNorm(embedding_dim) + + self.cross_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate) + self.norm2 = nn.LayerNorm(embedding_dim) + + self.mlp = MLPBlock(embedding_dim, mlp_dim, activation) + self.norm3 = nn.LayerNorm(embedding_dim) + + self.norm4 = nn.LayerNorm(embedding_dim) + self.cross_attn_image_to_token = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate) + + self.skip_first_layer_pe = skip_first_layer_pe + + def forward( + self, queries: torch.Tensor, keys: torch.Tensor, query_pe: torch.Tensor, key_pe: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + """Apply two-way attention to process query and key embeddings in a transformer block. + + Args: + queries (torch.Tensor): Query embeddings with shape (B, N_queries, embedding_dim). + keys (torch.Tensor): Key embeddings with shape (B, N_keys, embedding_dim). + query_pe (torch.Tensor): Positional encodings for queries with same shape as queries. + key_pe (torch.Tensor): Positional encodings for keys with same shape as keys. + + Returns: + queries (torch.Tensor): Processed query embeddings with shape (B, N_queries, embedding_dim). + keys (torch.Tensor): Processed key embeddings with shape (B, N_keys, embedding_dim). + """ + # Self attention block + if self.skip_first_layer_pe: + queries = self.self_attn(q=queries, k=queries, v=queries) + else: + q = queries + query_pe + attn_out = self.self_attn(q=q, k=q, v=queries) + queries = queries + attn_out + queries = self.norm1(queries) + + # Cross attention block, tokens attending to image embedding + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm2(queries) + + # MLP block + mlp_out = self.mlp(queries) + queries = queries + mlp_out + queries = self.norm3(queries) + + # Cross attention block, image embedding attending to tokens + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries) + keys = keys + attn_out + keys = self.norm4(keys) + + return queries, keys + + +class Attention(nn.Module): + """An attention layer with downscaling capability for embedding size after projection. + + This class implements a multi-head attention mechanism with the option to downsample the internal dimension of + queries, keys, and values. + + Attributes: + embedding_dim (int): Dimensionality of input embeddings. + kv_in_dim (int): Dimensionality of key and value inputs. + internal_dim (int): Internal dimension after downsampling. + num_heads (int): Number of attention heads. + q_proj (nn.Linear): Linear projection for queries. + k_proj (nn.Linear): Linear projection for keys. + v_proj (nn.Linear): Linear projection for values. + out_proj (nn.Linear): Linear projection for output. + + Methods: + _separate_heads: Separate input tensor into attention heads. + _recombine_heads: Recombine separated attention heads. + forward: Compute attention output for given query, key, and value tensors. + + Examples: + >>> attn = Attention(embedding_dim=256, num_heads=8, downsample_rate=2) + >>> q = torch.randn(1, 100, 256) + >>> k = v = torch.randn(1, 50, 256) + >>> output = attn(q, k, v) + >>> print(output.shape) + torch.Size([1, 100, 256]) + """ + + def __init__( + self, + embedding_dim: int, + num_heads: int, + downsample_rate: int = 1, + kv_in_dim: int | None = None, + ) -> None: + """Initialize the Attention module with specified dimensions and settings. + + Args: + embedding_dim (int): Dimensionality of input embeddings. + num_heads (int): Number of attention heads. + downsample_rate (int, optional): Factor by which internal dimensions are downsampled. + kv_in_dim (int | None, optional): Dimensionality of key and value inputs. If None, uses embedding_dim. + + Raises: + AssertionError: If num_heads does not evenly divide the internal dim (embedding_dim / downsample_rate). + """ + super().__init__() + self.embedding_dim = embedding_dim + self.kv_in_dim = kv_in_dim if kv_in_dim is not None else embedding_dim + self.internal_dim = embedding_dim // downsample_rate + self.num_heads = num_heads + assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim." + + self.q_proj = nn.Linear(embedding_dim, self.internal_dim) + self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim) + self.v_proj = nn.Linear(self.kv_in_dim, self.internal_dim) + self.out_proj = nn.Linear(self.internal_dim, embedding_dim) + + @staticmethod + def _separate_heads(x: torch.Tensor, num_heads: int) -> torch.Tensor: + """Separate the input tensor into the specified number of attention heads.""" + b, n, c = x.shape + x = x.reshape(b, n, num_heads, c // num_heads) + return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head + + @staticmethod + def _recombine_heads(x: Tensor) -> Tensor: + """Recombine separated attention heads into a single tensor.""" + b, n_heads, n_tokens, c_per_head = x.shape + x = x.transpose(1, 2) + return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C + + def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor: + """Apply multi-head attention to query, key, and value tensors with optional downsampling. + + Args: + q (torch.Tensor): Query tensor with shape (B, N_q, embedding_dim). + k (torch.Tensor): Key tensor with shape (B, N_k, kv_in_dim). + v (torch.Tensor): Value tensor with shape (B, N_k, kv_in_dim). + + Returns: + (torch.Tensor): Output tensor after attention with shape (B, N_q, embedding_dim). + """ + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + # Attention + _, _, _, c_per_head = q.shape + attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens + attn = attn / math.sqrt(c_per_head) + attn = torch.softmax(attn, dim=-1) + + # Get output + out = attn @ v + out = self._recombine_heads(out) + return self.out_proj(out) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/utils.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..18c2ab5a35684af86bd642e70df4dbf3a6486a21 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/utils.py @@ -0,0 +1,512 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import math +from typing import Any + +import torch +import torch.nn.functional as F + + +def select_closest_cond_frames(frame_idx: int, cond_frame_outputs: dict[int, Any], max_cond_frame_num: int): + """Select the closest conditioning frames to a given frame index. + + Args: + frame_idx (int): Current frame index. + cond_frame_outputs (dict[int, Any]): Dictionary of conditioning frame outputs keyed by frame indices. + max_cond_frame_num (int): Maximum number of conditioning frames to select. + + Returns: + selected_outputs (dict[int, Any]): Selected items from cond_frame_outputs. + unselected_outputs (dict[int, Any]): Items not selected from cond_frame_outputs. + + Examples: + >>> frame_idx = 5 + >>> cond_frame_outputs = {1: "a", 3: "b", 7: "c", 9: "d"} + >>> max_cond_frame_num = 2 + >>> selected, unselected = select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num) + >>> print(selected) + {3: 'b', 7: 'c'} + >>> print(unselected) + {1: 'a', 9: 'd'} + """ + if max_cond_frame_num == -1 or len(cond_frame_outputs) <= max_cond_frame_num: + selected_outputs = cond_frame_outputs + unselected_outputs = {} + else: + assert max_cond_frame_num >= 2, "we should allow using 2+ conditioning frames" + selected_outputs = {} + + # The closest conditioning frame before `frame_idx` (if any) + idx_before = max((t for t in cond_frame_outputs if t < frame_idx), default=None) + if idx_before is not None: + selected_outputs[idx_before] = cond_frame_outputs[idx_before] + + # The closest conditioning frame after `frame_idx` (if any) + idx_after = min((t for t in cond_frame_outputs if t >= frame_idx), default=None) + if idx_after is not None: + selected_outputs[idx_after] = cond_frame_outputs[idx_after] + + # Add other temporally closest conditioning frames until reaching a total + # of `max_cond_frame_num` conditioning frames. + num_remain = max_cond_frame_num - len(selected_outputs) + inds_remain = sorted( + (t for t in cond_frame_outputs if t not in selected_outputs), + key=lambda x: abs(x - frame_idx), + )[:num_remain] + selected_outputs.update((t, cond_frame_outputs[t]) for t in inds_remain) + unselected_outputs = {t: v for t, v in cond_frame_outputs.items() if t not in selected_outputs} + + return selected_outputs, unselected_outputs + + +def get_1d_sine_pe(pos_inds: torch.Tensor, dim: int, temperature: float = 10000): + """Generate 1D sinusoidal positional embeddings for given positions and dimensions. + + Args: + pos_inds (torch.Tensor): Position indices for which to generate embeddings. + dim (int): Dimension of the positional embeddings. Should be an even number. + temperature (float, optional): Scaling factor for the frequency of the sinusoidal functions. + + Returns: + (torch.Tensor): Sinusoidal positional embeddings with shape (pos_inds.shape, dim). + + Examples: + >>> pos = torch.tensor([0, 1, 2, 3]) + >>> embeddings = get_1d_sine_pe(pos, 128) + >>> embeddings.shape + torch.Size([4, 128]) + """ + pe_dim = dim // 2 + dim_t = torch.arange(pe_dim, dtype=pos_inds.dtype, device=pos_inds.device) + dim_t = temperature ** (2 * (dim_t // 2) / pe_dim) + + pos_embed = pos_inds.unsqueeze(-1) / dim_t + pos_embed = torch.cat([pos_embed.sin(), pos_embed.cos()], dim=-1) + return pos_embed + + +def init_t_xy(end_x: int, end_y: int, scale: float = 1.0, offset: int = 0): + """Initialize 1D and 2D coordinate tensors for a grid of specified dimensions. + + This function creates coordinate tensors for a grid with dimensions end_x × end_y. It generates a linear index + tensor and corresponding x and y coordinate tensors. + + Args: + end_x (int): Width of the grid (number of columns). + end_y (int): Height of the grid (number of rows). + scale (float): Scaling factor to apply to the coordinates. + offset (int): Offset to add to the coordinates. + + Returns: + t_x (torch.Tensor): X-coordinates for each position, with shape (end_x * end_y). + t_y (torch.Tensor): Y-coordinates for each position, with shape (end_x * end_y). + + Examples: + >>> t_x, t_y = init_t_xy(3, 2) + >>> print(t_x) + tensor([0., 1., 2., 0., 1., 2.]) + >>> print(t_y) + tensor([0., 0., 0., 1., 1., 1.]) + """ + t = torch.arange(end_x * end_y, dtype=torch.float32) + t_x = (t % end_x).float() + t_y = torch.div(t, end_x, rounding_mode="floor").float() + return t_x * scale + offset, t_y * scale + offset + + +def compute_axial_cis(dim: int, end_x: int, end_y: int, theta: float = 10000.0, scale_pos: float = 1.0): + """Compute axial complex exponential positional encodings for 2D spatial positions in a grid. + + This function generates complex exponential positional encodings for a 2D grid of spatial positions, using separate + frequency components for the x and y dimensions. + + Args: + dim (int): Dimension of the positional encoding. + end_x (int): Width of the 2D grid. + end_y (int): Height of the 2D grid. + theta (float, optional): Scaling factor for frequency computation. + scale_pos (float, optional): Scaling factor for position coordinates. + + Returns: + (torch.Tensor): Complex exponential positional encodings with shape (end_x*end_y, dim//2). + + Examples: + >>> dim, end_x, end_y = 128, 8, 8 + >>> freqs_cis = compute_axial_cis(dim, end_x, end_y) + >>> freqs_cis.shape + torch.Size([64, 64]) + """ + freqs_x = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim)) + freqs_y = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim)) + + t_x, t_y = init_t_xy(end_x, end_y, scale=scale_pos) + freqs_x = torch.outer(t_x, freqs_x) + freqs_y = torch.outer(t_y, freqs_y) + freqs_cis_x = torch.polar(torch.ones_like(freqs_x), freqs_x) + freqs_cis_y = torch.polar(torch.ones_like(freqs_y), freqs_y) + return torch.cat([freqs_cis_x, freqs_cis_y], dim=-1) + + +def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor): + """Reshape frequency tensor for broadcasting with input tensor. + + Reshapes a frequency tensor to ensure dimensional compatibility for broadcasting with an input tensor. This function + is typically used in positional encoding operations. + + Args: + freqs_cis (torch.Tensor): Frequency tensor with shape matching the last two dimensions of x. + x (torch.Tensor): Input tensor to broadcast with. + + Returns: + (torch.Tensor): Reshaped frequency tensor ready for broadcasting with the input tensor. + + Raises: + AssertionError: If the shape of freqs_cis doesn't match the last two dimensions of x. + """ + ndim = x.ndim + assert ndim >= 2 + assert freqs_cis.shape == (x.shape[-2], x.shape[-1]) + shape = [d if i >= ndim - 2 else 1 for i, d in enumerate(x.shape)] + return freqs_cis.view(*shape) + + +def apply_rotary_enc( + xq: torch.Tensor, + xk: torch.Tensor, + freqs_cis: torch.Tensor, + repeat_freqs_k: bool = False, +): + """Apply rotary positional encoding to query and key tensors. + + This function applies rotary positional encoding (RoPE) to query and key tensors using complex-valued frequency + components. RoPE is a technique that injects relative position information into self-attention mechanisms. + + Args: + xq (torch.Tensor): Query tensor to encode with positional information. + xk (torch.Tensor): Key tensor to encode with positional information. + freqs_cis (torch.Tensor): Complex-valued frequency components for rotary encoding with shape matching the last + two dimensions of xq. + repeat_freqs_k (bool, optional): Whether to repeat frequency components along sequence length dimension to match + key sequence length. + + Returns: + xq_out (torch.Tensor): Query tensor with rotary positional encoding applied. + xk_out (torch.Tensor): Key tensor with rotary positional encoding applied, or original xk if xk is empty. + + Examples: + >>> import torch + >>> xq = torch.randn(2, 8, 16, 64) # [batch, heads, seq_len, dim] + >>> xk = torch.randn(2, 8, 16, 64) + >>> freqs_cis = compute_axial_cis(64, 4, 4) # For a 4x4 spatial grid with dim=64 + >>> q_encoded, k_encoded = apply_rotary_enc(xq, xk, freqs_cis) + """ + xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2)) + xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2)) if xk.shape[-2] != 0 else None + freqs_cis = reshape_for_broadcast(freqs_cis, xq_) + xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3) + if xk_ is None: + # No keys to rotate, due to dropout + return xq_out.type_as(xq).to(xq.device), xk + # Repeat freqs along seq_len dim to match k seq_len + if repeat_freqs_k and (r := xk_.shape[-2] // xq_.shape[-2]) > 1: + # MPS doesn't support repeat on complex tensors, decompose to real representation + if freqs_cis.device.type == "mps": + freqs_cis = torch.view_as_real(freqs_cis) + freqs_cis = freqs_cis.repeat(*([1] * (freqs_cis.ndim - 3)), r, 1, 1) + freqs_cis = torch.view_as_complex(freqs_cis.contiguous()) + else: + freqs_cis = freqs_cis.repeat(*([1] * (freqs_cis.ndim - 2)), r, 1) + xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3) + return xq_out.type_as(xq).to(xq.device), xk_out.type_as(xk).to(xk.device) + + +def window_partition(x: torch.Tensor, window_size: int): + """Partition input tensor into non-overlapping windows with padding if needed. + + Args: + x (torch.Tensor): Input tensor with shape (B, H, W, C). + window_size (int): Size of each window. + + Returns: + windows (torch.Tensor): Partitioned windows with shape (B * num_windows, window_size, window_size, C). + padded_h_w (tuple[int, int]): Padded height and width before partition. + + Examples: + >>> x = torch.randn(1, 16, 16, 3) + >>> windows, (Hp, Wp) = window_partition(x, window_size=4) + >>> print(windows.shape, Hp, Wp) + torch.Size([16, 4, 4, 3]) 16 16 + """ + B, H, W, C = x.shape + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + if pad_h > 0 or pad_w > 0: + x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) + Hp, Wp = H + pad_h, W + pad_w + + x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows, (Hp, Wp) + + +def window_unpartition(windows: torch.Tensor, window_size: int, pad_hw: tuple[int, int], hw: tuple[int, int]): + """Unpartition windowed sequences into original sequences and remove padding. + + This function reverses the windowing process, reconstructing the original input from windowed segments and removing + any padding that was added during the windowing process. + + Args: + windows (torch.Tensor): Input tensor of windowed sequences with shape (B * num_windows, window_size, + window_size, C), where B is the batch size, num_windows is the number of windows, window_size is the size of + each window, and C is the number of channels. + window_size (int): Size of each window. + pad_hw (tuple[int, int]): Padded height and width (Hp, Wp) of the input before windowing. + hw (tuple[int, int]): Original height and width (H, W) of the input before padding and windowing. + + Returns: + (torch.Tensor): Unpartitioned sequences with shape (B, H, W, C), where B is the batch size, H and W are the + original height and width, and C is the number of channels. + + Examples: + >>> windows = torch.rand(32, 8, 8, 64) # 32 windows of size 8x8 with 64 channels + >>> pad_hw = (16, 16) # Padded height and width + >>> hw = (15, 14) # Original height and width + >>> x = window_unpartition(windows, window_size=8, pad_hw=pad_hw, hw=hw) + >>> print(x.shape) + torch.Size([8, 15, 14, 64]) + """ + Hp, Wp = pad_hw + H, W = hw + B = windows.shape[0] // (Hp * Wp // window_size // window_size) + x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) + + if Hp > H or Wp > W: + x = x[:, :H, :W, :].contiguous() + return x + + +def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor: + """Extract relative positional embeddings based on query and key sizes. + + Args: + q_size (int): Size of the query. + k_size (int): Size of the key. + rel_pos (torch.Tensor): Relative position embeddings with shape (L, C), where L is the maximum relative distance + and C is the embedding dimension. + + Returns: + (torch.Tensor): Extracted positional embeddings according to relative positions, with shape (q_size, k_size, C). + + Examples: + >>> q_size, k_size = 8, 16 + >>> rel_pos = torch.randn(31, 64) # 31 = 2 * max(8, 16) - 1 + >>> extracted_pos = get_rel_pos(q_size, k_size, rel_pos) + >>> print(extracted_pos.shape) + torch.Size([8, 16, 64]) + """ + max_rel_dist = int(2 * max(q_size, k_size) - 1) + # Interpolate rel pos if needed. + if rel_pos.shape[0] != max_rel_dist: + # Interpolate rel pos. + rel_pos_resized = F.interpolate( + rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), + size=max_rel_dist, + mode="linear", + ) + rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) + else: + rel_pos_resized = rel_pos + + # Scale the coords with short length if shapes for q and k are different. + q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) + k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) + relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) + + return rel_pos_resized[relative_coords.long()] + + +def add_decomposed_rel_pos( + attn: torch.Tensor, + q: torch.Tensor, + rel_pos_h: torch.Tensor, + rel_pos_w: torch.Tensor, + q_size: tuple[int, int], + k_size: tuple[int, int], +) -> torch.Tensor: + """Add decomposed Relative Positional Embeddings to the attention map. + + This function calculates and applies decomposed Relative Positional Embeddings as described in the MVITv2 + paper. It enhances the attention mechanism by incorporating spatial relationships between query and key + positions. + + Args: + attn (torch.Tensor): Attention map with shape (B, q_h * q_w, k_h * k_w). + q (torch.Tensor): Query tensor in the attention layer with shape (B, q_h * q_w, C). + rel_pos_h (torch.Tensor): Relative position embeddings for height axis with shape (Lh, C). + rel_pos_w (torch.Tensor): Relative position embeddings for width axis with shape (Lw, C). + q_size (tuple[int, int]): Spatial sequence size of query q as (q_h, q_w). + k_size (tuple[int, int]): Spatial sequence size of key k as (k_h, k_w). + + Returns: + (torch.Tensor): Updated attention map with added relative positional embeddings, shape (B, q_h * q_w, k_h * + k_w). + + Examples: + >>> B, C, q_h, q_w, k_h, k_w = 1, 64, 8, 8, 8, 8 + >>> attn = torch.rand(B, q_h * q_w, k_h * k_w) + >>> q = torch.rand(B, q_h * q_w, C) + >>> rel_pos_h = torch.rand(2 * max(q_h, k_h) - 1, C) + >>> rel_pos_w = torch.rand(2 * max(q_w, k_w) - 1, C) + >>> q_size, k_size = (q_h, q_w), (k_h, k_w) + >>> updated_attn = add_decomposed_rel_pos(attn, q, rel_pos_h, rel_pos_w, q_size, k_size) + >>> print(updated_attn.shape) + torch.Size([1, 64, 64]) + + References: + https://github.com/facebookresearch/mvit/blob/main/mvit/models/attention.py + """ + q_h, q_w = q_size + k_h, k_w = k_size + Rh = get_rel_pos(q_h, k_h, rel_pos_h) + Rw = get_rel_pos(q_w, k_w, rel_pos_w) + + B, _, dim = q.shape + r_q = q.reshape(B, q_h, q_w, dim) + rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) + rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) + + attn = (attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]).view( + B, q_h * q_w, k_h * k_w + ) + + return attn + + +def get_abs_pos( + abs_pos: torch.Tensor, + has_cls_token: bool, + hw: tuple[int, int], + retain_cls_token: bool = False, + tiling: bool = False, +) -> torch.Tensor: + """Calculate absolute positional embeddings. If needed, resize embeddings and remove cls_token dimension for the + original embeddings. + + Args: + abs_pos (torch.Tensor): Absolute positional embeddings with shape (1, num_position, C). + has_cls_token (bool): If true, has 1 embedding in abs_pos for cls token. + hw (tuple[int, int]): Size of input image tokens. + retain_cls_token (bool): Whether to retain the cls_token. + tiling (bool): Whether to tile the embeddings, *instead* of interpolation (a la abs_win). + + Returns: + (torch.Tensor): Absolute positional embeddings after processing with shape (1, H, W, C) if retain_cls_token is + False, otherwise (1, 1+H*W, C). + """ + if retain_cls_token: + assert has_cls_token + + h, w = hw + if has_cls_token: + cls_pos = abs_pos[:, :1] + abs_pos = abs_pos[:, 1:] + + xy_num = abs_pos.shape[1] + size = int(math.sqrt(xy_num)) + assert size * size == xy_num + + if size != h or size != w: + new_abs_pos = abs_pos.reshape(1, size, size, -1).permute(0, 3, 1, 2) + if tiling: + new_abs_pos = new_abs_pos.tile([1, 1] + [x // y + 1 for x, y in zip((h, w), new_abs_pos.shape[2:])])[ + :, :, :h, :w + ] + else: + new_abs_pos = F.interpolate( + new_abs_pos, + size=(h, w), + mode="bicubic", + align_corners=False, + ) + + if not retain_cls_token: + return new_abs_pos.permute(0, 2, 3, 1) + else: + # add cls_token back, flatten spatial dims + assert has_cls_token + return torch.cat( + [cls_pos, new_abs_pos.permute(0, 2, 3, 1).reshape(1, h * w, -1)], + dim=1, + ) + + else: + if not retain_cls_token: + return abs_pos.reshape(1, h, w, -1) + else: + assert has_cls_token + return torch.cat([cls_pos, abs_pos], dim=1) + + +def concat_rel_pos( + q: torch.Tensor, + k: torch.Tensor, + q_hw: tuple[int, int], + k_hw: tuple[int, int], + rel_pos_h: torch.Tensor, + rel_pos_w: torch.Tensor, + rescale: bool = False, + relative_coords: torch.Tensor = None, +) -> tuple[torch.Tensor, torch.Tensor]: + """Concatenate rel pos coeffs to the q & k tensors, so that qk^T is now effectively including rel pos biases. + + Args: + q (torch.Tensor): Query tensor with shape (B, L_q, C). + k (torch.Tensor): Key tensor with shape (B, L_k, C). + q_hw (tuple[int, int]): Spatial size of query tensors as (height, width). + k_hw (tuple[int, int]): Spatial size of key tensors as (height, width). + rel_pos_h (torch.Tensor): Relative positional embeddings for the height axis. + rel_pos_w (torch.Tensor): Relative positional embeddings for the width axis. + rescale (bool): Whether to rescale for use with SDPA, which would scale by the wrong factor due to the concat. + relative_coords (torch.Tensor | None): Precomputed relative coords index tensor. + + Returns: + q (torch.Tensor): Query tensor padded so that qk^T accounts for relative position biases. + k (torch.Tensor): Key tensor padded so that qk^T accounts for relative position biases. + """ + q_h, q_w = q_hw + k_h, k_w = k_hw + + assert (q_h == q_w) and (k_h == k_w), "only square inputs supported" + + if relative_coords is not None: + Rh = rel_pos_h[relative_coords] + Rw = rel_pos_w[relative_coords] + else: + Rh = get_rel_pos(q_h, k_h, rel_pos_h) + Rw = get_rel_pos(q_w, k_w, rel_pos_w) + + B, _, dim = q.shape + r_q = q.reshape(B, q_h, q_w, dim) + + old_scale = dim**0.5 + new_scale = (dim + k_h + k_w) ** 0.5 if rescale else old_scale # for sdpa + # attn will be divided by new_scale, but we want to divide q by old_scale + scale_ratio = new_scale / old_scale + + rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) * new_scale # (B, q_h, q_w, k_h) + rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) * new_scale # (B, q_h, q_w, k_w) + + eye_h = torch.eye(k_h, dtype=q.dtype, device=q.device) + eye_w = torch.eye(k_w, dtype=q.dtype, device=q.device) + + eye_h = eye_h.view(1, k_h, 1, k_h).expand([B, k_h, k_w, k_h]) + eye_w = eye_w.view(1, 1, k_w, k_w).expand([B, k_h, k_w, k_w]) + + q = torch.cat([r_q * scale_ratio, rel_h, rel_w], dim=-1).view(B, q_h * q_w, -1) + k = torch.cat([k.view(B, k_h, k_w, -1), eye_h, eye_w], dim=-1).view(B, k_h * k_w, -1) + + return q, k diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/predict.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..eaddad95831a9039640a21bf2a6cb35e7fa6a7b3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/predict.py @@ -0,0 +1,3987 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Generate predictions using the Segment Anything Model (SAM). + +SAM is an advanced image segmentation model offering features like promptable segmentation and zero-shot performance. +This module contains the implementation of the prediction logic and auxiliary utilities required to perform segmentation +using SAM. It forms an integral part of the Ultralytics framework and is designed for high-performance, real-time image +segmentation tasks. +""" + +from __future__ import annotations + +from collections import OrderedDict, defaultdict +from copy import deepcopy +from typing import TYPE_CHECKING, Any + +import cv2 +import numpy as np +import torch +import torch.nn.functional as F + +from ultralytics.data.augment import LetterBox +from ultralytics.engine.predictor import BasePredictor +from ultralytics.engine.results import Results +from ultralytics.utils import DEFAULT_CFG, LOGGER, ops +from ultralytics.utils.metrics import box_iou, mask_iou +from ultralytics.utils.torch_utils import select_device, smart_inference_mode + +from .amg import ( + batch_iterator, + batched_mask_to_box, + build_all_layer_point_grids, + calculate_stability_score, + generate_crop_boxes, + is_box_near_crop_edge, + remove_small_regions, + uncrop_boxes_xyxy, + uncrop_masks, +) + +if TYPE_CHECKING: + from .sam3.geometry_encoders import Prompt + + +class Predictor(BasePredictor): + """Predictor class for SAM, enabling real-time image segmentation with promptable capabilities. + + This class extends BasePredictor and implements the Segment Anything Model (SAM) for advanced image segmentation + tasks. It supports various input prompts like points, bounding boxes, and masks for fine-grained control over + segmentation results. + + Attributes: + args (SimpleNamespace): Configuration arguments for the predictor. + model (torch.nn.Module): The loaded SAM model. + device (torch.device): The device (CPU or GPU) on which the model is loaded. + im (torch.Tensor): The preprocessed input image. + features (torch.Tensor): Extracted image features. + prompts (dict[str, Any]): Dictionary to store various types of prompts (e.g., bboxes, points, masks). + segment_all (bool): Flag to indicate if full image segmentation should be performed. + non_overlap_masks (bool): Whether each pixel is assigned to at most one of the predicted masks. + mean (torch.Tensor): Mean values for image normalization. + std (torch.Tensor): Standard deviation values for image normalization. + + Methods: + preprocess: Prepare input images for model inference. + pre_transform: Perform initial transformations on the input image. + inference: Perform segmentation inference based on input prompts. + prompt_inference: Internal function for prompt-based segmentation inference. + generate: Generate segmentation masks for an entire image. + setup_model: Initialize the SAM model for inference. + get_model: Build and return a SAM model. + postprocess: Post-process model outputs to generate final results. + setup_source: Set up the data source for inference. + set_image: Set and preprocess a single image for inference. + get_im_features: Extract image features using the SAM image encoder. + set_prompts: Set prompts for subsequent inference. + reset_image: Reset the current image and its features. + remove_small_regions: Remove small disconnected regions and holes from masks. + + Examples: + >>> predictor = Predictor() + >>> predictor.setup_model(model_path="sam_model.pt") + >>> predictor.set_image("image.jpg") + >>> bboxes = [[100, 100, 200, 200]] + >>> results = predictor(bboxes=bboxes) + """ + + stride = 16 + + def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks: dict | None = None): + """Initialize the Predictor with configuration, overrides, and callbacks. + + Sets up the Predictor object for SAM (Segment Anything Model) and applies any configuration overrides or + callbacks provided. Initializes task-specific settings for SAM, such as retina_masks being set to True for + optimal results. + + Args: + cfg (dict): Configuration dictionary containing default settings. + overrides (dict | None): Dictionary of values to override default configuration. + _callbacks (dict | None): Dictionary of callback functions to customize behavior. + """ + if overrides is None: + overrides = {} + overrides.update({"task": "segment", "mode": "predict", "batch": 1}) + super().__init__(cfg, overrides, _callbacks) + self.args.retina_masks = True + self.im = None + self.features = None + self.prompts = {} + self.segment_all = False + self.non_overlap_masks = False + + def preprocess(self, im): + """Preprocess the input image for model inference. + + This method prepares the input image by applying transformations and normalization. It supports both + torch.Tensor and list of np.ndarray as input formats. For OpenCV-loaded images, the input is typically BGR and + is converted to RGB during preprocessing. + + Args: + im (torch.Tensor | list[np.ndarray]): Input image(s) in BCHW tensor format or a list of HWC NumPy arrays. + NumPy arrays are expected to be in BGR order (as returned by OpenCV) and will be converted to RGB. + + Returns: + (torch.Tensor): The preprocessed image tensor, normalized and converted to the appropriate dtype. + + Examples: + >>> predictor = Predictor() + >>> image = torch.rand(1, 3, 640, 640) + >>> preprocessed_image = predictor.preprocess(image) + """ + if self.im is not None: + return self.im + not_tensor = not isinstance(im, torch.Tensor) + if not_tensor: + im = np.stack(self.pre_transform(im)) + im = im[..., ::-1].transpose((0, 3, 1, 2)) + im = np.ascontiguousarray(im) + im = torch.from_numpy(im) + + im = im.to(self.device) + if not_tensor: + im = (im - self.mean) / self.std + im = im.half() if self.model.fp16 else im.float() + return im + + def pre_transform(self, im): + """Perform initial transformations on the input image for preprocessing. + + This method applies transformations such as resizing to prepare the image for further preprocessing. Currently, + batched inference is not supported; hence the list length should be 1. + + Args: + im (list[np.ndarray]): List containing a single image in HWC numpy array format. + + Returns: + (list[np.ndarray]): List containing the transformed image. + + Raises: + AssertionError: If the input list contains more than one image. + + Examples: + >>> predictor = Predictor() + >>> predictor.imgsz = [1024, 1024] # normally set by setup_source() + >>> image = np.random.rand(480, 640, 3) # Single HWC image + >>> transformed = predictor.pre_transform([image]) + >>> print(len(transformed)) + 1 + """ + assert len(im) == 1, "SAM model does not currently support batched inference" + letterbox = LetterBox(self.imgsz, auto=False, center=False) + return [letterbox(image=x) for x in im] + + @property + def src_shape(self): + """Return the source image (height, width): an HWC array from files and streams, or a CHW tensor source.""" + im0 = self.batch[1][0] + return im0.shape[-2:] if isinstance(im0, torch.Tensor) else im0.shape[:2] + + def inference(self, im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False, *args, **kwargs): + """Perform image segmentation inference based on the given input cues, using the currently loaded image. + + This method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt encoder, + and mask decoder for real-time and promptable segmentation tasks. + + Args: + im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W). + bboxes (np.ndarray | list | None): Bounding boxes with shape (N, 4), in XYXY format. + points (np.ndarray | list | None): Points indicating object locations with shape (N, 2), in pixels. + labels (np.ndarray | list | None): Labels for point prompts, shape (N,). 1 = foreground, 0 = background. + masks (np.ndarray | None): Low-resolution masks from previous predictions, shape (N, H, W). For SAM H=W=256. + multimask_output (bool): Flag to return multiple masks. Helpful for ambiguous prompts. + *args (Any): Additional positional arguments. + **kwargs (Any): Additional keyword arguments. + + Returns: + pred_masks (torch.Tensor): The output masks in shape (C, H, W), where C is the number of generated masks. + pred_scores (torch.Tensor): An array of length C containing quality scores predicted by the model for each + mask. + + Examples: + >>> predictor = Predictor() + >>> predictor.setup_model(model_path="sam_model.pt") + >>> predictor.set_image("image.jpg") + >>> results = predictor(bboxes=[[0, 0, 100, 100]]) + """ + # Override prompts if any stored in self.prompts + bboxes = self.prompts.pop("bboxes", bboxes) + points = self.prompts.pop("points", points) + masks = self.prompts.pop("masks", masks) + labels = self.prompts.pop("labels", labels) + + if all(i is None for i in [bboxes, points, masks]): + return self.generate(im, *args, **kwargs) + + return self.prompt_inference(im, bboxes, points, labels, masks, multimask_output) + + def prompt_inference(self, im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False): + """Perform image segmentation inference based on input cues using SAM's specialized architecture. + + This internal function leverages the Segment Anything Model (SAM) for prompt-based, real-time segmentation. It + processes various input prompts such as bounding boxes, points, and masks to generate segmentation masks. + + Args: + im (torch.Tensor): Preprocessed input image tensor with shape (N, C, H, W). + bboxes (np.ndarray | list | None): Bounding boxes in XYXY format with shape (N, 4). + points (np.ndarray | list | None): Points indicating object locations with shape (N, 2) or (N, num_points, + 2), in pixels. + labels (np.ndarray | list | None): Point prompt labels with shape (N) or (N, num_points). 1 for foreground, + 0 for background. + masks (np.ndarray | None): Low-res masks from previous predictions with shape (N, H, W). For SAM, H=W=256. + multimask_output (bool): Flag to return multiple masks for ambiguous prompts. + + Returns: + pred_masks (torch.Tensor): Output masks with shape (C, H, W), where C is the number of generated masks. + pred_scores (torch.Tensor): Quality scores predicted by the model for each mask, with length C. + + Examples: + >>> predictor = Predictor() + >>> im = torch.rand(1, 3, 1024, 1024) + >>> bboxes = [[100, 100, 200, 200]] + >>> masks, scores = predictor.prompt_inference(im, bboxes=bboxes) + """ + features = self.get_im_features(im) if self.features is None else self.features + prompts = self._prepare_prompts(im.shape[2:], self.src_shape, bboxes, points, labels, masks) + return self._inference_features(features, *prompts, multimask_output) + + def _inference_features( + self, + features, + bboxes=None, + points=None, + labels=None, + masks=None, + multimask_output=False, + ): + """Perform inference on image features using the SAM model. + + Args: + features (torch.Tensor): Extracted image features with shape (B, C, H, W) from the SAM model image encoder. + bboxes (np.ndarray | list[list[float]] | None): Bounding boxes in XYXY format with shape (N, 4). + points (np.ndarray | list[list[float]] | None): Object location points with shape (N, 2), in pixels. + labels (np.ndarray | list[int] | None): Point prompt labels with shape (N,). 1 = foreground, 0 = background. + masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array. + multimask_output (bool): Flag to return multiple masks for ambiguous prompts. + + Returns: + pred_masks (torch.Tensor): Output masks with shape (C, H, W), where C is the number of generated masks. + pred_scores (torch.Tensor): Quality scores for each mask, with length C. + """ + points = (points, labels) if points is not None else None + # Embed prompts + sparse_embeddings, dense_embeddings = self.model.prompt_encoder(points=points, boxes=bboxes, masks=masks) + + # Predict masks + pred_masks, pred_scores = self.model.mask_decoder( + image_embeddings=features, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + + # (N, d, H, W) --> (N*d, H, W), (N, d) --> (N*d, ) + # `d` could be 1 or 3 depends on `multimask_output`. + return pred_masks.flatten(0, 1), pred_scores.flatten(0, 1) + + def _prepare_prompts(self, dst_shape, src_shape, bboxes=None, points=None, labels=None, masks=None): + """Prepare and transform the input prompts for processing based on the destination shape. + + Args: + dst_shape (tuple[int, int]): The target shape (height, width) for the prompts. + src_shape (tuple[int, int]): The source shape (height, width) of the input image. + bboxes (np.ndarray | list | None): Bounding boxes in XYXY format with shape (N, 4). + points (np.ndarray | list | None): Points indicating object locations with shape (N, 2) or (N, num_points, + 2), in pixels. + labels (np.ndarray | list | None): Point prompt labels with shape (N) or (N, num_points). 1 for foreground, + 0 for background. + masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array with + shape (H, W). + + Returns: + bboxes (torch.Tensor | None): Transformed bounding boxes. + points (torch.Tensor | None): Transformed points. + labels (torch.Tensor | None): Transformed labels. + masks (torch.Tensor | None): Transformed masks. + + Raises: + AssertionError: If the number of points don't match the number of labels, in case labels were passed. + """ + r = 1.0 if self.segment_all else min(dst_shape[0] / src_shape[0], dst_shape[1] / src_shape[1]) + # Transform input prompts + if points is not None: + points = torch.as_tensor(points, dtype=self.torch_dtype, device=self.device) + points = points[None] if points.ndim == 1 else points + # Assuming labels are all positive if users don't pass labels. + if labels is None: + labels = np.ones(points.shape[:-1]) + labels = torch.as_tensor(labels, dtype=torch.int32, device=self.device) + assert points.shape[-2] == labels.shape[-1], ( + f"Number of points {points.shape[-2]} should match number of labels {labels.shape[-1]}." + ) + points *= r + if points.ndim == 2: + # (N, 2) --> (N, 1, 2), (N, ) --> (N, 1) + points, labels = points[:, None, :], labels[:, None] + if bboxes is not None: + bboxes = torch.as_tensor(bboxes, dtype=self.torch_dtype, device=self.device) + bboxes = bboxes[None] if bboxes.ndim == 1 else bboxes + bboxes *= r + if masks is not None: + masks = np.asarray(masks, dtype=np.uint8) + masks = masks[None] if masks.ndim == 2 else masks + letterbox = LetterBox(dst_shape, auto=False, center=False, padding_value=0, interpolation=cv2.INTER_NEAREST) + masks = np.stack([letterbox(image=x).squeeze() for x in masks], axis=0) + masks = torch.tensor(masks, dtype=self.torch_dtype, device=self.device) + return bboxes, points, labels, masks + + def generate( + self, + im, + crop_n_layers=0, + crop_overlap_ratio=512 / 1500, + crop_downscale_factor=1, + point_grids=None, + points_stride=32, + points_batch_size=64, + conf_thres=0.88, + stability_score_thresh=0.95, + stability_score_offset=0.95, + crop_nms_thresh=0.7, + min_mask_region_area=0, + ): + """Perform image segmentation using the Segment Anything Model (SAM). + + This method segments an entire image into constituent parts by leveraging SAM's advanced architecture and + real-time performance capabilities. It can optionally work on image crops for finer segmentation. + + Args: + im (torch.Tensor): Input tensor representing the preprocessed image with shape (N, C, H, W). + crop_n_layers (int): Number of layers for additional mask predictions on image crops. + crop_overlap_ratio (float): Overlap between crops, scaled down in subsequent layers. + crop_downscale_factor (int): Scaling factor for sampled points-per-side in each layer. + point_grids (list[np.ndarray] | None): Custom grids for point sampling normalized to [0,1]. + points_stride (int): Number of points to sample along each side of the image. + points_batch_size (int): Batch size for the number of points processed simultaneously. + conf_thres (float): Confidence threshold [0,1] on the predicted mask quality; the predictor's conf also + applies after the cross-crop NMS. + stability_score_thresh (float): Stability threshold [0,1] for mask filtering based on stability. + stability_score_offset (float): Offset value for calculating stability score. + crop_nms_thresh (float): IoU cutoff for NMS to remove duplicate masks between crops. + min_mask_region_area (int): If > 0, remove disconnected regions and holes smaller than this area in + original-image pixels (the largest region of a mask is always kept), then re-run NMS on the + cleaned masks. + + Returns: + pred_masks (torch.Tensor): Segmented masks with shape (N, H, W). + pred_scores (torch.Tensor): Confidence scores for each mask with shape (N,). + pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 4). + + Examples: + >>> predictor = Predictor() + >>> im = torch.rand(1, 3, 1024, 1024) # Example input image + >>> masks, scores, boxes = predictor.generate(im) + """ + import torchvision # scope for faster 'import ultralytics' + + self.segment_all = True + ih, iw = im.shape[2:] + crop_regions, layer_idxs = generate_crop_boxes((ih, iw), crop_n_layers, crop_overlap_ratio) + if point_grids is None: + point_grids = build_all_layer_point_grids(points_stride, crop_n_layers, crop_downscale_factor) + pred_masks, pred_scores, pred_bboxes, region_areas = [], [], [], [] + for crop_region, layer_idx in zip(crop_regions, layer_idxs): + x1, y1, x2, y2 = crop_region + w, h = x2 - x1, y2 - y1 + area = torch.tensor(w * h, device=im.device) + points_scale = np.array([[iw, ih]]) # the crop is resized to the model input, so prompts live in that space + # Crop image and interpolate to input size + crop_im = F.interpolate(im[..., y1:y2, x1:x2], (ih, iw), mode="bilinear", align_corners=False) + crop_features = self.get_im_features(crop_im) + points_for_image = point_grids[layer_idx] * points_scale + crop_masks, crop_scores, crop_bboxes = [], [], [] + for (points,) in batch_iterator(points_batch_size, points_for_image): + prompts = self._prepare_prompts(crop_im.shape[2:], self.src_shape, points=points) + pred_mask, pred_score = self._inference_features(crop_features, *prompts, multimask_output=True) + # Interpolate predicted masks to input size + pred_mask = F.interpolate(pred_mask[None], (h, w), mode="bilinear", align_corners=False)[0] + idx = pred_score > conf_thres + pred_mask, pred_score = pred_mask[idx], pred_score[idx] + + stability_score = calculate_stability_score( + pred_mask, self.model.mask_threshold, stability_score_offset + ) + idx = stability_score > stability_score_thresh + pred_mask, pred_score = pred_mask[idx], pred_score[idx] + # Bool type is much more memory-efficient. + pred_mask = pred_mask > self.model.mask_threshold + # (N, 4) + pred_bbox = batched_mask_to_box(pred_mask).float() + keep_mask = ~is_box_near_crop_edge(pred_bbox, crop_region, [0, 0, iw, ih]) + if not torch.all(keep_mask): + pred_bbox, pred_mask, pred_score = pred_bbox[keep_mask], pred_mask[keep_mask], pred_score[keep_mask] + + crop_masks.append(pred_mask) + crop_bboxes.append(pred_bbox) + crop_scores.append(pred_score) + + # Do nms within this crop + crop_masks = torch.cat(crop_masks) + crop_bboxes = torch.cat(crop_bboxes) + crop_scores = torch.cat(crop_scores) + keep = torchvision.ops.nms(crop_bboxes, crop_scores, self.args.iou) # NMS + crop_bboxes = uncrop_boxes_xyxy(crop_bboxes[keep], crop_region) + crop_masks = uncrop_masks(crop_masks[keep], crop_region, ih, iw) + crop_scores = crop_scores[keep] + + pred_masks.append(crop_masks) + pred_bboxes.append(crop_bboxes) + pred_scores.append(crop_scores) + region_areas.append(area.expand(crop_masks.shape[0])) + + pred_masks = torch.cat(pred_masks) + pred_bboxes = torch.cat(pred_bboxes) + pred_scores = torch.cat(pred_scores) + region_areas = torch.cat(region_areas) + + # Remove duplicate masks between crops + if len(crop_regions) > 1: + scores = 1 / region_areas + keep = torchvision.ops.nms(pred_bboxes, scores, crop_nms_thresh) + pred_masks, pred_bboxes, pred_scores = pred_masks[keep], pred_bboxes[keep], pred_scores[keep] + + idx = pred_scores > self.args.conf # postprocess applies conf too, so it must not decide the cleanup NMS + pred_masks, pred_scores, pred_bboxes = pred_masks[idx], pred_scores[idx], pred_bboxes[idx] + + if min_mask_region_area > 0: + h0, w0 = self.src_shape + gain = min(ih / h0, iw / w0) # masks are in letterboxed model space, the threshold is in original pixels + min_area = min_mask_region_area * gain * gain + pred_masks, keep = self.remove_small_regions(pred_masks, min_area, max(self.args.iou, crop_nms_thresh)) + pred_scores, pred_bboxes = pred_scores[keep], batched_mask_to_box(pred_masks).float() + + return pred_masks, pred_scores, pred_bboxes + + @smart_inference_mode(False) # the model outlives this call, so its weights must not be inference tensors + def setup_model(self, model=None, verbose=True): + """Initialize the Segment Anything Model (SAM) for inference. + + This method sets up the SAM model by allocating it to the appropriate device and initializing the necessary + parameters for image normalization and other Ultralytics compatibility settings. + + Args: + model (torch.nn.Module | None): A pretrained SAM model. If None, a new model is built based on config. + verbose (bool): If True, prints selected device information. + + Examples: + >>> predictor = Predictor() + >>> predictor.setup_model(model=sam_model, verbose=True) + """ + device = select_device(self.args.device, verbose=verbose) + if self.args.channels_last: + LOGGER.warning("'channels_last=True' is not supported for SAM predictors, ignoring.") + if model is None: + model = self.get_model() + # Move model to device first, then cast dtype, then set eval so any eval-time caches are created on-device. + model = model.to(device) + model = model.half() if self.args.quantize == 16 else model.float() + model.eval() + self.model = model + self.device = device + self.mean = torch.tensor([123.675, 116.28, 103.53]).view(-1, 1, 1).to(device) + self.std = torch.tensor([58.395, 57.12, 57.375]).view(-1, 1, 1).to(device) + + # Ultralytics compatibility settings + self.model.format = "sam" + self.model.base_model = False # SAMModel is no Ultralytics BaseModel and honors neither `augment` nor `embed` + self.model.stride = 32 + self.model.fp16 = self.args.quantize == 16 + self.done_warmup = True + self.torch_dtype = torch.float16 if self.model.fp16 else torch.float32 + + def get_model(self): + """Retrieve or build the Segment Anything Model (SAM) for image segmentation tasks.""" + from .build import build_sam # slow import + + return build_sam(self.args.model) + + def postprocess(self, preds, img, orig_imgs): + """Post-process SAM's inference outputs to generate object detection masks and bounding boxes. + + This method scales masks and boxes to the original image size and applies a threshold to the mask + predictions. It leverages SAM's advanced architecture for real-time, promptable segmentation tasks. + + Args: + preds (tuple): The output from SAM model inference, containing: + - pred_masks (torch.Tensor): Predicted masks with shape (N, 1, H, W). + - pred_scores (torch.Tensor): Confidence scores for each mask with shape (N, 1). + - pred_bboxes (torch.Tensor, optional): Predicted bounding boxes if segment_all is True. + img (torch.Tensor): The processed input image tensor with shape (C, H, W). + orig_imgs (list[np.ndarray] | torch.Tensor): The original, unprocessed images. + + Returns: + (list[Results]): List of Results objects containing detection masks, bounding boxes, and other metadata for + each processed image. + + Examples: + >>> predictor = Predictor() + >>> preds = predictor.inference(img) + >>> results = predictor.postprocess(preds, img, orig_imgs) + """ + # (N, 1, H, W), (N, 1) + pred_masks, pred_scores = preds[:2] + pred_bboxes = preds[2] if self.segment_all else None + names = dict(enumerate(str(i) for i in range(pred_masks.shape[0]))) + + if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list + orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)[..., ::-1] + + results = [] + for masks, orig_img, img_path in zip([pred_masks], orig_imgs, self.batch[0]): + if masks.shape[0] == 0: + masks, pred_bboxes = None, torch.zeros((0, 6), device=pred_masks.device) + else: + idx = pred_scores > self.args.conf + masks = ops.scale_masks(masks[idx][None].float(), orig_img.shape[:2], padding=False)[0] + if self.non_overlap_masks: + masks = self.model._apply_non_overlapping_constraints(masks[:, None])[:, 0] + masks = masks > self.model.mask_threshold # to bool + if pred_bboxes is not None: + pred_bboxes = ops.scale_boxes( + img.shape[2:], pred_bboxes[idx].float(), orig_img.shape, padding=False + ) + else: + pred_bboxes = batched_mask_to_box(masks) + # NOTE: SAM models do not return cls info. This `cls` here is just a placeholder for consistency. + cls = torch.arange(pred_masks.shape[0], dtype=torch.int32, device=pred_masks.device)[idx] + pred_bboxes = torch.cat([pred_bboxes, pred_scores[idx, None], cls[:, None]], dim=-1) + results.append(Results(orig_img, path=img_path, names=names, masks=masks, boxes=pred_bboxes)) + # Reset segment-all mode. + self.segment_all = False + return results + + @smart_inference_mode() + def set_image(self, image): + """Preprocess and set a single image for inference. + + This method prepares the model for inference on a single image by setting up the model if not already + initialized, configuring the data source, and preprocessing the image for feature extraction. It ensures that + only one image is set at a time and extracts image features for subsequent use. + + Args: + image (str | np.ndarray): Path to the image file as a string, or a numpy array representing an image read by + cv2 (BGR channel order). + + Raises: + AssertionError: If more than one image is attempted to be set. + + Examples: + >>> predictor = Predictor() + >>> predictor.set_image("path/to/image.jpg") + >>> predictor.set_image(cv2.imread("path/to/image.jpg")) + + Notes: + - This method should be called before performing inference on a new image. + - The extracted features are stored in the `self.features` attribute for later use. + """ + if self.model is None: + self.setup_model() + self.setup_source(image) + assert len(self.dataset) == 1, "`set_image` only supports setting one image!" + for batch in self.dataset: + im = self.preprocess(batch[1]) + self.features = self.get_im_features(im) + break + + def setup_source(self, source): + """Set up the data source for SAM inference.""" + if source is None: # handle the situation when set_imgsz in advance + return + super().setup_source(source, self.stride) + assert isinstance(self.imgsz, (tuple, list)) and self.imgsz[0] == self.imgsz[1], ( + f"SAM models only support square image size, but got {self.imgsz}." + ) + self.model.set_imgsz(self.imgsz) + + def get_im_features(self, im): + """Extract image features using the SAM model's image encoder for subsequent mask prediction.""" + return self.model.image_encoder(im) + + def set_prompts(self, prompts): + """Set prompts for subsequent inference operations.""" + self.prompts = prompts + + def reset_image(self): + """Reset the current image and its features, clearing them for subsequent inference.""" + self.im = None + self.features = None + + @staticmethod + def remove_small_regions(masks, min_area=0, nms_thresh=0.7): + """Remove small disconnected regions and holes from segmentation masks. + + This function performs post-processing on segmentation masks generated by the Segment Anything Model (SAM). It + removes small disconnected regions and holes from the input masks, and then performs Non-Maximum Suppression + (NMS) to eliminate any newly created duplicate boxes. + + Args: + masks (torch.Tensor): Segmentation masks to be processed, with shape (N, H, W) where N is the number of + masks, H is height, and W is width. + min_area (float): Minimum area threshold for removing disconnected regions and holes. Regions smaller than + this will be removed. + nms_thresh (float): IoU threshold for the NMS algorithm to remove duplicate boxes. + + Returns: + new_masks (torch.Tensor): Processed masks with small regions removed, shape (N, H, W). + keep (torch.Tensor): Indices of remaining masks after NMS, for filtering corresponding boxes. + + Examples: + >>> masks = torch.rand(5, 640, 640) > 0.5 # 5 random binary masks + >>> new_masks, keep = remove_small_regions(masks, min_area=100, nms_thresh=0.7) + >>> print(f"Original masks: {masks.shape}, Processed masks: {new_masks.shape}") + >>> print(f"Indices of kept masks: {keep}") + """ + import torchvision # scope for faster 'import ultralytics' + + if masks.shape[0] == 0: + return masks, torch.arange(0) + + # Filter small disconnected regions and holes + new_masks = [] + scores = [] + for mask in masks: + mask = mask.cpu().numpy().astype(np.uint8) + mask, changed = remove_small_regions(mask, min_area, mode="holes") + unchanged = not changed + mask, changed = remove_small_regions(mask, min_area, mode="islands") + unchanged = unchanged and not changed + + new_masks.append(torch.as_tensor(mask).unsqueeze(0)) + # Give score=0 to changed masks and 1 to unchanged masks so NMS prefers masks not needing postprocessing + scores.append(float(unchanged)) + + # Recalculate boxes and remove any new duplicates + new_masks = torch.cat(new_masks, dim=0) + # batched_mask_to_box requires bool masks; on uint8 it returns all-zero boxes and the NMS dedup below is a no-op + boxes = batched_mask_to_box(new_masks.bool()) + keep = torchvision.ops.nms(boxes.float(), torch.as_tensor(scores), nms_thresh) + + return new_masks[keep].to(device=masks.device, dtype=masks.dtype), keep + + @smart_inference_mode() + def inference_features( + self, + features, + src_shape, + dst_shape=None, + bboxes=None, + points=None, + labels=None, + masks=None, + multimask_output=False, + ): + """Perform prompts preprocessing and inference on provided image features using the SAM model. + + Args: + features (torch.Tensor | dict[str, Any]): Extracted image features from the SAM/SAM2 model image encoder. + src_shape (tuple[int, int]): The source shape (height, width) of the input image. + dst_shape (tuple[int, int] | None): The target shape (height, width) for the prompts. If None, defaults to + (imgsz, imgsz). + bboxes (np.ndarray | list[list[float]] | None): Bounding boxes in xyxy format with shape (N, 4). + points (np.ndarray | list[list[float]] | None): Points indicating object locations with shape (N, 2), in + pixels. + labels (np.ndarray | list[int] | None): Point prompt labels with shape (N, ). + masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array. + multimask_output (bool): Flag to return multiple masks for ambiguous prompts. + + Returns: + pred_masks (torch.Tensor): The output masks in shape (C, H, W), where C is the number of generated masks. + pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 6), where N is the number of boxes. + Each box is in xyxy format with additional columns for score and class. + + Notes: + - The input features is a torch.Tensor of shape (B, C, H, W) if performing on SAM, or a dict[str, Any] if performing on SAM2. + """ + dst_shape = dst_shape or (self.args.imgsz, self.args.imgsz) + prompts = self._prepare_prompts(dst_shape, src_shape, bboxes, points, labels, masks) + pred_masks, pred_scores = self._inference_features(features, *prompts, multimask_output) + if pred_masks.shape[0] == 0: + pred_masks, pred_bboxes = None, torch.zeros((0, 6), device=pred_masks.device) + else: + pred_masks = ops.scale_masks(pred_masks[None].float(), src_shape, padding=False)[0] + pred_masks = pred_masks > self.model.mask_threshold # to bool + pred_bboxes = batched_mask_to_box(pred_masks) + # NOTE: SAM models do not return cls info. This `cls` here is just a placeholder for consistency. + cls = torch.arange(pred_masks.shape[0], dtype=torch.int32, device=pred_masks.device) + pred_bboxes = torch.cat([pred_bboxes, pred_scores[:, None], cls[:, None]], dim=-1) + return pred_masks, pred_bboxes + + +class SAM2Predictor(Predictor): + """SAM2Predictor class for advanced image segmentation using Segment Anything Model 2 architecture. + + This class extends the base Predictor class to implement SAM2-specific functionality for image segmentation tasks. + It provides methods for model initialization, feature extraction, and prompt-based inference. + + Attributes: + _bb_feat_sizes (list[tuple]): Feature sizes for different backbone levels. + model (torch.nn.Module): The loaded SAM2 model. + device (torch.device): The device (CPU or GPU) on which the model is loaded. + features (dict): Cached image features for efficient inference. + segment_all (bool): Flag to indicate if all segments should be predicted. + prompts (dict[str, Any]): Dictionary to store various types of prompts for inference. + + Methods: + get_model: Retrieve and initialize the SAM2 model. + prompt_inference: Perform image segmentation inference based on various prompts. + set_image: Preprocess and set a single image for inference. + get_im_features: Extract and process image features using SAM2's image encoder. + + Examples: + >>> predictor = SAM2Predictor(cfg) + >>> predictor.set_image("path/to/image.jpg") + >>> bboxes = [[100, 100, 200, 200]] + >>> result = predictor(bboxes=bboxes)[0] + >>> print(f"Predicted {len(result.masks)} masks with average score {result.boxes.conf.mean():.2f}") + """ + + _bb_feat_sizes = [ + (256, 256), + (128, 128), + (64, 64), + ] + stride = 16 + + def get_model(self): + """Retrieve and initialize the Segment Anything Model 2 (SAM2) for image segmentation tasks.""" + from .build import build_sam # slow import + + return build_sam(self.args.model) + + def _prepare_prompts(self, dst_shape, src_shape, bboxes=None, points=None, labels=None, masks=None): + """Prepare and transform the input prompts for processing based on the destination shape. + + Args: + dst_shape (tuple[int, int]): The target shape (height, width) for the prompts. + src_shape (tuple[int, int]): The source shape (height, width) of the input image. + bboxes (np.ndarray | list | None): Bounding boxes in XYXY format with shape (N, 4). + points (np.ndarray | list | None): Points indicating object locations with shape (N, 2) or (N, num_points, + 2), in pixels. + labels (np.ndarray | list | None): Point prompt labels with shape (N,) or (N, num_points). 1 for foreground, + 0 for background. + masks (list | np.ndarray | None): Masks for the objects, where each mask is a 2D array. + + Returns: + points (torch.Tensor | None): Transformed points. + labels (torch.Tensor | None): Transformed labels. + masks (torch.Tensor | None): Transformed masks. + + Raises: + AssertionError: If the number of points don't match the number of labels, in case labels were passed. + """ + bboxes, points, labels, masks = super()._prepare_prompts(dst_shape, src_shape, bboxes, points, labels, masks) + if bboxes is not None: + bboxes = bboxes.view(-1, 2, 2) + bbox_labels = torch.tensor([[2, 3]], dtype=torch.int32, device=bboxes.device).expand(bboxes.shape[0], -1) + # NOTE: merge "boxes" and "points" into a single "points" input + # (where boxes are added at the beginning) to model.sam_prompt_encoder + if points is not None: + points = torch.cat([bboxes, points], dim=1) + labels = torch.cat([bbox_labels, labels], dim=1) + else: + points, labels = bboxes, bbox_labels + return points, labels, masks + + def setup_source(self, source): + """Set up the data source and image size for SAM2 inference.""" + super().setup_source(source) + self._bb_feat_sizes = [[int(x / (self.stride * i)) for x in self.imgsz] for i in [1 / 4, 1 / 2, 1]] + + def get_im_features(self, im): + """Extract image features from the SAM image encoder for subsequent processing.""" + backbone_out = self.model.forward_image(im) + _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out) + if self.model.directly_add_no_mem_embed: + vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed + feats = [ + feat.permute(1, 2, 0).view(1, -1, *feat_size) for feat, feat_size in zip(vision_feats, self._bb_feat_sizes) + ] + return {"image_embed": feats[-1], "high_res_feats": feats[:-1]} + + def _inference_features( + self, + features, + points=None, + labels=None, + masks=None, + multimask_output=False, + img_idx=-1, + ): + """Perform inference on image features using the SAM2 model. + + Args: + features (torch.Tensor | dict[str, Any]): Extracted image features with shape (B, C, H, W) from the SAM2 + model image encoder. Can also be a dict with 'image_embed' (torch.Tensor) of shape (B, C, H, W) and + 'high_res_feats' (list[torch.Tensor]) high-resolution feature maps from the backbone. + points (np.ndarray | list[list[float]] | None): Object location points with shape (N, 2), in pixels. + labels (np.ndarray | list[int] | None): Point prompt labels with shape (N,). 1 = foreground, 0 = background. + masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array. + multimask_output (bool): Flag to return multiple masks for ambiguous prompts. + img_idx (int): Index of the image in the batch to process. + + Returns: + pred_masks (torch.Tensor): Output masks with shape (C, H, W), where C is the number of generated masks. + pred_scores (torch.Tensor): Quality scores for each mask, with length C. + """ + points = (points, labels) if points is not None else None + sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder( + points=points, + boxes=None, + masks=masks, + ) + # Predict masks + batched_mode = points is not None and points[0].shape[0] > 1 # multi object prediction + high_res_features = None + if isinstance(features, dict): + high_res_features = [feat_level[img_idx].unsqueeze(0) for feat_level in features["high_res_feats"]] + features = features["image_embed"][[img_idx]] + pred_masks, pred_scores, _, _ = self.model.sam_mask_decoder( + image_embeddings=features, + image_pe=self.model.sam_prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + repeat_image=batched_mode, + high_res_features=high_res_features, + ) + # (N, d, H, W) --> (N*d, H, W), (N, d) --> (N*d, ) + # `d` could be 1 or 3 depends on `multimask_output`. + return pred_masks.flatten(0, 1), pred_scores.flatten(0, 1) + + +class SAM2VideoPredictor(SAM2Predictor): + """SAM2VideoPredictor to handle user interactions with videos and manage inference states. + + This class extends the functionality of SAM2Predictor to support video processing and maintains the state of + inference operations. It includes configurations for managing non-overlapping masks and clearing memory for + non-conditional inputs. + + Attributes: + inference_state (dict): A dictionary to store the current state of inference operations. + non_overlap_masks (bool): A flag indicating whether masks should be non-overlapping. + clear_non_cond_mem_around_input (bool): A flag to control clearing non-conditional memory around inputs. + clear_non_cond_mem_for_multi_obj (bool): A flag to control clearing non-conditional memory for multi-object + scenarios. + + Methods: + get_model: Retrieve and configure the model with binarization enabled. + inference: Perform image segmentation inference based on the given input cues. + add_new_prompts: Add new points or masks to a specific frame for a given object ID. + propagate_in_video_preflight: Prepare inference_state and consolidate temporary outputs before tracking. + init_state: Initialize an inference state for the predictor. + get_im_features: Extract image features using SAM2's image encoder for subsequent segmentation tasks. + + Examples: + >>> predictor = SAM2VideoPredictor(cfg=DEFAULT_CFG) + >>> predictor.set_image("path/to/video_frame.jpg") + >>> bboxes = [[100, 100, 200, 200]] + >>> results = predictor(bboxes=bboxes) + + Notes: + The `fill_hole_area` attribute is defined but not used in the current implementation. + """ + + # fill_hole_area = 8 # not used + + def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks: dict | None = None): + """Initialize the predictor with configuration and optional overrides. + + This constructor initializes the SAM2VideoPredictor with a given configuration, applies any specified overrides, + and sets up the inference state along with certain flags that control the behavior of the predictor. + + Args: + cfg (dict): Configuration dictionary containing default settings. + overrides (dict | None): Dictionary of values to override default configuration. + _callbacks (dict | None): Dictionary of callback functions to customize behavior. + """ + super().__init__(cfg, overrides, _callbacks) + self.inference_state = {} + self.non_overlap_masks = True + self.clear_non_cond_mem_around_input = False + self.clear_non_cond_mem_for_multi_obj = False + self.clear_non_cond_mem = True # Whether to clear non-conditioning memory periodically + + def setup_source(self, source): + """Set up the source and build the video inference state before any prediction callback runs.""" + super().setup_source(source) + if self.dataset is not None and self.dataset.mode == "video": + self.init_state(self) + + def get_model(self): + """Retrieve and configure the model with binarization enabled. + + Notes: + This method overrides the base class implementation to set the binarize flag to True. + """ + model = super().get_model() + model.set_binarize(True) + return model + + def inference(self, im, bboxes=None, points=None, labels=None, masks=None): + """Perform image segmentation inference based on the given input cues, using the currently loaded image. This + method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt + encoder, and mask decoder for real-time and promptable segmentation tasks. + + Args: + im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W). + bboxes (np.ndarray | list, optional): Bounding boxes with shape (N, 4), in XYXY format. + points (np.ndarray | list, optional): Points indicating object locations with shape (N, 2), in pixels. + labels (np.ndarray | list, optional): Labels for point prompts, shape (N, ). 1 = foreground, 0 = background. + masks (np.ndarray, optional): Low-resolution masks from previous predictions shape (N,H,W). For SAM H=W=256. + + Returns: + pred_masks (torch.Tensor): The output masks in shape CxHxW, where C is the number of generated masks. + pred_scores (torch.Tensor): An array of length C containing predicted quality scores for each mask. + """ + # Override prompts if any stored in self.prompts + bboxes = self.prompts.pop("bboxes", bboxes) + points = self.prompts.pop("points", points) + masks = self.prompts.pop("masks", masks) + + frame = self.dataset.frame + self.inference_state["im"] = im + output_dict = self.inference_state["output_dict"] + if len(output_dict["cond_frame_outputs"]) == 0: # initialize prompts + points, labels, masks = self._prepare_prompts(im.shape[2:], self.src_shape, bboxes, points, labels, masks) + if points is not None: + for i in range(len(points)): + self.add_new_prompts(obj_id=i, points=points[[i]], labels=labels[[i]], frame_idx=frame) + elif masks is not None: + for i in range(len(masks)): + self.add_new_prompts(obj_id=i, masks=masks[[i]], frame_idx=frame) + self.propagate_in_video_preflight() + + consolidated_frame_inds = self.inference_state["consolidated_frame_inds"] + batch_size = len(self.inference_state["obj_idx_to_id"]) + if len(output_dict["cond_frame_outputs"]) == 0: + raise RuntimeError("No points are provided; please add points first") + + if frame in consolidated_frame_inds["cond_frame_outputs"]: + storage_key = "cond_frame_outputs" + current_out = output_dict[storage_key][frame] + if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1): + # clear non-conditioning memory of the surrounding frames + self._clear_non_cond_mem_around_input(frame) + elif frame in consolidated_frame_inds["non_cond_frame_outputs"]: + storage_key = "non_cond_frame_outputs" + current_out = output_dict[storage_key][frame] + else: + storage_key = "non_cond_frame_outputs" + current_out = self._run_single_frame_inference( + output_dict=output_dict, + frame_idx=frame, + batch_size=batch_size, + is_init_cond_frame=False, + point_inputs=None, + mask_inputs=None, + reverse=False, + run_mem_encoder=True, + ) + output_dict[storage_key][frame] = current_out + self._prune_non_cond_memory(frame) + # Create slices of per-object outputs for subsequent interaction with each + # individual object after tracking. + self._add_output_per_object(frame, current_out, storage_key) + self.inference_state["frames_already_tracked"].append(frame) + pred_masks = current_out["pred_masks"].flatten(0, 1) + pred_masks = pred_masks[(pred_masks > self.model.mask_threshold).sum((1, 2)) > 0] # filter blank masks + + return pred_masks, torch.ones(pred_masks.shape[0], dtype=pred_masks.dtype, device=pred_masks.device) + + @smart_inference_mode() + def add_new_prompts( + self, + obj_id, + points=None, + labels=None, + masks=None, + frame_idx=0, + inference_state: dict[str, Any] | None = None, + ): + """Add new points or masks to a specific frame for a given object ID. + + This method updates the inference state with new prompts (points or masks) for a specified object and frame + index. It ensures that the prompts are either points or masks, but not both, and updates the internal state + accordingly. It also handles the generation of new segmentations based on the provided prompts and the existing + state. + + Args: + obj_id (int): The ID of the object to which the prompts are associated. + points (torch.Tensor, optional): The coordinates of the points of interest. + labels (torch.Tensor, optional): The labels corresponding to the points. + masks (torch.Tensor, optional): Binary masks for the object. + frame_idx (int, optional): The index of the frame to which the prompts are applied. + inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's + inference state. + + Returns: + pred_masks (torch.Tensor): The flattened predicted masks. + pred_scores (torch.Tensor): A tensor of ones indicating the number of objects. + + Raises: + AssertionError: If both `masks` and `points` are provided, or neither is provided. + + Notes: + - Only one type of prompt (either points or masks) can be added per call. + - If the frame is being tracked for the first time, it is treated as an initial conditioning frame. + - The method handles the consolidation of outputs and resizing of masks to the original video resolution. + """ + inference_state = inference_state or self.inference_state + assert (masks is None) ^ (points is None), "'masks' and 'points' prompts are not compatible with each other." + obj_idx = self._obj_id_to_idx(obj_id, inference_state) + + point_inputs = None + pop_key = "point_inputs_per_obj" + if points is not None: + point_inputs = {"point_coords": points, "point_labels": labels} + inference_state["point_inputs_per_obj"][obj_idx][frame_idx] = point_inputs + pop_key = "mask_inputs_per_obj" + inference_state["mask_inputs_per_obj"][obj_idx][frame_idx] = masks + inference_state[pop_key][obj_idx].pop(frame_idx, None) + # If this frame hasn't been tracked before, we treat it as an initial conditioning + # frame, meaning that the inputs points are to generate segments on this frame without + # using any memory from other frames, like in SAM. Otherwise (if it has been tracked), + # the input points will be used to correct the already tracked masks. + is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"] + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] + obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] + # Add a frame to conditioning output if it's an initial conditioning frame or + # if the model sees all frames receiving clicks/mask as conditioning frames. + is_cond = is_init_cond_frame or self.model.add_all_frames_to_correct_as_cond + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + + # Get any previously predicted mask logits on this object and feed it along with + # the new clicks into the SAM mask decoder. + prev_sam_mask_logits = None + # lookup temporary output dict first, which contains the most recent output + # (if not found, then lookup conditioning and non-conditioning frame output) + if point_inputs is not None: + prev_out = ( + obj_temp_output_dict[storage_key].get(frame_idx) + or obj_output_dict["cond_frame_outputs"].get(frame_idx) + or obj_output_dict["non_cond_frame_outputs"].get(frame_idx) + ) + + if prev_out is not None and prev_out.get("pred_masks") is not None: + prev_sam_mask_logits = prev_out["pred_masks"].to( + device=self.device, non_blocking=self.device.type == "cuda" + ) + # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues. + prev_sam_mask_logits.clamp_(-32.0, 32.0) + current_out = self._run_single_frame_inference( + output_dict=obj_output_dict, # run on the slice of a single object + frame_idx=frame_idx, + batch_size=1, # run on the slice of a single object + is_init_cond_frame=is_init_cond_frame, + point_inputs=point_inputs, + mask_inputs=masks, + reverse=False, + # Skip the memory encoder when adding clicks or mask. We execute the memory encoder + # at the beginning of `propagate_in_video` (after user finalize their clicks). This + # allows us to enforce non-overlapping constraints on all objects before encoding + # them into memory. + run_mem_encoder=False, + prev_sam_mask_logits=prev_sam_mask_logits, + inference_state=inference_state, + ) + # Add the output to the output dict (to be used as future memory) + obj_temp_output_dict[storage_key][frame_idx] = current_out + + # Resize the output mask to the original video resolution + consolidated_out = self._consolidate_temp_output_across_obj( + frame_idx, + is_cond=is_cond, + run_mem_encoder=False, + inference_state=inference_state, + ) + pred_masks = consolidated_out["pred_masks"].flatten(0, 1) + return pred_masks.flatten(0, 1), torch.ones(1, dtype=pred_masks.dtype, device=pred_masks.device) + + @smart_inference_mode() + def propagate_in_video_preflight(self, inference_state: dict[str, Any] | None = None): + """Prepare inference_state and consolidate temporary outputs before tracking. + + This method marks the start of tracking, disallowing the addition of new objects until the session is reset. It + consolidates temporary outputs from `temp_output_dict_per_obj` and merges them into `output_dict`. Additionally, + it clears non-conditioning memory around input frames and ensures that the state is consistent with the provided + inputs. + + Args: + inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's + inference state. + """ + inference_state = inference_state or self.inference_state + # Tracking has started and we don't allow adding new objects until session is reset. + inference_state["tracking_has_started"] = True + batch_size = len(inference_state["obj_idx_to_id"]) + + # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and + # add them into "output_dict". + temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"] + output_dict = inference_state["output_dict"] + # "consolidated_frame_inds" contains indices of those frames where consolidated + # temporary outputs have been added (either in this call or any previous calls + # to `propagate_in_video_preflight`). + consolidated_frame_inds = inference_state["consolidated_frame_inds"] + for is_cond in (False, True): + # Separately consolidate conditioning and non-conditioning temp outputs + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + # Find all the frames that contain temporary outputs for any objects + # (these should be the frames that have just received clicks for mask inputs + # via `add_new_points` or `add_new_mask`) + temp_frame_inds = set() + for obj_temp_output_dict in temp_output_dict_per_obj.values(): + temp_frame_inds.update(obj_temp_output_dict[storage_key].keys()) + consolidated_frame_inds[storage_key].update(temp_frame_inds) + # consolidate the temporary output across all objects on this frame + for frame_idx in temp_frame_inds: + consolidated_out = self._consolidate_temp_output_across_obj( + frame_idx, is_cond=is_cond, run_mem_encoder=True, inference_state=inference_state + ) + # merge them into "output_dict" and also create per-object slices + output_dict[storage_key][frame_idx] = consolidated_out + self._add_output_per_object(frame_idx, consolidated_out, storage_key, inference_state=inference_state) + if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1): + # clear non-conditioning memory of the surrounding frames + self._clear_non_cond_mem_around_input(frame_idx) + + # clear temporary outputs in `temp_output_dict_per_obj` + for obj_temp_output_dict in temp_output_dict_per_obj.values(): + obj_temp_output_dict[storage_key].clear() + + # edge case: if an output is added to "cond_frame_outputs", we remove any prior + # output on the same frame in "non_cond_frame_outputs" + for frame_idx in output_dict["cond_frame_outputs"]: + output_dict["non_cond_frame_outputs"].pop(frame_idx, None) + for obj_output_dict in inference_state["output_dict_per_obj"].values(): + for frame_idx in obj_output_dict["cond_frame_outputs"]: + obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None) + for frame_idx in consolidated_frame_inds["cond_frame_outputs"]: + assert frame_idx in output_dict["cond_frame_outputs"] + consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx) + + # Make sure that the frame indices in "consolidated_frame_inds" are exactly those frames + # with either points or mask inputs (which should be true under a correct workflow). + all_consolidated_frame_inds = ( + consolidated_frame_inds["cond_frame_outputs"] | consolidated_frame_inds["non_cond_frame_outputs"] + ) + input_frames_inds = set() + for point_inputs_per_frame in inference_state["point_inputs_per_obj"].values(): + input_frames_inds.update(point_inputs_per_frame.keys()) + for mask_inputs_per_frame in inference_state["mask_inputs_per_obj"].values(): + input_frames_inds.update(mask_inputs_per_frame.keys()) + assert all_consolidated_frame_inds == input_frames_inds + + @staticmethod + def init_state(predictor): + """Initialize an inference state for the predictor. + + This function sets up the initial state required for performing inference on video data. It includes + initializing various dictionaries and ordered dictionaries that will store inputs, outputs, and other metadata + relevant to the tracking process. + + Args: + predictor (SAM2VideoPredictor): The predictor object for which to initialize the state. + """ + if len(predictor.inference_state) > 0: # means initialized + return + assert predictor.dataset is not None + assert predictor.dataset.mode == "video" + predictor.inference_state = predictor._init_state(predictor.dataset.frames) + + @staticmethod + def _init_state(num_frames): + """Initialize an inference state. + + This function sets up the initial state required for performing inference on video data. It includes + initializing various dictionaries and ordered dictionaries that will store inputs, outputs, and other metadata + relevant to the tracking process. + + Args: + num_frames (int): The number of frames in the video. + """ + inference_state = { + "num_frames": num_frames, # TODO: see if there's any chance to remove it + "point_inputs_per_obj": {}, # inputs points on each frame + "mask_inputs_per_obj": {}, # inputs mask on each frame + "constants": {}, # values that don't change across frames (so we only need to hold one copy of them) + # mapping between client-side object id and model-side object index + "obj_id_to_idx": OrderedDict(), + "obj_idx_to_id": OrderedDict(), + "obj_ids": [], + # A storage to hold the model's tracking results and states on each frame + "output_dict": { + "cond_frame_outputs": {}, # dict containing {frame_idx: } + "non_cond_frame_outputs": {}, # dict containing {frame_idx: } + }, + # Slice (view) of each object tracking results, sharing the same memory with "output_dict" + "output_dict_per_obj": {}, + # A temporary storage to hold new outputs when user interact with a frame + # to add clicks or mask (it's merged into "output_dict" before propagation starts) + "temp_output_dict_per_obj": {}, + # Frames that already holds consolidated outputs from click or mask inputs + # (we directly use their consolidated outputs during tracking) + "consolidated_frame_inds": { + "cond_frame_outputs": set(), # set containing frame indices + "non_cond_frame_outputs": set(), # set containing frame indices + }, + # metadata for each tracking frame (e.g. which direction it's tracked) + "tracking_has_started": False, + "frames_already_tracked": [], + } + return inference_state + + def get_im_features(self, im, batch=1): + """Extract and process image features using SAM2's image encoder for subsequent segmentation tasks. + + Args: + im (torch.Tensor): The input image tensor. + batch (int, optional): The batch size for expanding features if there are multiple prompts. + + Returns: + vis_feats (torch.Tensor): The visual features extracted from the image. + vis_pos_embed (torch.Tensor): The positional embeddings for the visual features. + feat_sizes (list[tuple]): A list containing the sizes of the extracted features. + + Notes: + - If `batch` is greater than 1, the features are expanded to fit the batch size. + - The method leverages the model's `_prepare_backbone_features` method to prepare the backbone features. + """ + # check if there's precomputed backbone output + backbone_out = getattr(self, "backbone_out", None) + if backbone_out is None: + backbone_out = self.model.forward_image(im) + _, vis_feats, vis_pos_embed, feat_sizes = self.model._prepare_backbone_features(backbone_out, batch=batch) + return vis_feats, vis_pos_embed, feat_sizes + + def _obj_id_to_idx(self, obj_id, inference_state: dict[str, Any] | None = None): + """Map client-side object id to model-side object index. + + Args: + obj_id (int): The unique identifier of the object provided by the client side. + inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's + inference state. + + Returns: + (int): The index of the object on the model side. + + Raises: + RuntimeError: If an attempt is made to add a new object after tracking has started. + + Notes: + - The method updates or retrieves mappings between object IDs and indices stored in + `inference_state`. + - It ensures that new objects can only be added before tracking commences. + - It maintains two-way mappings between IDs and indices (`obj_id_to_idx` and `obj_idx_to_id`). + - Additional data structures are initialized for the new object to store inputs and outputs. + """ + inference_state = inference_state or self.inference_state + obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None) + if obj_idx is not None: + return obj_idx + + # This is a new object id not sent to the server before. We only allow adding + # new objects *before* the tracking starts. + allow_new_object = not inference_state["tracking_has_started"] + if allow_new_object: + # get the next object slot + obj_idx = len(inference_state["obj_id_to_idx"]) + inference_state["obj_id_to_idx"][obj_id] = obj_idx + inference_state["obj_idx_to_id"][obj_idx] = obj_id + inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"]) + # set up input and output structures for this object + inference_state["point_inputs_per_obj"][obj_idx] = {} + inference_state["mask_inputs_per_obj"][obj_idx] = {} + inference_state["output_dict_per_obj"][obj_idx] = { + "cond_frame_outputs": {}, # dict containing {frame_idx: } + "non_cond_frame_outputs": {}, # dict containing {frame_idx: } + } + inference_state["temp_output_dict_per_obj"][obj_idx] = { + "cond_frame_outputs": {}, # dict containing {frame_idx: } + "non_cond_frame_outputs": {}, # dict containing {frame_idx: } + } + return obj_idx + else: + raise RuntimeError( + f"Cannot add new object id {obj_id} after tracking starts. " + f"All existing object ids: {inference_state['obj_ids']}. " + f"Please call 'reset_state' to restart from scratch." + ) + + def _run_single_frame_inference( + self, + output_dict, + frame_idx, + batch_size, + is_init_cond_frame, + point_inputs, + mask_inputs, + reverse, + run_mem_encoder, + prev_sam_mask_logits=None, + inference_state: dict[str, Any] | None = None, + ): + """Run tracking on a single frame based on current inputs and previous memory. + + Args: + output_dict (dict): The dictionary containing the output states of the tracking process. + frame_idx (int): The index of the current frame. + batch_size (int): The batch size for processing the frame. + is_init_cond_frame (bool): Indicates if the current frame is an initial conditioning frame. + point_inputs (dict | None): Input points and their labels. + mask_inputs (torch.Tensor | None): Input binary masks. + reverse (bool): Indicates if the tracking should be performed in reverse order. + run_mem_encoder (bool): Indicates if the memory encoder should be executed. + prev_sam_mask_logits (torch.Tensor | None): Previous mask logits for the current object. + inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's + inference state. + + Returns: + (dict): A dictionary containing the output of the tracking step, including updated features and predictions. + + Raises: + AssertionError: If both `point_inputs` and `mask_inputs` are provided simultaneously. + + Notes: + - The method assumes that `point_inputs` and `mask_inputs` are mutually exclusive. + - The method retrieves image features using the `get_im_features` method. + - The `maskmem_pos_enc` is assumed to be constant across frames, hence only one copy is stored. + - The `fill_holes_in_mask_scores` function is commented out and currently unsupported due to CUDA extension requirements. + """ + inference_state = inference_state or self.inference_state + # Retrieve correct image features + current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features( + inference_state["im"], batch_size + ) + + # point and mask should not appear as input simultaneously on the same frame + assert point_inputs is None or mask_inputs is None + current_out = self.model.track_step( + frame_idx=frame_idx, + is_init_cond_frame=is_init_cond_frame, + current_vision_feats=current_vision_feats, + current_vision_pos_embeds=current_vision_pos_embeds, + feat_sizes=feat_sizes, + point_inputs=point_inputs, + mask_inputs=mask_inputs, + output_dict=output_dict, + num_frames=inference_state["num_frames"], + track_in_reverse=reverse, + run_mem_encoder=run_mem_encoder, + prev_sam_mask_logits=prev_sam_mask_logits, + ) + + maskmem_features = current_out["maskmem_features"] + if maskmem_features is not None: + current_out["maskmem_features"] = maskmem_features.to( + dtype=torch.float16, device=self.device, non_blocking=self.device.type == "cuda" + ) + # NOTE: Do not support the `fill_holes_in_mask_scores` function since it needs cuda extensions + # potentially fill holes in the predicted masks + # if self.fill_hole_area > 0: + # pred_masks = current_out["pred_masks"].to(self.device, non_blocking=self.device.type == "cuda") + # pred_masks = fill_holes_in_mask_scores(pred_masks, self.fill_hole_area) + + # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it + current_out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(current_out["maskmem_pos_enc"], inference_state) + return current_out + + def _get_maskmem_pos_enc(self, out_maskmem_pos_enc, inference_state: dict[str, Any] | None = None): + """Cache and manage the positional encoding for mask memory across frames and objects. + + This method optimizes storage by caching the positional encoding (`maskmem_pos_enc`) for mask memory, which is + constant across frames and objects, thus reducing the amount of redundant information stored during an inference + session. It checks if the positional encoding has already been cached; if not, it caches a slice of the provided + encoding. If the batch size is greater than one, it expands the cached positional encoding to match the current + batch size. + + Args: + out_maskmem_pos_enc (list[torch.Tensor] | None): The positional encoding for mask memory. Should be a list + of tensors or None. + inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's + inference state. + + Returns: + (list[torch.Tensor]): The positional encoding for mask memory, either cached or expanded. + + Notes: + - The method assumes that `out_maskmem_pos_enc` is a list of tensors or None. + - Only a single object's slice is cached since the encoding is the same across objects. + - The method checks if the positional encoding has already been cached in the session's constants. + - If the batch size is greater than one, the cached encoding is expanded to fit the batch size. + """ + inference_state = inference_state or self.inference_state + model_constants = inference_state["constants"] + # "out_maskmem_pos_enc" should be either a list of tensors or None + if out_maskmem_pos_enc is not None: + if "maskmem_pos_enc" not in model_constants: + assert isinstance(out_maskmem_pos_enc, list) + # only take the slice for one object, since it's same across objects + maskmem_pos_enc = [x[:1].clone() for x in out_maskmem_pos_enc] + model_constants["maskmem_pos_enc"] = maskmem_pos_enc + else: + maskmem_pos_enc = model_constants["maskmem_pos_enc"] + # expand the cached maskmem_pos_enc to the actual batch size + batch_size = out_maskmem_pos_enc[0].shape[0] + if batch_size > 1: + out_maskmem_pos_enc = [x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc] + return out_maskmem_pos_enc + + def _consolidate_temp_output_across_obj( + self, + frame_idx, + is_cond=False, + run_mem_encoder=False, + inference_state: dict[str, Any] | None = None, + ): + """Consolidate per-object temporary outputs into a single output for all objects. + + This method combines the temporary outputs for each object on a given frame into a unified + output. It fills in any missing objects either from the main output dictionary or leaves + placeholders if they do not exist in the main output. Optionally, it can re-run the memory encoder after + applying non-overlapping constraints to the object scores. + + Args: + frame_idx (int): The index of the frame for which to consolidate outputs. + is_cond (bool, optional): Indicates if the frame is considered a conditioning frame. + run_mem_encoder (bool, optional): Specifies whether to run the memory encoder after consolidating the + outputs. + inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's + inference state. + + Returns: + (dict): A consolidated output dictionary containing the combined results for all objects. + + Notes: + - The method initializes the consolidated output with placeholder values for missing objects. + - It searches for outputs in both the temporary and main output dictionaries. + - If `run_mem_encoder` is True, it applies non-overlapping constraints and re-runs the memory encoder. + - The `maskmem_features` and `maskmem_pos_enc` are only populated when `run_mem_encoder` is True. + """ + inference_state = inference_state or self.inference_state + batch_size = len(inference_state["obj_idx_to_id"]) + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + + # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc" + # will be added when rerunning the memory encoder after applying non-overlapping + # constraints to object scores. Its "pred_masks" are prefilled with a large + # negative value (NO_OBJ_SCORE) to represent missing objects. + consolidated_out = { + "maskmem_features": None, + "maskmem_pos_enc": None, + "pred_masks": torch.full( + # size=(batch_size, 1, self.imgsz[0] // 4, self.imgsz[1] // 4), + size=(batch_size, 1, *self._bb_feat_sizes[0]), + fill_value=-1024.0, + dtype=self.torch_dtype, + device=self.device, + ), + "obj_ptr": torch.full( + size=(batch_size, self.model.hidden_dim), + fill_value=-1024.0, + dtype=self.torch_dtype, + device=self.device, + ), + "object_score_logits": torch.full( + size=(batch_size, 1), + # default to 10.0 for object_score_logits, i.e. assuming the object is + # present as sigmoid(10)=1, same as in `predict_masks` of `MaskDecoder` + fill_value=10.0, + dtype=self.torch_dtype, + device=self.device, + ), + } + for obj_idx in range(batch_size): + obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] + out = ( + obj_temp_output_dict[storage_key].get(frame_idx) + # If the object doesn't appear in "temp_output_dict_per_obj" on this frame, + # we fall back and look up its previous output in "output_dict_per_obj". + # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in + # "output_dict_per_obj" to find a previous output for this object. + or obj_output_dict["cond_frame_outputs"].get(frame_idx) + or obj_output_dict["non_cond_frame_outputs"].get(frame_idx) + ) + # If the object doesn't appear in "output_dict_per_obj" either, we skip it + # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE + # placeholder above) and set its object pointer to be a dummy pointer. + if out is None: + # Fill in dummy object pointers for those objects without any inputs or + # tracking outcomes on this frame (only do it under `run_mem_encoder=True`, + # i.e. when we need to build the memory for tracking). + if run_mem_encoder: + # fill object pointer with a dummy pointer (based on an empty mask) + consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = self._get_empty_mask_ptr(frame_idx) + continue + # Add the temporary object output mask to consolidated output mask + consolidated_out["pred_masks"][obj_idx : obj_idx + 1] = out["pred_masks"] + consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"] + + # Optionally, apply non-overlapping constraints on the consolidated scores and rerun the memory encoder + if run_mem_encoder: + high_res_masks = F.interpolate( + consolidated_out["pred_masks"], + size=self.imgsz, + mode="bilinear", + align_corners=False, + ) + if self.model.non_overlap_masks_for_mem_enc: + high_res_masks = self.model._apply_non_overlapping_constraints(high_res_masks) + consolidated_out["maskmem_features"], consolidated_out["maskmem_pos_enc"] = self._run_memory_encoder( + batch_size=batch_size, + high_res_masks=high_res_masks, + is_mask_from_pts=True, # these frames are what the user interacted with + object_score_logits=consolidated_out["object_score_logits"], + inference_state=inference_state, + ) + + return consolidated_out + + def _get_empty_mask_ptr(self, frame_idx, inference_state: dict[str, Any] | None = None): + """Get a dummy object pointer based on an empty mask on the current frame. + + Args: + frame_idx (int): The index of the current frame for which to generate the dummy object pointer. + inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's + inference state. + + Returns: + (torch.Tensor): A tensor representing the dummy object pointer generated from the empty mask. + """ + inference_state = inference_state or self.inference_state + # Retrieve correct image features + current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(inference_state["im"]) + + # Feed the empty mask and image feature above to get a dummy object pointer + current_out = self.model.track_step( + frame_idx=frame_idx, + is_init_cond_frame=True, + current_vision_feats=current_vision_feats, + current_vision_pos_embeds=current_vision_pos_embeds, + feat_sizes=feat_sizes, + point_inputs=None, + # A dummy (empty) mask with a single object + mask_inputs=torch.zeros((1, 1, *self.imgsz), dtype=self.torch_dtype, device=self.device), + output_dict={}, + num_frames=inference_state["num_frames"], + track_in_reverse=False, + run_mem_encoder=False, + prev_sam_mask_logits=None, + ) + return current_out["obj_ptr"] + + def _run_memory_encoder( + self, + batch_size, + high_res_masks, + object_score_logits, + is_mask_from_pts, + inference_state: dict[str, Any] | None = None, + ): + """Run the memory encoder on masks. + + This is usually after applying non-overlapping constraints to object scores. Since their scores changed, their + memory also needs to be computed again with the memory encoder. + + Args: + batch_size (int): The batch size for processing the frame. + high_res_masks (torch.Tensor): High-resolution masks for which to compute the memory. + object_score_logits (torch.Tensor): Logits representing the object scores. + is_mask_from_pts (bool): Indicates if the mask is derived from point interactions. + inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's + inference state. + + Returns: + maskmem_features (torch.Tensor): The encoded mask features. + maskmem_pos_enc (torch.Tensor): The positional encoding. + """ + inference_state = inference_state or self.inference_state + # Retrieve correct image features + current_vision_feats, _, feat_sizes = self.get_im_features(inference_state["im"], batch_size) + maskmem_features, maskmem_pos_enc = self.model._encode_new_memory( + current_vision_feats=current_vision_feats, + feat_sizes=feat_sizes, + pred_masks_high_res=high_res_masks, + is_mask_from_pts=is_mask_from_pts, + object_score_logits=object_score_logits, + ) + + # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it + maskmem_pos_enc = self._get_maskmem_pos_enc(maskmem_pos_enc, inference_state) + return maskmem_features.to( + dtype=torch.float16, device=self.device, non_blocking=self.device.type == "cuda" + ), maskmem_pos_enc + + def _add_output_per_object( + self, frame_idx, current_out, storage_key, inference_state: dict[str, Any] | None = None + ): + """Split a multi-object output into per-object output slices and add them into Output_Dict_Per_Obj. + + The resulting slices share the same tensor storage. + + Args: + frame_idx (int): The index of the current frame. + current_out (dict): The current output dictionary containing multi-object outputs. + storage_key (str): The key used to store the output in the per-object output dictionary. + inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's + inference state. + """ + inference_state = inference_state or self.inference_state + maskmem_features = current_out["maskmem_features"] + assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor) + + maskmem_pos_enc = current_out["maskmem_pos_enc"] + assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list) + + for obj_idx, obj_output_dict in inference_state["output_dict_per_obj"].items(): + obj_slice = slice(obj_idx, obj_idx + 1) + obj_out = { + "maskmem_features": None, + "maskmem_pos_enc": None, + "pred_masks": current_out["pred_masks"][obj_slice], + "obj_ptr": current_out["obj_ptr"][obj_slice], + } + if maskmem_features is not None: + obj_out["maskmem_features"] = maskmem_features[obj_slice] + if maskmem_pos_enc is not None: + obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc] + obj_output_dict[storage_key][frame_idx] = obj_out + + def _clear_non_cond_mem_around_input(self, frame_idx, inference_state: dict[str, Any] | None = None): + """Remove the non-conditioning memory around the input frame. + + When users provide correction clicks, the surrounding frames' non-conditioning memories can still contain + outdated object appearance information and could confuse the model. This method clears those non-conditioning + memories surrounding the interacted frame to avoid giving the model both old and new information about the + object. + + Args: + frame_idx (int): The index of the current frame where user interaction occurred. + inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's + inference state. + """ + inference_state = inference_state or self.inference_state + r = self.model.memory_temporal_stride_for_eval + frame_idx_begin = frame_idx - r * self.model.num_maskmem + frame_idx_end = frame_idx + r * self.model.num_maskmem + for t in range(frame_idx_begin, frame_idx_end + 1): + inference_state["output_dict"]["non_cond_frame_outputs"].pop(t, None) + for obj_output_dict in inference_state["output_dict_per_obj"].values(): + obj_output_dict["non_cond_frame_outputs"].pop(t, None) + + @smart_inference_mode() + def remove_object(self, inference_state, obj_id, strict=False): + """Remove an object id from the tracking state. If strict is True, we check whether the object id actually + exists and raise an error if it doesn't exist. + """ + old_obj_idx_to_rm = inference_state["obj_id_to_idx"].get(obj_id, None) + # Check whether this object_id to remove actually exists and possibly raise an error. + if old_obj_idx_to_rm is None: + if not strict: + return inference_state["obj_ids"] + raise RuntimeError( + f"Cannot remove object id {obj_id} as it doesn't exist. " + f"All existing object ids: {inference_state['obj_ids']}." + ) + + # If this is the only remaining object id, we simply reset the state. + if len(inference_state["obj_id_to_idx"]) == 1: + self.clear_all_points_in_video(inference_state) + return inference_state["obj_ids"] + + # There are still remaining objects after removing this object id. In this case, + # we need to delete the object storage from inference state tensors. + # Step 0: clear the input on those frames where this object id has point or mask input + # (note that this step is required as it might downgrade conditioning frames to + # non-conditioning ones) + obj_input_frames_inds = set() + obj_input_frames_inds.update(inference_state["point_inputs_per_obj"][old_obj_idx_to_rm]) + obj_input_frames_inds.update(inference_state["mask_inputs_per_obj"][old_obj_idx_to_rm]) + for frame_idx in obj_input_frames_inds: + self.clear_all_points_in_frame(inference_state, frame_idx, obj_id) + + # Step 1: Update the object id mapping (note that it must be done after Step 0, + # since Step 0 still requires the old object id mappings in inference_state) + old_obj_ids = inference_state["obj_ids"] + old_obj_inds = list(range(len(old_obj_ids))) + remain_old_obj_inds = old_obj_inds.copy() + remain_old_obj_inds.remove(old_obj_idx_to_rm) + new_obj_ids = [old_obj_ids[old_idx] for old_idx in remain_old_obj_inds] + new_obj_inds = list(range(len(new_obj_ids))) + # build new mappings + old_idx_to_new_idx = dict(zip(remain_old_obj_inds, new_obj_inds)) + inference_state["obj_id_to_idx"] = dict(zip(new_obj_ids, new_obj_inds)) + inference_state["obj_idx_to_id"] = dict(zip(new_obj_inds, new_obj_ids)) + inference_state["obj_ids"] = new_obj_ids + + # Step 2: For per-object tensor storage, we shift their obj_idx in the dict keys. + # (note that "consolidated_frame_inds" doesn't need to be updated in this step as + # it's already handled in Step 0) + def _map_keys(container): + new_kvs = [] + for k in old_obj_inds: + v = container.pop(k) + if k in old_idx_to_new_idx: + new_kvs.append((old_idx_to_new_idx[k], v)) + container.update(new_kvs) + + _map_keys(inference_state["point_inputs_per_obj"]) + _map_keys(inference_state["mask_inputs_per_obj"]) + _map_keys(inference_state["output_dict_per_obj"]) + _map_keys(inference_state["temp_output_dict_per_obj"]) + + # Step 3: For packed tensor storage, we index the remaining ids and rebuild the per-object slices. + def _slice_state(output_dict, storage_key): + for frame_idx, out in output_dict[storage_key].items(): + out["maskmem_features"] = out["maskmem_features"][remain_old_obj_inds] + out["maskmem_pos_enc"] = [x[remain_old_obj_inds] for x in out["maskmem_pos_enc"]] + # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it + out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(out["maskmem_pos_enc"], inference_state) + out["pred_masks"] = out["pred_masks"][remain_old_obj_inds] + out["obj_ptr"] = out["obj_ptr"][remain_old_obj_inds] + out["object_score_logits"] = out["object_score_logits"][remain_old_obj_inds] + # also update the per-object slices + self._add_output_per_object(frame_idx, out, storage_key, inference_state=inference_state) + + _slice_state(inference_state["output_dict"], "cond_frame_outputs") + _slice_state(inference_state["output_dict"], "non_cond_frame_outputs") + + return inference_state["obj_ids"] + + @smart_inference_mode() + def clear_all_points_in_frame(self, inference_state, frame_idx, obj_id): + """Remove all input points or mask in a specific frame for a given object.""" + obj_idx = self._obj_id_to_idx(obj_id, inference_state) + + # Clear the conditioning information on the given frame + inference_state["point_inputs_per_obj"][obj_idx].pop(frame_idx, None) + inference_state["mask_inputs_per_obj"][obj_idx].pop(frame_idx, None) + + temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"] + temp_output_dict_per_obj[obj_idx]["cond_frame_outputs"].pop(frame_idx, None) + temp_output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].pop(frame_idx, None) + + # Check and see if there are still any inputs left on this frame + batch_size = len(inference_state["obj_idx_to_id"]) + frame_has_input = False + for obj_idx2 in range(batch_size): + if frame_idx in inference_state["point_inputs_per_obj"][obj_idx2]: + frame_has_input = True + break + if frame_idx in inference_state["mask_inputs_per_obj"][obj_idx2]: + frame_has_input = True + break + + # If this frame has no remaining inputs for any objects, we further clear its + # conditioning frame status + if not frame_has_input: + output_dict = inference_state["output_dict"] + consolidated_frame_inds = inference_state["consolidated_frame_inds"] + consolidated_frame_inds["cond_frame_outputs"].discard(frame_idx) + consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx) + # Remove the frame's conditioning output (possibly downgrading it to non-conditioning) + out = output_dict["cond_frame_outputs"].pop(frame_idx, None) + if out is not None: + # The frame is not a conditioning frame anymore since it's not receiving inputs, + # so we "downgrade" its output (if exists) to a non-conditioning frame output. + output_dict["non_cond_frame_outputs"][frame_idx] = out + inference_state["frames_already_tracked"].pop(frame_idx, None) + # Similarly, do it for the sliced output on each object. + for obj_idx2 in range(batch_size): + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx2] + obj_out = obj_output_dict["cond_frame_outputs"].pop(frame_idx, None) + if obj_out is not None: + obj_output_dict["non_cond_frame_outputs"][frame_idx] = obj_out + + # If all the conditioning frames have been removed, we also clear the tracking outputs + if len(output_dict["cond_frame_outputs"]) == 0: + self._reset_tracking_results(inference_state) + + @smart_inference_mode() + def clear_all_points_in_video(self, inference_state): + """Remove all input points or mask in all frames throughout the video.""" + self._reset_tracking_results(inference_state) + # Remove all object ids + inference_state["obj_id_to_idx"].clear() + inference_state["obj_idx_to_id"].clear() + inference_state["obj_ids"].clear() + inference_state["point_inputs_per_obj"].clear() + inference_state["mask_inputs_per_obj"].clear() + inference_state["output_dict_per_obj"].clear() + inference_state["temp_output_dict_per_obj"].clear() + + @staticmethod + def _reset_tracking_results(inference_state): + """Reset all tracking inputs and results across the videos.""" + for v in inference_state["point_inputs_per_obj"].values(): + v.clear() + for v in inference_state["mask_inputs_per_obj"].values(): + v.clear() + for v in inference_state["output_dict_per_obj"].values(): + v["cond_frame_outputs"].clear() + v["non_cond_frame_outputs"].clear() + for v in inference_state["temp_output_dict_per_obj"].values(): + v["cond_frame_outputs"].clear() + v["non_cond_frame_outputs"].clear() + inference_state["output_dict"]["cond_frame_outputs"].clear() + inference_state["output_dict"]["non_cond_frame_outputs"].clear() + inference_state["consolidated_frame_inds"]["cond_frame_outputs"].clear() + inference_state["consolidated_frame_inds"]["non_cond_frame_outputs"].clear() + inference_state["tracking_has_started"] = False + inference_state["frames_already_tracked"].clear() + inference_state["first_ann_frame_idx"] = None + + def _prune_non_cond_memory(self, frame_idx, inference_state=None): + """Prune old non-conditioning frames to bound memory usage.""" + if not self.clear_non_cond_mem: + return + inference_state = inference_state or self.inference_state + + # Determine window size + min_frame = frame_idx - self.model.num_maskmem * self.model.memory_temporal_stride_for_eval + output_dict = inference_state["output_dict"] + + # Prune global non_cond_frame_outputs + for f in [k for k in output_dict["non_cond_frame_outputs"] if k < min_frame]: + output_dict["non_cond_frame_outputs"].pop(f, None) + + # Prune per-object non_cond_frame_outputs + for obj_output_dict in inference_state.get("output_dict_per_obj", {}).values(): + for f in [k for k in obj_output_dict["non_cond_frame_outputs"] if k < min_frame]: + obj_output_dict["non_cond_frame_outputs"].pop(f, None) + + +class SAM2DynamicInteractivePredictor(SAM2Predictor): + """SAM2DynamicInteractivePredictor extends SAM2Predictor to support dynamic interactions with video frames or a + sequence of images. + + Attributes: + memory_bank (list): OrderedDict: Stores the states of each image with prompts. + obj_idx_set (set): A set to keep track of the object indices that have been added. + obj_id_to_idx (OrderedDict): Maps object IDs to their corresponding indices. + obj_idx_to_id (OrderedDict): Maps object indices to their corresponding IDs. + + Methods: + get_model: Retrieves and configures the model with binarization enabled. + inference: Performs inference on a single image with optional prompts and object IDs. + postprocess: Post-processes the predictions to apply non-overlapping constraints if required. + update_memory: Append the imgState to the memory_bank and update the memory for the model. + track_step: Tracking step for the current image state to predict masks. + get_maskmem_enc: Get memory and positional encoding from the memory bank. + + Examples: + >>> predictor = SAM2DynamicInteractivePredictor(cfg=DEFAULT_CFG) + >>> predictor(source=support_img1, bboxes=bboxes1, obj_ids=labels1, update_memory=True) + >>> results1 = predictor(source=query_img1) + >>> predictor(source=support_img2, bboxes=bboxes2, obj_ids=labels2, update_memory=True) + >>> results2 = predictor(source=query_img2) + """ + + def __init__( + self, + cfg: Any = DEFAULT_CFG, + overrides: dict[str, Any] | None = None, + max_obj_num: int = 3, + _callbacks: dict | None = None, + ) -> None: + """Initialize the predictor with configuration and optional overrides. + + This constructor initializes the SAM2DynamicInteractivePredictor with a given configuration, applies any + specified overrides + + Args: + cfg (Any): Configuration dictionary containing default settings. + overrides (dict[str, Any] | None): Dictionary of values to override default configuration. + max_obj_num (int): Maximum number of objects to track. Default is 3. This is set to keep fixed feature size + for the model. + _callbacks (dict | None): Dictionary of callback functions to customize behavior. + """ + super().__init__(cfg, overrides, _callbacks) + self.non_overlap_masks = True + + # Initialize the memory bank to store image states + # NOTE: probably need to use dict for better query + self.memory_bank = [] + + # Initialize the object index set and mappings + self.obj_idx_set = set() + self.obj_id_to_idx = self.obj_idx_to_id = OrderedDict(enumerate(range(max_obj_num))) + self._max_obj_num = max_obj_num + + @smart_inference_mode() + def inference( + self, + im: torch.Tensor | np.ndarray, + bboxes: list[list[float]] | None = None, + masks: torch.Tensor | np.ndarray | None = None, + points: list[list[float]] | None = None, + labels: list[int] | None = None, + obj_ids: list[int] | None = None, + update_memory: bool = False, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Perform inference on a single image with optional bounding boxes, masks, points and object IDs. It has two + modes: one is to run inference on a single image without updating the memory, and the other is to update + the memory with the provided prompts and object IDs. When update_memory is True, it will update the + memory with the provided prompts and obj_ids. When update_memory is False, it will only run inference on + the provided image without updating the memory. + + Args: + im (torch.Tensor | np.ndarray): The input image tensor or numpy array. + bboxes (list[list[float]] | None): Optional list of bounding boxes to update the memory. + masks (torch.Tensor | np.ndarray | None): Optional masks to update the memory. + points (list[list[float]] | None): Optional list of points to update the memory, each point is [x, y]. + labels (list[int] | None): Optional list of labels for point prompts (>0 for positive, 0 for negative). + obj_ids (list[int] | None): Optional list of object IDs corresponding to the prompts. + update_memory (bool): Flag to indicate whether to update the memory with new objects. + + Returns: + res_masks (torch.Tensor): The output masks in shape (C, H, W) + object_score_logits (torch.Tensor): Quality scores for each mask + """ + self.get_im_features(im) + points, labels, masks = self._prepare_prompts( + dst_shape=self.imgsz, + src_shape=self.src_shape, + points=points, + bboxes=bboxes, + labels=labels, + masks=masks, + ) + + if update_memory: + if isinstance(obj_ids, int): + obj_ids = [obj_ids] + assert obj_ids is not None, "obj_ids must be provided when update_memory is True" + assert masks is not None or points is not None, ( + "bboxes, masks, or points must be provided when update_memory is True" + ) + if points is None: # placeholder + points = torch.zeros((len(obj_ids), 0, 2), dtype=self.torch_dtype, device=self.device) + labels = torch.zeros((len(obj_ids), 0), dtype=torch.int32, device=self.device) + if masks is not None: + assert len(masks) == len(obj_ids), "masks and obj_ids must have the same length." + assert len(points) == len(obj_ids), "points and obj_ids must have the same length." + self.update_memory(obj_ids, points, labels, masks) + + current_out = self.track_step() + pred_masks, pred_scores = current_out["pred_masks"], current_out["object_score_logits"] + # filter the masks and logits based on the object indices + if len(self.obj_idx_set) == 0: + raise RuntimeError("No objects have been added to the state. Please add objects before inference.") + idx = list(self.obj_idx_set) # cls id + pred_masks, pred_scores = pred_masks[idx], pred_scores[idx] + # The original scores are in [-32, 32]. An object score larger than 0 means the object is present. + # Map scores to [0, 1] so that the object score logits are non-negative and can be used as a mask. + pred_scores = torch.clamp_(pred_scores / 32, min=0) + return pred_masks.flatten(0, 1), pred_scores.flatten(0, 1) + + def get_im_features(self, img: torch.Tensor | np.ndarray) -> None: + """Initialize the image state by processing the input image and extracting features. + + Args: + img (torch.Tensor | np.ndarray): The input image tensor or numpy array. + """ + vis_feats, vis_pos_embed, feat_sizes = SAM2VideoPredictor.get_im_features(self, img, batch=self._max_obj_num) + self.high_res_features = [ + feat.permute(1, 2, 0).view(*feat.shape[1:], *feat_size) + for feat, feat_size in zip(vis_feats[:-1], feat_sizes[:-1]) + ] + + self.vision_feats = vis_feats + self.vision_pos_embeds = vis_pos_embed + self.feat_sizes = feat_sizes + + @smart_inference_mode() + def update_memory( + self, + obj_ids: list[int] | None = None, + points: torch.Tensor | None = None, + labels: torch.Tensor | None = None, + masks: torch.Tensor | None = None, + ) -> None: + """Append the imgState to the memory_bank and update the memory for the model. + + Args: + obj_ids (list[int]): List of object IDs corresponding to the prompts. + points (torch.Tensor | None): Tensor of shape (B, N, 2) representing the input points for N objects. + labels (torch.Tensor | None): Tensor of shape (B, N) representing the labels for the input points. + masks (torch.Tensor | None): Optional tensor of shape (N, H, W) representing the input masks for N objects. + """ + consolidated_out = { + "maskmem_features": None, + "maskmem_pos_enc": None, + "pred_masks": torch.full( + size=(self._max_obj_num, 1, self.imgsz[0] // 4, self.imgsz[1] // 4), + fill_value=-1024.0, + dtype=self.torch_dtype, + device=self.device, + ), + "obj_ptr": torch.full( + size=(self._max_obj_num, self.model.hidden_dim), + fill_value=-1024.0, + dtype=self.torch_dtype, + device=self.device, + ), + "object_score_logits": torch.full( + size=(self._max_obj_num, 1), + # default to 10.0 for object_score_logits, i.e. assuming the object is + # present as sigmoid(10)=1, same as in `predict_masks` of `MaskDecoder` + fill_value=-32, # 10.0, + dtype=self.torch_dtype, + device=self.device, + ), + } + + for i, obj_id in enumerate(obj_ids): + assert obj_id < self._max_obj_num + obj_idx = self._obj_id_to_idx(int(obj_id)) + self.obj_idx_set.add(obj_idx) + point, label = points[[i]], labels[[i]] + mask = masks[[i]][None] if masks is not None else None + # Currently, only bbox prompt or mask prompt is supported, so we assert that bbox is not None. + assert point is not None or mask is not None, "Either bbox, points or mask is required" + out = self.track_step(obj_idx, point, label, mask) + if out is not None: + obj_mask = out["pred_masks"] + assert obj_mask.shape[-2:] == consolidated_out["pred_masks"].shape[-2:], ( + f"Expected mask shape {consolidated_out['pred_masks'].shape[-2:]} but got {obj_mask.shape[-2:]} for object {obj_idx}." + ) + consolidated_out["pred_masks"][obj_idx : obj_idx + 1] = obj_mask + consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"] + + if "object_score_logits" in out: + consolidated_out["object_score_logits"][obj_idx : obj_idx + 1] = out["object_score_logits"] + + high_res_masks = F.interpolate( + consolidated_out["pred_masks"].to(self.device, non_blocking=self.device.type == "cuda"), + size=self.imgsz, + mode="bilinear", + align_corners=False, + ) + + if self.model.non_overlap_masks_for_mem_enc: + high_res_masks = self.model._apply_non_overlapping_constraints(high_res_masks) + maskmem_features, maskmem_pos_enc = self.model._encode_new_memory( + current_vision_feats=self.vision_feats, + feat_sizes=self.feat_sizes, + pred_masks_high_res=high_res_masks, + object_score_logits=consolidated_out["object_score_logits"], + is_mask_from_pts=True, + ) + consolidated_out["maskmem_features"] = maskmem_features + consolidated_out["maskmem_pos_enc"] = maskmem_pos_enc + self.memory_bank.append(consolidated_out) + + def _prepare_memory_conditioned_features(self, obj_idx: int | None) -> torch.Tensor: + """Prepare memory-conditioned features for the current image state. + + If ``obj_idx`` is provided, features are prepared for a specific prompted object in the image. If ``obj_idx`` is + None, features are prepared for all objects. If no memory is available, a no-memory embedding is added to the + current vision features. Otherwise, memory from previous frames is used to condition the current vision features + via a transformer attention mechanism. + + Args: + obj_idx (int | None): The index of the object for which to prepare the features. + + Returns: + pix_feat_with_mem (torch.Tensor): The memory-conditioned pixel features. + """ + if len(self.memory_bank) == 0 or isinstance(obj_idx, int): + # For initial conditioning frames, encode without using any previous memory. + # Directly add the no-memory embedding (instead of using the transformer encoder). + pix_feat_with_mem = self.vision_feats[-1] + self.model.no_mem_embed + else: + # for inference frames, use the memory features from previous frames + memory, memory_pos_embed = self.get_maskmem_enc() + pix_feat_with_mem = self.model.memory_attention( + curr=self.vision_feats[-1:], + curr_pos=self.vision_pos_embeds[-1:], + memory=memory, + memory_pos=memory_pos_embed, + num_obj_ptr_tokens=0, # num_obj_ptr_tokens + ) + # Reshape output (HW)BC => BCHW + return pix_feat_with_mem.permute(1, 2, 0).view( + self._max_obj_num, + self.model.memory_attention.d_model, + *self.feat_sizes[-1], + ) + + def get_maskmem_enc(self) -> tuple[torch.Tensor, torch.Tensor]: + """Get memory and positional encoding from memory, which is used to condition the current image features.""" + to_cat_memory, to_cat_memory_pos_embed = [], [] + for consolidated_out in self.memory_bank: + to_cat_memory.append(consolidated_out["maskmem_features"].flatten(2).permute(2, 0, 1)) # (H*W, B, C) + maskmem_enc = consolidated_out["maskmem_pos_enc"][-1].flatten(2).permute(2, 0, 1) + maskmem_enc = maskmem_enc + self.model.maskmem_tpos_enc[self.model.num_maskmem - 1] + to_cat_memory_pos_embed.append(maskmem_enc) + + memory = torch.cat(to_cat_memory, dim=0) + memory_pos_embed = torch.cat(to_cat_memory_pos_embed, dim=0) + return memory, memory_pos_embed + + def _obj_id_to_idx(self, obj_id: int) -> int | None: + """Map client-side object id to model-side object index. + + Args: + obj_id (int): The client-side object ID. + + Returns: + (int | None): The model-side object index, or None if not found. + """ + return self.obj_id_to_idx.get(obj_id, None) + + def track_step( + self, + obj_idx: int | None = None, + point: torch.Tensor | None = None, + label: torch.Tensor | None = None, + mask: torch.Tensor | None = None, + ) -> dict[str, Any]: + """Tracking step for the current image state to predict masks. + + This method processes the image features and runs the SAM heads to predict masks. If obj_idx is provided, it + processes the features for a specific prompted object in the image. If obj_idx is None, it processes the + features for all objects in the image. The method supports both mask-based output without SAM and full SAM + processing with memory-conditioned features. + + Args: + obj_idx (int | None): The index of the object for which to predict masks. If None, it processes all objects. + point (torch.Tensor | None): The coordinates of the points of interest with shape (N, 2). + label (torch.Tensor | None): The labels corresponding to the points where 1 means positive clicks, 0 means + negative clicks. + mask (torch.Tensor | None): The mask input for the object with shape (H, W). + + Returns: + current_out (dict[str, Any]): A dictionary containing the current output with mask predictions and object + pointers. Keys include 'point_inputs', 'mask_inputs', 'pred_masks', 'pred_masks_high_res', + 'obj_ptr', 'object_score_logits'. + """ + if mask is not None and self.model.use_mask_input_as_output_without_sam: + # When use_mask_input_as_output_without_sam=True, we directly output the mask input + # (see it as a GT mask) without using a SAM prompt encoder + mask decoder. + pix_feat = self.vision_feats[-1].permute(1, 2, 0) + pix_feat = pix_feat.view(-1, self.model.memory_attention.d_model, *self.feat_sizes[-1]) + _, _, _, low_res_masks, high_res_masks, obj_ptr, object_score_logits = self.model._use_mask_as_output(mask) + else: + # Fuse visual features with previous memory features in the memory bank. + pix_feat_with_mem = self._prepare_memory_conditioned_features(obj_idx) + # If ``obj_idx`` is provided (i.e., prompts are being added), keep only the first feature map. + pix_feat_with_mem = pix_feat_with_mem[:1] if obj_idx is not None else pix_feat_with_mem + _, _, _, low_res_masks, high_res_masks, obj_ptr, object_score_logits = self.model._forward_sam_heads( + backbone_features=pix_feat_with_mem, + point_inputs={"point_coords": point, "point_labels": label} if obj_idx is not None else None, + mask_inputs=mask, + multimask_output=False, + high_res_features=[feat[: pix_feat_with_mem.shape[0]] for feat in self.high_res_features], + ) + return { + "pred_masks": low_res_masks, + "pred_masks_high_res": high_res_masks, + "obj_ptr": obj_ptr, + "object_score_logits": object_score_logits, + } + + +class SAM3Predictor(SAM2Predictor): + """Segment Anything Model 3 (SAM3) Interactive Predictor for image segmentation tasks.""" + + _bb_feat_sizes = [ + (288, 288), + (144, 144), + (72, 72), + ] + stride = 14 + + def setup_model(self, model=None, verbose=True): + """Setup the SAM3 model with appropriate mean and standard deviation for preprocessing.""" + super().setup_model(model, verbose) + # update mean and std + self.mean = torch.tensor([127.5, 127.5, 127.5]).view(-1, 1, 1).to(self.device) + self.std = torch.tensor([127.5, 127.5, 127.5]).view(-1, 1, 1).to(self.device) + + def get_model(self): + """Retrieve and initialize the Segment Anything Model 3 (SAM3) for image segmentation tasks.""" + from .build_sam3 import build_interactive_sam3 # slow import + + compile_mode = "default" if self.args.compile is True else self.args.compile or None + return build_interactive_sam3(self.args.model, compile=compile_mode) + + +class SAM3SemanticPredictor(SAM3Predictor): + """Segment Anything Model 3 (SAM3) Predictor for image segmentation tasks.""" + + def get_model(self): + """Retrieve and initialize the Segment Anything Model 3 (SAM3) for image segmentation tasks.""" + from .build_sam3 import build_sam3_image_model # slow import + + return build_sam3_image_model(self.args.model, compile=self.args.compile) + + @smart_inference_mode() + def get_im_features(self, im): + """Extract image features using the model's backbone.""" + return self.model.backbone.forward_image(im) + + def pre_transform(self, im): + """Perform initial transformations on the input image for preprocessing. + + This method applies transformations such as resizing to prepare the image for further preprocessing. Currently, + batched inference is not supported; hence the list length should be 1. + + Args: + im (list[np.ndarray]): List containing a single image in HWC numpy array format. + + Returns: + (list[np.ndarray]): List containing the transformed image. + + Raises: + AssertionError: If the input list contains more than one image. + + Examples: + >>> predictor = SAM3SemanticPredictor() + >>> predictor.imgsz = [1024, 1024] # normally set by setup_source() + >>> image = np.random.rand(480, 640, 3) # Single HWC image + >>> transformed = predictor.pre_transform([image]) + >>> print(len(transformed)) + 1 + """ + assert len(im) == 1, "SAM model does not currently support batched inference" + letterbox = LetterBox(self.imgsz, auto=False, center=False, scale_fill=True) # hardcode here for sam3 + return [letterbox(image=x) for x in im] + + def _prepare_geometric_prompts(self, src_shape, bboxes=None, labels=None): + """Prepare prompts by normalizing bounding boxes and points to the destination shape.""" + if bboxes is not None: + bboxes = torch.as_tensor(bboxes, dtype=self.torch_dtype, device=self.device) + bboxes = bboxes[None] if bboxes.ndim == 1 else bboxes + # needs xywh as input + bboxes = ops.xyxy2xywh(bboxes) + bboxes[:, 0::2] /= src_shape[1] + bboxes[:, 1::2] /= src_shape[0] + # Assuming labels are all positive if users don't pass labels. + if labels is None: + labels = np.ones(bboxes.shape[:-1]) + labels = torch.as_tensor(labels, dtype=torch.int32, device=self.device) + assert bboxes.shape[-2] == labels.shape[-1], ( + f"Number of points {bboxes.shape[-2]} should match number of labels {labels.shape[-1]}." + ) + bboxes = bboxes.view(-1, 1, 4) # (N, 1, 4) + labels = labels.view(-1, 1) # (N, 1) + return bboxes, labels + + def _inference_features(self, features, bboxes=None, labels=None, text: list[str] | None = None): + """Run inference on the extracted features with optional bounding boxes and labels.""" + # NOTE: priority: bboxes > text > pre-set classes + nc = 1 if bboxes is not None else len(text) if text is not None else len(self.model.names) + geometric_prompt = None + if bboxes is not None: + geometric_prompt = self._get_dummy_prompt(nc) + for i in range(len(bboxes)): + geometric_prompt.append_boxes(bboxes[[i]], labels[[i]]) + if text is None: + text = ["visual"] # bboxes needs this `visual` text prompt if no text passed + if text is not None and self.model.names != text: + self.model.set_classes(text=text) + outputs = self.model.forward_grounding( + backbone_out=features, + text_ids=torch.arange(nc, device=self.device, dtype=torch.long), + geometric_prompt=geometric_prompt, + ) + return outputs + + def _upscale_masks(self, masks: torch.Tensor, shape: tuple[int, int]) -> torch.Tensor: + """Upscale (N, h, w) mask logits to a boolean (N, *shape) mask in memory-bounded chunks. + + Args: + masks (torch.Tensor): Low resolution mask logits with shape (N, h, w). + shape (tuple[int, int]): Target height and width. + + Returns: + (torch.Tensor): Binary masks with shape (N, *shape). + """ + MAX_CHUNK_MEM = 2048 # MB + upscaled = masks.new_empty((masks.shape[0], *shape), dtype=torch.bool) + chunk = max(1, MAX_CHUNK_MEM * 2**20 // (4 * shape[0] * shape[1])) + for i in range(0, masks.shape[0], chunk): + torch.gt( + F.interpolate(masks[i : i + chunk].float()[None], shape, mode="bilinear")[0], + self.model.mask_threshold, + out=upscaled[i : i + chunk], + ) + return upscaled + + def postprocess(self, preds, img, orig_imgs): + """Post-process the predictions to apply non-overlapping constraints if required.""" + import torchvision + + pred_boxes = preds["pred_boxes"] # (nc, num_query, 4) + pred_logits = preds["pred_logits"] + pred_masks = preds["pred_masks"] + pred_scores = pred_logits.sigmoid() + presence_score = preds["presence_logit_dec"].sigmoid().unsqueeze(1) + pred_scores = (pred_scores * presence_score).squeeze(-1) + pred_cls = torch.tensor( + list(range(pred_scores.shape[0])), + dtype=pred_scores.dtype, + device=pred_scores.device, + )[:, None].expand_as(pred_scores) + pred_boxes = torch.cat([pred_boxes, pred_scores[..., None], pred_cls[..., None]], dim=-1) + + keep = pred_scores > self.args.conf + pred_masks, pred_boxes = pred_masks[keep], pred_boxes[keep] + pred_boxes[:, :4] = ops.xywh2xyxy(pred_boxes[:, :4]) + + c = pred_boxes[:, 5:6] * (0 if self.args.agnostic_nms else 7680) # classes + nms_boxes = pred_boxes[:, :4] + c # boxes (offset by class) + keep = torchvision.ops.nms(nms_boxes, pred_boxes[:, 4], self.args.iou) # NMS + pred_boxes, pred_masks = pred_boxes[keep], pred_masks[keep] + + names = getattr(self.model, "names", [str(i) for i in range(pred_scores.shape[0])]) + if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list + orig_imgs = ops.convert_torch2numpy_batch(orig_imgs) + results = [] + for masks, boxes, orig_img, img_path in zip([pred_masks], [pred_boxes], orig_imgs, self.batch[0]): + if masks.shape[0] == 0: + masks, boxes = None, torch.zeros((0, 6), device=pred_masks.device) + else: + masks = self._upscale_masks(masks, orig_img.shape[:2]) + boxes[..., [0, 2]] *= orig_img.shape[1] + boxes[..., [1, 3]] *= orig_img.shape[0] + results.append(Results(orig_img, path=img_path, names=names, masks=masks, boxes=boxes)) + return results + + def inference(self, im, bboxes=None, labels=None, text: list[str] | None = None, *args, **kwargs): + """Perform inference on a single image with optional prompts.""" + bboxes = self.prompts.pop("bboxes", bboxes) + labels = self.prompts.pop("labels", labels) + text = self.prompts.pop("text", text) + features = self.get_im_features(im) if self.features is None else self.features + prompts = self._prepare_geometric_prompts(self.src_shape, bboxes, labels) + return self._inference_features(features, *prompts, text=text) + + @smart_inference_mode() + def inference_features( + self, + features, + src_shape, + bboxes=None, + labels=None, + text: list[str] | None = None, + ): + """Perform prompts preprocessing and inference on provided image features using the SAM model. + + Args: + features (dict[str, Any]): Extracted image features from the SAM3 model image encoder. + src_shape (tuple[int, int]): The source shape (height, width) of the input image. + bboxes (np.ndarray | list[list[float]] | None): Bounding boxes in xyxy format with shape (N, 4). pixels. + labels (np.ndarray | list[int] | None): Point prompt labels with shape (N, ). + text (list[str] | None): List of text prompts corresponding to the classes. + + Returns: + pred_masks (torch.Tensor): The output masks in shape (C, H, W), where C is the number of generated masks. + pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 6), where N is the number of boxes. + Each box is in xyxy format with additional columns for score and class. + + Notes: + - The input features is a torch.Tensor of shape (B, C, H, W) if performing on SAM, or a dict[str, Any] if performing on SAM2. + """ + import torchvision + + prompts = self._prepare_geometric_prompts(src_shape[:2], bboxes, labels) + preds = self._inference_features(features, *prompts, text=text) + pred_boxes = preds["pred_boxes"] # (nc, num_query, 4) + pred_logits = preds["pred_logits"] + pred_masks = preds["pred_masks"] + pred_scores = pred_logits.sigmoid() + presence_score = preds["presence_logit_dec"].sigmoid().unsqueeze(1) + pred_scores = (pred_scores * presence_score).squeeze(-1) + pred_cls = torch.tensor( + list(range(pred_scores.shape[0])), + dtype=pred_scores.dtype, + device=pred_scores.device, + )[:, None].expand_as(pred_scores) + pred_boxes = torch.cat([pred_boxes, pred_scores[..., None], pred_cls[..., None]], dim=-1) + + keep = pred_scores > self.args.conf + pred_masks, pred_boxes = pred_masks[keep], pred_boxes[keep] + pred_boxes[:, :4] = ops.xywh2xyxy(pred_boxes[:, :4]) + + c = pred_boxes[:, 5:6] * (0 if self.args.agnostic_nms else 7680) # classes + nms_boxes = pred_boxes[:, :4] + c # boxes (offset by class) + keep = torchvision.ops.nms(nms_boxes, pred_boxes[:, 4], self.args.iou) # NMS + pred_boxes, pred_masks = pred_boxes[keep], pred_masks[keep] + + if pred_masks.shape[0] == 0: + pred_masks, pred_boxes = None, torch.zeros((0, 6), device=pred_masks.device) + else: + pred_masks = self._upscale_masks(pred_masks, src_shape[:2]) + pred_boxes[..., 0] *= src_shape[1] + pred_boxes[..., 1] *= src_shape[0] + pred_boxes[..., 2] *= src_shape[1] + pred_boxes[..., 3] *= src_shape[0] + return pred_masks, pred_boxes + + def reset_prompts(self): + """Reset the prompts for the predictor.""" + self.prompts = {} + self.model.text_embeddings = {} + + def _get_dummy_prompt(self, num_prompts=1): + """Get a dummy geometric prompt with zero boxes.""" + # Scoped for import ultralytics speed: SAM3 geometry imports optional torchvision ops. + from .sam3.geometry_encoders import Prompt + + geometric_prompt = Prompt( + box_embeddings=torch.zeros(0, num_prompts, 4, device=self.device), + box_mask=torch.zeros(num_prompts, 0, device=self.device, dtype=torch.bool), + ) + return geometric_prompt + + +class SAM3VideoPredictor(SAM2VideoPredictor, SAM3Predictor): + """Segment Anything Model 3 (SAM3) Video Predictor for video segmentation tasks.""" + + def propagate_in_video(self, inference_state, frame_idx): + """Perform image segmentation inference based on the given input cues, using the currently loaded image. This + method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt + encoder, and mask decoder for real-time and promptable segmentation tasks. + + Args: + inference_state (dict): The current state of inference, including input cues and previous outputs. + frame_idx (int): The index of the current frame in the video sequence. + """ + frame = frame_idx + output_dict = inference_state["output_dict"] + obj_ids = inference_state["obj_ids"] + consolidated_frame_inds = inference_state["consolidated_frame_inds"] + batch_size = len(inference_state["obj_idx_to_id"]) + if len(output_dict["cond_frame_outputs"]) == 0: + raise RuntimeError("No points are provided; please add points first") + + if frame in consolidated_frame_inds["cond_frame_outputs"]: + storage_key = "cond_frame_outputs" + current_out = output_dict[storage_key][frame] + if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1): + # clear non-conditioning memory of the surrounding frames + self._clear_non_cond_mem_around_input(frame) + elif frame in consolidated_frame_inds["non_cond_frame_outputs"]: + storage_key = "non_cond_frame_outputs" + current_out = output_dict[storage_key][frame] + else: + storage_key = "non_cond_frame_outputs" + current_out = self._run_single_frame_inference( + output_dict=output_dict, + frame_idx=frame, + batch_size=batch_size, + is_init_cond_frame=False, + point_inputs=None, + mask_inputs=None, + reverse=False, + run_mem_encoder=True, + inference_state=inference_state, + ) + output_dict[storage_key][frame] = current_out + self._prune_non_cond_memory(frame, inference_state=inference_state) + # Create slices of per-object outputs for subsequent interaction with each + # individual object after tracking. + self._add_output_per_object(frame, current_out, storage_key, inference_state=inference_state) + inference_state["frames_already_tracked"].append(frame) + pred_masks = current_out["pred_masks"].flatten(0, 1) + obj_scores = current_out["object_score_logits"] + + return obj_ids, pred_masks, obj_scores + + +class SAM3VideoSemanticPredictor(SAM3SemanticPredictor): + """Segment Anything Model 3 (SAM3) Video Semantic Predictor.""" + + HIGH_CONF_THRESH = 0.8 + HIGH_IOU_THRESH = 0.8 + NO_OBJ_LOGIT = -10.0 + NEVER_OCCLUDED = -1 + ALWAYS_OCCLUDED = 100000 + + UNCONFIRMED = 1 # newly added masklet, not confirmed by any detection yet + CONFIRMED = 2 # confirmed by at least one detection + _bb_feat_sizes = [ + (288, 288), + (144, 144), + (72, 72), + ] + stride = 14 + + def __init__( + self, + cfg=DEFAULT_CFG, + overrides=None, + _callbacks: dict | None = None, + # prob threshold for detection outputs -- only keep detections above this threshold + # enters NMS and det-to-track matching + score_threshold_detection=0.5, + # IoU threshold for detection NMS + det_nms_thresh=0.0, + # IoU threshold for det-to-track matching -- a detection is considered "matched" to a tracklet it + # overlaps with a tracklet above this threshold -- it is often a loose threshold like 0.1 + assoc_iou_thresh=0.5, + # IoU threshold for det-to-track matching, which is used to determine whether a masklet is "unmatched" + # by any detections -- it is often a stricter threshold like 0.5 + trk_assoc_iou_thresh=0.5, + # prob threshold for a detection to be added as a new object + new_det_thresh=0.0, + # hotstart parameters: we hold off the outputs for `hotstart_delay` frames and + # 1) remove those tracklets unmatched by any detections based on `hotstart_unmatch_thresh` + # 2) remove those tracklets overlapping with one another based on `hotstart_dup_thresh` + hotstart_delay=0, + hotstart_unmatch_thresh=3, + hotstart_dup_thresh=3, + init_trk_keep_alive=10, + max_trk_keep_alive=10, + min_trk_keep_alive=-4, + # Threshold for suppressing overlapping objects based on recent occlusion + suppress_overlapping_based_on_recent_occlusion_threshold=0.0, + decrease_trk_keep_alive_for_empty_masklets=True, + o2o_matching_masklets_enable=False, # Enable hungarian matching to match existing masklets + suppress_det_close_to_boundary=False, + fill_hole_area=16, + # The maximum number of objects (masklets) to track across all GPUs (for no limit, set it to -1) + max_num_objects=-1, + recondition_every_nth_frame=-1, + # masket confirmation status (to suppress unconfirmed masklets) + masklet_confirmation_enable=True, + # a masklet is confirmed after being consecutively detected and matched for + # `masklet_confirmation_consecutive_det_thresh` + masklet_confirmation_consecutive_det_thresh=3, + # bbox heuristic parameters + reconstruction_bbox_iou_thresh=0.0, + reconstruction_bbox_det_score=0.0, + ): + """Initialize the SAM3VideoSemanticPredictor with configuration and optional overrides.""" + super().__init__(cfg, overrides, _callbacks) + self.score_threshold_detection = score_threshold_detection + self.det_nms_thresh = det_nms_thresh + self.assoc_iou_thresh = assoc_iou_thresh + self.trk_assoc_iou_thresh = trk_assoc_iou_thresh + self.new_det_thresh = new_det_thresh + + # hotstart parameters + if hotstart_delay > 0: + assert hotstart_unmatch_thresh <= hotstart_delay + assert hotstart_dup_thresh <= hotstart_delay + self.hotstart_delay = hotstart_delay + self.hotstart_unmatch_thresh = hotstart_unmatch_thresh + self.hotstart_dup_thresh = hotstart_dup_thresh + self.init_trk_keep_alive = init_trk_keep_alive + self.max_trk_keep_alive = max_trk_keep_alive + self.min_trk_keep_alive = min_trk_keep_alive + self.suppress_overlapping_based_on_recent_occlusion_threshold = ( + suppress_overlapping_based_on_recent_occlusion_threshold + ) + self.suppress_det_close_to_boundary = suppress_det_close_to_boundary + self.decrease_trk_keep_alive_for_empty_masklets = decrease_trk_keep_alive_for_empty_masklets + self.o2o_matching_masklets_enable = o2o_matching_masklets_enable + self.fill_hole_area = fill_hole_area + self._dist_pg_cpu = None # CPU process group (lazy-initialized on first use) + + max_num_objects = 10000 # no limit + num_obj_for_compile = 16 + self.max_num_objects = max_num_objects + self.num_obj_for_compile = num_obj_for_compile + self.recondition_every_nth_frame = recondition_every_nth_frame + self.masklet_confirmation_enable = masklet_confirmation_enable + self.masklet_confirmation_consecutive_det_thresh = masklet_confirmation_consecutive_det_thresh + self.reconstruction_bbox_iou_thresh = reconstruction_bbox_iou_thresh + self.reconstruction_bbox_det_score = reconstruction_bbox_det_score + + # build SAM3 tracker + self.tracker = SAM3VideoPredictor(overrides=overrides) + + self.inference_state = {} + + @smart_inference_mode(False) # the tracker model is built after super() returns, outside its decorator + def setup_model(self, model=None, verbose=True): + """Setup the SAM3VideoSemanticPredictor model.""" + super().setup_model(model, verbose) + from .build_sam3 import build_interactive_sam3 + + # Initialize the SAM3 tracker model without backbone (backbone is handled in the detector) + model = build_interactive_sam3(self.args.model, with_backbone=False) + self.tracker.setup_model(model=model, verbose=False) + + def setup_source(self, source): + """Setup the source for the SAM3VideoSemanticPredictor model.""" + super().setup_source(source) + self.tracker.imgsz = self.imgsz + self.tracker.model.set_imgsz(self.imgsz) + self.tracker._bb_feat_sizes = [[int(x / (self.stride * i)) for x in self.imgsz] for i in [1 / 4, 1 / 2, 1]] + self.interpol_size = self.tracker.model.memory_encoder.mask_downsampler.interpol_size + if self.dataset is not None and self.dataset.mode == "video": + self.init_state(self) + + @staticmethod + def init_state(predictor): + """Initialize an inference state for the predictor. + + This function sets up the initial state required for performing inference on video data. It includes + initializing various dictionaries and ordered dictionaries that will store inputs, outputs, and other metadata + relevant to the tracking process. + + Args: + predictor (SAM3VideoSemanticPredictor): The predictor object for which to initialize the state. + """ + if len(predictor.inference_state) > 0: # means initialized + return + assert predictor.dataset is not None + assert predictor.dataset.mode == "video" + num_frames = predictor.dataset.frames + inference_state = { + "num_frames": num_frames, + "tracker_inference_states": [], + "tracker_metadata": {}, + "text_prompt": None, + "per_frame_geometric_prompt": [None] * num_frames, + } + predictor.inference_state = inference_state + + def inference(self, im, bboxes=None, labels=None, text: list[str] | None = None, *args, **kwargs): + """Perform inference on a video sequence with optional prompts.""" + frame = self.dataset.frame - 1 # align frame index to be 0-based + self.inference_state["im"] = im # only pass image for subsequent frames + if "text_ids" not in self.inference_state: # first frame processing + self.add_prompt(frame_idx=frame, text=text, bboxes=bboxes, labels=labels) + return self._run_single_frame_inference(frame, reverse=False) + + def postprocess(self, preds, img, orig_imgs): + """Post-process the predictions to apply non-overlapping constraints if required.""" + obj_id_to_mask = preds["obj_id_to_mask"] # low res masks + curr_obj_ids = sorted(obj_id_to_mask.keys()) + if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list + orig_imgs = ops.convert_torch2numpy_batch(orig_imgs) + + names = self.model.names if self.model.names != "visual" else {} + if len(curr_obj_ids) == 0: + pred_masks, pred_boxes = None, torch.zeros((0, 7), device=self.device) + else: + pred_masks = torch.cat([obj_id_to_mask[obj_id] for obj_id in curr_obj_ids], dim=0) + pred_masks = self._upscale_masks(pred_masks, orig_imgs[0].shape[:2]) + pred_ids = torch.tensor(curr_obj_ids, dtype=torch.int32, device=pred_masks.device) + pred_scores = torch.tensor( + [preds["obj_id_to_score"][obj_id] for obj_id in curr_obj_ids], device=pred_masks.device + ) + pred_cls = torch.tensor( + [preds["obj_id_to_cls"][obj_id] for obj_id in curr_obj_ids], device=pred_masks.device + ) + keep = (pred_scores > self.args.conf) & pred_masks.any(dim=(1, 2)) + pred_masks = pred_masks[keep] + pred_boxes = batched_mask_to_box(pred_masks) + pred_boxes = torch.cat( + [pred_boxes, pred_ids[keep][:, None], pred_scores[keep][..., None], pred_cls[keep][..., None]], dim=-1 + ) + if pred_boxes.shape[0]: + names = names or dict(enumerate(str(i) for i in range(pred_boxes[:, 6].int().max() + 1))) + if pred_masks.shape[0] > 1: + tracker_scores = torch.tensor( + [(preds["obj_id_to_tracker_score"].get(obj_id, 0.0)) for obj_id in curr_obj_ids], + device=pred_masks.device, + )[keep] + pred_masks = ( + self._apply_object_wise_non_overlapping_constraints( + pred_masks.unsqueeze(1), + tracker_scores.unsqueeze(1), + background_value=0, + ).squeeze(1) + ) > 0 + + results = [] + for masks, boxes, orig_img, img_path in zip([pred_masks], [pred_boxes], orig_imgs, self.batch[0]): + results.append(Results(orig_img, path=img_path, names=names, masks=masks, boxes=boxes)) + return results + + def _run_single_frame_inference(self, frame_idx, reverse=False, inference_state=None): + """Perform inference on a single frame and get its inference results.""" + inference_state = inference_state or self.inference_state + # prepare inputs + tracker_states_local = inference_state["tracker_inference_states"] + has_text_prompt = inference_state["text_prompt"] is not None + has_geometric_prompt = inference_state["per_frame_geometric_prompt"][frame_idx] is not None + # run inference for the current frame + ( + obj_id_to_mask, + obj_id_to_score, + obj_id_to_cls, + tracker_states_local_new, + tracker_metadata_new, + frame_stats, + _, + ) = self._det_track_one_frame( + frame_idx=frame_idx, + num_frames=inference_state["num_frames"], + reverse=reverse, + im=inference_state["im"], + text_ids=inference_state["text_ids"], + geometric_prompt=( + self._get_dummy_prompt(num_prompts=len(inference_state["text_ids"])) + if not has_geometric_prompt + else inference_state["per_frame_geometric_prompt"][frame_idx] + ), + tracker_states_local=tracker_states_local, + tracker_metadata_prev=inference_state["tracker_metadata"], + allow_new_detections=has_text_prompt or has_geometric_prompt, + ) + # update inference state + inference_state["tracker_inference_states"] = tracker_states_local_new + inference_state["tracker_metadata"] = tracker_metadata_new + + out = { + "obj_id_to_mask": obj_id_to_mask, + "obj_id_to_score": obj_id_to_score, # first frame detection score + "obj_id_to_cls": obj_id_to_cls, # first frame detection score + "obj_id_to_tracker_score": tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx], + } + # removed_obj_ids is only needed on rank 0 to handle hotstart delay buffer + metadata = tracker_metadata_new["metadata"] + removed_obj_ids = metadata["removed_obj_ids"] + out["removed_obj_ids"] = removed_obj_ids + out["frame_stats"] = frame_stats + if self.masklet_confirmation_enable: + status = metadata["masklet_confirmation"]["status"] + is_unconfirmed = status == self.UNCONFIRMED + out["unconfirmed_obj_ids"] = tracker_metadata_new["obj_ids"][is_unconfirmed].tolist() + else: + out["unconfirmed_obj_ids"] = [] + return out + + @smart_inference_mode() + def add_prompt( + self, + frame_idx, + text=None, + bboxes=None, + labels=None, + inference_state=None, + ): + """Add text, point or box prompts on a single frame. This method returns the inference outputs only on the + prompted frame. + + Note that text prompts are NOT associated with a particular frame (i.e. they apply + to all frames). However, we only run inference on the frame specified in `frame_idx`. + """ + inference_state = inference_state or self.inference_state + assert text is not None or bboxes is not None, "at least one type of prompt (text, boxes) must be provided" + + # 1) handle text prompt + use_text = text is not None + text = text if use_text else "visual" + text_batch = [text] if isinstance(text, str) else text + inference_state["text_prompt"] = text if use_text else None + n = len(text_batch) + text_ids = torch.arange(n, device=self.device, dtype=torch.long) + inference_state["text_ids"] = text_ids + if text is not None and self.model.names != text: + self.model.set_classes(text=text) + + # 2) handle box prompt + bboxes, labels = self._prepare_geometric_prompts(self.src_shape, bboxes, labels) + assert (bboxes is not None) == (labels is not None) + geometric_prompt = self._get_dummy_prompt(num_prompts=n) + if bboxes is not None: + for i in range(len(bboxes)): + geometric_prompt.append_boxes(bboxes[[i]], labels[[i]]) + inference_state["per_frame_geometric_prompt"][frame_idx] = geometric_prompt + out = self._run_single_frame_inference(frame_idx, reverse=False, inference_state=inference_state) + return frame_idx, out + + def _apply_object_wise_non_overlapping_constraints(self, pred_masks, obj_scores, background_value=-10.0): + """Applies non-overlapping constraints object wise (i.e. only one object can claim the overlapping region).""" + # Replace pixel scores with object scores + pred_masks_single_score = torch.where(pred_masks > 0, obj_scores[..., None, None], background_value) + # Apply pixel-wise non-overlapping constraint based on mask scores + pixel_level_non_overlapping_masks = self.tracker.model._apply_non_overlapping_constraints( + pred_masks_single_score + ) + # Replace object scores with pixel scores. Note, that now only one object can claim the overlapping region + pred_masks = torch.where( + pixel_level_non_overlapping_masks > 0, + pred_masks, + torch.clamp(pred_masks, max=background_value), + ) + return pred_masks + + def _det_track_one_frame( + self, + im: torch.Tensor, + text_ids: torch.Tensor, + frame_idx: int, + num_frames: int, + reverse: bool, + geometric_prompt: Prompt, + tracker_states_local: list[Any], + tracker_metadata_prev: dict[str, Any], + allow_new_detections: bool = True, + ): + """This function handles one-step inference for the DenseTracking model in an SPMD manner. At a high-level, all + GPUs execute the same function calls as if it's done on a single GPU, while under the hood, some + function calls involve distributed computation based on sharded SAM2 states. + + - `input_batch` contains image and other inputs on the entire video; it should be identical across GPUs + - `tracker_states_local` holds the local masklet information in this GPU shard + - `tracker_metadata_prev` manages the metadata for SAM2 objects, such as which masklet is hold on which GPUs + it contains both global and local masklet information + """ + # Step 1: run backbone and detector in a distributed manner -- this is done via Sam3ImageOnVideoMultiGPU, + # a MultiGPU model (assigned to `self.detector`) that shards frames in a round-robin manner. + det_out = self.run_backbone_and_detection( + im=im, + text_ids=text_ids, + geometric_prompt=geometric_prompt, + allow_new_detections=allow_new_detections, + ) + + # Step 2: each GPU propagates its local SAM2 states to get the SAM2 prediction masks. + # the returned `tracker_low_res_masks_global` contains the concatenated masklet predictions + # gathered from all GPUs (as if they are propagated on a single GPU). Note that this step only + # runs the SAM2 propagation step, but doesn't encode new memory for the predicted masks; + # we defer memory encoding to `run_tracker_update_execution_phase` after resolving all heuristics. + if tracker_metadata_prev == {}: + # initialize masklet metadata if it's uninitialized (empty dict) + tracker_metadata_prev.update(self._initialize_metadata()) + tracker_low_res_masks_global, tracker_obj_scores_global = self.run_tracker_propagation( + frame_idx=frame_idx, + tracker_states_local=tracker_states_local, + tracker_metadata_prev=tracker_metadata_prev, + ) + + # Step 3: based on detection outputs and the propagated SAM2 prediction masks, we make plans + # for SAM2 masklet updates (i.e. which objects to add and remove, how to load-balance them, etc). + # We also run SAM2 memory encoder globally in this step to resolve non-overlapping constraints. + # **This step should involve all the heuristics needed for any updates.** Most of the update + # planning will be done on the master rank (GPU 0) and the resulting plan `tracker_update_plan` is + # broadcasted to other GPUs (to be executed in a distributed manner). This step also generates the + # new masklet metadata `tracker_metadata_new` (based on its previous version `tracker_metadata_prev`). + tracker_update_plan, tracker_metadata_new = self.run_tracker_update_planning_phase( + frame_idx=frame_idx, + reverse=reverse, + det_out=det_out, + tracker_low_res_masks_global=tracker_low_res_masks_global, + tracker_obj_scores_global=tracker_obj_scores_global, + tracker_metadata_prev=tracker_metadata_prev, + tracker_states_local=tracker_states_local, + ) + + # Get reconditioning info from the update plan + reconditioned_obj_ids = tracker_update_plan.get("reconditioned_obj_ids", set()) + + # Step 4: based on `tracker_update_plan`, each GPU executes the update w.r.t. its local SAM2 inference states + tracker_states_local_new = self.run_tracker_update_execution_phase( + frame_idx=frame_idx, + num_frames=num_frames, + det_out=det_out, + tracker_states_local=tracker_states_local, + tracker_update_plan=tracker_update_plan, + ) + + # Step 5: finally, build the outputs for this frame (it only needs to be done on GPU 0 since + # only GPU 0 will send outputs to the server). + obj_id_to_mask = self.build_outputs( + det_out=det_out, + tracker_low_res_masks_global=tracker_low_res_masks_global, + tracker_metadata_prev=tracker_metadata_prev, + tracker_update_plan=tracker_update_plan, + reconditioned_obj_ids=reconditioned_obj_ids, + ) + obj_id_to_score = tracker_metadata_new["obj_id_to_score"] + obj_id_to_cls = tracker_metadata_new["obj_id_to_cls"] + # a few statistics for the current frame as a part of the output + frame_stats = { + "num_obj_tracked": np.sum(tracker_metadata_new["num_obj"]), + "num_obj_dropped": tracker_update_plan["num_obj_dropped_due_to_limit"], + } + # add tracker scores to metadata, it should be fired for frames except the first frame + if tracker_obj_scores_global.shape[0] > 0: + # Convert tracker_obj_scores_global to sigmoid scores before updating + tracker_obj_scores_global = tracker_obj_scores_global.sigmoid().tolist() + tracker_obj_ids = tracker_metadata_prev["obj_ids"] + tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx].update( + dict(zip(tracker_obj_ids, tracker_obj_scores_global)) + ) + return ( + obj_id_to_mask, # a dict: obj_id --> output mask + obj_id_to_score, # a dict: obj_id --> output score (prob) + obj_id_to_cls, # a dict: obj_id --> output cls (int) + tracker_states_local_new, + tracker_metadata_new, + frame_stats, + tracker_obj_scores_global, # a dict: obj_id --> tracker frame-level scores + ) + + @staticmethod + def _suppress_detections_close_to_boundary(boxes, margin=0.025): + """Suppress detections too close to image edges (for normalized boxes). + + boxes: (N, 4) in xyxy format, normalized [0,1] + margin: fraction of image + """ + x_min, y_min, x_max, y_max = boxes.unbind(-1) + x_c = (x_min + x_max) / 2 + y_c = (y_min + y_max) / 2 + keep = (x_c > margin) & (x_c < 1.0 - margin) & (y_c > margin) & (y_c < 1.0 - margin) + + return keep + + def run_backbone_and_detection( + self, im: torch.Tensor, text_ids: torch.Tensor, geometric_prompt: Prompt, allow_new_detections: bool + ): + """Run backbone and detection for a single frame.""" + features = self.get_im_features(im) + sam3_image_out = self.model.forward_grounding( + backbone_out=features, text_ids=text_ids, geometric_prompt=geometric_prompt + ) + det_out = self._extract_detection_outputs(sam3_image_out, allow_new_detections) + self._cache_backbone_features(sam3_image_out) + return det_out + + def _extract_detection_outputs(self, sam3_image_out, allow_new_detections): + """Extract and filter detection outputs.""" + pred_probs = sam3_image_out["pred_logits"].squeeze(-1).sigmoid() + if not allow_new_detections: + pred_probs = pred_probs - 1e8 + + pred_cls = torch.tensor( + list(range(pred_probs.shape[0])), + dtype=pred_probs.dtype, + device=pred_probs.device, + )[:, None].expand_as(pred_probs) + + pred_boxes_xyxy = sam3_image_out["pred_boxes_xyxy"] + pred_masks = sam3_image_out["pred_masks"] + + keep = pred_probs > self.score_threshold_detection + return { + "bbox": pred_boxes_xyxy[keep], + "mask": pred_masks[keep], + "scores": pred_probs[keep], + "cls": pred_cls[keep], + } + + def _cache_backbone_features(self, sam3_image_out): + """Build and cache SAM2 backbone features.""" + sam_mask_decoder = self.tracker.model.sam_mask_decoder + feats = sam3_image_out["backbone_out"]["sam2_backbone_out"] + tracker_backbone_fpn = [ + sam_mask_decoder.conv_s0(feats["backbone_fpn"][0]), + sam_mask_decoder.conv_s1(feats["backbone_fpn"][1]), + feats["backbone_fpn"][2], + ] + tracker_backbone_out = { + "vision_features": tracker_backbone_fpn[-1], + "vision_pos_enc": feats["vision_pos_enc"], + "backbone_fpn": tracker_backbone_fpn, + } + # cache the SAM2 backbone features for `frame_idx` in the tracker + self.tracker.backbone_out = tracker_backbone_out + + def run_tracker_propagation( + self, frame_idx: int, tracker_states_local: list[Any], tracker_metadata_prev: dict[str, np.ndarray] + ): + """Run the tracker propagation phase for a single frame in an SPMD manner.""" + # Step 1: propagate the local SAM2 states to get the current frame's prediction + # `low_res_masks_local` of the existing masklets on this GPU + # - obj_ids_local: list[int] -- list of object IDs + # - low_res_masks_local: Tensor -- (num_local_obj, H_mask, W_mask) + obj_ids_local, low_res_masks_local, obj_scores_local = self._propogate_tracker_one_frame_local_gpu( + tracker_states_local, frame_idx=frame_idx + ) + + assert np.all(obj_ids_local == tracker_metadata_prev["obj_ids"]), "{} != {}".format( + obj_ids_local, tracker_metadata_prev["obj_ids"] + ) + + # Step 2: all-gather `low_res_masks_local` into `low_res_masks_global` + # - low_res_masks_global: Tensor -- (num_global_obj, H_mask, W_mask) + low_res_masks_global = low_res_masks_local + obj_scores_global = obj_scores_local + return low_res_masks_global, obj_scores_global + + def _recondition_masklets( + self, + frame_idx, + det_out: dict[str, torch.Tensor], + trk_id_to_max_iou_high_conf_det: list[int], + tracker_states_local: list[Any], + tracker_metadata: dict[str, np.ndarray], + tracker_obj_scores_global: torch.Tensor, + ): + """Recondition masklets based on new high-confidence detections.""" + # Recondition the masklets based on the new detections + for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items(): + new_mask = det_out["mask"][det_idx : det_idx + 1] + new_mask_binary = ( + F.interpolate(new_mask.unsqueeze(1), size=self.interpol_size, mode="bilinear", align_corners=False) > 0 + ) + HIGH_CONF_THRESH = 0.8 + reconditioned_states_idx = set() + obj_idx = np.where(tracker_metadata["obj_ids"] == trk_obj_id)[0].item() + obj_score = tracker_obj_scores_global[obj_idx] + for state_idx, inference_state in enumerate(tracker_states_local): + if ( + trk_obj_id in inference_state["obj_ids"] + # NOTE: Goal of this condition is to avoid reconditioning masks that are occluded/low quality. + # Unfortunately, these can get reconditioned anyway due to batching. We should consider removing these heuristics. + and obj_score > HIGH_CONF_THRESH + ): + LOGGER.debug( + f"Adding new mask for track {trk_obj_id} at frame {frame_idx}. Objects {inference_state['obj_ids']} are all reconditioned." + ) + self.tracker.add_new_prompts( + inference_state=inference_state, + frame_idx=frame_idx, + obj_id=trk_obj_id, + masks=new_mask_binary, + ) + reconditioned_states_idx.add(state_idx) + + for idx in reconditioned_states_idx: + self.tracker.propagate_in_video_preflight(tracker_states_local[idx]) + return tracker_states_local + + def run_tracker_update_planning_phase( + self, + frame_idx: int, + reverse: bool, + det_out: dict[str, torch.Tensor], + tracker_low_res_masks_global: torch.Tensor, + tracker_obj_scores_global: torch.Tensor, + tracker_metadata_prev: dict[str, np.ndarray], + tracker_states_local: list[Any], + ): + """Run the tracker update planning phase for a single frame in an SPMD manner.""" + # initialize new metadata from previous metadata (its values will be updated later) + tracker_metadata_new = { + "obj_ids": deepcopy(tracker_metadata_prev["obj_ids"]), + "num_obj": deepcopy(tracker_metadata_prev["num_obj"]), + "obj_id_to_score": deepcopy(tracker_metadata_prev["obj_id_to_score"]), + "obj_id_to_cls": deepcopy(tracker_metadata_prev["obj_id_to_cls"]), + "obj_id_to_tracker_score_frame_wise": deepcopy(tracker_metadata_prev["obj_id_to_tracker_score_frame_wise"]), + "obj_id_to_last_occluded": {}, # will be filled later + "max_obj_id": deepcopy(tracker_metadata_prev["max_obj_id"]), + } + + # Initialize reconditioned_obj_ids early to avoid UnboundLocalError + reconditioned_obj_ids = set() + + # Step 1: make the update plan and resolve heuristics on GPU 0 + det_mask_preds: torch.Tensor = det_out["mask"] # low-res mask logits + det_scores_np: np.ndarray = det_out["scores"].float().cpu().numpy() + det_cls_np: np.ndarray = det_out["cls"].float().cpu().numpy() + det_bbox_xyxy: torch.Tensor = det_out["bbox"] + # a) match detector and tracker masks and find new objects + ( + new_det_fa_inds, + unmatched_trk_obj_ids, + det_to_matched_trk_obj_ids, + trk_id_to_max_iou_high_conf_det, + empty_trk_obj_ids, + ) = self._associate_det_trk( + det_masks=det_mask_preds, + det_scores_np=det_scores_np, + trk_masks=tracker_low_res_masks_global, + trk_obj_ids=tracker_metadata_prev["obj_ids"], + ) + if self.suppress_det_close_to_boundary: + keep = self._suppress_detections_close_to_boundary(det_bbox_xyxy[new_det_fa_inds]) + new_det_fa_inds = new_det_fa_inds[keep.cpu().numpy()] + + # check whether we've hit the maximum number of objects we can track (and if so, drop some detections) + prev_obj_num = np.sum(tracker_metadata_prev["num_obj"]) + new_det_num = len(new_det_fa_inds) + num_obj_dropped_due_to_limit = 0 + if prev_obj_num + new_det_num > self.max_num_objects: + LOGGER.warning(f"hitting {self.max_num_objects=} with {new_det_num=} and {prev_obj_num=}") + new_det_num_to_keep = self.max_num_objects - prev_obj_num + num_obj_dropped_due_to_limit = new_det_num - new_det_num_to_keep + new_det_fa_inds = self._drop_new_det_with_obj_limit(new_det_fa_inds, det_scores_np, new_det_num_to_keep) + assert len(new_det_fa_inds) == new_det_num_to_keep + new_det_num = len(new_det_fa_inds) + + # assign object IDs to new detections and decide which GPU to place them + new_det_obj_ids = tracker_metadata_prev["max_obj_id"] + 1 + np.arange(new_det_num) + + # b) handle hotstart heuristics to remove objects + # here `metadata` contains metadata stored on (and only accessible to) GPU 0; + # we avoid broadcasting them to other GPUs to save communication cost, assuming + # that `metadata` is not needed by other GPUs + metadata_new = deepcopy(tracker_metadata_prev["metadata"]) + if not hasattr(self, "_warm_up_complete") or self._warm_up_complete: + obj_ids_newly_removed, metadata_new = self._process_hotstart( + frame_idx=frame_idx, + reverse=reverse, + det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids, + new_det_obj_ids=new_det_obj_ids, + empty_trk_obj_ids=empty_trk_obj_ids, + unmatched_trk_obj_ids=unmatched_trk_obj_ids, + metadata=metadata_new, + ) + else: + # if warm-up is not complete, we don't remove any objects + obj_ids_newly_removed = set() + tracker_metadata_new["metadata"] = metadata_new + + # `tracker_update_plan` should be identical on all GPUs after broadcasting + tracker_update_plan = { + "new_det_fa_inds": new_det_fa_inds, # np.ndarray + "new_det_obj_ids": new_det_obj_ids, # np.ndarray + # "new_det_gpu_ids": new_det_gpu_ids, # np.ndarray + "unmatched_trk_obj_ids": unmatched_trk_obj_ids, # np.ndarray + "det_to_matched_trk_obj_ids": det_to_matched_trk_obj_ids, # dict + "obj_ids_newly_removed": obj_ids_newly_removed, # set + "num_obj_dropped_due_to_limit": num_obj_dropped_due_to_limit, # int + "trk_id_to_max_iou_high_conf_det": trk_id_to_max_iou_high_conf_det, # dict + "reconditioned_obj_ids": reconditioned_obj_ids, # set + } + + # Step 3 (optional): recondition masklets based on high-confidence detections before memory encoding + # NOTE: Running this in execution phase (after memory encoding) can lead to suboptimal results + should_recondition_iou = False + + # Evaluate tracklets for reconditioning based on bbox IoU mismatch with detections + if self.reconstruction_bbox_iou_thresh > 0 and len(trk_id_to_max_iou_high_conf_det) > 0: + for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items(): + det_box = det_out["bbox"][det_idx] + det_score = det_out["scores"][det_idx] + + try: + trk_idx = list(tracker_metadata_prev["obj_ids"]).index(trk_obj_id) + except ValueError: + continue # Skip if tracklet not found + + tracker_mask = tracker_low_res_masks_global[trk_idx] + mask_binary = tracker_mask > 0 + mask_area = mask_binary.sum().item() + + if mask_area == 0: + continue # Skip tracklets with zero mask area + + # Get bounding box from SAM2 mask and convert to normalized coordinates + tracker_box_pixels = batched_mask_to_box(mask_binary.unsqueeze(0)).squeeze(0) + mask_height, mask_width = tracker_mask.shape[-2:] + tracker_box_normalized = torch.tensor( + [ + tracker_box_pixels[0] / mask_width, + tracker_box_pixels[1] / mask_height, + tracker_box_pixels[2] / mask_width, + tracker_box_pixels[3] / mask_height, + ], + device=tracker_box_pixels.device, + ) + + # Compute IoU between detection and SAM2 tracklet bounding boxes + det_box_batch = det_box.unsqueeze(0) + tracker_box_batch = tracker_box_normalized.unsqueeze(0) + iou = box_iou(det_box_batch, tracker_box_batch)[0] + + if iou < self.reconstruction_bbox_iou_thresh and det_score >= self.reconstruction_bbox_det_score: + should_recondition_iou = True + reconditioned_obj_ids.add(trk_obj_id) + + should_recondition_periodic = ( + self.recondition_every_nth_frame > 0 + and frame_idx % self.recondition_every_nth_frame == 0 + and len(trk_id_to_max_iou_high_conf_det) > 0 + ) + + # Recondition if periodic or IoU condition met + if should_recondition_periodic or should_recondition_iou: + self._recondition_masklets( + frame_idx, + det_out, + trk_id_to_max_iou_high_conf_det, + tracker_states_local, + tracker_metadata_prev, + tracker_obj_scores_global, + ) + + # Step 4: Run SAM2 memory encoder on the current frame's prediction masks + # This is done on all GPUs + batch_size = tracker_low_res_masks_global.size(0) + if ( + batch_size > 0 + and (not hasattr(self, "_warm_up_complete") or self._warm_up_complete) + and self.suppress_overlapping_based_on_recent_occlusion_threshold > 0.0 + ): + # NOTE: tracker_low_res_masks_global is updated in-place then returned + tracker_low_res_masks_global = self._suppress_overlapping_based_on_recent_occlusion( + frame_idx, + tracker_low_res_masks_global, + tracker_metadata_prev, + tracker_metadata_new, + obj_ids_newly_removed, + reverse, + ) + + if batch_size > 0: + self._tracker_update_memories(tracker_states_local, frame_idx, low_res_masks=tracker_low_res_masks_global) + + # Step 4: update the SAM2 metadata based on the update plan + updated_obj_ids_this_gpu = tracker_metadata_new["obj_ids"] + if len(new_det_obj_ids) > 0: + updated_obj_ids_this_gpu = np.concatenate([updated_obj_ids_this_gpu, new_det_obj_ids]) + if len(obj_ids_newly_removed) > 0: + is_removed = np.isin(updated_obj_ids_this_gpu, list(obj_ids_newly_removed)) + updated_obj_ids_this_gpu = updated_obj_ids_this_gpu[~is_removed] + tracker_metadata_new["obj_ids"] = updated_obj_ids_this_gpu + tracker_metadata_new["num_obj"] = len(updated_obj_ids_this_gpu) + # update object scores and the maximum object ID assigned so far + if len(new_det_obj_ids) > 0: + tracker_metadata_new["obj_id_to_score"].update(zip(new_det_obj_ids, det_scores_np[new_det_fa_inds])) + tracker_metadata_new["obj_id_to_cls"].update(zip(new_det_obj_ids, det_cls_np[new_det_fa_inds])) + # tracker scores are not available for new objects, use det score instead. + tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx].update( + zip(new_det_obj_ids, det_scores_np[new_det_fa_inds]) + ) + tracker_metadata_new["max_obj_id"] = max(tracker_metadata_new["max_obj_id"], np.max(new_det_obj_ids)) + # for removed objects, we set their scores to a very low value (-1e4) but still + # keep them in "obj_id_to_score" (it's easier to handle outputs this way) + for obj_id in obj_ids_newly_removed: + tracker_metadata_new["obj_id_to_score"][obj_id] = -1e4 + tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx][obj_id] = -1e4 + tracker_metadata_new["obj_id_to_last_occluded"].pop(obj_id, None) + # check that "metadata" is in tracker_metadata_new if and only if it's GPU 0 + assert "metadata" in tracker_metadata_new + if self.masklet_confirmation_enable: + metadata = self.update_masklet_confirmation_status( + metadata=tracker_metadata_new["metadata"], + obj_ids_all_gpu_prev=tracker_metadata_prev["obj_ids"], + obj_ids_all_gpu_updated=tracker_metadata_new["obj_ids"], + det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids, + new_det_obj_ids=new_det_obj_ids, + ) + tracker_metadata_new["metadata"] = metadata + + return tracker_update_plan, tracker_metadata_new + + def _suppress_overlapping_based_on_recent_occlusion( + self, + frame_idx: int, + tracker_low_res_masks_global: torch.Tensor, + tracker_metadata_prev: dict[str, Any], + tracker_metadata_new: dict[str, Any], + obj_ids_newly_removed: set[int], + reverse: bool = False, + ): + """Suppress overlapping masks based on the most recent occlusion information. If an object is removed by + hotstart, we always suppress it if it overlaps with any other object. + + Args: + frame_idx (int): The current frame index. + tracker_low_res_masks_global (torch.Tensor): The low-resolution masks for the current frame. + tracker_metadata_prev (dict[str, Any]): The metadata from the previous frame. + tracker_metadata_new (dict[str, Any]): The metadata for the current frame. + obj_ids_newly_removed (set[int]): The object IDs that have been removed. + reverse (bool): Whether the tracking is in reverse order. + + Returns: + (torch.Tensor): The updated low-resolution masks with some objects suppressed. + """ + obj_ids_global = tracker_metadata_prev["obj_ids"] + binary_tracker_low_res_masks_global = tracker_low_res_masks_global > 0 + batch_size = tracker_low_res_masks_global.size(0) + if batch_size > 0: + assert len(obj_ids_global) == batch_size, ( + f"Mismatch in number of objects: {len(obj_ids_global)} vs {batch_size}" + ) + last_occluded_prev = torch.cat( + [ + tracker_metadata_prev["obj_id_to_last_occluded"].get( + obj_id, + torch.full( + (1,), + fill_value=( + self.NEVER_OCCLUDED if obj_id not in obj_ids_newly_removed else self.ALWAYS_OCCLUDED + ), + device=binary_tracker_low_res_masks_global.device, + dtype=torch.long, + ), + ) + for obj_id in obj_ids_global + ], + dim=0, + ) + to_suppress = self._get_objects_to_suppress_based_on_most_recently_occluded( + binary_tracker_low_res_masks_global, + last_occluded_prev, + obj_ids_global, + frame_idx, + reverse, + ) + + # Update metadata with occlusion information + is_obj_occluded = ~(binary_tracker_low_res_masks_global.any(dim=(-1, -2))) + is_obj_occluded_or_suppressed = is_obj_occluded | to_suppress + last_occluded_new = last_occluded_prev.clone() + last_occluded_new[is_obj_occluded_or_suppressed] = frame_idx + # Slice out the last occluded frame for each object + tracker_metadata_new["obj_id_to_last_occluded"] = { + obj_id: last_occluded_new[obj_idx : obj_idx + 1] for obj_idx, obj_id in enumerate(obj_ids_global) + } + + # Zero out suppressed masks before memory encoding + tracker_low_res_masks_global[to_suppress] = self.NO_OBJ_LOGIT + + return tracker_low_res_masks_global + + def run_tracker_update_execution_phase( + self, + frame_idx: int, + num_frames: int, + det_out: dict[str, torch.Tensor], + tracker_states_local: list[Any], + tracker_update_plan: dict[str, np.ndarray], + ): + """Execute the tracker update plan for a single frame in an SPMD manner.""" + # initialize tracking scores with detection scores + new_det_fa_inds: np.ndarray = tracker_update_plan["new_det_fa_inds"] + new_det_obj_ids: np.ndarray = tracker_update_plan["new_det_obj_ids"] + # new_det_gpu_ids: np.ndarray = tracker_update_plan["new_det_gpu_ids"] + new_det_obj_ids_local: np.ndarray = new_det_obj_ids + new_det_fa_inds_local: np.ndarray = new_det_fa_inds + obj_ids_newly_removed: set[int] = tracker_update_plan["obj_ids_newly_removed"] + + # Step 1: add new objects from the detector to SAM2 inference states + if len(new_det_fa_inds_local) > 0: + new_det_fa_inds_local_t = torch.from_numpy(new_det_fa_inds_local) + new_det_masks: torch.Tensor = det_out["mask"][new_det_fa_inds_local_t] + # initialize SAM2 with new object masks + tracker_states_local = self._tracker_add_new_objects( + frame_idx=frame_idx, + num_frames=num_frames, + new_obj_ids=new_det_obj_ids_local, + new_obj_masks=new_det_masks, + tracker_states_local=tracker_states_local, + ) + + # Step 2: remove from SAM2 inference states those objects removed by heuristics + if len(obj_ids_newly_removed) > 0: + self._tracker_remove_objects(tracker_states_local, obj_ids_newly_removed) + + return tracker_states_local + + @staticmethod + def build_outputs( + det_out: dict[str, torch.Tensor], + tracker_low_res_masks_global: torch.Tensor, + tracker_metadata_prev: dict[str, np.ndarray], + tracker_update_plan: dict[str, np.ndarray], + reconditioned_obj_ids: set | None = None, + ): + """Build the output masks for the current frame.""" + new_det_fa_inds: np.ndarray = tracker_update_plan["new_det_fa_inds"] + new_det_obj_ids: np.ndarray = tracker_update_plan["new_det_obj_ids"] + obj_id_to_mask = {} # obj_id --> output mask tensor + + # Part 1: masks from previous SAM2 propagation + existing_masklet_obj_ids = tracker_metadata_prev["obj_ids"] + existing_masklet_logits = tracker_low_res_masks_global.unsqueeze(1) + assert len(existing_masklet_obj_ids) == len(existing_masklet_logits) + for obj_id, mask in zip(existing_masklet_obj_ids, existing_masklet_logits): + obj_id_to_mask[obj_id] = mask # (1, H_video, W_video) + + # Part 2: masks from new detections + new_det_fa_inds_t = torch.from_numpy(new_det_fa_inds) + new_det_low_res_masks = det_out["mask"][new_det_fa_inds_t].unsqueeze(1) + assert len(new_det_obj_ids) == len(new_det_low_res_masks) + for obj_id, mask in zip(new_det_obj_ids, new_det_low_res_masks): + obj_id_to_mask[obj_id] = mask # (1, H_video, W_video) + + # Part 3: Override masks for reconditioned objects using detection masks + if reconditioned_obj_ids is not None and len(reconditioned_obj_ids) > 0: + trk_id_to_max_iou_high_conf_det = tracker_update_plan.get("trk_id_to_max_iou_high_conf_det", {}) + + for obj_id in reconditioned_obj_ids: + det_idx = trk_id_to_max_iou_high_conf_det.get(obj_id) + + if det_idx is not None: + obj_id_to_mask[obj_id] = det_out["mask"][det_idx].unsqueeze(0) + + return obj_id_to_mask + + def _get_objects_to_suppress_based_on_most_recently_occluded( + self, + binary_low_res_masks: torch.Tensor, + last_occluded: list[int], + obj_ids: list[int], + frame_idx: int | None = None, + reverse: bool = False, + ): + # Suppress overlapping masks for objects that were most recently occluded + assert binary_low_res_masks.dtype == torch.bool, f"Expected boolean tensor, got {binary_low_res_masks.dtype}" + to_suppress = torch.zeros( + binary_low_res_masks.size(0), + device=binary_low_res_masks.device, + dtype=torch.bool, + ) + if len(obj_ids) <= 1: + return to_suppress + + iou = mask_iou(binary_low_res_masks.flatten(1), binary_low_res_masks.flatten(1)) # [N,N] + + # Create masks for upper triangular matrix (i < j) and IoU threshold + mask_iou_thresh = iou >= self.suppress_overlapping_based_on_recent_occlusion_threshold + overlapping_pairs = torch.triu(mask_iou_thresh, diagonal=1) # [N,N] + + last_occ_expanded_i = last_occluded.unsqueeze(1) # (N, 1) + last_occ_expanded_j = last_occluded.unsqueeze(0) # (1, N) + # Suppress most recently occluded + cmp_op = torch.gt if not reverse else torch.lt + suppress_i_mask = ( + overlapping_pairs + & cmp_op(last_occ_expanded_i, last_occ_expanded_j) # (last_occ_expanded_i > last_occ_expanded_j) + & (last_occ_expanded_j > -1) # j can suppress i only if i was previously occluded + ) + suppress_j_mask = ( + overlapping_pairs + & cmp_op(last_occ_expanded_j, last_occ_expanded_i) + & (last_occ_expanded_i > -1) # i can suppress j only if j was previously occluded + ) + # Apply suppression + to_suppress = suppress_i_mask.any(dim=1) | suppress_j_mask.any(dim=0) + + # Log for debugging + if LOGGER.isEnabledFor(10) and frame_idx is not None: + suppress_i_mask = suppress_i_mask.cpu().numpy() + suppress_j_mask = suppress_j_mask.cpu().numpy() + last_occluded = last_occluded.cpu().numpy() + + # Find all suppression pairs without using torch.where + batch_size = suppress_i_mask.shape[0] + + # Log i-suppression cases (where i gets suppressed in favor of j) + for i in range(batch_size): + for j in range(batch_size): + if suppress_i_mask[i, j]: + LOGGER.debug( + f"{frame_idx=}: Suppressing obj {obj_ids[i]} last occluded {last_occluded[i]} in favor of {obj_ids[j]} last occluded {last_occluded[j]}" + ) + + # Log j-suppression cases (where j gets suppressed in favor of i) + for i in range(batch_size): + for j in range(batch_size): + if suppress_j_mask[i, j]: + LOGGER.debug( + f"{frame_idx=}: Suppressing obj {obj_ids[j]} last occluded {last_occluded[j]} in favor of {obj_ids[i]} last occluded {last_occluded[i]}" + ) + + return to_suppress + + def _propogate_tracker_one_frame_local_gpu(self, inference_states: list[Any], frame_idx: int): + """Inference_states: list of inference states, each state corresponds to a different set of objects.""" + obj_ids_local = [] + low_res_masks_list = [] + obj_scores_list = [] + for inference_state in inference_states: + if len(inference_state["obj_ids"]) == 0: + continue # skip propagation on empty inference states + + out_obj_ids, out_low_res_masks, out_obj_scores = self.tracker.propagate_in_video( + inference_state, frame_idx=frame_idx + ) + assert isinstance(out_obj_ids, list) + obj_ids_local.extend(out_obj_ids) + low_res_masks_list.append(out_low_res_masks.squeeze(1)) + obj_scores_list.append(out_obj_scores.squeeze(1)) + + # concatenate the output masklets from all local inference states + if len(low_res_masks_list) > 0: + low_res_masks_local = torch.cat(low_res_masks_list, dim=0) + obj_scores_local = torch.cat(obj_scores_list, dim=0) + low_res_masks_local = low_res_masks_local.squeeze(1) + else: + low_res_masks_local = torch.zeros(0, *self._bb_feat_sizes[0], device=self.device) + obj_scores_local = torch.zeros(0, device=self.device) + + return obj_ids_local, low_res_masks_local, obj_scores_local + + def _associate_det_trk( + self, + det_masks: torch.Tensor, + det_scores_np: np.ndarray, + trk_masks: torch.Tensor, + trk_obj_ids: np.ndarray, + ): + """Match detections on the current frame with the existing masklets. + + Args: + det_masks: (N, H, W) tensor of predicted masks + det_scores_np: (N,) array of detection scores + trk_masks: (M, H, W) tensor of track masks + trk_obj_ids: (M,) array of object IDs corresponding to trk_masks + + Returns: + new_det_fa_inds: array of new object indices. + unmatched_trk_obj_ids: array of existing masklet object IDs that are not matched to any detections on this + frame (for unmatched, we only count masklets with >0 area) + det_to_matched_trk_obj_ids: dict[int, np.ndarray]: mapping from detector's detection indices to the list of + matched tracklet object IDs + empty_trk_obj_ids: array of existing masklet object IDs with zero area in SAM2 prediction + """ + iou_threshold = self.assoc_iou_thresh + iou_threshold_trk = self.trk_assoc_iou_thresh + new_det_thresh = self.new_det_thresh + + assert det_masks.is_floating_point(), "float tensor expected (do not binarize)" + assert trk_masks.is_floating_point(), "float tensor expected (do not binarize)" + assert trk_masks.size(0) == len(trk_obj_ids), ( + f"trk_masks and trk_obj_ids should have the same length, {trk_masks.size(0)} vs {len(trk_obj_ids)}" + ) + if trk_masks.size(0) == 0: + # all detections are new + new_det_fa_inds = np.arange(det_masks.size(0)) + unmatched_trk_obj_ids = np.array([], np.int64) + empty_trk_obj_ids = np.array([], np.int64) + det_to_matched_trk_obj_ids = {} + trk_id_to_max_iou_high_conf_det = {} + return ( + new_det_fa_inds, + unmatched_trk_obj_ids, + det_to_matched_trk_obj_ids, + trk_id_to_max_iou_high_conf_det, + empty_trk_obj_ids, + ) + elif det_masks.size(0) == 0: + # all previous tracklets are unmatched if they have a non-zero area + new_det_fa_inds = np.array([], np.int64) + trk_is_nonempty = (trk_masks > 0).any(dim=(1, 2)).cpu().numpy() + unmatched_trk_obj_ids = trk_obj_ids[trk_is_nonempty] + empty_trk_obj_ids = trk_obj_ids[~trk_is_nonempty] + det_to_matched_trk_obj_ids = {} + trk_id_to_max_iou_high_conf_det = {} + return ( + new_det_fa_inds, + unmatched_trk_obj_ids, + det_to_matched_trk_obj_ids, + trk_id_to_max_iou_high_conf_det, + empty_trk_obj_ids, + ) + + if det_masks.shape[-2:] != trk_masks.shape[-2:]: + # resize to the smaller size to save GPU memory + if np.prod(det_masks.shape[-2:]) < np.prod(trk_masks.shape[-2:]): + trk_masks = F.interpolate( + trk_masks.unsqueeze(1), + size=det_masks.shape[-2:], + mode="bilinear", + align_corners=False, + ).squeeze(1) + else: + # resize detections to track size + det_masks = F.interpolate( + det_masks.unsqueeze(1), + size=trk_masks.shape[-2:], + mode="bilinear", + align_corners=False, + ).squeeze(1) + + det_masks_binary = det_masks > 0 + trk_masks_binary = trk_masks > 0 + ious = mask_iou(det_masks_binary.flatten(1).float(), trk_masks_binary.flatten(1).float()) # (N, M) + + ious_np = ious.cpu().numpy() + if self.o2o_matching_masklets_enable: + from ultralytics.utils.ops import linear_sum_assignment + + # Hungarian matching for tracks (one-to-one: each track matches at most one detection) + cost_matrix = 1 - ious_np # Hungarian solves for minimum cost + row_ind, col_ind = linear_sum_assignment(cost_matrix) + trk_is_matched = np.zeros(trk_masks.size(0), dtype=bool) + for d, t in zip(row_ind, col_ind): + if ious_np[d, t] >= iou_threshold_trk: + trk_is_matched[t] = True + else: + trk_is_matched = (ious_np >= iou_threshold_trk).any(axis=0) + # Non-empty tracks not matched by Hungarian assignment above threshold are unmatched + trk_is_nonempty = trk_masks_binary.any(dim=(1, 2)).cpu().numpy() + trk_is_unmatched = np.logical_and(trk_is_nonempty, ~trk_is_matched) + unmatched_trk_obj_ids = trk_obj_ids[trk_is_unmatched] + # also record masklets that have zero area in SAM 2 prediction + empty_trk_obj_ids = trk_obj_ids[~trk_is_nonempty] + + # For detections: allow many tracks to match to the same detection (many-to-one) + # So, a detection is 'new' if it does not match any track above threshold + is_new_det = np.logical_and( + det_scores_np >= new_det_thresh, + np.logical_not(np.any(ious_np >= iou_threshold, axis=1)), + ) + new_det_fa_inds = np.nonzero(is_new_det)[0] + + # for each detection, which tracks it matched to (above threshold) + det_to_matched_trk_obj_ids = {} + trk_id_to_max_iou_high_conf_det = {} # trk id --> exactly one detection idx + det_to_max_iou_trk_idx = np.argmax(ious_np, axis=1) + det_is_high_conf = (det_scores_np >= self.HIGH_CONF_THRESH) & ~is_new_det + det_is_high_iou = np.max(ious_np, axis=1) >= self.HIGH_IOU_THRESH + det_is_high_conf_and_iou = set(np.nonzero(det_is_high_conf & det_is_high_iou)[0]) + for d in range(det_masks.size(0)): + det_to_matched_trk_obj_ids[d] = trk_obj_ids[ious_np[d, :] >= iou_threshold] + if d in det_is_high_conf_and_iou: + trk_obj_id = trk_obj_ids[det_to_max_iou_trk_idx[d]].item() + trk_id_to_max_iou_high_conf_det[trk_obj_id] = d + + return ( + new_det_fa_inds, + unmatched_trk_obj_ids, + det_to_matched_trk_obj_ids, + trk_id_to_max_iou_high_conf_det, + empty_trk_obj_ids, + ) + + def _process_hotstart( + self, + frame_idx: int, + reverse: bool, + det_to_matched_trk_obj_ids: dict[int, np.ndarray], + new_det_obj_ids: np.ndarray, + empty_trk_obj_ids: np.ndarray, + unmatched_trk_obj_ids: np.ndarray, + metadata: dict[str, Any], + ): + """Handle hotstart heuristics to remove unmatched or duplicated objects.""" + # obj_id --> first frame index where the object was detected + obj_first_frame_idx = metadata["obj_first_frame_idx"] + # obj_id --> [mismatched frame indices] + unmatched_frame_inds = metadata["unmatched_frame_inds"] + trk_keep_alive = metadata["trk_keep_alive"] + # (first_appear_obj_id, obj_id) --> [overlap frame indices] + overlap_pair_to_frame_inds = metadata["overlap_pair_to_frame_inds"] + # removed_obj_ids: object IDs that are suppressed via hot-start + removed_obj_ids = metadata["removed_obj_ids"] + + obj_ids_newly_removed = set() # object IDs to be newly removed on this frame + hotstart_diff = frame_idx - self.hotstart_delay if not reverse else frame_idx + self.hotstart_delay + + # Step 1: log the frame index where each object ID first appears + for obj_id in new_det_obj_ids: + if obj_id not in obj_first_frame_idx: + obj_first_frame_idx[obj_id] = frame_idx + assert obj_id not in trk_keep_alive + trk_keep_alive[obj_id] = self.init_trk_keep_alive + + matched_trks = set() + # We use the det-->tracks list to check for matched objects. Otherwise, we need to compute areas to decide whether they're occluded + for matched_trks_per_det in det_to_matched_trk_obj_ids.values(): + matched_trks.update(matched_trks_per_det) + for obj_id in matched_trks: + # NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the max value of trk_keep_alive + trk_keep_alive[obj_id] = min(self.max_trk_keep_alive, trk_keep_alive[obj_id] + 1) + for obj_id in unmatched_trk_obj_ids: + unmatched_frame_inds[obj_id].append(frame_idx) + # NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the min value of trk_keep_alive + # The max keep alive is 2x the min, means the model prefers to keep the prediction rather than suppress it if it was matched long enough. + trk_keep_alive[obj_id] = max(self.min_trk_keep_alive, trk_keep_alive[obj_id] - 1) + if self.decrease_trk_keep_alive_for_empty_masklets: + for obj_id in empty_trk_obj_ids: + # NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the min value of trk_keep_alive + trk_keep_alive[obj_id] = max(self.min_trk_keep_alive, trk_keep_alive[obj_id] - 1) + + # Step 2: removed tracks that has not matched with detections for `hotstart_unmatch_thresh` frames with hotstart period + # a) add unmatched frame indices for each existing object ID + # note that `unmatched_trk_obj_ids` contains those frames where the SAM2 output mask + # doesn't match any detection; it excludes those frames where SAM2 gives an empty mask + # b) remove a masklet if it first appears after `hotstart_diff` and is unmatched for more + # than `self.hotstart_unmatch_thresh` frames + for obj_id, frame_indices in unmatched_frame_inds.items(): + if obj_id in removed_obj_ids or obj_id in obj_ids_newly_removed: + continue # skip if the object is already removed + if len(frame_indices) >= self.hotstart_unmatch_thresh: + is_within_hotstart = (obj_first_frame_idx[obj_id] > hotstart_diff and not reverse) or ( + obj_first_frame_idx[obj_id] < hotstart_diff and reverse + ) + if is_within_hotstart: + obj_ids_newly_removed.add(obj_id) + LOGGER.debug( + f"Removing object {obj_id} at frame {frame_idx} " + f"since it is unmatched for frames: {frame_indices}" + ) + if ( + trk_keep_alive[obj_id] <= 0 # Object has not been matched for too long + and obj_id not in removed_obj_ids + and obj_id not in obj_ids_newly_removed + ): + LOGGER.debug(f"Removing object {obj_id} at frame {frame_idx}, due to being unmatched") + # directly removed the object instead of suppressing it + obj_ids_newly_removed.add(obj_id) + + # Step 3: removed tracks that overlaps with another track for `hotstart_dup_thresh` frames + # a) find overlaps tracks -- we consider overlap if they match to the same detection + for matched_trk_obj_ids in det_to_matched_trk_obj_ids.values(): + if len(matched_trk_obj_ids) < 2: + continue # only count detections that are matched to multiple (>=2) masklets + # if there are multiple matched track ids, we need to find the one that appeared first; + # these later appearing ids may be removed since they may be considered as duplicates + first_appear_obj_id = ( + min(matched_trk_obj_ids, key=lambda x: obj_first_frame_idx[x]) + if not reverse + else max(matched_trk_obj_ids, key=lambda x: obj_first_frame_idx[x]) + ) + for obj_id in matched_trk_obj_ids: + if obj_id != first_appear_obj_id: + key = (first_appear_obj_id, obj_id) + overlap_pair_to_frame_inds[key].append(frame_idx) + + # b) remove a masklet if it first appears after `hotstart_diff` and it overlaps with another + # masklet (that appears earlier) for more than `self.hotstart_dup_thresh` frames + for (first_obj_id, obj_id), frame_indices in overlap_pair_to_frame_inds.items(): + if obj_id in removed_obj_ids or obj_id in obj_ids_newly_removed: + continue # skip if the object is already removed + if ( + (obj_first_frame_idx[obj_id] > hotstart_diff and not reverse) + or (obj_first_frame_idx[obj_id] < hotstart_diff and reverse) + ) and len(frame_indices) >= self.hotstart_dup_thresh: + obj_ids_newly_removed.add(obj_id) + LOGGER.debug( + f"Removing object {obj_id} at frame {frame_idx} " + f"since it overlaps with another track {first_obj_id} at frames: {frame_indices}" + ) + + removed_obj_ids.update(obj_ids_newly_removed) + return obj_ids_newly_removed, metadata + + def _tracker_update_memories( + self, tracker_inference_states: list[Any], frame_idx: int, low_res_masks: torch.Tensor + ): + """Run Sam2 memory encoder, enforcing non-overlapping constraints globally.""" + if len(tracker_inference_states) == 0: + return + # NOTE: inspect this part if we observe OOMs in the demo + high_res_masks = F.interpolate( + low_res_masks.unsqueeze(1), + size=self.interpol_size, + mode="bilinear", + align_corners=False, + ) + # We first apply non-overlapping constraints before memory encoding. This may include some suppression heuristics. + if not hasattr(self, "_warm_up_complete") or self._warm_up_complete: + high_res_masks = self.tracker.model._suppress_object_pw_area_shrinkage(high_res_masks) + # Instead of gathering the predicted object scores, we use mask areas as a proxy. + object_score_logits = torch.where((high_res_masks > 0).any(dim=(-1, -2)), 10.0, -10.0) + + # Run the memory encoder on local slices for each GPU + start_idx_gpu = 0 + start_idx_state = start_idx_gpu + for tracker_state in tracker_inference_states: + num_obj_per_state = len(tracker_state["obj_ids"]) + if num_obj_per_state == 0: + continue + # Get the local high-res masks and object score logits for this inference state + end_idx_state = start_idx_state + num_obj_per_state + local_high_res_masks = high_res_masks[start_idx_state:end_idx_state] + local_object_score_logits = object_score_logits[start_idx_state:end_idx_state] + local_batch_size = local_high_res_masks.size(0) + # Run Sam2 memory encoder. Note that we do not re-enforce the non-overlapping constraint as it is turned off by default + + encoded_mem = self.tracker._run_memory_encoder( + local_batch_size, + local_high_res_masks, + local_object_score_logits, + is_mask_from_pts=False, + inference_state=tracker_state, + ) + local_maskmem_features, local_maskmem_pos_enc = encoded_mem + # Store encoded memories in the local inference state + output_dict = tracker_state["output_dict"] + for storage_key in ["cond_frame_outputs", "non_cond_frame_outputs"]: + if frame_idx not in output_dict[storage_key]: + continue + output_dict[storage_key][frame_idx]["maskmem_features"] = local_maskmem_features + output_dict[storage_key][frame_idx]["maskmem_pos_enc"] = [pos for pos in local_maskmem_pos_enc] + # for batched inference state, we also need to add per-object + # memory slides to support instance interactivity + self.tracker._add_output_per_object( + inference_state=tracker_state, + frame_idx=frame_idx, + current_out=output_dict[storage_key][frame_idx], + storage_key=storage_key, + ) + start_idx_state += num_obj_per_state + + def _tracker_add_new_objects( + self, + frame_idx: int, + num_frames: int, + new_obj_ids: list[int], + new_obj_masks: torch.Tensor, + tracker_states_local: list[Any], + ): + """Add a new object to SAM2 inference states.""" + prev_tracker_state = tracker_states_local[0] if len(tracker_states_local) > 0 else None + + # prepare inference_state + # batch objects that first appear on the same frame together + # Clear inference state. Keep the cached image features if available. + new_tracker_state = self.tracker._init_state(num_frames=num_frames) + # NOTE: adding image placeholder + new_tracker_state["im"] = None + new_tracker_state["backbone_out"] = ( + prev_tracker_state.get("backbone_out", None) if prev_tracker_state is not None else None + ) + + assert len(new_obj_ids) == new_obj_masks.size(0) + assert new_obj_masks.is_floating_point() + new_obj_masks = F.interpolate( + new_obj_masks.unsqueeze(0), + size=self.interpol_size, + mode="bilinear", + align_corners=False, + ).squeeze(0) + new_obj_masks = new_obj_masks > 0 + + # add object one by one + for new_obj_id, new_mask in zip(new_obj_ids, new_obj_masks): + self.tracker.add_new_prompts( + inference_state=new_tracker_state, + frame_idx=frame_idx, + obj_id=new_obj_id, + masks=new_mask[None, None], # add bs, channel + ) + # NOTE: we skip enforcing the non-overlapping constraint **globally** when adding new objects. + self.tracker.propagate_in_video_preflight(new_tracker_state) + tracker_states_local.append(new_tracker_state) + return tracker_states_local + + def _tracker_remove_objects(self, tracker_states_local: list[Any], obj_ids: list[int]): + """Remove an object from SAM2 inference states. This would remove the object from all frames in the video.""" + if not obj_ids: + return + # Filter out states that become empty after removal + active_states = [] + for state in tracker_states_local: + for obj_id in obj_ids: + # we try to remove `obj_id` on every inference state with `strict=False` + # it will not do anything if an inference state doesn't contain `obj_id` + self.tracker.remove_object(state, obj_id, strict=False) + + if len(state["obj_ids"]) > 0: + active_states.append(state) + + # Update the list in-place + tracker_states_local[:] = active_states + + def _initialize_metadata(self): + """Initialize metadata for the masklets.""" + tracker_metadata = { + "obj_ids": np.array([], np.int32), + "num_obj": np.zeros(1, np.int32), + "max_obj_id": -1, + "obj_id_to_score": {}, + "obj_id_to_cls": {}, + "obj_id_to_tracker_score_frame_wise": defaultdict(dict), + "obj_id_to_last_occluded": {}, + } + # "metadata" contains metadata that is only stored on (and accessible to) GPU 0 + # - obj_first_frame_idx: obj_id --> first frame index where the object was detected + # - unmatched_frame_inds: obj_id --> [mismatched frame indices] + # - overlap_pair_to_frame_inds: (first_appear_obj_id, obj_id) --> [overlap frame indices] + # - removed_obj_ids: object IDs that are suppressed via hot-start + metadata = { + "obj_first_frame_idx": {}, + "unmatched_frame_inds": defaultdict(list), + "trk_keep_alive": defaultdict(int), # This is used only for object suppression not for removal + "overlap_pair_to_frame_inds": defaultdict(list), + "removed_obj_ids": set(), + } + if self.masklet_confirmation_enable: + # all the following are np.ndarray with the same shape as `obj_ids_all_gpu` + metadata["masklet_confirmation"] = { + # "status" is the confirmation status of each masklet + "status": np.array([], np.int64), + # "consecutive_det_num" is the number of consecutive frames where the masklet is + # detected by the detector (with a matched detection) + "consecutive_det_num": np.array([], np.int64), + } + tracker_metadata["metadata"] = metadata + + return tracker_metadata + + def update_masklet_confirmation_status( + self, + metadata: dict[str, Any], + obj_ids_all_gpu_prev: np.ndarray, + obj_ids_all_gpu_updated: np.ndarray, + det_to_matched_trk_obj_ids: dict[int, np.ndarray], + new_det_obj_ids: np.ndarray, + ): + """Update the confirmation status of masklets based on the current frame's detection results.""" + confirmation_data = metadata["masklet_confirmation"] + + # a) first, expand "confirmation_data" to include new masklets added in this frame + status_prev = confirmation_data["status"] + consecutive_det_num_prev = confirmation_data["consecutive_det_num"] + assert status_prev.shape == obj_ids_all_gpu_prev.shape, ( + f"Got {status_prev.shape} vs {obj_ids_all_gpu_prev.shape}" + ) + + obj_id_to_updated_idx = {obj_id: idx for idx, obj_id in enumerate(obj_ids_all_gpu_updated)} + prev_elem_is_in_updated = np.isin(obj_ids_all_gpu_prev, obj_ids_all_gpu_updated) + prev_elem_obj_ids_in_updated = obj_ids_all_gpu_prev[prev_elem_is_in_updated] + prev_elem_inds_in_updated = np.array( + [obj_id_to_updated_idx[obj_id] for obj_id in prev_elem_obj_ids_in_updated], + dtype=np.int64, + ) + # newly added masklets are initialized to "UNCONFIRMED" status + unconfirmed_val = self.UNCONFIRMED + status = np.full_like(obj_ids_all_gpu_updated, fill_value=unconfirmed_val) + status[prev_elem_inds_in_updated] = status_prev[prev_elem_is_in_updated] + consecutive_det_num = np.zeros_like(obj_ids_all_gpu_updated) + consecutive_det_num[prev_elem_inds_in_updated] = consecutive_det_num_prev[prev_elem_is_in_updated] + + # b) update the confirmation status of all masklets based on the current frame + # b.1) update "consecutive_det_num" + # "is_matched": whether a masklet is matched to a detection on this frame + is_matched = np.isin(obj_ids_all_gpu_updated, new_det_obj_ids) + for matched_trk_obj_ids in det_to_matched_trk_obj_ids.values(): + is_matched |= np.isin(obj_ids_all_gpu_updated, matched_trk_obj_ids) + consecutive_det_num = np.where(is_matched, consecutive_det_num + 1, 0) + + # b.2) update "status" + change_to_confirmed = consecutive_det_num >= self.masklet_confirmation_consecutive_det_thresh + status[change_to_confirmed] = self.CONFIRMED + + confirmation_data["status"] = status + confirmation_data["consecutive_det_num"] = consecutive_det_num + return metadata + + def _load_checkpoint(self, ckpt_path: str, strict: bool = True): + sd = torch.load(ckpt_path, map_location="cpu", weights_only=True)["model"] + missing_keys, unexpected_keys = self.load_state_dict(sd, strict=strict) + if len(missing_keys) > 0 or len(unexpected_keys) > 0: + LOGGER.warning(f"Loaded ckpt with {missing_keys=}, {unexpected_keys=}") + else: + LOGGER.info("Loaded ckpt successfully without missing or unexpected keys") + + def _encode_prompt(self, **kwargs): + return self.model._encode_prompt(**kwargs) + + @staticmethod + def _drop_new_det_with_obj_limit(new_det_fa_inds, det_scores_np, num_to_keep): + """Drop a few new detections based on the maximum number of objects. We drop new objects based on their + detection scores, keeping the high-scoring ones and dropping the low-scoring ones. + """ + assert 0 <= num_to_keep <= len(new_det_fa_inds) + if num_to_keep == 0: + return np.array([], np.int64) # keep none + if num_to_keep == len(new_det_fa_inds): + return new_det_fa_inds # keep all + + # keep the top-scoring detections + score_order = np.argsort(det_scores_np[new_det_fa_inds])[::-1] + new_det_fa_inds = new_det_fa_inds[score_order[:num_to_keep]] + return new_det_fa_inds diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fbe077b6185a945ab3eb45248050c2e8b0ad6979 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__init__.py @@ -0,0 +1,3 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8920fe6c0bb51c12a20b2143325a9c22341530dd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/decoder.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/decoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a6a1bc63a692eb910b77fa00672a3bec48ccab8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/decoder.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/encoder.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/encoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f232a31deb3963debfc6afd099e33074ed2bc7d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/encoder.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/geometry_encoders.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/geometry_encoders.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b11469e936d0ba11dfec13a36cecdca36a193626 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/geometry_encoders.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/maskformer_segmentation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/maskformer_segmentation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..893e442b339e5a8f041c4f3137c5e79bdbf07f99 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/maskformer_segmentation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/model_misc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/model_misc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24acb4484b65ac3b89efa7cfe4a4f9eb2d1d60dd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/model_misc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/necks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/necks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..028ab7b4167a6b7245d6e7bc86871690d73b2066 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/necks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/sam3_image.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/sam3_image.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea26991d9d5f4a14e957dbd384d6c99a08edc2f1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/sam3_image.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/text_encoder_ve.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/text_encoder_ve.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb54c0b3416c2ae0c537d2d7995cc92fa456e2bd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/text_encoder_ve.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/vitdet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/vitdet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c07acddf014af21be10d3ef79b2892c69b38c39f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/vitdet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/vl_combiner.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/vl_combiner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b4120d5a74e529fbdc4d9f679c7537f5040f2e0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/__pycache__/vl_combiner.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/decoder.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..0220ba31c5ca8cd5ec46424cead90d4b940adf68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/decoder.py @@ -0,0 +1,512 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved +""" +Transformer decoder. +Inspired from Pytorch's version, adds the pre-norm variant. +""" + +from __future__ import annotations + +import numpy as np +import torch +from torch import nn + +from ultralytics.nn.modules.transformer import MLP +from ultralytics.nn.modules.utils import _get_clones, inverse_sigmoid +from ultralytics.utils.ops import xywh2xyxy + +from .model_misc import gen_sineembed_for_position + + +class TransformerDecoderLayer(nn.Module): + """TransformerDecoderLayer is made up of self-attn, cross-attn, and feedforward network (FFN).""" + + def __init__( + self, + d_model: int, + dim_feedforward: int, + dropout: float, + cross_attention: nn.Module, + n_heads: int, + use_text_cross_attention: bool = False, + ): + """Initialize the TransformerDecoderLayer.""" + super().__init__() + # cross attention + self.cross_attn = cross_attention + self.dropout1 = nn.Dropout(dropout) if dropout > 0 else nn.Identity() + self.norm1 = nn.LayerNorm(d_model) + + # cross attention text + self.use_text_cross_attention = use_text_cross_attention + if use_text_cross_attention: + self.ca_text = nn.MultiheadAttention(d_model, n_heads, dropout=dropout) + self.catext_dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity() + self.catext_norm = nn.LayerNorm(d_model) + + # self attention + self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout) + self.dropout2 = nn.Dropout(dropout) if dropout > 0 else nn.Identity() + self.norm2 = nn.LayerNorm(d_model) + + # ffn + self.linear1 = nn.Linear(d_model, dim_feedforward) + self.activation = nn.ReLU() + self.dropout3 = nn.Dropout(dropout) if dropout > 0 else nn.Identity() + self.linear2 = nn.Linear(dim_feedforward, d_model) + self.dropout4 = nn.Dropout(dropout) if dropout > 0 else nn.Identity() + self.norm3 = nn.LayerNorm(d_model) + + @staticmethod + def with_pos_embed(tensor, pos): + """Add positional embedding to the tensor.""" + return tensor if pos is None else tensor + pos + + def forward_ffn(self, tgt): + """Feedforward network forward pass.""" + tgt2 = self.linear2(self.dropout3(self.activation(self.linear1(tgt)))) + tgt = tgt + self.dropout4(tgt2) + tgt = self.norm3(tgt) + return tgt + + def forward( + self, + # for tgt + tgt: torch.Tensor, # nq, bs, d_model + tgt_query_pos: torch.Tensor = None, # pos for query. MLP(Sine(pos)) + memory_text: torch.Tensor = None, # num_token, bs, d_model + text_attention_mask: torch.Tensor = None, # bs, num_token + # for memory + memory: torch.Tensor = None, # hw, bs, d_model + memory_key_padding_mask: torch.Tensor = None, + memory_pos: torch.Tensor = None, # pos for memory + # sa + self_attn_mask: torch.Tensor = None, # mask used for self-attention + cross_attn_mask: torch.Tensor = None, # mask used for cross-attention + # dac + dac=False, + dac_use_selfatt_ln=True, + presence_token=None, + # skip inside deformable attn + **kwargs, # additional kwargs for compatibility + ): + """Forward pass of the TransformerDecoderLayer.""" + # self attention + tgt, tgt_query_pos = self._apply_self_attention( + tgt, tgt_query_pos, dac, dac_use_selfatt_ln, presence_token, self_attn_mask + ) + + if self.use_text_cross_attention: + tgt2 = self.ca_text( + self.with_pos_embed(tgt, tgt_query_pos), + memory_text.to(tgt.dtype), + memory_text.to(tgt.dtype), + key_padding_mask=text_attention_mask, + )[0] + tgt = tgt + self.catext_dropout(tgt2) + tgt = self.catext_norm(tgt) + + if presence_token is not None: + presence_token_mask = torch.zeros_like(cross_attn_mask[:, :1, :]) + cross_attn_mask = torch.cat([presence_token_mask, cross_attn_mask], dim=1) # (bs*nheads, 1+nq, hw) + + # Cross attention to image + tgt2 = self.cross_attn( + query=self.with_pos_embed(tgt, tgt_query_pos), + key=self.with_pos_embed(memory, memory_pos), + value=memory, + attn_mask=cross_attn_mask, + key_padding_mask=(memory_key_padding_mask.transpose(0, 1) if memory_key_padding_mask is not None else None), + need_weights=False, + )[0] + + tgt = tgt + self.dropout1(tgt2) + tgt = self.norm1(tgt) + + # ffn + tgt = self.forward_ffn(tgt.to(memory.dtype)) + + presence_token_out = None + if presence_token is not None: + presence_token_out = tgt[:1] + tgt = tgt[1:] + + return tgt, presence_token_out + + def _apply_self_attention(self, tgt, tgt_query_pos, dac, dac_use_selfatt_ln, presence_token, self_attn_mask): + """Apply self-attention with optional DAC splitting.""" + if self.self_attn is None: + return tgt + + if dac: + # Split queries for DAC (detect-and-classify) + assert tgt.shape[0] % 2 == 0, "DAC requires even number of queries" + num_o2o_queries = tgt.shape[0] // 2 + tgt_o2o = tgt[:num_o2o_queries] + tgt_query_pos_o2o = tgt_query_pos[:num_o2o_queries] + tgt_o2m = tgt[num_o2o_queries:] + else: + tgt_o2o = tgt + tgt_query_pos_o2o = tgt_query_pos + + # Handle presence token + if presence_token is not None: + tgt_o2o = torch.cat([presence_token, tgt_o2o], dim=0) + tgt_query_pos_o2o = torch.cat([torch.zeros_like(presence_token), tgt_query_pos_o2o], dim=0).to( + tgt_o2o.dtype + ) + tgt_query_pos = torch.cat([torch.zeros_like(presence_token), tgt_query_pos], dim=0) + + # Self-attention + q = k = self.with_pos_embed(tgt_o2o, tgt_query_pos_o2o) + tgt2 = self.self_attn(q, k, tgt_o2o, attn_mask=self_attn_mask)[0].to(tgt.dtype) + tgt_o2o = tgt_o2o + self.dropout2(tgt2) + + # Recombine and normalize + if dac: + if not dac_use_selfatt_ln: + tgt_o2o = self.norm2(tgt_o2o) + tgt = torch.cat((tgt_o2o, tgt_o2m), dim=0) + if dac_use_selfatt_ln: + tgt = self.norm2(tgt) + else: + tgt = tgt_o2o + tgt = self.norm2(tgt) + + return tgt, tgt_query_pos + + +class TransformerDecoder(nn.Module): + """Transformer Decoder consisting of multiple layers.""" + + def __init__( + self, + d_model: int, + frozen: bool, + interaction_layer, + layer, + num_layers: int, + num_queries: int, + return_intermediate: bool, + box_refine: bool = False, + num_o2m_queries: int = 0, + dac: bool = False, + boxRPB: str = "none", + # Experimental: An object query for SAM 2 tasks + instance_query: bool = False, + # Defines the number of additional instance queries, + # 1 or 4 are the most likely for single vs multi mask support + num_instances: int = 1, # Irrelevant if instance_query is False + dac_use_selfatt_ln: bool = True, + use_act_checkpoint: bool = False, + compile_mode=None, + presence_token: bool = False, + clamp_presence_logits: bool = True, + clamp_presence_logit_max_val: float = 10.0, + use_normed_output_consistently: bool = True, + separate_box_head_instance: bool = False, + separate_norm_instance: bool = False, + ): + """Initialize the TransformerDecoder.""" + super().__init__() + self.d_model = d_model + self.layers = _get_clones(layer, num_layers) + self.fine_layers = ( + _get_clones(interaction_layer, num_layers) if interaction_layer is not None else [None] * num_layers + ) + self.num_layers = num_layers + self.num_queries = num_queries + self.dac = dac + if dac: + self.num_o2m_queries = num_queries + tot_num_queries = num_queries + else: + self.num_o2m_queries = num_o2m_queries + tot_num_queries = num_queries + num_o2m_queries + self.norm = nn.LayerNorm(d_model) + self.return_intermediate = return_intermediate + self.bbox_embed = MLP(d_model, d_model, 4, 3) + self.query_embed = nn.Embedding(tot_num_queries, d_model) + self.instance_query_embed = None + self.instance_query_reference_points = None + self.use_instance_query = instance_query + self.num_instances = num_instances + self.use_normed_output_consistently = use_normed_output_consistently + + self.instance_norm = nn.LayerNorm(d_model) if separate_norm_instance else None + self.instance_bbox_embed = None + if separate_box_head_instance: + self.instance_bbox_embed = MLP(d_model, d_model, 4, 3) + if instance_query: + self.instance_query_embed = nn.Embedding(num_instances, d_model) + self.box_refine = box_refine + if box_refine: + nn.init.constant_(self.bbox_embed.layers[-1].weight.data, 0) + nn.init.constant_(self.bbox_embed.layers[-1].bias.data, 0) + + self.reference_points = nn.Embedding(num_queries, 4) + if instance_query: + self.instance_reference_points = nn.Embedding(num_instances, 4) + + assert boxRPB in ["none", "log", "linear", "both"] + self.boxRPB = boxRPB + if boxRPB != "none": + try: + nheads = self.layers[0].cross_attn_image.num_heads + except AttributeError: + nheads = self.layers[0].cross_attn.num_heads + + n_input = 4 if boxRPB == "both" else 2 + self.boxRPB_embed_x = MLP(n_input, d_model, nheads, 2) + self.boxRPB_embed_y = MLP(n_input, d_model, nheads, 2) + + if interaction_layer is not None: + # Scoped for import ultralytics speed: ROI align requires optional torchvision ops. + from torchvision.ops.roi_align import RoIAlign + + self.roi_pooler = RoIAlign(output_size=7, spatial_scale=1, sampling_ratio=-1, aligned=True) + else: + self.roi_pooler = None + if frozen: + for p in self.parameters(): + p.requires_grad_(False) + + self.presence_token = None + self.clamp_presence_logits = clamp_presence_logits + self.clamp_presence_logit_max_val = clamp_presence_logit_max_val + if presence_token: + self.presence_token = nn.Embedding(1, d_model) + self.presence_token_head = MLP(d_model, d_model, 1, 3) + self.presence_token_out_norm = nn.LayerNorm(d_model) + + self.ref_point_head = MLP(2 * self.d_model, self.d_model, self.d_model, 2) + self.dac_use_selfatt_ln = dac_use_selfatt_ln + self.use_act_checkpoint = use_act_checkpoint + + nn.init.normal_(self.query_embed.weight.data) + if self.instance_query_embed is not None: + nn.init.normal_(self.instance_query_embed.weight.data) + + assert self.roi_pooler is None + assert self.return_intermediate, "support return_intermediate only" + assert self.box_refine, "support box refine only" + + if compile_mode is not None: + self.forward = torch.compile(self.forward, mode=compile_mode, fullgraph=True) + + # assign layer index to each layer so that some layers can decide what to do + # based on which layer index they are (e.g. cross attention to memory bank only + # in selected layers) + for layer_idx, decoder_layer in enumerate(self.layers): + decoder_layer.layer_idx = layer_idx + + def _get_rpb_matrix(self, reference_boxes, feat_size): + """Get the relative position bias (RPB) matrix for box-relative position bias.""" + H, W = feat_size + boxes_xyxy = xywh2xyxy(reference_boxes).transpose(0, 1) + bs, num_queries, _ = boxes_xyxy.shape + coords_h = torch.arange(H, device=reference_boxes.device, dtype=reference_boxes.dtype) / H + coords_w = torch.arange(W, device=reference_boxes.device, dtype=reference_boxes.dtype) / W + + deltas_y = coords_h.view(1, -1, 1) - boxes_xyxy.reshape(-1, 1, 4)[:, :, 1:4:2] + deltas_y = deltas_y.view(bs, num_queries, -1, 2) + deltas_x = coords_w.view(1, -1, 1) - boxes_xyxy.reshape(-1, 1, 4)[:, :, 0:3:2] + deltas_x = deltas_x.view(bs, num_queries, -1, 2) + + if self.boxRPB in ["log", "both"]: + deltas_x_log = deltas_x * 8 # normalize to -8, 8 + deltas_x_log = torch.sign(deltas_x_log) * torch.log2(torch.abs(deltas_x_log) + 1.0) / np.log2(8) + + deltas_y_log = deltas_y * 8 # normalize to -8, 8 + deltas_y_log = torch.sign(deltas_y_log) * torch.log2(torch.abs(deltas_y_log) + 1.0) / np.log2(8) + if self.boxRPB == "log": + deltas_x = deltas_x_log + deltas_y = deltas_y_log + else: + deltas_x = torch.cat([deltas_x, deltas_x_log], dim=-1) + deltas_y = torch.cat([deltas_y, deltas_y_log], dim=-1) + + if self.training: + assert self.use_act_checkpoint, "activation ckpt not enabled in decoder" + deltas_x = self.boxRPB_embed_x(x=deltas_x) # bs, num_queries, W, n_heads + deltas_y = self.boxRPB_embed_y(x=deltas_y) # bs, num_queries, H, n_heads + + if not torch.compiler.is_dynamo_compiling(): + assert deltas_x.shape[:3] == (bs, num_queries, W) + assert deltas_y.shape[:3] == (bs, num_queries, H) + + B = deltas_y.unsqueeze(3) + deltas_x.unsqueeze(2) # bs, num_queries, H, W, n_heads + if not torch.compiler.is_dynamo_compiling(): + assert B.shape[:4] == (bs, num_queries, H, W) + B = B.flatten(2, 3) # bs, num_queries, H*W, n_heads + B = B.permute(0, 3, 1, 2) # bs, n_heads, num_queries, H*W + B = B.contiguous() # memeff attn likes ordered strides + if not torch.compiler.is_dynamo_compiling(): + assert B.shape[2:] == (num_queries, H * W) + return B + + def forward( + self, + tgt, + memory, + tgt_mask: torch.Tensor = None, + memory_mask: torch.Tensor = None, + memory_key_padding_mask: torch.Tensor = None, + pos: torch.Tensor = None, + reference_boxes: torch.Tensor = None, # num_queries, bs, 4 + # for memory + spatial_shapes: list[tuple[int, int]] | None = None, # height and width of each feature level + valid_ratios: torch.Tensor = None, + # for text + memory_text: torch.Tensor = None, + text_attention_mask: torch.Tensor = None, + # if `apply_dac` is None, it will default to `self.dac` + apply_dac: bool | None = None, + is_instance_prompt=False, + decoder_extra_kwargs: dict | None = None, + # ROI memory bank + obj_roi_memory_feat=None, + obj_roi_memory_mask=None, + box_head_trk=None, + ): + """Forward pass of the TransformerDecoder.""" + if memory_mask is not None: + assert self.boxRPB == "none", ( + "inputting a memory_mask in the presence of boxRPB is unexpected/not implemented" + ) + + apply_dac = apply_dac if apply_dac is not None else self.dac + if apply_dac: + assert (tgt.shape[0] == self.num_queries) or ( + self.use_instance_query and (tgt.shape[0] == self.instance_query_embed.num_embeddings) + ) + + tgt = tgt.repeat(2, 1, 1) + # note that we don't tile tgt_mask, since DAC doesn't + # use self-attention in o2m queries + if reference_boxes is not None: + assert (reference_boxes.shape[0] == self.num_queries) or ( + self.use_instance_query and (reference_boxes.shape[0] == self.instance_query_embed.num_embeddings) + ) + reference_boxes = reference_boxes.repeat(2, 1, 1) + + bs = tgt.shape[1] + intermediate = [] + intermediate_presence_logits = [] + presence_feats = None + + if self.box_refine: + if reference_boxes is None: + # In this case, we're in a one-stage model, so we generate the reference boxes + reference_boxes = self.reference_points.weight.unsqueeze(1) + reference_boxes = reference_boxes.repeat(2, bs, 1) if apply_dac else reference_boxes.repeat(1, bs, 1) + reference_boxes = reference_boxes.sigmoid() + intermediate_ref_boxes = [reference_boxes] + else: + reference_boxes = None + intermediate_ref_boxes = None + + output = tgt + presence_out = None + if self.presence_token is not None and is_instance_prompt is False: + # expand to batch dim + presence_out = self.presence_token.weight[None].expand(1, bs, -1) + + box_head = self.bbox_embed + if is_instance_prompt and self.instance_bbox_embed is not None: + box_head = self.instance_bbox_embed + + out_norm = self.norm + if is_instance_prompt and self.instance_norm is not None: + out_norm = self.instance_norm + + for layer_idx, layer in enumerate(self.layers): + reference_points_input = ( + reference_boxes[:, :, None] * torch.cat([valid_ratios, valid_ratios], -1)[None, :] + ) # nq, bs, nlevel, 4 + + query_sine_embed = gen_sineembed_for_position( + reference_points_input[:, :, 0, :], self.d_model + ) # nq, bs, d_model*2 + + # conditional query + query_pos = self.ref_point_head(query_sine_embed) # nq, bs, d_model + + if self.boxRPB != "none" and reference_boxes is not None: + assert len(spatial_shapes) == 1, "only single scale support implemented" + memory_mask = self._get_rpb_matrix(reference_boxes, spatial_shapes[0]) + memory_mask = memory_mask.flatten(0, 1) # (bs*n_heads, nq, H*W) + if self.training: + assert self.use_act_checkpoint, "Activation checkpointing not enabled in the decoder" + output, presence_out = layer( + tgt=output, + tgt_query_pos=query_pos, + memory_text=memory_text, + text_attention_mask=text_attention_mask, + memory=memory, + memory_key_padding_mask=memory_key_padding_mask, + memory_pos=pos, + self_attn_mask=tgt_mask, + cross_attn_mask=memory_mask, + dac=apply_dac, + dac_use_selfatt_ln=self.dac_use_selfatt_ln, + presence_token=presence_out, + **(decoder_extra_kwargs or {}), + # ROI memory bank + obj_roi_memory_feat=obj_roi_memory_feat, + obj_roi_memory_mask=obj_roi_memory_mask, + ) + + # iter update + if self.box_refine: + reference_before_sigmoid = inverse_sigmoid(reference_boxes) + if box_head_trk is None: + # delta_unsig = self.bbox_embed(output) + if not self.use_normed_output_consistently: + delta_unsig = box_head(output) + else: + delta_unsig = box_head(out_norm(output)) + else: + # box_head_trk use a separate box head for tracking queries + Q_det = decoder_extra_kwargs["Q_det"] + assert output.size(0) >= Q_det + delta_unsig_det = self.bbox_embed(output[:Q_det]) + delta_unsig_trk = box_head_trk(output[Q_det:]) + delta_unsig = torch.cat([delta_unsig_det, delta_unsig_trk], dim=0) + outputs_unsig = delta_unsig + reference_before_sigmoid + new_reference_points = outputs_unsig.sigmoid() + + reference_boxes = new_reference_points.detach() + if layer_idx != self.num_layers - 1: + intermediate_ref_boxes.append(new_reference_points) + else: + raise NotImplementedError("not implemented yet") + + intermediate.append(out_norm(output)) + if self.presence_token is not None and is_instance_prompt is False: + # norm, mlp head + intermediate_layer_presence_logits = self.presence_token_head( + self.presence_token_out_norm(presence_out) + ).squeeze(-1) + + # clamp to mitigate numerical issues + if self.clamp_presence_logits: + intermediate_layer_presence_logits.clamp_( + min=-self.clamp_presence_logit_max_val, + max=self.clamp_presence_logit_max_val, + ) + + intermediate_presence_logits.append(intermediate_layer_presence_logits) + presence_feats = presence_out.clone() + + return ( + torch.stack(intermediate), + torch.stack(intermediate_ref_boxes), + ( + torch.stack(intermediate_presence_logits) + if self.presence_token is not None and is_instance_prompt is False + else None + ), + presence_feats, + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/encoder.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..686881a7b740aca88cf2405246b1370507e7a1c3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/encoder.py @@ -0,0 +1,505 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved +# Based on https://github.com/IDEA-Research/GroundingDINO +from __future__ import annotations + +import torch +from torch import nn + +from ultralytics.nn.modules.utils import _get_clones + +from .model_misc import get_valid_ratio + + +class TransformerEncoderLayer(nn.Module): + """Transformer encoder layer that performs self-attention followed by cross-attention. + + This layer was previously called TransformerDecoderLayer but was renamed to better reflect its role in the + architecture. It processes input sequences through self-attention and then cross-attention with another input + (typically image features). + + The layer supports both pre-norm and post-norm configurations, as well as positional encoding at different stages of + the attention mechanism. + """ + + def __init__( + self, + d_model: int, + dim_feedforward: int, + dropout: float, + pos_enc_at_attn: bool, + pos_enc_at_cross_attn_keys: bool, + pos_enc_at_cross_attn_queries: bool, + pre_norm: bool, + self_attention: nn.Module = None, + cross_attention: nn.Module = None, + ): + """Initialize a transformer encoder layer. + + Args: + d_model: Model dimension/hidden size + dim_feedforward: Dimension of the feedforward network + dropout: Dropout probability + pos_enc_at_attn: Whether to add positional encodings at self-attention + pos_enc_at_cross_attn_keys: Whether to add positional encodings to keys in cross-attention + pos_enc_at_cross_attn_queries: Whether to add positional encodings to queries in cross-attention + pre_norm: Whether to use pre-norm (True) or post-norm (False) architecture + self_attention: Self-attention module + cross_attention: Cross-attention module for attending to image features + """ + super().__init__() + self.d_model = d_model + self.dim_feedforward = dim_feedforward + self.dropout_value = dropout + self.self_attn = self_attention or nn.MultiheadAttention(num_heads=8, dropout=0.1, embed_dim=256) + self.cross_attn_image = cross_attention or nn.MultiheadAttention(num_heads=8, dropout=0.1, embed_dim=256) + + # Implementation of Feedforward model + self.linear1 = nn.Linear(d_model, dim_feedforward) + self.dropout = nn.Dropout(dropout) + self.linear2 = nn.Linear(dim_feedforward, d_model) + + self.norm1 = nn.LayerNorm(d_model) + self.norm2 = nn.LayerNorm(d_model) + self.norm3 = nn.LayerNorm(d_model) + self.dropout1 = nn.Dropout(dropout) + self.dropout2 = nn.Dropout(dropout) + self.dropout3 = nn.Dropout(dropout) + + self.activation = nn.ReLU() + self.pre_norm = pre_norm + + self.pos_enc_at_attn = pos_enc_at_attn + self.pos_enc_at_cross_attn_queries = pos_enc_at_cross_attn_queries + self.pos_enc_at_cross_attn_keys = pos_enc_at_cross_attn_keys + + self.layer_idx = None + + def forward_post( + self, + tgt: torch.Tensor, + memory: torch.Tensor, + tgt_mask: torch.Tensor = None, + memory_mask: torch.Tensor = None, + tgt_key_padding_mask: torch.Tensor = None, + memory_key_padding_mask: torch.Tensor = None, + pos: torch.Tensor = None, + query_pos: torch.Tensor = None, + **kwargs, + ) -> torch.Tensor: + """Forward pass for post-norm architecture. + + In post-norm architecture, normalization is applied after attention and feedforward operations. + + Args: + tgt (torch.Tensor): Input tensor to be processed. + memory (torch.Tensor): Memory tensor for cross-attention. + tgt_mask (torch.Tensor): Mask for self-attention. + memory_mask (torch.Tensor): Mask for cross-attention. + tgt_key_padding_mask (torch.Tensor): Key padding mask for self-attention. + memory_key_padding_mask (torch.Tensor): Key padding mask for cross-attention. + pos (torch.Tensor): Positional encoding for memory. + query_pos (torch.Tensor): Positional encoding for query. + **kwargs (Any): Additional keyword arguments. + + Returns: + Processed tensor + """ + q = k = tgt + query_pos if self.pos_enc_at_attn else tgt + + # Self attention + tgt2 = self.self_attn( + q, k, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask, need_weights=False + )[0] + tgt = tgt + self.dropout1(tgt2) + tgt = self.norm1(tgt) + + # Cross attention to image + tgt2 = self.cross_attn_image( + query=tgt + query_pos if self.pos_enc_at_cross_attn_queries else tgt, + key=memory + pos if self.pos_enc_at_cross_attn_keys else memory, + value=memory, + attn_mask=memory_mask, + key_padding_mask=memory_key_padding_mask, + need_weights=False, + )[0] + tgt = tgt + self.dropout2(tgt2) + tgt = self.norm2(tgt) + + # FFN + tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) + tgt = tgt + self.dropout3(tgt2) + tgt = self.norm3(tgt) + return tgt + + def forward_pre( + self, + tgt: torch.Tensor, + memory: torch.Tensor, + dac: bool = False, + tgt_mask: torch.Tensor = None, + memory_mask: torch.Tensor = None, + tgt_key_padding_mask: torch.Tensor = None, + memory_key_padding_mask: torch.Tensor = None, + pos: torch.Tensor = None, + query_pos: torch.Tensor = None, + ) -> torch.Tensor: + """Forward pass for pre-norm architecture. + + In pre-norm architecture, normalization is applied before attention and feedforward operations. + + Args: + tgt: Input tensor to be processed + memory: Memory tensor for cross-attention + dac: Whether to use Divide-and-Conquer attention + tgt_mask: Mask for self-attention + memory_mask: Mask for cross-attention + tgt_key_padding_mask: Key padding mask for self-attention + memory_key_padding_mask: Key padding mask for cross-attention + pos: Positional encoding for memory + query_pos: Positional encoding for query + + Returns: + Processed tensor + """ + if dac: + # we only apply self attention to the first half of the queries + assert tgt.shape[0] % 2 == 0 + other_tgt = tgt[tgt.shape[0] // 2 :] + tgt = tgt[: tgt.shape[0] // 2] + tgt2 = self.norm1(tgt).contiguous() + q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2 + tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0] + tgt = tgt + self.dropout1(tgt2) + if dac: + # Recombine + tgt = torch.cat((tgt, other_tgt), dim=0) + tgt2 = self.norm2(tgt) + memory = memory.to(tgt2.dtype).contiguous() + tgt2 = self.cross_attn_image( + query=tgt2 + query_pos if self.pos_enc_at_cross_attn_queries else tgt2, + key=memory + pos if self.pos_enc_at_cross_attn_keys else memory, + value=memory, + attn_mask=memory_mask, + key_padding_mask=memory_key_padding_mask, + )[0] + tgt = tgt + self.dropout2(tgt2) + tgt2 = self.norm3(tgt) + tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) + tgt = tgt + self.dropout3(tgt2) + return tgt + + def forward( + self, + tgt: torch.Tensor, + memory: torch.Tensor, + dac: bool = False, + tgt_mask: torch.Tensor = None, + memory_mask: torch.Tensor = None, + tgt_key_padding_mask: torch.Tensor = None, + memory_key_padding_mask: torch.Tensor = None, + pos: torch.Tensor = None, + query_pos: torch.Tensor = None, + ) -> torch.Tensor: + """Forward pass for the transformer encoder layer. + + Args: + tgt: Input tensor to be processed + memory: Memory tensor (e.g., image features) for cross-attention + dac: Whether to use Divide-and-Conquer attention (only apply self-attention to first half) + tgt_mask: Mask for self-attention + memory_mask: Mask for cross-attention + tgt_key_padding_mask: Key padding mask for self-attention + memory_key_padding_mask: Key padding mask for cross-attention + pos: Positional encoding for memory + query_pos: Positional encoding for query + + Returns: + Processed tensor after self-attention, cross-attention, and feedforward network + """ + fwd_fn = self.forward_pre if self.pre_norm else self.forward_post + return fwd_fn( + tgt, + memory, + dac=dac, + tgt_mask=tgt_mask, + memory_mask=memory_mask, + tgt_key_padding_mask=tgt_key_padding_mask, + memory_key_padding_mask=memory_key_padding_mask, + pos=pos, + query_pos=query_pos, + # attn_bias=attn_bias, + # **kwds, + ) + + +class TransformerEncoder(nn.Module): + """Transformer encoder that processes multi-level features. + + This encoder takes multi-level features (e.g., from a backbone network) and processes them through a stack of + transformer encoder layers. It supports features from multiple levels (e.g., different resolutions) and can apply + activation checkpointing for memory efficiency during training. + + Args: + layer: The encoder layer to be stacked multiple times + num_layers: Number of encoder layers to stack + d_model: Model dimension/hidden size + num_feature_levels: Number of feature levels to process + frozen: Whether to freeze the parameters of this module + use_act_checkpoint: Whether to use activation checkpointing during training + """ + + def __init__( + self, + layer: nn.Module, + num_layers: int, + d_model: int, + num_feature_levels: int, + frozen: bool = False, + use_act_checkpoint: bool = False, + ): + """Initialize the transformer encoder.""" + super().__init__() + self.layers = _get_clones(layer, num_layers) + self.num_layers = num_layers + + self.num_feature_levels = num_feature_levels + self.level_embed = None + if num_feature_levels > 1: + self.level_embed = nn.Parameter(torch.Tensor(num_feature_levels, d_model)) + + if frozen: + for p in self.parameters(): + p.requires_grad_(False) + + self.use_act_checkpoint = use_act_checkpoint + + # assign layer index to each layer so that some layers can decide what to do + # based on which layer index they are (e.g. cross attention to memory bank only + # in selected layers) + for layer_idx, encoder_layer in enumerate(self.layers): + encoder_layer.layer_idx = layer_idx + + def _prepare_multilevel_features(self, srcs, masks, pos_embeds): + """Prepare multi-level features for transformer encoder.""" + assert len(srcs) == self.num_feature_levels, "mismatch between expected and received # of feature levels" + + src_flatten = [] + mask_flatten = [] + lvl_pos_embed_flatten = [] + has_mask = masks is not None and masks[0] is not None + for lvl, (src, mask, pos_embed) in enumerate(zip(srcs, masks, pos_embeds)): + src = src.flatten(2).transpose(1, 2) # bs, hw, c + if has_mask: + mask = mask.flatten(1) + pos_embed = pos_embed.flatten(2).transpose(1, 2) # bs, hw, c + if self.level_embed is not None: + lvl_pos_embed = pos_embed + self.level_embed[lvl].view(1, 1, -1) + else: + lvl_pos_embed = pos_embed + lvl_pos_embed_flatten.append(lvl_pos_embed) + src_flatten.append(src) + if has_mask: + mask_flatten.append(mask) + src_flatten = torch.cat(src_flatten, 1) # bs, \sum{hxw}, c + mask_flatten = torch.cat(mask_flatten, 1) if has_mask else None # bs, \sum{hxw} + lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1) # bs, \sum{hxw}, c + if has_mask: + valid_ratios = torch.stack([get_valid_ratio(m) for m in masks], 1) + else: + valid_ratios = torch.ones( + (src_flatten.shape[0], self.num_feature_levels, 2), + device=src_flatten.device, + dtype=src_flatten.dtype, + ) + + return ( + src_flatten, + mask_flatten, + lvl_pos_embed_flatten, + valid_ratios, + ) + + def forward( + self, + src: list[torch.Tensor], + src_key_padding_masks: list[torch.Tensor] | None = None, + pos: list[torch.Tensor] | None = None, + prompt: torch.Tensor = None, + prompt_key_padding_mask: torch.Tensor = None, + encoder_extra_kwargs: dict | None = None, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Process multi-level features through the transformer encoder. + + Args: + src: List of multi-level features, each with shape (batch_size, channels, height, width) + src_key_padding_masks: List of padding masks for each feature level, each with shape (batch_size, height, + width) + pos: List of positional embeddings for each feature level, each with shape (batch_size, channels, height, + width) + prompt: Optional text/prompt features to attend to, with shape (seq_len, batch_size, d_model) + prompt_key_padding_mask: Optional padding mask for prompt, with shape (batch_size, seq_len) + encoder_extra_kwargs: Optional additional arguments to pass to each encoder layer + + Returns: + A tuple containing: + - output: Processed features with shape (seq_len, batch_size, d_model) + - key_padding_masks_flatten: Flattened padding masks + - lvl_pos_embed_flatten: Flattened positional embeddings + - valid_ratios: Valid ratios for each feature level + """ + assert len(src) == self.num_feature_levels, "must be equal to num_feature_levels" + if src_key_padding_masks is not None: + assert len(src_key_padding_masks) == self.num_feature_levels + if pos is not None: + assert len(pos) == self.num_feature_levels + # Flatten multilevel feats and add level pos embeds + ( + src_flatten, + key_padding_masks_flatten, + lvl_pos_embed_flatten, + valid_ratios, + ) = self._prepare_multilevel_features(src, src_key_padding_masks, pos) + + output = src_flatten + for layer in self.layers: + layer_kwargs = {} + + assert isinstance(layer, TransformerEncoderLayer) + layer_kwargs["memory"] = prompt + layer_kwargs["memory_key_padding_mask"] = prompt_key_padding_mask + layer_kwargs["query_pos"] = lvl_pos_embed_flatten + layer_kwargs["tgt"] = output + layer_kwargs["tgt_key_padding_mask"] = key_padding_masks_flatten + + if self.training: + assert self.use_act_checkpoint, "activation ckpt not enabled in encoder" + if encoder_extra_kwargs is not None: + layer_kwargs.update(encoder_extra_kwargs) + output = layer(**layer_kwargs) + # return as seq first + return ( + output.transpose(0, 1), + (key_padding_masks_flatten.transpose(0, 1) if key_padding_masks_flatten is not None else None), + lvl_pos_embed_flatten.transpose(0, 1), + valid_ratios, + ) + + +class TransformerEncoderFusion(TransformerEncoder): + """Transformer encoder that fuses text and image features. + + This encoder extends TransformerEncoder to handle both text and image features, with the ability to add pooled text + features to image features for better cross-modal fusion. It supports torch.compile for performance optimization. + + Args: + layer (nn.Module): The encoder layer to be stacked multiple times. + num_layers (int): Number of encoder layers to stack. + d_model (int): Model dimension/hidden size. + num_feature_levels (int): Number of feature levels to process. + add_pooled_text_to_img_feat (bool): Whether to add pooled text features to image features. + pool_text_with_mask (bool): Whether to use the mask when pooling text features. + compile_mode (str | None): Mode for torch.compile, or None to disable compilation. + **kwargs (Any): Additional arguments to pass to the parent class. + """ + + def __init__( + self, + layer: nn.Module, + num_layers: int, + d_model: int, + num_feature_levels: int, + add_pooled_text_to_img_feat: bool = True, + pool_text_with_mask: bool = False, + compile_mode: str | None = None, + **kwargs, + ): + """Initialize the transformer encoder with text-image fusion.""" + super().__init__( + layer, + num_layers, + d_model, + num_feature_levels, + **kwargs, + ) + self.add_pooled_text_to_img_feat = add_pooled_text_to_img_feat + if self.add_pooled_text_to_img_feat: + self.text_pooling_proj = nn.Linear(d_model, d_model) + self.pool_text_with_mask = pool_text_with_mask + if compile_mode is not None: + self.forward = torch.compile(self.forward, mode=compile_mode, fullgraph=True) + + def forward( + self, + src: list[torch.Tensor], + prompt: torch.Tensor, + src_key_padding_mask: list[torch.Tensor] | None = None, + src_pos: list[torch.Tensor] | None = None, + prompt_key_padding_mask: torch.Tensor = None, + feat_sizes: list[int] | None = None, + encoder_extra_kwargs: dict | None = None, + ): + """Forward pass for the transformer encoder with text-image fusion.""" + # Restore spatial shapes of vision + bs = src[0].shape[1] # seq first + if feat_sizes is not None: + assert len(feat_sizes) == len(src) + if src_key_padding_mask is None: + src_key_padding_mask = [None] * len(src) + for i, (h, w) in enumerate(feat_sizes): + src[i] = src[i].reshape(h, w, bs, -1).permute(2, 3, 0, 1) + src_pos[i] = src_pos[i].reshape(h, w, bs, -1).permute(2, 3, 0, 1) + src_key_padding_mask[i] = ( + src_key_padding_mask[i].reshape(h, w, bs).permute(2, 0, 1) + if src_key_padding_mask[i] is not None + else None + ) + else: + assert all(x.dim() == 4 for x in src), "expected list of (bs, c, h, w) tensors" + + if self.add_pooled_text_to_img_feat: + # Fusion: Add mean pooled text to image features + pooled_text = pool_text_feat(prompt, prompt_key_padding_mask, self.pool_text_with_mask) + pooled_text = self.text_pooling_proj(pooled_text)[..., None, None] # prompt is seq first + src = [x.add_(pooled_text) for x in src] + + ( + out, + key_padding_masks_flatten, + lvl_pos_embed_flatten, + valid_ratios, + ) = super().forward( + src, + src_key_padding_masks=src_key_padding_mask, + pos=src_pos, + prompt=prompt.transpose(0, 1), + prompt_key_padding_mask=prompt_key_padding_mask, + encoder_extra_kwargs=encoder_extra_kwargs, + ) + + return { + "memory": out, + "padding_mask": key_padding_masks_flatten, + "pos_embed": lvl_pos_embed_flatten, + "memory_text": prompt, + "valid_ratios": valid_ratios, + } + + +def pool_text_feat(prompt, prompt_mask, pool_with_mask): + """Mean-pool the prompt embeddings over the valid tokens only.""" + # prompt has shape (seq, bs, dim) + if not pool_with_mask: + return prompt.mean(dim=0) + + # prompt_mask has shape (bs, seq), where False is valid and True is padding + assert prompt_mask.dim() == 2 + # is_valid has shape (seq, bs, 1), where 1 is valid and 0 is padding + is_valid = (~prompt_mask).float().permute(1, 0)[..., None] + # num_valid has shape (bs, 1) + num_valid = torch.clamp(torch.sum(is_valid, dim=0), min=1.0) + + # mean pool over all the valid tokens + pooled_text = (prompt * is_valid).sum(dim=0) / num_valid + return pooled_text diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/geometry_encoders.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/geometry_encoders.py new file mode 100644 index 0000000000000000000000000000000000000000..a6b9ab6bbdb5cf0a8f172ee6bb39f492b9a952bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/geometry_encoders.py @@ -0,0 +1,417 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved + +import torch +from torch import nn + +from ultralytics.nn.modules.utils import _get_clones +from ultralytics.utils.ops import xywh2xyxy + + +def is_right_padded(mask: torch.Tensor): + """Given a padding mask (following pytorch convention, 1s for padded values), returns whether the padding is on the + right or not. + """ + return (mask.long() == torch.sort(mask.long(), dim=-1)[0]).all() + + +def concat_padded_sequences(seq1, mask1, seq2, mask2, return_index: bool = False): + """Concatenate two right-padded sequences into a contiguous, right-padded sequence. + + Following PyTorch convention, tensors are sequence-first and masks are batch-first, with 1s for padded values. + + Args: + seq1 (torch.Tensor): A tensor of shape (seq1_length, batch_size, hidden_size). + mask1 (torch.Tensor): A tensor of shape (batch_size, seq1_length). + seq2 (torch.Tensor): A tensor of shape (seq2_length, batch_size, hidden_size). + mask2 (torch.Tensor): A tensor of shape (batch_size, seq2_length). + return_index (bool): If True, also return the index of the ids of the elements of seq2 in the concatenated + sequence, which can be used to retrieve the elements of seq2. + + Returns: + (tuple): (concatenated_sequence, concatenated_mask) if return_index is False, otherwise (concatenated_sequence, + concatenated_mask, index). + """ + seq1_length, batch_size, hidden_size = seq1.shape + seq2_length, batch_size, hidden_size = seq2.shape + + assert batch_size == seq1.size(1) == seq2.size(1) == mask1.size(0) == mask2.size(0) + assert hidden_size == seq1.size(2) == seq2.size(2) + assert seq1_length == mask1.size(1) + assert seq2_length == mask2.size(1) + + torch._assert(is_right_padded(mask1), "Mask is not right padded") + torch._assert(is_right_padded(mask2), "Mask is not right padded") + + actual_seq1_lengths = (~mask1).sum(dim=-1) + actual_seq2_lengths = (~mask2).sum(dim=-1) + + final_lengths = actual_seq1_lengths + actual_seq2_lengths + max_length = seq1_length + seq2_length + concatenated_mask = ( + torch.arange(max_length, device=seq2.device)[None].repeat(batch_size, 1) >= final_lengths[:, None] + ) + + # (max_len, batch_size, hidden_size) + concatenated_sequence = torch.zeros((max_length, batch_size, hidden_size), device=seq2.device, dtype=seq2.dtype) + concatenated_sequence[:seq1_length, :, :] = seq1 + + # At this point, the element of seq1 are in the right place + # We just need to shift the elements of seq2 + + index = torch.arange(seq2_length, device=seq2.device)[:, None].repeat(1, batch_size) + index = index + actual_seq1_lengths[None] + + concatenated_sequence = concatenated_sequence.scatter(0, index[:, :, None].expand(-1, -1, hidden_size), seq2) + + if return_index: + return concatenated_sequence, concatenated_mask, index + + return concatenated_sequence, concatenated_mask + + +class Prompt: + """Utility class to manipulate geometric prompts. + + We expect the sequences in pytorch convention, that is sequence first, batch second The dimensions are expected as + follows: box_embeddings shape: N_boxes x B x C_box box_mask shape: B x N_boxes. Can be None if nothing is masked out + point_embeddings shape: N_points x B x C_point point_mask shape: B x N_points. Can be None if nothing is masked out + mask_embeddings shape: N_masks x B x 1 x H_mask x W_mask mask_mask shape: B x N_masks. Can be None if nothing is + masked out + + We also store positive/negative labels. These tensors are also stored batch-first If they are None, we'll assume + positive labels everywhere box_labels: long tensor of shape N_boxes x B point_labels: long tensor of shape N_points + x B mask_labels: long tensor of shape N_masks x B + """ + + def __init__(self, box_embeddings=None, box_mask=None, box_labels=None): + """Initialize the Prompt object.""" + # Check for null prompt + # Check for null prompt + if box_embeddings is None: + self.box_embeddings = None + self.box_labels = None + self.box_mask = None + return + + # Get sequence length, batch size, and device + box_seq_len = box_embeddings.shape[0] + bs = box_embeddings.shape[1] + device = box_embeddings.device + + # Initialize labels and attention mask if not provided + if box_labels is None: + box_labels = torch.ones(box_seq_len, bs, device=device, dtype=torch.long) + if box_mask is None: + box_mask = torch.zeros(bs, box_seq_len, device=device, dtype=torch.bool) + + # Dimension checks + assert list(box_embeddings.shape[:2]) == [box_seq_len, bs], ( + f"Wrong dimension for box embeddings. Expected [{box_seq_len}, {bs}, *] got {box_embeddings.shape}" + ) + assert box_embeddings.shape[-1] == 4, ( + f"Expected box embeddings to have 4 coordinates, got {box_embeddings.shape[-1]}" + ) + assert list(box_mask.shape) == [bs, box_seq_len], ( + f"Wrong dimension for box mask. Expected [{bs}, {box_seq_len}] got {box_mask.shape}" + ) + assert list(box_labels.shape) == [box_seq_len, bs], ( + f"Wrong dimension for box labels. Expected [{box_seq_len}, {bs}] got {box_labels.shape}" + ) + + # Device checks + assert box_embeddings.device == device, ( + f"Expected box embeddings to be on device {device}, got {box_embeddings.device}" + ) + assert box_mask.device == device, f"Expected box mask to be on device {device}, got {box_mask.device}" + assert box_labels.device == device, f"Expected box labels to be on device {device}, got {box_labels.device}" + + self.box_embeddings = box_embeddings + self.box_mask = box_mask + self.box_labels = box_labels + + def append_boxes(self, boxes, labels=None, mask=None): + """Append box prompts to existing prompts. + + Args: + boxes (torch.Tensor): Tensor of shape (N_new_boxes, B, 4) with normalized box coordinates. + labels (torch.Tensor | None): Optional tensor of shape (N_new_boxes, B) with positive/negative labels. + mask (torch.Tensor | None): Optional tensor of shape (B, N_new_boxes) for attention mask. + """ + if self.box_embeddings is None: + # First boxes - initialize + self.box_embeddings = boxes + bs = boxes.shape[1] + box_seq_len = boxes.shape[0] + + if labels is None: + labels = torch.ones(box_seq_len, bs, device=boxes.device, dtype=torch.long) + if mask is None: + mask = torch.zeros(bs, box_seq_len, device=boxes.device, dtype=torch.bool) + + self.box_labels = labels + self.box_mask = mask + return + + # Append to existing boxes + bs = self.box_embeddings.shape[1] + assert boxes.shape[1] == bs, f"Batch size mismatch: expected {bs}, got {boxes.shape[1]}" + + if labels is None: + labels = torch.ones(boxes.shape[0], bs, device=boxes.device, dtype=torch.long) + if mask is None: + mask = torch.zeros(bs, boxes.shape[0], dtype=torch.bool, device=boxes.device) + + assert list(boxes.shape[:2]) == list(labels.shape[:2]), ( + f"Shape mismatch between boxes {boxes.shape} and labels {labels.shape}" + ) + + # Concatenate using the helper function + self.box_labels, _ = concat_padded_sequences( + self.box_labels.unsqueeze(-1), self.box_mask, labels.unsqueeze(-1), mask + ) + self.box_labels = self.box_labels.squeeze(-1) + self.box_embeddings, self.box_mask = concat_padded_sequences(self.box_embeddings, self.box_mask, boxes, mask) + + +class SequenceGeometryEncoder(nn.Module): + """Encoder for geometric box prompts. Assumes boxes are passed in the "normalized CxCyWH" format. + + Boxes can be encoded with any of the three possibilities: + - direct projection: linear projection from coordinate space to d_model + - pooling: RoI align features from the backbone + - pos encoder: position encoding of the box center + + These three options are mutually compatible and will be summed if multiple are selected. + + As an alternative, boxes can be encoded as two corner points (top-left and bottom-right). + + The encoded sequence can be further processed with a transformer. + """ + + def __init__( + self, + encode_boxes_as_points: bool, + boxes_direct_project: bool, + boxes_pool: bool, + boxes_pos_enc: bool, + d_model: int, + pos_enc, + num_layers: int, + layer: nn.Module, + roi_size: int = 7, + add_cls: bool = True, + add_post_encode_proj: bool = True, + use_act_ckpt: bool = False, + ): + """Initialize the SequenceGeometryEncoder.""" + super().__init__() + + self.d_model = d_model + self.pos_enc = pos_enc + self.encode_boxes_as_points = encode_boxes_as_points + self.roi_size = roi_size + + # Label embeddings: 2 labels if encoding as boxes (pos/neg) + # 6 labels if encoding as points (regular pos/neg, top-left pos/neg, bottom-right pos/neg) + num_labels = 6 if self.encode_boxes_as_points else 2 + self.label_embed = torch.nn.Embedding(num_labels, self.d_model) + + # CLS token for pooling + self.cls_embed = None + if add_cls: + self.cls_embed = torch.nn.Embedding(1, self.d_model) + + # Point encoding (used when encode_boxes_as_points is True) + if encode_boxes_as_points: + self.points_direct_project = nn.Linear(2, self.d_model) + self.points_pool_project = None + self.points_pos_enc_project = None + else: + # Box encoding modules + assert boxes_direct_project or boxes_pos_enc or boxes_pool, "Error: need at least one way to encode boxes" + self.points_direct_project = None + self.points_pool_project = None + self.points_pos_enc_project = None + + self.boxes_direct_project = None + self.boxes_pool_project = None + self.boxes_pos_enc_project = None + + if boxes_direct_project: + self.boxes_direct_project = nn.Linear(4, self.d_model) + if boxes_pool: + self.boxes_pool_project = nn.Conv2d(self.d_model, self.d_model, self.roi_size) + if boxes_pos_enc: + self.boxes_pos_enc_project = nn.Linear(self.d_model + 2, self.d_model) + + self.final_proj = None + if add_post_encode_proj: + self.final_proj = nn.Linear(self.d_model, self.d_model) + self.norm = nn.LayerNorm(self.d_model) + + self.img_pre_norm = nn.Identity() + if self.points_pool_project is not None or self.boxes_pool_project is not None: + self.img_pre_norm = nn.LayerNorm(self.d_model) + + self.encode = None + if num_layers > 0: + assert add_cls, "It's currently highly recommended to add a CLS when using a transformer" + self.encode = _get_clones(layer, num_layers) + self.encode_norm = nn.LayerNorm(self.d_model) + + self.use_act_ckpt = use_act_ckpt + + def _encode_points(self, points, points_mask, points_labels, img_feats): + """Encode points (used when boxes are converted to corner points).""" + # Direct projection of coordinates + points_embed = self.points_direct_project(points.to(img_feats.dtype)) + + # Add label embeddings + type_embed = self.label_embed(points_labels.long()) + return type_embed + points_embed, points_mask + + def _encode_boxes(self, boxes, boxes_mask, boxes_labels, img_feats: torch.Tensor): + """Encode boxes using configured encoding methods.""" + boxes_embed = None + n_boxes, bs = boxes.shape[:2] + + if self.boxes_direct_project is not None: + proj = self.boxes_direct_project(boxes.to(img_feats.dtype)) + boxes_embed = proj + + if self.boxes_pool_project is not None: + H, W = img_feats.shape[-2:] + + # Convert boxes to xyxy format and denormalize + boxes_xyxy = xywh2xyxy(boxes.to(img_feats.dtype)) + scale = torch.tensor([W, H, W, H], dtype=boxes_xyxy.dtype) + scale = scale.to(device=boxes_xyxy.device, non_blocking=True) + scale = scale.view(1, 1, 4) + boxes_xyxy = boxes_xyxy * scale + + # RoI align + # Scoped for import ultralytics speed: ROI align requires optional torchvision ops. + from torchvision.ops import roi_align + + sampled = roi_align(img_feats, boxes_xyxy.transpose(0, 1).unbind(0), self.roi_size) + assert list(sampled.shape) == [ + bs * n_boxes, + self.d_model, + self.roi_size, + self.roi_size, + ] + proj = self.boxes_pool_project(sampled) + proj = proj.view(bs, n_boxes, self.d_model).transpose(0, 1) + + if boxes_embed is None: + boxes_embed = proj + else: + boxes_embed = boxes_embed + proj + + if self.boxes_pos_enc_project is not None: + cx, cy, w, h = boxes.unbind(-1) + enc = self.pos_enc.encode_boxes(cx.flatten(), cy.flatten(), w.flatten(), h.flatten()) + enc = enc.view(boxes.shape[0], boxes.shape[1], enc.shape[-1]) + + proj = self.boxes_pos_enc_project(enc.to(img_feats.dtype)) + if boxes_embed is None: + boxes_embed = proj + else: + boxes_embed = boxes_embed + proj + + # Add label embeddings + type_embed = self.label_embed(boxes_labels.long()) + return type_embed + boxes_embed, boxes_mask + + def forward(self, geo_prompt: Prompt, img_feats, img_sizes, img_pos_embeds=None): + """Encode geometric box prompts. + + Args: + geo_prompt (Prompt): Prompt object containing box embeddings, masks, and labels. + img_feats (list[torch.Tensor]): List of image features from backbone. + img_sizes (list[tuple[int, int]]): List of (H, W) tuples for each feature level. + img_pos_embeds (list[torch.Tensor] | None): Optional position embeddings for image features. + + Returns: + Tuple of (encoded_embeddings, attention_mask) + """ + boxes = geo_prompt.box_embeddings + boxes_mask = geo_prompt.box_mask + boxes_labels = geo_prompt.box_labels + + seq_first_img_feats = img_feats[-1] # [H*W, B, C] + seq_first_img_pos_embeds = ( + img_pos_embeds[-1] if img_pos_embeds is not None else torch.zeros_like(seq_first_img_feats) + ) + + # Prepare image features for pooling if needed + if self.points_pool_project or self.boxes_pool_project: + assert len(img_feats) == len(img_sizes) + cur_img_feat = img_feats[-1] + cur_img_feat = self.img_pre_norm(cur_img_feat) + H, W = img_sizes[-1] + assert cur_img_feat.shape[0] == H * W + N, C = cur_img_feat.shape[-2:] + # Reshape to NxCxHxW + cur_img_feat = cur_img_feat.permute(1, 2, 0) + cur_img_feat = cur_img_feat.view(N, C, H, W) + img_feats = cur_img_feat + + if self.encode_boxes_as_points: + # Convert boxes to corner points + assert boxes is not None and boxes.shape[-1] == 4 + + boxes_xyxy = xywh2xyxy(boxes) + top_left, bottom_right = boxes_xyxy.split(split_size=2, dim=-1) + + # Adjust labels for corner points (offset by 2 and 4) + labels_tl = boxes_labels + 2 + labels_br = boxes_labels + 4 + + # Concatenate top-left and bottom-right points + points = torch.cat([top_left, bottom_right], dim=0) + points_labels = torch.cat([labels_tl, labels_br], dim=0) + points_mask = torch.cat([boxes_mask, boxes_mask], dim=1) + + final_embeds, final_mask = self._encode_points( + points=points, + points_mask=points_mask, + points_labels=points_labels, + img_feats=img_feats, + ) + else: + # Encode boxes directly + final_embeds, final_mask = self._encode_boxes( + boxes=boxes, + boxes_mask=boxes_mask, + boxes_labels=boxes_labels, + img_feats=img_feats, + ) + + bs = final_embeds.shape[1] + assert final_mask.shape[0] == bs + + # Add CLS token if configured + if self.cls_embed is not None: + cls = self.cls_embed.weight.view(1, 1, self.d_model).repeat(1, bs, 1) + cls_mask = torch.zeros(bs, 1, dtype=final_mask.dtype, device=final_mask.device) + final_embeds, final_mask = concat_padded_sequences(final_embeds, final_mask, cls, cls_mask) + + # Final projection + if self.final_proj is not None: + final_embeds = self.norm(self.final_proj(final_embeds)) + + # Transformer encoding layers + if self.encode is not None: + for lay in self.encode: + final_embeds = lay( + tgt=final_embeds, + memory=seq_first_img_feats, + tgt_key_padding_mask=final_mask, + pos=seq_first_img_pos_embeds, + ) + final_embeds = self.encode_norm(final_embeds) + + return final_embeds, final_mask diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/maskformer_segmentation.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/maskformer_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..d9677e15bc1dee13b35a17544bd548a0e774b112 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/maskformer_segmentation.py @@ -0,0 +1,286 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved + +from __future__ import annotations + +import math + +import torch +import torch.nn.functional as F +from torch import nn +from torch.utils import checkpoint + +from ultralytics.nn.modules.transformer import MLP + + +class LinearPresenceHead(nn.Sequential): + """Linear presence head for predicting the presence of classes in an image.""" + + def __init__(self, d_model): + """Initializes the LinearPresenceHead.""" + # a hack to make `LinearPresenceHead` compatible with old checkpoints + super().__init__(nn.Identity(), nn.Identity(), nn.Linear(d_model, 1)) + + def forward(self, hs, prompt, prompt_mask): + """Forward pass of the presence head.""" + return super().forward(hs) + + +class MaskPredictor(nn.Module): + """Predicts masks from object queries and pixel embeddings.""" + + def __init__(self, hidden_dim, mask_dim): + """Initializes the MaskPredictor.""" + super().__init__() + self.mask_embed = MLP(hidden_dim, hidden_dim, mask_dim, 3) + + def forward(self, obj_queries, pixel_embed): + """Predicts masks from object queries and pixel embeddings.""" + if len(obj_queries.shape) == 3: + if pixel_embed.ndim == 3: + # batch size was omitted + mask_preds = torch.einsum("bqc,chw->bqhw", self.mask_embed(obj_queries), pixel_embed) + else: + mask_preds = torch.einsum("bqc,bchw->bqhw", self.mask_embed(obj_queries), pixel_embed) + else: + # Assumed to have aux masks + if pixel_embed.ndim == 3: + # batch size was omitted + mask_preds = torch.einsum("lbqc,chw->lbqhw", self.mask_embed(obj_queries), pixel_embed) + else: + mask_preds = torch.einsum("lbqc,bchw->lbqhw", self.mask_embed(obj_queries), pixel_embed) + + return mask_preds + + +class SegmentationHead(nn.Module): + """Segmentation head that predicts masks from backbone features and object queries.""" + + def __init__( + self, + hidden_dim, + upsampling_stages, + use_encoder_inputs=False, + aux_masks=False, + no_dec=False, + pixel_decoder=None, + act_ckpt=False, + shared_conv=False, + compile_mode_pixel_decoder=None, + ): + """Initializes the SegmentationHead.""" + super().__init__() + self.use_encoder_inputs = use_encoder_inputs + self.aux_masks = aux_masks + if pixel_decoder is not None: + self.pixel_decoder = pixel_decoder + else: + self.pixel_decoder = PixelDecoder( + hidden_dim, + upsampling_stages, + shared_conv=shared_conv, + compile_mode=compile_mode_pixel_decoder, + ) + self.no_dec = no_dec + if no_dec: + self.mask_predictor = nn.Conv2d(hidden_dim, 1, kernel_size=3, stride=1, padding=1) + else: + self.mask_predictor = MaskPredictor(hidden_dim, mask_dim=hidden_dim) + + self.act_ckpt = act_ckpt + + # used to update the output dictionary + self.instance_keys = ["pred_masks"] + + def _embed_pixels(self, backbone_feats: list[torch.Tensor], encoder_hidden_states) -> torch.Tensor: + """Embeds pixels using the pixel decoder.""" + if self.use_encoder_inputs: + backbone_visual_feats = [bb_feat.clone() for bb_feat in backbone_feats] + # Extract visual embeddings + encoder_hidden_states = encoder_hidden_states.permute(1, 2, 0) + spatial_dim = math.prod(backbone_feats[-1].shape[-2:]) + encoder_visual_embed = encoder_hidden_states[..., :spatial_dim].reshape(-1, *backbone_feats[-1].shape[1:]) + + backbone_visual_feats[-1] = encoder_visual_embed + if self.act_ckpt: + pixel_embed = checkpoint.checkpoint(self.pixel_decoder, backbone_visual_feats, use_reentrant=False) + else: + pixel_embed = self.pixel_decoder(backbone_visual_feats) + else: + backbone_feats = [x for x in backbone_feats] + pixel_embed = self.pixel_decoder(backbone_feats) + if pixel_embed.shape[0] == 1: + # For batch_size=1 training, we can avoid the indexing to save memory + pixel_embed = pixel_embed.squeeze(0) + else: + pixel_embed = pixel_embed[[0], ...] + return pixel_embed + + def forward( + self, + backbone_feats: list[torch.Tensor], + obj_queries: torch.Tensor, + encoder_hidden_states: torch.Tensor = None, + **kwargs, + ) -> dict[str, torch.Tensor]: + """Forward pass of the SegmentationHead.""" + if self.use_encoder_inputs: + assert encoder_hidden_states is not None + + pixel_embed = self._embed_pixels(backbone_feats=backbone_feats, encoder_hidden_states=encoder_hidden_states) + + if self.no_dec: + mask_pred = self.mask_predictor(pixel_embed) + elif self.aux_masks: + mask_pred = self.mask_predictor(obj_queries, pixel_embed) + else: + mask_pred = self.mask_predictor(obj_queries[-1], pixel_embed) + + return {"pred_masks": mask_pred} + + +class PixelDecoder(nn.Module): + """Pixel decoder module that upsamples backbone features.""" + + def __init__( + self, + hidden_dim, + num_upsampling_stages, + interpolation_mode="nearest", + shared_conv=False, + compile_mode=None, + ): + """Initializes the PixelDecoder.""" + super().__init__() + self.hidden_dim = hidden_dim + self.num_upsampling_stages = num_upsampling_stages + self.interpolation_mode = interpolation_mode + conv_layers = [] + norms = [] + num_convs = 1 if shared_conv else num_upsampling_stages + for _ in range(num_convs): + conv_layers.append(nn.Conv2d(self.hidden_dim, self.hidden_dim, 3, 1, 1)) + norms.append(nn.GroupNorm(8, self.hidden_dim)) + + self.conv_layers = nn.ModuleList(conv_layers) + self.norms = nn.ModuleList(norms) + self.shared_conv = shared_conv + self.out_dim = self.conv_layers[-1].out_channels + if compile_mode is not None: + self.forward = torch.compile(self.forward, mode=compile_mode, dynamic=True, fullgraph=True) + # Needed to make checkpointing happy. But we don't know if the module is checkpointed, so we disable it by default. + torch._dynamo.config.optimize_ddp = False + + def forward(self, backbone_feats: list[torch.Tensor]): + """Forward pass of the PixelDecoder.""" + prev_fpn = backbone_feats[-1] + fpn_feats = backbone_feats[:-1] + for layer_idx, bb_feat in enumerate(fpn_feats[::-1]): + curr_fpn = bb_feat + prev_fpn = curr_fpn + F.interpolate(prev_fpn, size=curr_fpn.shape[-2:], mode=self.interpolation_mode) + if self.shared_conv: + # only one conv layer + layer_idx = 0 + prev_fpn = self.conv_layers[layer_idx](prev_fpn) + prev_fpn = F.relu(self.norms[layer_idx](prev_fpn)) + + return prev_fpn + + +class UniversalSegmentationHead(SegmentationHead): + """This module handles semantic+instance segmentation.""" + + def __init__( + self, + hidden_dim, + upsampling_stages, + pixel_decoder, + aux_masks=False, + no_dec=False, + act_ckpt=False, + presence_head: bool = False, + dot_product_scorer=None, + cross_attend_prompt=None, + ): + """Initializes the UniversalSegmentationHead.""" + super().__init__( + hidden_dim=hidden_dim, + upsampling_stages=upsampling_stages, + use_encoder_inputs=True, + aux_masks=aux_masks, + no_dec=no_dec, + pixel_decoder=pixel_decoder, + act_ckpt=act_ckpt, + ) + self.d_model = hidden_dim + + if dot_product_scorer is not None: + assert presence_head, "Specifying a dot product scorer without a presence head is likely a mistake" + + self.presence_head = None + if presence_head: + self.presence_head = ( + dot_product_scorer if dot_product_scorer is not None else LinearPresenceHead(self.d_model) + ) + + self.cross_attend_prompt = cross_attend_prompt + if self.cross_attend_prompt is not None: + self.cross_attn_norm = nn.LayerNorm(self.d_model) + + self.semantic_seg_head = nn.Conv2d(self.pixel_decoder.out_dim, 1, kernel_size=1) + self.instance_seg_head = nn.Conv2d(self.pixel_decoder.out_dim, self.d_model, kernel_size=1) + + def forward( + self, + backbone_feats: list[torch.Tensor], + obj_queries: torch.Tensor, + encoder_hidden_states: torch.Tensor = None, + prompt: torch.Tensor = None, + prompt_mask: torch.Tensor = None, + **kwargs, + ) -> dict[str, torch.Tensor]: + """Forward pass of the UniversalSegmentationHead.""" + assert encoder_hidden_states is not None + bs = encoder_hidden_states.shape[1] + + if self.cross_attend_prompt is not None: + tgt2 = self.cross_attn_norm(encoder_hidden_states) + tgt2 = self.cross_attend_prompt( + query=tgt2, + key=prompt.to(tgt2.dtype), + value=prompt.to(tgt2.dtype), + key_padding_mask=prompt_mask, + need_weights=False, + )[0] + encoder_hidden_states = tgt2 + encoder_hidden_states + + presence_logit = None + if self.presence_head is not None: + pooled_enc = encoder_hidden_states.mean(0) + presence_logit = ( + self.presence_head( + pooled_enc.view(1, bs, 1, self.d_model), + prompt=prompt, + prompt_mask=prompt_mask, + ) + .squeeze(0) + .squeeze(1) + ) + + pixel_embed = self._embed_pixels(backbone_feats=backbone_feats, encoder_hidden_states=encoder_hidden_states) + + instance_embeds = self.instance_seg_head(pixel_embed) + + if self.no_dec: + mask_pred = self.mask_predictor(instance_embeds) + elif self.aux_masks: + mask_pred = self.mask_predictor(obj_queries, instance_embeds) + else: + mask_pred = self.mask_predictor(obj_queries[-1], instance_embeds) + + return { + "pred_masks": mask_pred, + "semantic_seg": self.semantic_seg_head(pixel_embed), + "presence_logit": presence_logit, + } diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/model_misc.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/model_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..5962957fe84fe20c5bb6fdb0a0e12912427f4ca5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/model_misc.py @@ -0,0 +1,198 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved + +"""Various utility models.""" + +from __future__ import annotations + +import math + +import numpy as np +import torch +from torch import Tensor, nn + + +class DotProductScoring(torch.nn.Module): + """A module that computes dot-product scores between query features and pooled prompt embeddings.""" + + def __init__( + self, + d_model, + d_proj, + prompt_mlp=None, + clamp_logits=True, + clamp_max_val=12.0, + ): + """Initialize the DotProductScoring module.""" + super().__init__() + self.d_proj = d_proj + assert isinstance(prompt_mlp, torch.nn.Module) or prompt_mlp is None + self.prompt_mlp = prompt_mlp # an optional MLP projection for prompt + self.prompt_proj = torch.nn.Linear(d_model, d_proj) + self.hs_proj = torch.nn.Linear(d_model, d_proj) + self.scale = float(1.0 / np.sqrt(d_proj)) + self.clamp_logits = clamp_logits + if self.clamp_logits: + self.clamp_max_val = clamp_max_val + + @staticmethod + def mean_pool_text(prompt, prompt_mask): + """Mean-pool the prompt embeddings over the valid tokens only.""" + # is_valid has shape (seq, bs, 1), where 1 is valid and 0 is padding + is_valid = (~prompt_mask).to(prompt.dtype).permute(1, 0)[..., None] + # num_valid has shape (bs, 1) + num_valid = torch.clamp(torch.sum(is_valid, dim=0), min=1.0) + # mean pool over all the valid tokens -- pooled_prompt has shape (bs, proj_dim) + pooled_prompt = (prompt * is_valid).sum(dim=0) / num_valid + return pooled_prompt + + def forward(self, hs, prompt, prompt_mask): + """Compute dot-product scores between hs and prompt.""" + # hs has shape (num_layer, bs, num_query, d_model) + # prompt has shape (seq, bs, d_model) + # prompt_mask has shape (bs, seq), where 1 is padding and 0 is valid + assert hs.dim() == 4 and prompt.dim() == 3 and prompt_mask.dim() == 2 + + # apply MLP on prompt if specified + if self.prompt_mlp is not None: + prompt = self.prompt_mlp(prompt.to(hs.dtype)) + + # first, get the mean-pooled version of the prompt + pooled_prompt = self.mean_pool_text(prompt, prompt_mask) + + # then, project pooled_prompt and hs to d_proj dimensions + proj_pooled_prompt = self.prompt_proj(pooled_prompt) # (bs, d_proj) + proj_hs = self.hs_proj(hs) # (num_layer, bs, num_query, d_proj) + + # finally, get dot-product scores of shape (num_layer, bs, num_query, 1) + scores = torch.matmul(proj_hs, proj_pooled_prompt.unsqueeze(-1)) + scores *= self.scale + + # clamp scores to a max value to avoid numerical issues in loss or matcher + if self.clamp_logits: + scores.clamp_(min=-self.clamp_max_val, max=self.clamp_max_val) + + return scores + + +class LayerScale(nn.Module): + """LayerScale module for per-channel scaling of layer outputs.""" + + def __init__( + self, + dim: int, + init_values: float | Tensor = 1e-5, + inplace: bool = False, + ) -> None: + """Initialize the LayerScale module.""" + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x: Tensor) -> Tensor: + """Apply LayerScale to the input tensor.""" + return x.mul_(self.gamma) if self.inplace else x * self.gamma + + +class TransformerWrapper(nn.Module): + """A wrapper for the transformer consisting of an encoder and a decoder.""" + + def __init__( + self, + encoder, + decoder, + d_model: int, + two_stage_type="none", # ["none"] only for now + pos_enc_at_input_dec=True, + ): + """Initialize the TransformerWrapper.""" + super().__init__() + self.encoder = encoder + self.decoder = decoder + self.num_queries = decoder.num_queries if decoder is not None else None + self.pos_enc_at_input_dec = pos_enc_at_input_dec + + # for two stage + assert two_stage_type in ["none"], f"unknown param {two_stage_type} of two_stage_type" + self.two_stage_type = two_stage_type + + self._reset_parameters() + self.d_model = d_model + + def _reset_parameters(self): + """Initialize the parameters of the model.""" + for n, p in self.named_parameters(): + if p.dim() > 1 and "box_embed" not in n and "query_embed" not in n and "reference_points" not in n: + nn.init.xavier_uniform_(p) + + +def get_valid_ratio(mask): + """Compute the valid ratio of height and width from the mask.""" + _, H, W = mask.shape + valid_H = torch.sum(~mask[:, :, 0], 1) + valid_W = torch.sum(~mask[:, 0, :], 1) + valid_ratio_h = valid_H.float() / H + valid_ratio_w = valid_W.float() / W + valid_ratio = torch.stack([valid_ratio_w, valid_ratio_h], -1) + return valid_ratio + + +def gen_sineembed_for_position(pos_tensor: torch.Tensor, num_feats: int = 256): + """Generate sinusoidal position embeddings for 2D or 4D coordinate tensors. + + This function creates sinusoidal embeddings using sine and cosine functions at different frequencies, similar to the + positional encoding used in Transformer models. It supports both 2D position tensors (x, y) and 4D tensors (x, y, w, + h) for bounding box coordinates. + + Args: + pos_tensor (torch.Tensor): Input position tensor of shape (n_query, bs, 2) for 2D coordinates or (n_query, bs, + 4) for 4D coordinates (bounding boxes). + num_feats (int): Number of feature dimensions for the output embedding. Must be even. Defaults to 256. + + Returns: + (torch.Tensor): Sinusoidal position embeddings of shape (n_query, bs, num_feats) for 2D input or (n_query, bs, + num_feats * 2) for 4D input. + + Raises: + AssertionError: If num_feats is not even. + ValueError: If pos_tensor.size(-1) is not 2 or 4. + + Examples: + >>> pos_2d = torch.rand(100, 8, 2) # 100 queries, batch size 8, 2D coordinates + >>> embeddings_2d = gen_sineembed_for_position(pos_2d, num_feats=256) + >>> embeddings_2d.shape + torch.Size([100, 8, 256]) + >>> pos_4d = torch.rand(50, 4, 4) # 50 queries, batch size 4, 4D coordinates + >>> embeddings_4d = gen_sineembed_for_position(pos_4d, num_feats=128) + >>> embeddings_4d.shape + torch.Size([50, 4, 256]) + """ + assert num_feats % 2 == 0 + num_feats = num_feats // 2 + # n_query, bs, _ = pos_tensor.size() + # sineembed_tensor = torch.zeros(n_query, bs, 256) + scale = 2 * math.pi + dim_t = torch.arange(num_feats, dtype=pos_tensor.dtype, device=pos_tensor.device) + dim_t = 10000 ** (2 * (torch.div(dim_t, 2, rounding_mode="floor")) / num_feats) + x_embed = pos_tensor[:, :, 0] * scale + y_embed = pos_tensor[:, :, 1] * scale + pos_x = x_embed[:, :, None] / dim_t + pos_y = y_embed[:, :, None] / dim_t + pos_x = torch.stack((pos_x[:, :, 0::2].sin(), pos_x[:, :, 1::2].cos()), dim=3).flatten(2) + pos_y = torch.stack((pos_y[:, :, 0::2].sin(), pos_y[:, :, 1::2].cos()), dim=3).flatten(2) + if pos_tensor.size(-1) == 2: + pos = torch.cat((pos_y, pos_x), dim=2) + elif pos_tensor.size(-1) == 4: + w_embed = pos_tensor[:, :, 2] * scale + pos_w = w_embed[:, :, None] / dim_t + pos_w = torch.stack((pos_w[:, :, 0::2].sin(), pos_w[:, :, 1::2].cos()), dim=3).flatten(2) + + h_embed = pos_tensor[:, :, 3] * scale + pos_h = h_embed[:, :, None] / dim_t + pos_h = torch.stack((pos_h[:, :, 0::2].sin(), pos_h[:, :, 1::2].cos()), dim=3).flatten(2) + + pos = torch.cat((pos_y, pos_x, pos_w, pos_h), dim=2) + else: + raise ValueError(f"Unknown pos_tensor shape(-1):{pos_tensor.size(-1)}") + return pos diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/necks.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/necks.py new file mode 100644 index 0000000000000000000000000000000000000000..fc4b186a2e41e4650102a0430c1288de32f9413e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/necks.py @@ -0,0 +1,132 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved + +"""Necks are the interface between a vision backbone and the rest of the detection model.""" + +from __future__ import annotations + +from copy import deepcopy + +import torch +from torch import nn + + +class Sam3DualViTDetNeck(nn.Module): + """A neck that implements a simple FPN as in ViTDet, with support for dual necks (for SAM3 and SAM2).""" + + def __init__( + self, + trunk: nn.Module, + position_encoding: nn.Module, + d_model: int, + scale_factors=(4.0, 2.0, 1.0, 0.5), + add_sam2_neck: bool = False, + ): + """SimpleFPN neck a la ViTDet, very lightly adapted from detectron2. + + Supports a "dual neck" setting with two identical necks (for SAM3 and SAM2) that have different weights. + + Args: + trunk (nn.Module): The backbone. + position_encoding (nn.Module): The positional encoding to use. + d_model (int): The dimension of the model. + scale_factors (tuple): Scale factors for each FPN level. + add_sam2_neck (bool): Whether to add a second neck for SAM2. + """ + super().__init__() + self.trunk = trunk + self.position_encoding = position_encoding + self.convs = nn.ModuleList() + + self.scale_factors = scale_factors + use_bias = True + dim: int = self.trunk.channel_list[-1] + + for _, scale in enumerate(scale_factors): + current = nn.Sequential() + + if scale == 4.0: + current.add_module( + "dconv_2x2_0", + nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2), + ) + current.add_module( + "gelu", + nn.GELU(), + ) + current.add_module( + "dconv_2x2_1", + nn.ConvTranspose2d(dim // 2, dim // 4, kernel_size=2, stride=2), + ) + out_dim = dim // 4 + elif scale == 2.0: + current.add_module( + "dconv_2x2", + nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2), + ) + out_dim = dim // 2 + elif scale == 1.0: + out_dim = dim + elif scale == 0.5: + current.add_module( + "maxpool_2x2", + nn.MaxPool2d(kernel_size=2, stride=2), + ) + out_dim = dim + else: + raise NotImplementedError(f"scale_factor={scale} is not supported yet.") + + current.add_module( + "conv_1x1", + nn.Conv2d( + in_channels=out_dim, + out_channels=d_model, + kernel_size=1, + bias=use_bias, + ), + ) + current.add_module( + "conv_3x3", + nn.Conv2d( + in_channels=d_model, + out_channels=d_model, + kernel_size=3, + padding=1, + bias=use_bias, + ), + ) + self.convs.append(current) + + self.sam2_convs = None + if add_sam2_neck: + # Assumes sam2 neck is just a clone of the original neck + self.sam2_convs = deepcopy(self.convs) + + def forward( + self, tensor_list: list[torch.Tensor] + ) -> tuple[list[torch.Tensor], list[torch.Tensor], list[torch.Tensor] | None, list[torch.Tensor] | None]: + """Get feature maps and positional encodings from the neck.""" + xs = self.trunk(tensor_list) + x = xs[-1] # simpleFPN + sam3_out, sam3_pos = self.sam_forward_feature_levels(x, self.convs) + if self.sam2_convs is None: + return sam3_out, sam3_pos, None, None + sam2_out, sam2_pos = self.sam_forward_feature_levels(x, self.sam2_convs) + return sam3_out, sam3_pos, sam2_out, sam2_pos + + def sam_forward_feature_levels( + self, x: torch.Tensor, convs: nn.ModuleList + ) -> tuple[list[torch.Tensor], list[torch.Tensor]]: + """Run neck convolutions and compute positional encodings for each feature level.""" + outs, poss = [], [] + for conv in convs: + feat = conv(x) + outs.append(feat) + poss.append(self.position_encoding(feat).to(feat.dtype)) + return outs, poss + + def set_imgsz(self, imgsz: list[int] | None = None): + """Set the image size for the trunk backbone.""" + imgsz = imgsz if imgsz is not None else [1008, 1008] + self.trunk.set_imgsz(imgsz) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/sam3_image.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/sam3_image.py new file mode 100644 index 0000000000000000000000000000000000000000..9b5eec5548021f87fd1eb97d253b43ecfe30a7e2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/sam3_image.py @@ -0,0 +1,363 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved + +from __future__ import annotations + +from copy import deepcopy + +import torch + +from ultralytics.nn.modules.utils import inverse_sigmoid +from ultralytics.utils.ops import xywh2xyxy + +from ..modules.sam import SAM2Model +from .geometry_encoders import Prompt +from .vl_combiner import SAM3VLBackbone + + +def _update_out(out, out_name, out_value, auxiliary=True, update_aux=True): + """Helper function to update output dictionary with main and auxiliary outputs.""" + out[out_name] = out_value[-1] if auxiliary else out_value + if auxiliary and update_aux: + if "aux_outputs" not in out: + out["aux_outputs"] = [{} for _ in range(len(out_value) - 1)] + assert len(out["aux_outputs"]) == len(out_value) - 1 + for aux_output, aux_value in zip(out["aux_outputs"], out_value[:-1]): + aux_output[out_name] = aux_value + + +class SAM3SemanticModel(torch.nn.Module): + """SAM3 model for semantic segmentation with vision-language backbone.""" + + mask_threshold: float = 0.0 + # Max text prompts per grounding pass; each prompt is a batch item, so VRAM scales linearly with the count + max_text_batch: int = 16 + + def __init__( + self, + backbone: SAM3VLBackbone, + transformer, + input_geometry_encoder, + segmentation_head=None, + num_feature_levels=1, + o2m_mask_predict=True, + dot_prod_scoring=None, + use_instance_query: bool = True, + multimask_output: bool = True, + use_act_checkpoint_seg_head: bool = True, + matcher=None, + use_dot_prod_scoring=True, + supervise_joint_box_scores: bool = False, # only relevant if using presence token/score + detach_presence_in_joint_score: bool = False, # only relevant if using presence token/score + separate_scorer_for_instance: bool = False, + num_interactive_steps_val: int = 0, + ): + """Initialize the SAM3SemanticModel.""" + super().__init__() + self.backbone = backbone + self.geometry_encoder = input_geometry_encoder + self.transformer = transformer + self.hidden_dim = transformer.d_model + self.num_feature_levels = num_feature_levels + self.segmentation_head = segmentation_head + + self.o2m_mask_predict = o2m_mask_predict + + self.dot_prod_scoring = dot_prod_scoring + self.use_act_checkpoint_seg_head = use_act_checkpoint_seg_head + self.matcher = matcher + + self.num_interactive_steps_val = num_interactive_steps_val + self.use_dot_prod_scoring = use_dot_prod_scoring + + if self.use_dot_prod_scoring: + assert dot_prod_scoring is not None + self.dot_prod_scoring = dot_prod_scoring + self.instance_dot_prod_scoring = None + if separate_scorer_for_instance: + self.instance_dot_prod_scoring = deepcopy(dot_prod_scoring) + else: + self.class_embed = torch.nn.Linear(self.hidden_dim, 1) + self.instance_class_embed = None + if separate_scorer_for_instance: + self.instance_class_embed = deepcopy(self.class_embed) + + self.supervise_joint_box_scores = supervise_joint_box_scores + self.detach_presence_in_joint_score = detach_presence_in_joint_score + + # verify the number of queries for O2O and O2M + num_o2o_static = self.transformer.decoder.num_queries + num_o2m_static = self.transformer.decoder.num_o2m_queries + assert num_o2m_static == (num_o2o_static if self.transformer.decoder.dac else 0) + self.dac = self.transformer.decoder.dac + + self.use_instance_query = use_instance_query + self.multimask_output = multimask_output + + self.text_embeddings = {} + self.names = [] + + def _encode_prompt( + self, + img_feats, + img_pos_embeds, + vis_feat_sizes, + geometric_prompt, + visual_prompt_embed=None, + visual_prompt_mask=None, + prev_mask_pred=None, + ): + """Encode the geometric and visual prompts.""" + if prev_mask_pred is not None: + img_feats = [img_feats[-1] + prev_mask_pred] + # Encode geometry + geo_feats, geo_masks = self.geometry_encoder( + geo_prompt=geometric_prompt, + img_feats=img_feats, + img_sizes=vis_feat_sizes, + img_pos_embeds=img_pos_embeds, + ) + if visual_prompt_embed is None: + visual_prompt_embed = torch.zeros((0, *geo_feats.shape[1:]), device=geo_feats.device) + visual_prompt_mask = torch.zeros( + (*geo_masks.shape[:-1], 0), + device=geo_masks.device, + dtype=geo_masks.dtype, + ) + prompt = torch.cat([geo_feats, visual_prompt_embed], dim=0) + prompt_mask = torch.cat([geo_masks, visual_prompt_mask], dim=1) + return prompt, prompt_mask + + def _run_encoder( + self, + img_feats, + img_pos_embeds, + vis_feat_sizes, + prompt, + prompt_mask, + encoder_extra_kwargs: dict | None = None, + ): + """Run the transformer encoder.""" + # Run the encoder + # make a copy of the image feature lists since the encoder may modify these lists in-place + memory = self.transformer.encoder( + src=img_feats.copy(), + src_key_padding_mask=None, + src_pos=img_pos_embeds.copy(), + prompt=prompt, + prompt_key_padding_mask=prompt_mask, + feat_sizes=vis_feat_sizes, + encoder_extra_kwargs=encoder_extra_kwargs, + ) + encoder_out = { + # encoded image features + "encoder_hidden_states": memory["memory"], + "pos_embed": memory["pos_embed"], + "padding_mask": memory["padding_mask"], + "valid_ratios": memory["valid_ratios"], + "vis_feat_sizes": vis_feat_sizes, + # encoded text features (or other prompts) + "prompt_before_enc": prompt, + "prompt_after_enc": memory.get("memory_text", prompt), + "prompt_mask": prompt_mask, + } + return encoder_out + + def _run_decoder( + self, + pos_embed, + memory, + src_mask, + out, + prompt, + prompt_mask, + encoder_out, + ): + """Run the transformer decoder.""" + bs = memory.shape[1] + query_embed = self.transformer.decoder.query_embed.weight + tgt = query_embed.unsqueeze(1).repeat(1, bs, 1) + + hs, reference_boxes, dec_presence_out, _ = self.transformer.decoder( + tgt=tgt, + memory=memory, + memory_key_padding_mask=src_mask, + pos=pos_embed, + reference_boxes=None, + spatial_shapes=encoder_out["vis_feat_sizes"], + valid_ratios=encoder_out["valid_ratios"], + tgt_mask=None, + memory_text=prompt, + text_attention_mask=prompt_mask, + apply_dac=False, + ) + hs = hs.transpose(1, 2) # seq-first to batch-first + reference_boxes = reference_boxes.transpose(1, 2) # seq-first to batch-first + if dec_presence_out is not None: + # seq-first to batch-first + dec_presence_out = dec_presence_out.transpose(1, 2) + self._update_scores_and_boxes( + out, + hs, + reference_boxes, + prompt, + prompt_mask, + dec_presence_out=dec_presence_out, + ) + return out, hs + + def _update_scores_and_boxes( + self, + out, + hs, + reference_boxes, + prompt, + prompt_mask, + dec_presence_out=None, + is_instance_prompt=False, + ): + """Update output dict with class scores and box predictions.""" + num_o2o = hs.size(2) + # score prediction + if self.use_dot_prod_scoring: + dot_prod_scoring_head = self.dot_prod_scoring + if is_instance_prompt and self.instance_dot_prod_scoring is not None: + dot_prod_scoring_head = self.instance_dot_prod_scoring + outputs_class = dot_prod_scoring_head(hs, prompt, prompt_mask) + else: + class_embed_head = self.class_embed + if is_instance_prompt and self.instance_class_embed is not None: + class_embed_head = self.instance_class_embed + outputs_class = class_embed_head(hs) + + # box prediction + box_head = self.transformer.decoder.bbox_embed + if is_instance_prompt and self.transformer.decoder.instance_bbox_embed is not None: + box_head = self.transformer.decoder.instance_bbox_embed + anchor_box_offsets = box_head(hs) + reference_boxes_inv_sig = inverse_sigmoid(reference_boxes) + outputs_coord = (reference_boxes_inv_sig + anchor_box_offsets).sigmoid() + outputs_boxes_xyxy = xywh2xyxy(outputs_coord) + + if dec_presence_out is not None: + _update_out(out, "presence_logit_dec", dec_presence_out, update_aux=False) + + if self.supervise_joint_box_scores: + assert dec_presence_out is not None + prob_dec_presence_out = dec_presence_out.clone().sigmoid() + if self.detach_presence_in_joint_score: + prob_dec_presence_out = prob_dec_presence_out.detach() + + outputs_class = inverse_sigmoid(outputs_class.sigmoid() * prob_dec_presence_out.unsqueeze(2)).clamp( + min=-10.0, max=10.0 + ) + + _update_out(out, "pred_logits", outputs_class[:, :, :num_o2o], update_aux=False) + _update_out(out, "pred_boxes", outputs_coord[:, :, :num_o2o], update_aux=False) + _update_out(out, "pred_boxes_xyxy", outputs_boxes_xyxy[:, :, :num_o2o], update_aux=False) + + def _run_segmentation_heads( + self, + out, + backbone_out, + encoder_hidden_states, + prompt, + prompt_mask, + hs, + ): + """Run segmentation heads and get masks.""" + if self.segmentation_head is not None: + num_o2o = hs.size(2) + obj_queries = hs if self.o2m_mask_predict else hs[:, :, :num_o2o] + seg_head_outputs = self.segmentation_head( + backbone_feats=backbone_out["backbone_fpn"], + obj_queries=obj_queries, + encoder_hidden_states=encoder_hidden_states, + prompt=prompt, + prompt_mask=prompt_mask, + ) + for k, v in seg_head_outputs.items(): + if k in self.segmentation_head.instance_keys: + _update_out(out, k, v[:, :num_o2o], auxiliary=False) + else: + out[k] = v + else: + backbone_out.pop("backbone_fpn", None) + + def forward_grounding( + self, backbone_out: dict[str, torch.Tensor], text_ids: torch.Tensor, geometric_prompt: Prompt = None + ): + """Forward pass for grounding (detection + segmentation) given input images and text.""" + if len(text_ids) > self.max_text_batch and ( + geometric_prompt is None or geometric_prompt.box_embeddings.shape[0] == 0 + ): + # Chunk text prompts to bound peak VRAM; prompts are independent batch items so results concatenate + # exactly. An empty geometric prompt carries no boxes, so slicing its batch dim preserves numerics. + outs = [] + for i in range(0, len(text_ids), self.max_text_batch): + prompt = None + if geometric_prompt is not None: + prompt = Prompt( + box_embeddings=geometric_prompt.box_embeddings[:, i : i + self.max_text_batch], + box_mask=geometric_prompt.box_mask[i : i + self.max_text_batch], + box_labels=geometric_prompt.box_labels[:, i : i + self.max_text_batch], + ) + outs.append(self.forward_grounding(backbone_out, text_ids[i : i + self.max_text_batch], prompt)) + return { + k: torch.cat([o[k] for o in outs]) if isinstance(v, torch.Tensor) else v for k, v in outs[0].items() + } + backbone_out, img_feats, img_pos_embeds, vis_feat_sizes = SAM2Model._prepare_backbone_features( + self, backbone_out, batch=len(text_ids) + ) + backbone_out.update({k: v for k, v in self.text_embeddings.items()}) + # index text features (note that regardless of early or late fusion, the batch size of + # `txt_feats` is always the number of *prompts* in the encoder) + txt_feats = backbone_out["language_features"][:, text_ids] + txt_masks = backbone_out["language_mask"][text_ids] + if geometric_prompt is not None: + with torch.profiler.record_function("SAM3Image._encode_prompt"): + geo_prompt, geo_mask = self._encode_prompt(img_feats, img_pos_embeds, vis_feat_sizes, geometric_prompt) + prompt = torch.cat([txt_feats, geo_prompt], dim=0) + prompt_mask = torch.cat([txt_masks, geo_mask], dim=1) + else: + prompt = txt_feats + prompt_mask = txt_masks + + # Run the encoder + with torch.profiler.record_function("SAM3Image._run_encoder"): + encoder_out = self._run_encoder(img_feats, img_pos_embeds, vis_feat_sizes, prompt, prompt_mask) + out = {"backbone_out": backbone_out} + + # Run the decoder + with torch.profiler.record_function("SAM3Image._run_decoder"): + out, hs = self._run_decoder( + memory=encoder_out["encoder_hidden_states"], + pos_embed=encoder_out["pos_embed"], + src_mask=encoder_out["padding_mask"], + out=out, + prompt=prompt, + prompt_mask=prompt_mask, + encoder_out=encoder_out, + ) + + # Run segmentation heads + with torch.profiler.record_function("SAM3Image._run_segmentation_heads"): + self._run_segmentation_heads( + out=out, + backbone_out=backbone_out, + encoder_hidden_states=encoder_out["encoder_hidden_states"], + prompt=prompt, + prompt_mask=prompt_mask, + hs=hs, + ) + return out + + def set_classes(self, text: list[str]): + """Set the text embeddings for the given class names.""" + self.text_embeddings = self.backbone.forward_text(text) + self.names = text + + def set_imgsz(self, imgsz: tuple[int, int]): + """Set the image size for the model.""" + self.backbone.set_imgsz(imgsz) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/text_encoder_ve.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/text_encoder_ve.py new file mode 100644 index 0000000000000000000000000000000000000000..03b5316593c16364485e867b4297bb7fc9192475 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/text_encoder_ve.py @@ -0,0 +1,305 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved + +from __future__ import annotations + +from collections import OrderedDict +from typing import Callable + +import torch +from torch import nn +from torch.utils.checkpoint import checkpoint + +from .model_misc import LayerScale + + +class ResidualAttentionBlock(nn.Module): + """Transformer block with multi-head attention, layer normalization, and MLP feed-forward network.""" + + def __init__( + self, + d_model: int, + n_head: int, + mlp_ratio: float = 4.0, + ls_init_value: float | None = None, + act_layer: Callable[[], nn.Module] = nn.GELU, + norm_layer: Callable[[int], nn.Module] = nn.LayerNorm, + ): + """Initialize residual attention block with configurable dimensions and normalization.""" + super().__init__() + # Attention + self.attn = nn.MultiheadAttention(d_model, n_head, batch_first=True) + + # LayerNorm, LayerScale + self.ln_1 = norm_layer(d_model) + self.ln_2 = norm_layer(d_model) + + self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity() + self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity() + + # MLP + mlp_width = int(d_model * mlp_ratio) + self.mlp = nn.Sequential( + OrderedDict( + [ + ("c_fc", nn.Linear(d_model, mlp_width)), + ("gelu", act_layer()), + ("c_proj", nn.Linear(mlp_width, d_model)), + ] + ) + ) + + def attention( + self, q_x: torch.Tensor, k_x: torch.Tensor = None, v_x: torch.Tensor = None, attn_mask: torch.Tensor = None + ) -> torch.Tensor: + """Compute multi-head attention with optional cross-attention support and masking.""" + k_x = k_x if k_x is not None else q_x + v_x = v_x if v_x is not None else q_x + if attn_mask is not None and attn_mask.dtype != torch.bool: # leave boolean masks as is + attn_mask = attn_mask.to(q_x.dtype) + + return self.attn(q_x, k_x, v_x, need_weights=False, attn_mask=attn_mask)[0] + + def forward( + self, q_x: torch.Tensor, k_x: torch.Tensor = None, v_x: torch.Tensor = None, attn_mask: torch.Tensor = None + ) -> torch.Tensor: + """Apply residual attention with layer normalization and MLP, supporting optional cross-attention.""" + k_x = self.ln_1_kv(k_x) if hasattr(self, "ln_1_kv") and k_x is not None else None + v_x = self.ln_1_kv(v_x) if hasattr(self, "ln_1_kv") and v_x is not None else None + x = q_x + self.ls_1(self.attention(q_x=self.ln_1(q_x), k_x=k_x, v_x=v_x, attn_mask=attn_mask)) + x = x + self.ls_2(self.mlp(self.ln_2(x))) + return x + + +class Transformer(nn.Module): + """Stack of residual attention blocks forming a transformer encoder with optional gradient checkpointing.""" + + def __init__( + self, + width: int, + layers: int, + heads: int, + mlp_ratio: float = 4.0, + ls_init_value: float | None = None, + act_layer: Callable[[], nn.Module] = nn.GELU, + norm_layer: Callable[[int], nn.Module] = nn.LayerNorm, + compile_mode: str | None = None, + use_act_checkpoint: bool = False, + ): + """Initialize transformer with configurable depth, width, and optional compilation/checkpointing.""" + super().__init__() + self.width = width + self.layers = layers + self.grad_checkpointing = use_act_checkpoint + self.resblocks = nn.ModuleList( + [ + ResidualAttentionBlock( + width, + heads, + mlp_ratio, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + ) + for _ in range(layers) + ] + ) + + if compile_mode is not None: + self.forward = torch.compile(self.forward, mode=compile_mode, fullgraph=True) + if self.grad_checkpointing: + torch._dynamo.config.optimize_ddp = False + + def forward(self, x: torch.Tensor, attn_mask: torch.Tensor = None) -> torch.Tensor: + """Process input through all transformer blocks with optional gradient checkpointing during training.""" + for _, r in enumerate(self.resblocks): + if self.grad_checkpointing and not torch.jit.is_scripting() and self.training: + x = checkpoint(r, x, None, None, attn_mask, use_reentrant=False) + else: + x = r(x, attn_mask=attn_mask) + return x + + +def text_global_pool( + x: torch.Tensor, text: torch.Tensor = None, pool_type: str = "argmax" +) -> tuple[torch.Tensor, torch.Tensor]: + """Extract pooled representation and tokens from text embeddings using specified pooling strategy + (first/last/argmax/none). + """ + if pool_type == "first": + pooled, tokens = x[:, 0], x[:, 1:] + elif pool_type == "last": + pooled, tokens = x[:, -1], x[:, :-1] + elif pool_type == "argmax": + # take features from the eot embedding (eot_token is the highest number in each sequence) + assert text is not None + pooled, tokens = x[torch.arange(x.shape[0]), text.argmax(dim=-1)], x + else: + pooled = tokens = x + return pooled, tokens + + +class TextTransformer(nn.Module): + """Text transformer encoder with causal masking and flexible pooling strategies.""" + + def __init__( + self, + context_length: int = 77, + vocab_size: int = 49408, + width: int = 512, + heads: int = 8, + layers: int = 12, + mlp_ratio: float = 4.0, + ls_init_value: float | None = None, + output_dim: int = 512, + no_causal_mask: bool = False, + pool_type: str = "none", # no pooling + proj_bias: bool = False, + act_layer: Callable = nn.GELU, + norm_layer: Callable = nn.LayerNorm, + output_tokens: bool = False, + use_ln_post: bool = True, + compile_mode: str | None = None, + use_act_checkpoint: bool = False, + ): + """Initialize text transformer with embedding layers, transformer blocks, and pooling options.""" + super().__init__() + assert pool_type in ("first", "last", "argmax", "none") + self.output_tokens = output_tokens + self.num_pos = self.context_length = context_length + self.vocab_size = vocab_size + self.width = width + self.output_dim = output_dim + self.heads = heads + self.pool_type = pool_type + + self.token_embedding = nn.Embedding(self.vocab_size, width) + self.positional_embedding = nn.Parameter(torch.empty(self.num_pos, width)) + self.transformer = Transformer( + width=width, + layers=layers, + heads=heads, + mlp_ratio=mlp_ratio, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + compile_mode=compile_mode, + use_act_checkpoint=use_act_checkpoint, + ) + self.ln_final = norm_layer(width) if use_ln_post else nn.Identity() + if no_causal_mask: + self.attn_mask = None + else: + self.register_buffer("attn_mask", self.build_causal_mask(), persistent=False) + if proj_bias: + self.text_projection = nn.Linear(width, output_dim) + else: + self.text_projection = nn.Parameter(torch.empty(width, output_dim)) + + def build_causal_mask(self) -> torch.Tensor: + """Create a causal attention mask to prevent attention to future tokens.""" + # lazily create causal attention mask, with full attention between the tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(self.num_pos, self.num_pos) + mask.fill_(float("-inf")) + mask.triu_(1) # zero out the lower diagonal + return mask + + def forward(self, text: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: + """Forward pass through the text transformer, returning pooled output and optionally token embeddings.""" + seq_len = text.shape[1] + x = self.token_embedding(text) # [batch_size, n_ctx, d_model] + + attn_mask = self.attn_mask + if attn_mask is not None: + attn_mask = attn_mask[:seq_len, :seq_len] + + x = x + self.positional_embedding[:seq_len] + x = self.transformer(x, attn_mask=attn_mask) + + x = self.ln_final(x) + pooled, tokens = text_global_pool(x, text, pool_type=self.pool_type) + if self.text_projection is not None: + if isinstance(self.text_projection, nn.Linear): + pooled = self.text_projection(pooled) + else: + pooled = pooled @ self.text_projection + if self.output_tokens: + return pooled, tokens + return pooled + + +class VETextEncoder(nn.Module): + """Text encoder for Vision Encoder (VE) models, combining a text transformer and a linear resizer.""" + + def __init__( + self, + d_model: int, + tokenizer: Callable, + width: int = 1024, + heads: int = 16, + layers: int = 24, + context_length: int = 32, + vocab_size: int = 49408, + use_ln_post: bool = True, + compile_mode: str | None = None, + use_act_checkpoint: bool = True, + ): + """Initialize VE text encoder with a text transformer and a linear resizer to match decoder dimensions.""" + super().__init__() + self.context_length = context_length + self.use_ln_post = use_ln_post + self.tokenizer = tokenizer + + self.encoder = TextTransformer( + context_length=self.context_length, + vocab_size=vocab_size, + width=width, + heads=heads, + layers=layers, + # we want the tokens, not just the pooled output + output_tokens=True, + use_ln_post=use_ln_post, + compile_mode=compile_mode, + use_act_checkpoint=use_act_checkpoint, + ) + self.resizer = nn.Linear(self.encoder.width, d_model) + + def forward( + self, text: list[str] | tuple[torch.Tensor, torch.Tensor, dict], input_boxes: list | None = None + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Encode text input, either raw strings or pre-encoded tensors, and resize to match decoder dimensions.""" + if isinstance(text[0], str): + # no use case for this + assert input_boxes is None or len(input_boxes) == 0, "not supported" + + # Encode the text + tokenized = self.tokenizer(text, context_length=self.context_length).to( + self.resizer.weight.device + ) # [b, seq_len] + text_attention_mask = (tokenized != 0).bool() + + # manually embed the tokens + inputs_embeds = self.encoder.token_embedding(tokenized) # [b, seq_len, d=1024] + _, text_memory = self.encoder(tokenized) # [b, seq_len, d=1024] + + assert text_memory.shape[1] == inputs_embeds.shape[1] + # Invert attention mask because its the opposite in pytorch transformer + text_attention_mask = text_attention_mask.ne(1) + # Transpose memory because pytorch's attention expects sequence first + text_memory = text_memory.transpose(0, 1) + # Resize the encoder hidden states to be of the same d_model as the decoder + text_memory_resized = self.resizer(text_memory) + else: + # The text is already encoded, use as is. + text_attention_mask, text_memory_resized, tokenized = text + inputs_embeds = tokenized["inputs_embeds"] + assert input_boxes is None or len(input_boxes) == 0, "Can't replace boxes in text if it's already encoded" + + # Note that the input_embeds are returned in pytorch's convention (sequence first) + return ( + text_attention_mask, + text_memory_resized, + inputs_embeds.transpose(0, 1), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/vitdet.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/vitdet.py new file mode 100644 index 0000000000000000000000000000000000000000..e15272d149e603747559739dc0fae089e5114f74 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/vitdet.py @@ -0,0 +1,549 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved + +""" +ViTDet backbone adapted from Detectron2. +This module implements Vision Transformer (ViT) backbone for object detection. + +Rope embedding code adopted from: +1. https://github.com/meta-llama/codellama/blob/main/llama/model.py +2. https://github.com/naver-ai/rope-vit +3. https://github.com/lucidrains/rotary-embedding-torch +""" + +from __future__ import annotations + +import math +from functools import partial +from typing import Callable + +import torch +import torch.nn.functional as F +from torch import Tensor, nn +from torch.utils import checkpoint + +from ultralytics.models.sam.modules.blocks import PatchEmbed +from ultralytics.models.sam.modules.utils import ( + apply_rotary_enc, + compute_axial_cis, + concat_rel_pos, + get_abs_pos, + window_partition, + window_unpartition, +) +from ultralytics.utils.checks import check_requirements + +from .model_misc import LayerScale + + +class Attention(nn.Module): + """Multi-head Attention block with relative position embeddings and 2d-rope.""" + + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + input_size: tuple[int, int] | None = None, + cls_token: bool = False, + use_rope: bool = False, + rope_theta: float = 10000.0, + rope_pt_size: tuple[int, int] | None = None, + rope_interp: bool = False, + ): + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + input_size (tuple[int, int] or None): Input resolution for calculating the relative positional parameter + size or rope size. + cls_token (bool): Whether a cls_token is present. + use_rope (bool): Whether to use rope 2d (independent of use_rel_pos, as it can be used together). + rope_theta (float): Control frequencies of rope. + rope_pt_size (tuple[int, int] or None): Size of rope in previous stage of training, needed for interpolation + or tiling. + rope_interp (bool): Whether to interpolate (or extrapolate) rope to match input size. + """ + super().__init__() + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim**-0.5 + self.cls_token = cls_token + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim) + + # rel_pos embeddings and rope + self.use_rel_pos = use_rel_pos + self.input_size = input_size + + self.use_rope = use_rope + self.rope_theta = rope_theta + self.rope_pt_size = rope_pt_size + self.rope_interp = rope_interp + + # init rel_pos embeddings and rope + self._setup_rel_pos(rel_pos_zero_init, input_size) + self._setup_rope_freqs(input_size) + + def _setup_rel_pos(self, rel_pos_zero_init: bool = True, input_size: tuple[int, int] | None = None) -> None: + """Setup relative positional embeddings.""" + if not self.use_rel_pos: + self.rel_pos_h = None + self.rel_pos_w = None + return + + assert input_size is not None + assert self.cls_token is False, "not supported" + # initialize relative positional embeddings + self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, self.head_dim)) + self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, self.head_dim)) + + if not rel_pos_zero_init: + nn.init.trunc_normal_(self.rel_pos_h, std=0.02) + nn.init.trunc_normal_(self.rel_pos_w, std=0.02) + + # Precompute the relative coords + H, W = input_size + q_coords = torch.arange(H)[:, None] + k_coords = torch.arange(W)[None, :] + relative_coords = (q_coords - k_coords) + (H - 1) + self.relative_coords = relative_coords.long() + + def _setup_rope_freqs(self, input_size: tuple[int, int] | None = None) -> None: + """Setup 2d-rope frequencies.""" + if not self.use_rope: + self.freqs_cis = None + return + + assert input_size is not None + # determine rope input size + if self.rope_pt_size is None: + self.rope_pt_size = input_size + + # initialize 2d rope freqs + self.compute_cis = partial( + compute_axial_cis, + dim=self.head_dim, + theta=self.rope_theta, + ) + + # interpolate rope + scale_pos = 1.0 + if self.rope_interp: + scale_pos = self.rope_pt_size[0] / input_size[0] + # get scaled freqs_cis + freqs_cis = self.compute_cis( + end_x=input_size[0], + end_y=input_size[1], + scale_pos=scale_pos, + ) + if self.cls_token: + t = torch.zeros( + self.head_dim // 2, + dtype=torch.float32, + device=freqs_cis.device, + ) + cls_freqs_cis = torch.polar(torch.ones_like(t), t)[None, :] + freqs_cis = torch.cat([cls_freqs_cis, freqs_cis], dim=0) + + self.freqs_cis = freqs_cis + + def _apply_rope(self, q, k) -> tuple[Tensor, Tensor]: + """Apply 2d-rope to q and k.""" + if not self.use_rope: + return q, k + + assert self.freqs_cis is not None + return apply_rotary_enc(q, k, freqs_cis=self.freqs_cis.to(q.device)) + + def forward(self, x: Tensor) -> Tensor: + """Forward pass of attention block.""" + s = 1 if self.cls_token else 0 # used to exclude cls_token + if x.ndim == 4: + B, H, W, _ = x.shape + assert s == 0 # no cls_token + L = H * W + ndim = 4 + else: + assert x.ndim == 3 + B, L, _ = x.shape + ndim = 3 + H = W = math.sqrt(L - s) + + # qkv with shape (3, B, nHead, L, C) + qkv = self.qkv(x).reshape(B, L, 3, self.num_heads, -1) + # q, k, v with shape (B, nHead, L, C) + q, k, v = qkv.permute(2, 0, 3, 1, 4).unbind(0) + + # handle rope and rel pos embeddings + q, k = self._apply_rope(q, k) + if self.use_rel_pos: + q, k = concat_rel_pos( + q.flatten(0, 1), + k.flatten(0, 1), + (H, W), + x.shape[1:3], + self.rel_pos_h, + self.rel_pos_w, + rescale=True, + relative_coords=self.relative_coords, + ) + + # sdpa expects [B, nheads, H*W, C] so we transpose back + q = q.reshape(B, self.num_heads, H * W, -1) + k = k.reshape(B, self.num_heads, H * W, -1) + + x = F.scaled_dot_product_attention(q, k, v) + + if ndim == 4: + x = x.view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1) + else: + x = x.view(B, self.num_heads, L, -1).permute(0, 2, 1, 3).reshape(B, L, -1) + + x = self.proj(x) + + return x + + +class Block(nn.Module): + """Transformer blocks with support of window attention.""" + + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + drop_path: float = 0.0, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + act_layer: Callable[..., nn.Module] = nn.GELU, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + input_size: tuple[int, int] | None = None, + use_rope: bool = False, + rope_pt_size: tuple[int, int] | None = None, + rope_interp: bool = False, + cls_token: bool = False, + dropout: float = 0.0, + init_values: float | None = None, + ): + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + drop_path (float): Stochastic depth rate. + norm_layer (Callable): Normalization layer constructor. + act_layer (Callable): Activation layer constructor. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. If it equals 0, then not use window attention. + input_size (tuple[int, int] | None): Input resolution for calculating the relative positional parameter + size. + use_rope (bool): Whether to use rope 2d (independent of use_rel_pos, as it can be used together). + rope_pt_size (tuple[int, int] | None): Size of rope in previous stage of training, needed for interpolation + or tiling. + rope_interp (bool): Whether to interpolate (or extrapolate) rope to match target input size, expected to + specify source size as rope_pt_size. + cls_token (bool): Whether a cls_token is present. + dropout (float): Dropout rate. + init_values (float | None): Layer scale init, None for no layer scale. + """ + super().__init__() + + check_requirements("timm") + from timm.layers import DropPath, Mlp + + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + input_size=input_size if window_size == 0 else (window_size, window_size), + use_rope=use_rope, + rope_pt_size=rope_pt_size, + rope_interp=rope_interp, + cls_token=cls_token, + ) + self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.norm2 = norm_layer(dim) + self.mlp = Mlp( + in_features=dim, + hidden_features=int(dim * mlp_ratio), + act_layer=act_layer, + drop=(dropout, 0.0), + ) + self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() + self.dropout = nn.Dropout(dropout) + self.window_size = window_size + + def forward(self, x: Tensor) -> Tensor: + """Forward pass of the transformer block.""" + shortcut = x + x = self.norm1(x) + # Window partition + if self.window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, self.window_size) + + x = self.ls1(self.attn(x)) + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, self.window_size, pad_hw, (H, W)) + + x = shortcut + self.dropout(self.drop_path(x)) + x = x + self.dropout(self.drop_path(self.ls2(self.mlp(self.norm2(x))))) + + return x + + +class ViT(nn.Module): + """This module implements Vision Transformer (ViT) backbone in :paper:`vitdet`. "Exploring Plain Vision Transformer + Backbones for Object Detection", https://arxiv.org/abs/2203.16527. + """ + + def __init__( + self, + img_size: int = 1024, + patch_size: int = 16, + in_chans: int = 3, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + drop_path_rate: float = 0.0, + norm_layer: Callable[..., nn.Module] | str = "LayerNorm", + act_layer: Callable[..., nn.Module] = nn.GELU, + use_abs_pos: bool = True, + tile_abs_pos: bool = True, + rel_pos_blocks: tuple[int, ...] | bool = (2, 5, 8, 11), + rel_pos_zero_init: bool = True, + window_size: int = 14, + global_att_blocks: tuple[int, ...] = (2, 5, 8, 11), + use_rope: bool = False, + rope_pt_size: int | None = None, + use_interp_rope: bool = False, + pretrain_img_size: int = 224, + pretrain_use_cls_token: bool = True, + retain_cls_token: bool = True, + dropout: float = 0.0, + return_interm_layers: bool = False, + init_values: float | None = None, # for layerscale + ln_pre: bool = False, + ln_post: bool = False, + bias_patch_embed: bool = True, + compile_mode: str | None = None, + use_act_checkpoint: bool = True, + ): + """ + Args: + img_size (int): Input image size. Only relevant for rel pos or rope. + patch_size (int): Patch size. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + depth (int): Depth of ViT. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + drop_path_rate (float): Stochastic depth rate. + norm_layer (Callable or str): Normalization layer constructor or name. + act_layer (Callable): Activation layer constructor. + use_abs_pos (bool): If True, use absolute positional embeddings. + tile_abs_pos (bool): If True, tile absolute positional embeddings instead of interpolation. + rel_pos_blocks (tuple[int, ...] | bool): Blocks which have rel pos embeddings. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. + global_att_blocks (tuple[int, ...]): Indexes for blocks using global attention (other blocks use window + attention). + use_rope (bool): Whether to use rope 2d (independent of rel_pos_blocks, as it can be used together). + rope_pt_size (int | None): Size of rope in previous stage of training, needed for interpolation or tiling. + use_interp_rope (bool): Whether to interpolate (or extrapolate) rope to match target input size, expected to + specify source size as rope_pt_size. + pretrain_img_size (int): Input image size for pretraining models. + pretrain_use_cls_token (bool): If True, pretraining models use class token. + retain_cls_token (bool): Whether cls_token should be retained. + dropout (float): Dropout rate. Applied in residual blocks of attn, mlp and inside the mlp. + return_interm_layers (bool): Whether to return intermediate layers (all global attention blocks). + init_values (float | None): Layer scale init, None for no layer scale. + ln_pre (bool): If True, apply layer norm before transformer blocks. + ln_post (bool): If True, apply layer norm after transformer blocks. + bias_patch_embed (bool): If True, use bias in conv for patch embed. + compile_mode (str | None): Mode to compile the forward, or None to disable. + use_act_checkpoint (bool): If True, use activation checkpointing. + """ + super().__init__() + self.pretrain_use_cls_token = pretrain_use_cls_token + + window_block_indexes = [i for i in range(depth) if i not in global_att_blocks] + self.full_attn_ids = list(global_att_blocks) + self.rel_pos_blocks = [False] * depth + if isinstance(rel_pos_blocks, bool) and rel_pos_blocks: + self.rel_pos_blocks = [True] * depth + else: + for i in rel_pos_blocks: + self.rel_pos_blocks[i] = True + + self.retain_cls_token = retain_cls_token + if self.retain_cls_token: + assert pretrain_use_cls_token + assert len(window_block_indexes) == 0, "windowing not supported with cls token" + + assert sum(self.rel_pos_blocks) == 0, "rel pos not supported with cls token" + + scale = embed_dim**-0.5 + self.class_embedding = nn.Parameter(scale * torch.randn(1, 1, embed_dim)) + + if isinstance(norm_layer, str): + norm_layer = partial(getattr(nn, norm_layer), eps=1e-5) + + self.patch_embed = PatchEmbed( + kernel_size=(patch_size, patch_size), + stride=(patch_size, patch_size), + in_chans=in_chans, + embed_dim=embed_dim, + bias=bias_patch_embed, + ) + + # Handle absolute positional embedding + self.tile_abs_pos = tile_abs_pos + self.use_abs_pos = use_abs_pos + if self.tile_abs_pos: + assert self.use_abs_pos + + if self.use_abs_pos: + # Initialize absolute positional embedding with pretrain image size. + num_patches = (pretrain_img_size // patch_size) * (pretrain_img_size // patch_size) + num_positions = (num_patches + 1) if pretrain_use_cls_token else num_patches + self.pos_embed = nn.Parameter(torch.zeros(1, num_positions, embed_dim)) + else: + self.pos_embed = None + + # stochastic depth decay rule + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] + + self.patch_size = patch_size + self.window_size = window_size + self.blocks = nn.ModuleList() + cur_stage = 1 + for i in range(depth): + block = Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + drop_path=dpr[i], + norm_layer=norm_layer, + act_layer=act_layer, + use_rel_pos=self.rel_pos_blocks[i], + rel_pos_zero_init=rel_pos_zero_init, + window_size=window_size if i in window_block_indexes else 0, + input_size=(img_size // patch_size, img_size // patch_size), + use_rope=use_rope, + rope_pt_size=((window_size, window_size) if rope_pt_size is None else (rope_pt_size, rope_pt_size)), + rope_interp=use_interp_rope, + cls_token=self.retain_cls_token, + dropout=dropout, + init_values=init_values, + ) + + if i not in window_block_indexes: + cur_stage += 1 + + self.use_act_checkpoint = use_act_checkpoint + + self.blocks.append(block) + + self.return_interm_layers = return_interm_layers + self.channel_list = [embed_dim] * len(self.full_attn_ids) if return_interm_layers else [embed_dim] + + if self.pos_embed is not None: + nn.init.trunc_normal_(self.pos_embed, std=0.02) + + self.ln_pre = norm_layer(embed_dim) if ln_pre else nn.Identity() + self.ln_post = norm_layer(embed_dim) if ln_post else nn.Identity() + + self.apply(self._init_weights) + + if compile_mode is not None: + self.forward = torch.compile(self.forward, mode=compile_mode, fullgraph=True) + if self.use_act_checkpoint and self.training: + torch._dynamo.config.optimize_ddp = False + + @staticmethod + def _init_weights(m: nn.Module) -> None: + """Initialize the weights.""" + if isinstance(m, nn.Linear): + nn.init.trunc_normal_(m.weight, std=0.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + def forward(self, x: torch.Tensor) -> list[torch.Tensor]: + """Vit forward path and get feature maps.""" + x = self.patch_embed(x) + h, w = x.shape[1], x.shape[2] + + s = 0 + if self.retain_cls_token: + # If cls_token is retained, we don't + # maintain spatial shape + x = torch.cat([self.class_embedding, x.flatten(1, 2)], dim=1) + s = 1 + + if self.pos_embed is not None: + x = x + get_abs_pos( + self.pos_embed, + self.pretrain_use_cls_token, + (h, w), + self.retain_cls_token, + tiling=self.tile_abs_pos, + ) + + x = self.ln_pre(x) + + outputs = [] + for i, blk in enumerate(self.blocks): + if self.use_act_checkpoint and self.training: + x = checkpoint.checkpoint(blk, x, use_reentrant=False) + else: + x = blk(x) + if (i == self.full_attn_ids[-1]) or (self.return_interm_layers and i in self.full_attn_ids): + if i == self.full_attn_ids[-1]: + x = self.ln_post(x) + + feats = x[:, s:] + if feats.ndim == 4: + feats = feats.permute(0, 3, 1, 2) + else: + assert feats.ndim == 3 + h = w = math.sqrt(feats.shape[1]) + feats = feats.reshape(feats.shape[0], h, w, feats.shape[-1]).permute(0, 3, 1, 2) + + outputs.append(feats) + + return outputs + + def set_imgsz(self, imgsz: list[int] | None = None): + """Setup rel pos embeddings and rope freqs for a new input image size.""" + imgsz = imgsz if imgsz is not None else [1008, 1008] + for block in self.blocks: + if block.window_size != 0: + continue + block.attn._setup_rel_pos(input_size=(imgsz[0] // self.patch_size, imgsz[1] // self.patch_size)) + block.attn._setup_rope_freqs(input_size=(imgsz[0] // self.patch_size, imgsz[1] // self.patch_size)) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/vl_combiner.py b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/vl_combiner.py new file mode 100644 index 0000000000000000000000000000000000000000..47886f9904d85ebaa7e9b9ac767b211a32c93422 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/sam/sam3/vl_combiner.py @@ -0,0 +1,165 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved + +"""Provides utility to combine a vision backbone with a language backbone.""" + +from __future__ import annotations + +from copy import copy + +import torch +from torch import nn +from torch.nn.attention import SDPBackend, sdpa_kernel + +from .necks import Sam3DualViTDetNeck + + +class SAM3VLBackbone(nn.Module): + """This backbone combines a vision backbone and a language backbone without fusion. As such it is more of a + convenience wrapper to handle the two backbones together. + + It adds support for activation checkpointing and compilation. + """ + + def __init__( + self, + visual: Sam3DualViTDetNeck, + text, + compile_visual: bool = False, + act_ckpt_whole_vision_backbone: bool = False, + act_ckpt_whole_language_backbone: bool = False, + scalp=0, + ): + """Initialize the backbone combiner. + + Args: + visual (Sam3DualViTDetNeck): The vision backbone to use. + text (nn.Module): The text encoder to use. + compile_visual (bool): Whether to `torch.compile` the vision backbone. + act_ckpt_whole_vision_backbone (bool): Whether to checkpoint activations for the whole vision backbone. + act_ckpt_whole_language_backbone (bool): Whether to checkpoint activations for the whole language backbone. + scalp (int): Number of trailing (lowest-resolution) feature levels to drop from the backbone output. + """ + super().__init__() + self.vision_backbone: Sam3DualViTDetNeck = torch.compile(visual) if compile_visual else visual + self.language_backbone = text + self.scalp = scalp + # allow running activation checkpointing on the entire vision and language backbones + self.act_ckpt_whole_vision_backbone = act_ckpt_whole_vision_backbone + self.act_ckpt_whole_language_backbone = act_ckpt_whole_language_backbone + + def forward( + self, + samples: torch.Tensor, + captions: list[str], + input_boxes: torch.Tensor = None, + additional_text: list[str] | None = None, + ): + """Forward pass of the backbone combiner. + + Args: + samples (torch.Tensor): The input images. + captions (list[str]): The input captions. + input_boxes (torch.Tensor, optional): When the text contains box place-holders, the tensor containing their + spatial features. + additional_text (list[str], optional): Extra text (different from the captions) to encode in the same + backbone forward pass. + + Returns: + (dict): Output dictionary with the following keys: `vision_features` (the output of the vision backbone), + `language_features` (the output of the language backbone), `language_mask` (the attention mask of the + language backbone), `vision_pos_enc` (the positional encoding of the vision + backbone) and, when `additional_text` is provided, `additional_text_features` and + `additional_text_mask` (the language backbone output and attention mask for the additional text). + """ + output = self.forward_image(samples) + output.update(self.forward_text(captions, input_boxes, additional_text)) + return output + + def forward_image(self, samples: torch.Tensor): + """Forward pass of the vision backbone and get both SAM3 and SAM2 features.""" + # Forward through backbone + sam3_features, sam3_pos, sam2_features, sam2_pos = self.vision_backbone.forward(samples) + if self.scalp > 0: + # Discard the lowest resolution features + sam3_features, sam3_pos = ( + sam3_features[: -self.scalp], + sam3_pos[: -self.scalp], + ) + if sam2_features is not None and sam2_pos is not None: + sam2_features, sam2_pos = ( + sam2_features[: -self.scalp], + sam2_pos[: -self.scalp], + ) + + sam2_output = None + + if sam2_features is not None and sam2_pos is not None: + sam2_src = sam2_features[-1] + sam2_output = { + "vision_features": sam2_src, + "vision_pos_enc": sam2_pos, + "backbone_fpn": sam2_features, + } + + sam3_src = sam3_features[-1] + return { + "vision_features": sam3_src, + "vision_pos_enc": sam3_pos, + "backbone_fpn": sam3_features, + "sam2_backbone_out": sam2_output, + } + + def forward_image_sam2(self, samples: torch.Tensor): + """Forward pass of the vision backbone to get SAM2 features only.""" + xs = self.vision_backbone.trunk(samples) + x = xs[-1] # simpleFPN + + assert self.vision_backbone.sam2_convs is not None, "SAM2 neck is not available." + sam2_features, sam2_pos = self.vision_backbone.sam_forward_feature_levels(x, self.vision_backbone.sam2_convs) + + if self.scalp > 0: + # Discard the lowest resolution features + sam2_features, sam2_pos = ( + sam2_features[: -self.scalp], + sam2_pos[: -self.scalp], + ) + + return { + "vision_features": sam2_features[-1], + "vision_pos_enc": sam2_pos, + "backbone_fpn": sam2_features, + } + + def forward_text(self, captions, input_boxes=None, additional_text=None): + """Forward pass of the text encoder.""" + output = {} + + # Forward through text_encoder + text_to_encode = copy(captions) + if additional_text is not None: + # if there are additional_text, we piggy-back them into this forward. + # They'll be used later for output alignment + text_to_encode += additional_text + + with sdpa_kernel([SDPBackend.MATH, SDPBackend.EFFICIENT_ATTENTION, SDPBackend.FLASH_ATTENTION]): + text_attention_mask, text_memory, text_embeds = self.language_backbone(text_to_encode, input_boxes) + + if additional_text is not None: + output["additional_text_features"] = text_memory[:, -len(additional_text) :] + output["additional_text_mask"] = text_attention_mask[-len(additional_text) :] + + text_memory = text_memory[:, : len(captions)] + text_attention_mask = text_attention_mask[: len(captions)] + text_embeds = text_embeds[:, : len(captions)] + output["language_features"] = text_memory + output["language_mask"] = text_attention_mask + output["language_embeds"] = text_embeds # Text embeddings before forward to the encoder + + return output + + def set_imgsz(self, imgsz: list[int] | None = None): + """Set the image size for the vision backbone.""" + imgsz = imgsz if imgsz is not None else [1008, 1008] + self.vision_backbone.set_imgsz(imgsz) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/utils/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..77a19dcf0f8093de419453747db2e7e719f96349 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/utils/__init__.py @@ -0,0 +1 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/utils/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12f0567885cb82bf063f527b6f66088f4b995570 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/utils/__pycache__/loss.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/utils/__pycache__/loss.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f1812d0ea571390ad7096423339b548f697699c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/utils/__pycache__/loss.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/utils/__pycache__/ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/utils/__pycache__/ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44645b5b33c2e89d1353cf9505cade561ae48c61 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/utils/__pycache__/ops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/utils/loss.py b/.venv/lib/python3.12/site-packages/ultralytics/models/utils/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ad087262a10bf30dd3f60e6f3be343415cd587 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/utils/loss.py @@ -0,0 +1,462 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn + +from ultralytics.utils.loss import FocalLoss, VarifocalLoss +from ultralytics.utils.metrics import bbox_iou + +from .ops import HungarianMatcher + + +class DETRLoss(nn.Module): + """DETR (DEtection TRansformer) Loss class for calculating various loss components. + + This class computes classification loss, bounding box loss, GIoU loss, and optionally auxiliary losses for the DETR + object detection model. + + Attributes: + nc (int): Number of classes. + loss_gain (dict[str, float]): Coefficients for different loss components. + aux_loss (bool): Whether to compute auxiliary losses. + use_fl (bool): Whether to use FocalLoss. + use_vfl (bool): Whether to use VarifocalLoss. + use_uni_match (bool): Whether to use a fixed layer for auxiliary branch label assignment. + uni_match_ind (int): Index of fixed layer to use if use_uni_match is True. + matcher (HungarianMatcher): Object to compute matching cost and indices. + fl (FocalLoss | None): Focal Loss object if use_fl is True, otherwise None. + vfl (VarifocalLoss | None): Varifocal Loss object if use_vfl is True, otherwise None. + device (torch.device): Device on which tensors are stored. + """ + + def __init__( + self, + nc: int = 80, + loss_gain: dict[str, float] | None = None, + aux_loss: bool = True, + use_fl: bool = True, + use_vfl: bool = False, + use_uni_match: bool = False, + uni_match_ind: int = 0, + gamma: float = 1.5, + alpha: float = 0.25, + ): + """Initialize DETR loss function with customizable components and gains. + + Uses default loss_gain if not provided. Initializes HungarianMatcher with preset cost gains. Supports auxiliary + losses and various loss types. + + Args: + nc (int): Number of classes. + loss_gain (dict[str, float], optional): Coefficients for different loss components. + aux_loss (bool): Whether to use auxiliary losses from each decoder layer. + use_fl (bool): Whether to use FocalLoss. + use_vfl (bool): Whether to use VarifocalLoss. + use_uni_match (bool): Whether to use fixed layer for auxiliary branch label assignment. + uni_match_ind (int): Index of fixed layer for uni_match. + gamma (float): The focusing parameter that controls how much the loss focuses on hard-to-classify examples. + alpha (float): The balancing factor used to address class imbalance. + """ + super().__init__() + + if loss_gain is None: + loss_gain = {"class": 1, "bbox": 5, "giou": 2, "no_object": 0.1, "mask": 1, "dice": 1} + self.nc = nc + self.matcher = HungarianMatcher(cost_gain={"class": 2, "bbox": 5, "giou": 2}) + self.loss_gain = loss_gain + self.aux_loss = aux_loss + self.fl = FocalLoss(gamma, alpha) if use_fl else None + self.vfl = VarifocalLoss(gamma, alpha) if use_vfl else None + + self.use_uni_match = use_uni_match + self.uni_match_ind = uni_match_ind + self.device = None + + def _get_loss_class( + self, pred_scores: torch.Tensor, targets: torch.Tensor, gt_scores: torch.Tensor, num_gts: int, postfix: str = "" + ) -> dict[str, torch.Tensor]: + """Compute classification loss based on predictions, target values, and ground truth scores. + + Args: + pred_scores (torch.Tensor): Predicted class scores with shape (B, N, C). + targets (torch.Tensor): Target class indices with shape (B, N). + gt_scores (torch.Tensor): Ground truth confidence scores with shape (B, N). + num_gts (int): Number of ground truth objects. + postfix (str, optional): String to append to the loss name for identification in multi-loss scenarios. + + Returns: + (dict[str, torch.Tensor]): Dictionary containing classification loss value. + + Notes: + The function supports different classification loss types: + - Varifocal Loss (if self.vfl is not None and num_gts > 0) + - Focal Loss (if self.fl is not None) + - BCE Loss (default fallback) + """ + # Logits: [b, query, num_classes], gt_class: list[[n, 1]] + name_class = f"loss_class{postfix}" + bs, nq = pred_scores.shape[:2] + # one_hot = F.one_hot(targets, self.nc + 1)[..., :-1] # (bs, num_queries, num_classes) + one_hot = torch.zeros((bs, nq, self.nc + 1), dtype=torch.int64, device=targets.device) + one_hot.scatter_(2, targets.unsqueeze(-1), 1) + one_hot = one_hot[..., :-1] + gt_scores = gt_scores.view(bs, nq, 1) * one_hot + + if self.fl: + if num_gts and self.vfl: + loss_cls = self.vfl(pred_scores, gt_scores, one_hot) + else: + loss_cls = self.fl(pred_scores, one_hot.float()) + loss_cls /= max(num_gts, 1) / nq + else: + loss_cls = nn.BCEWithLogitsLoss(reduction="none")(pred_scores, gt_scores).mean(1).sum() # YOLO CLS loss + + return {name_class: loss_cls.squeeze() * self.loss_gain["class"]} + + def _get_loss_bbox( + self, pred_bboxes: torch.Tensor, gt_bboxes: torch.Tensor, postfix: str = "" + ) -> dict[str, torch.Tensor]: + """Compute bounding box and GIoU losses for predicted and ground truth bounding boxes. + + Args: + pred_bboxes (torch.Tensor): Predicted bounding boxes with shape (N, 4). + gt_bboxes (torch.Tensor): Ground truth bounding boxes with shape (N, 4). + postfix (str, optional): String to append to the loss names for identification in multi-loss scenarios. + + Returns: + (dict[str, torch.Tensor]): Dictionary containing: + - loss_bbox{postfix}: L1 loss between predicted and ground truth boxes, scaled by the bbox loss gain. + - loss_giou{postfix}: GIoU loss between predicted and ground truth boxes, scaled by the giou loss gain. + + Notes: + If no ground truth boxes are provided (empty list), zero-valued tensors are returned for both losses. + """ + # Boxes: [b, query, 4], gt_bbox: list[[n, 4]] + name_bbox = f"loss_bbox{postfix}" + name_giou = f"loss_giou{postfix}" + + loss = {} + if len(gt_bboxes) == 0: + # WARNING: lines below prevent Multi-GPU DDP 'unused gradient' PyTorch errors, do not remove + loss[name_bbox] = pred_bboxes[..., :0].sum() + loss[name_giou] = pred_bboxes[..., :0].sum() + return loss + + loss[name_bbox] = self.loss_gain["bbox"] * F.l1_loss(pred_bboxes, gt_bboxes, reduction="sum") / len(gt_bboxes) + loss[name_giou] = 1.0 - bbox_iou(pred_bboxes, gt_bboxes, xywh=True, GIoU=True) + loss[name_giou] = loss[name_giou].sum() / len(gt_bboxes) + loss[name_giou] = self.loss_gain["giou"] * loss[name_giou] + return {k: v.squeeze() for k, v in loss.items()} + + # This function is for future RT-DETR Segment models + # def _get_loss_mask(self, masks, gt_mask, match_indices, postfix=''): + # # masks: [b, query, h, w], gt_mask: list[[n, H, W]] + # name_mask = f'loss_mask{postfix}' + # name_dice = f'loss_dice{postfix}' + # + # loss = {} + # if sum(len(a) for a in gt_mask) == 0: + # loss[name_mask] = torch.tensor(0., device=self.device) + # loss[name_dice] = torch.tensor(0., device=self.device) + # return loss + # + # num_gts = len(gt_mask) + # src_masks, target_masks = self._get_assigned_bboxes(masks, gt_mask, match_indices) + # src_masks = F.interpolate(src_masks.unsqueeze(0), size=target_masks.shape[-2:], mode='bilinear')[0] + # # TODO: torch does not have `sigmoid_focal_loss`, but it's not urgent since we don't use mask branch for now. + # loss[name_mask] = self.loss_gain['mask'] * F.sigmoid_focal_loss(src_masks, target_masks, + # torch.tensor([num_gts], dtype=torch.float32)) + # loss[name_dice] = self.loss_gain['dice'] * self._dice_loss(src_masks, target_masks, num_gts) + # return loss + + # This function is for future RT-DETR Segment models + # @staticmethod + # def _dice_loss(inputs, targets, num_gts): + # inputs = F.sigmoid(inputs).flatten(1) + # targets = targets.flatten(1) + # numerator = 2 * (inputs * targets).sum(1) + # denominator = inputs.sum(-1) + targets.sum(-1) + # loss = 1 - (numerator + 1) / (denominator + 1) + # return loss.sum() / num_gts + + def _get_loss_aux( + self, + pred_bboxes: torch.Tensor, + pred_scores: torch.Tensor, + gt_bboxes: torch.Tensor, + gt_cls: torch.Tensor, + gt_groups: list[int], + match_indices: list[tuple] | None = None, + postfix: str = "", + masks: torch.Tensor | None = None, + gt_mask: torch.Tensor | None = None, + ) -> dict[str, torch.Tensor]: + """Get auxiliary losses for intermediate decoder layers. + + Args: + pred_bboxes (torch.Tensor): Predicted bounding boxes from auxiliary layers. + pred_scores (torch.Tensor): Predicted scores from auxiliary layers. + gt_bboxes (torch.Tensor): Ground truth bounding boxes. + gt_cls (torch.Tensor): Ground truth classes. + gt_groups (list[int]): Number of ground truths per image. + match_indices (list[tuple], optional): Pre-computed matching indices. + postfix (str, optional): String to append to loss names. + masks (torch.Tensor, optional): Predicted masks if using segmentation. + gt_mask (torch.Tensor, optional): Ground truth masks if using segmentation. + + Returns: + (dict[str, torch.Tensor]): Dictionary of auxiliary losses. + """ + # NOTE: loss class, bbox, giou, mask, dice + loss = torch.zeros(5 if masks is not None else 3, device=pred_bboxes.device) + if match_indices is None and self.use_uni_match: + match_indices = self.matcher( + pred_bboxes[self.uni_match_ind], + pred_scores[self.uni_match_ind], + gt_bboxes, + gt_cls, + gt_groups, + masks=masks[self.uni_match_ind] if masks is not None else None, + gt_mask=gt_mask, + ) + for i, (aux_bboxes, aux_scores) in enumerate(zip(pred_bboxes, pred_scores)): + aux_masks = masks[i] if masks is not None else None + loss_ = self._get_loss( + aux_bboxes, + aux_scores, + gt_bboxes, + gt_cls, + gt_groups, + masks=aux_masks, + gt_mask=gt_mask, + postfix=postfix, + match_indices=match_indices, + ) + loss[0] += loss_[f"loss_class{postfix}"] + loss[1] += loss_[f"loss_bbox{postfix}"] + loss[2] += loss_[f"loss_giou{postfix}"] + # if masks is not None and gt_mask is not None: + # loss_ = self._get_loss_mask(aux_masks, gt_mask, match_indices, postfix) + # loss[3] += loss_[f'loss_mask{postfix}'] + # loss[4] += loss_[f'loss_dice{postfix}'] + + loss = { + f"loss_class_aux{postfix}": loss[0], + f"loss_bbox_aux{postfix}": loss[1], + f"loss_giou_aux{postfix}": loss[2], + } + # if masks is not None and gt_mask is not None: + # loss[f'loss_mask_aux{postfix}'] = loss[3] + # loss[f'loss_dice_aux{postfix}'] = loss[4] + return loss + + @staticmethod + def _get_index(match_indices: list[tuple]) -> tuple[tuple[torch.Tensor, torch.Tensor], torch.Tensor]: + """Extract batch indices, source indices, and destination indices from match indices. + + Args: + match_indices (list[tuple]): List of tuples containing matched indices. + + Returns: + batch_idx (tuple[torch.Tensor, torch.Tensor]): Tuple containing (batch_idx, src_idx). + dst_idx (torch.Tensor): Destination indices. + """ + batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(match_indices)]) + src_idx = torch.cat([src for (src, _) in match_indices]) + dst_idx = torch.cat([dst for (_, dst) in match_indices]) + return (batch_idx, src_idx), dst_idx + + def _get_assigned_bboxes( + self, pred_bboxes: torch.Tensor, gt_bboxes: torch.Tensor, match_indices: list[tuple] + ) -> tuple[torch.Tensor, torch.Tensor]: + """Assign predicted bounding boxes to ground truth bounding boxes based on match indices. + + Args: + pred_bboxes (torch.Tensor): Predicted bounding boxes. + gt_bboxes (torch.Tensor): Ground truth bounding boxes. + match_indices (list[tuple]): List of tuples containing matched indices. + + Returns: + pred_assigned (torch.Tensor): Assigned predicted bounding boxes. + gt_assigned (torch.Tensor): Assigned ground truth bounding boxes. + """ + pred_assigned = torch.cat( + [ + t[i] if len(i) > 0 else torch.zeros(0, t.shape[-1], device=self.device) + for t, (i, _) in zip(pred_bboxes, match_indices) + ] + ) + gt_assigned = torch.cat( + [ + t[j] if len(j) > 0 else torch.zeros(0, t.shape[-1], device=self.device) + for t, (_, j) in zip(gt_bboxes, match_indices) + ] + ) + return pred_assigned, gt_assigned + + def _get_loss( + self, + pred_bboxes: torch.Tensor, + pred_scores: torch.Tensor, + gt_bboxes: torch.Tensor, + gt_cls: torch.Tensor, + gt_groups: list[int], + masks: torch.Tensor | None = None, + gt_mask: torch.Tensor | None = None, + postfix: str = "", + match_indices: list[tuple] | None = None, + ) -> dict[str, torch.Tensor]: + """Calculate losses for a single prediction layer. + + Args: + pred_bboxes (torch.Tensor): Predicted bounding boxes. + pred_scores (torch.Tensor): Predicted class scores. + gt_bboxes (torch.Tensor): Ground truth bounding boxes. + gt_cls (torch.Tensor): Ground truth classes. + gt_groups (list[int]): Number of ground truths per image. + masks (torch.Tensor, optional): Predicted masks if using segmentation. + gt_mask (torch.Tensor, optional): Ground truth masks if using segmentation. + postfix (str, optional): String to append to loss names. + match_indices (list[tuple], optional): Pre-computed matching indices. + + Returns: + (dict[str, torch.Tensor]): Dictionary of losses. + """ + if match_indices is None: + match_indices = self.matcher( + pred_bboxes, pred_scores, gt_bboxes, gt_cls, gt_groups, masks=masks, gt_mask=gt_mask + ) + + idx, gt_idx = self._get_index(match_indices) + pred_bboxes, gt_bboxes = pred_bboxes[idx], gt_bboxes[gt_idx] + + bs, nq = pred_scores.shape[:2] + targets = torch.full((bs, nq), self.nc, device=pred_scores.device, dtype=gt_cls.dtype) + targets[idx] = gt_cls[gt_idx] + + gt_scores = torch.zeros([bs, nq], device=pred_scores.device) + if len(gt_bboxes): + gt_scores[idx] = bbox_iou(pred_bboxes.detach(), gt_bboxes, xywh=True).squeeze(-1) + + return { + **self._get_loss_class(pred_scores, targets, gt_scores, len(gt_bboxes), postfix), + **self._get_loss_bbox(pred_bboxes, gt_bboxes, postfix), + # **(self._get_loss_mask(masks, gt_mask, match_indices, postfix) if masks is not None and gt_mask is not None else {}) + } + + def forward( + self, + pred_bboxes: torch.Tensor, + pred_scores: torch.Tensor, + batch: dict[str, Any], + postfix: str = "", + **kwargs: Any, + ) -> dict[str, torch.Tensor]: + """Calculate loss for predicted bounding boxes and scores. + + Args: + pred_bboxes (torch.Tensor): Predicted bounding boxes, shape (L, B, N, 4). + pred_scores (torch.Tensor): Predicted class scores, shape (L, B, N, C). + batch (dict[str, Any]): Batch information containing cls, bboxes, and gt_groups. + postfix (str, optional): Postfix for loss names. + **kwargs (Any): Additional arguments, may include 'match_indices'. + + Returns: + (dict[str, torch.Tensor]): Computed losses, including main and auxiliary (if enabled). + + Notes: + Uses last elements of pred_bboxes and pred_scores for main loss, and the rest for auxiliary losses if + self.aux_loss is True. + """ + self.device = pred_bboxes.device + match_indices = kwargs.get("match_indices", None) + gt_cls, gt_bboxes, gt_groups = batch["cls"], batch["bboxes"], batch["gt_groups"] + + total_loss = self._get_loss( + pred_bboxes[-1], pred_scores[-1], gt_bboxes, gt_cls, gt_groups, postfix=postfix, match_indices=match_indices + ) + + if self.aux_loss: + total_loss.update( + self._get_loss_aux( + pred_bboxes[:-1], pred_scores[:-1], gt_bboxes, gt_cls, gt_groups, match_indices, postfix + ) + ) + + return total_loss + + +class RTDETRDetectionLoss(DETRLoss): + """Real-Time DEtection TRansformer (RT-DETR) Detection Loss class that extends the DETRLoss. + + This class computes the detection loss for the RT-DETR model, which includes the standard detection loss as well as + an additional denoising training loss when provided with denoising metadata. + """ + + def forward( + self, + preds: tuple[torch.Tensor, torch.Tensor], + batch: dict[str, Any], + dn_bboxes: torch.Tensor | None = None, + dn_scores: torch.Tensor | None = None, + dn_meta: dict[str, Any] | None = None, + ) -> dict[str, torch.Tensor]: + """Forward pass to compute detection loss with optional denoising loss. + + Args: + preds (tuple[torch.Tensor, torch.Tensor]): Tuple containing predicted bounding boxes and scores. + batch (dict[str, Any]): Batch data containing ground truth information. + dn_bboxes (torch.Tensor, optional): Denoising bounding boxes. + dn_scores (torch.Tensor, optional): Denoising scores. + dn_meta (dict[str, Any], optional): Metadata for denoising. + + Returns: + (dict[str, torch.Tensor]): Dictionary containing total loss and denoising loss if applicable. + """ + pred_bboxes, pred_scores = preds + total_loss = super().forward(pred_bboxes, pred_scores, batch) + + # Check for denoising metadata to compute denoising training loss + if dn_meta is not None: + dn_pos_idx, dn_num_group = dn_meta["dn_pos_idx"], dn_meta["dn_num_group"] + assert len(batch["gt_groups"]) == len(dn_pos_idx) + + # Get the match indices for denoising + match_indices = self.get_dn_match_indices(dn_pos_idx, dn_num_group, dn_meta["dn_gt_idx"]) + + # Compute the denoising training loss + dn_loss = super().forward(dn_bboxes, dn_scores, batch, postfix="_dn", match_indices=match_indices) + total_loss.update(dn_loss) + else: + # If no denoising metadata is provided, set denoising loss to zero + total_loss.update({f"{k}_dn": torch.tensor(0.0, device=self.device) for k in total_loss}) + + return total_loss + + @staticmethod + def get_dn_match_indices( + dn_pos_idx: list[torch.Tensor], dn_num_group: int, dn_gt_idx: list[torch.Tensor] + ) -> list[tuple[torch.Tensor, torch.Tensor]]: + """Get match indices for denoising. + + Args: + dn_pos_idx (list[torch.Tensor]): List of tensors containing positive indices for denoising. + dn_num_group (int): Number of denoising groups. + dn_gt_idx (list[torch.Tensor]): Ground truth index each image's denoising queries reconstruct. + + Returns: + (list[tuple[torch.Tensor, torch.Tensor]]): List of tuples containing matched indices for denoising. + """ + dn_match_indices = [] + for i, gt_idx in enumerate(dn_gt_idx): + gt_idx = gt_idx.repeat(dn_num_group) + assert len(dn_pos_idx[i]) == len(gt_idx), ( + f"Expected the same length, but got {len(dn_pos_idx[i])} and {len(gt_idx)} respectively." + ) + dn_match_indices.append((dn_pos_idx[i], gt_idx)) + return dn_match_indices diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/utils/ops.py b/.venv/lib/python3.12/site-packages/ultralytics/models/utils/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..93ea35b0119f665dc9adb256237238ec601bfce7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/utils/ops.py @@ -0,0 +1,331 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn + +from ultralytics.utils.metrics import bbox_iou +from ultralytics.utils.ops import linear_sum_assignment, xywh2xyxy, xyxy2xywh + + +class HungarianMatcher(nn.Module): + """A module implementing the HungarianMatcher for optimal assignment between predictions and ground truth. + + HungarianMatcher performs optimal bipartite assignment over predicted and ground truth bounding boxes using a cost + function that considers classification scores, bounding box coordinates, and optionally mask predictions. This is + used in end-to-end object detection models like DETR. + + Attributes: + cost_gain (dict[str, float]): Dictionary of cost coefficients for 'class', 'bbox', 'giou', 'mask', and 'dice' + components. + use_fl (bool): Whether to use Focal Loss for classification cost calculation. + with_mask (bool): Whether the model makes mask predictions. + num_sample_points (int): Number of sample points used in mask cost calculation. + alpha (float): Alpha factor in Focal Loss calculation. + gamma (float): Gamma factor in Focal Loss calculation. + + Methods: + forward: Compute optimal assignment between predictions and ground truths for a batch. + _cost_mask: Compute mask cost and dice cost if masks are predicted. + + Examples: + Initialize a HungarianMatcher with custom cost gains + >>> matcher = HungarianMatcher(cost_gain={"class": 2, "bbox": 5, "giou": 2}) + + Perform matching between predictions and ground truth + >>> pred_boxes = torch.rand(2, 100, 4) # batch_size=2, num_queries=100 + >>> pred_scores = torch.rand(2, 100, 80) # 80 classes + >>> gt_boxes = torch.rand(10, 4) # 10 ground truth boxes + >>> gt_classes = torch.randint(0, 80, (10,)) + >>> gt_groups = [5, 5] # 5 GT boxes per image + >>> indices = matcher(pred_boxes, pred_scores, gt_boxes, gt_classes, gt_groups) + """ + + def __init__( + self, + cost_gain: dict[str, float] | None = None, + use_fl: bool = True, + with_mask: bool = False, + num_sample_points: int = 12544, + alpha: float = 0.25, + gamma: float = 2.0, + ): + """Initialize HungarianMatcher for optimal assignment of predicted and ground truth bounding boxes. + + Args: + cost_gain (dict[str, float], optional): Dictionary of cost coefficients for different matching cost + components. Should contain keys 'class', 'bbox', 'giou', 'mask', and 'dice'. + use_fl (bool): Whether to use Focal Loss for classification cost calculation. + with_mask (bool): Whether the model makes mask predictions. + num_sample_points (int): Number of sample points used in mask cost calculation. + alpha (float): Alpha factor in Focal Loss calculation. + gamma (float): Gamma factor in Focal Loss calculation. + """ + super().__init__() + if cost_gain is None: + cost_gain = {"class": 1, "bbox": 5, "giou": 2, "mask": 1, "dice": 1} + self.cost_gain = cost_gain + self.use_fl = use_fl + self.with_mask = with_mask + self.num_sample_points = num_sample_points + self.alpha = alpha + self.gamma = gamma + + def forward( + self, + pred_bboxes: torch.Tensor, + pred_scores: torch.Tensor, + gt_bboxes: torch.Tensor, + gt_cls: torch.Tensor, + gt_groups: list[int], + masks: torch.Tensor | None = None, + gt_mask: list[torch.Tensor] | None = None, + ) -> list[tuple[torch.Tensor, torch.Tensor]]: + """Compute optimal assignment between predictions and ground truth using Hungarian algorithm. + + This method calculates matching costs based on classification scores, bounding box coordinates, and optionally + mask predictions, then finds the optimal bipartite assignment between predictions and ground truth. + + Args: + pred_bboxes (torch.Tensor): Predicted bounding boxes with shape (batch_size, num_queries, 4). + pred_scores (torch.Tensor): Predicted classification scores with shape (batch_size, num_queries, + num_classes). + gt_bboxes (torch.Tensor): Ground truth bounding boxes with shape (num_gts, 4). + gt_cls (torch.Tensor): Ground truth class labels with shape (num_gts,). + gt_groups (list[int]): Number of ground truth boxes for each image in the batch. + masks (torch.Tensor, optional): Predicted masks with shape (batch_size, num_queries, height, width). + gt_mask (list[torch.Tensor], optional): Ground truth masks, each with shape (num_masks, Height, Width). + + Returns: + (list[tuple[torch.Tensor, torch.Tensor]]): A list of size batch_size, each element is a tuple (index_i, + index_j), where index_i is the tensor of indices of the selected predictions (in order) and index_j is + the tensor of indices of the corresponding selected ground truth targets (in order). + For each batch element, it holds: len(index_i) = len(index_j) = min(num_queries, num_target_boxes). + """ + bs, nq, _ = pred_scores.shape + + if sum(gt_groups) == 0: + return [(torch.tensor([], dtype=torch.long), torch.tensor([], dtype=torch.long)) for _ in range(bs)] + + # Pad targets to compute costs within each image. + gt_bboxes = torch.nn.utils.rnn.pad_sequence(gt_bboxes.split(gt_groups), batch_first=True) + gt_cls = torch.nn.utils.rnn.pad_sequence(gt_cls.split(gt_groups), batch_first=True) + pred_scores = pred_scores.detach() + pred_scores = F.sigmoid(pred_scores) if self.use_fl else F.softmax(pred_scores, dim=-1) + pred_bboxes = pred_bboxes.detach() + + # Compute classification cost + pred_scores = pred_scores.gather(2, gt_cls[:, None].expand(-1, nq, -1)) + if self.use_fl: + neg_cost_class = (1 - self.alpha) * (pred_scores**self.gamma) * (-(1 - pred_scores + 1e-8).log()) + pos_cost_class = self.alpha * ((1 - pred_scores) ** self.gamma) * (-(pred_scores + 1e-8).log()) + cost_class = pos_cost_class - neg_cost_class + else: + cost_class = -pred_scores + + # Compute L1 cost between boxes + cost_bbox = (pred_bboxes.unsqueeze(2) - gt_bboxes.unsqueeze(1)).abs().sum(-1) + + # Compute GIoU cost between boxes within each image + cost_giou = 1.0 - bbox_iou(pred_bboxes.unsqueeze(2), gt_bboxes.unsqueeze(1), xywh=True, GIoU=True).squeeze(-1) + + # Combine costs into final cost matrix + C = ( + self.cost_gain["class"] * cost_class + + self.cost_gain["bbox"] * cost_bbox + + self.cost_gain["giou"] * cost_giou + ) + + # Add mask costs if available + if self.with_mask: + mask_cost = self._cost_mask(bs, gt_groups, masks, gt_mask).view(bs, nq, -1) + C += torch.nn.utils.rnn.pad_sequence( + [c[i].T for i, c in enumerate(mask_cost.split(gt_groups, -1))], batch_first=True + ).transpose(1, 2) + + # Set invalid values (NaNs and infinities) to 0 + C[C.isnan() | C.isinf()] = 0.0 + + C = C.cpu() + indices = [linear_sum_assignment(c[:, :n]) for c, n in zip(C, gt_groups)] + gt_groups = torch.as_tensor([0, *gt_groups[:-1]]).cumsum_(0) # (idx for queries, idx for gt) + return [ + (torch.tensor(i, dtype=torch.long), torch.tensor(j, dtype=torch.long) + gt_groups[k]) + for k, (i, j) in enumerate(indices) + ] + + # This function is for future RT-DETR Segment models + # def _cost_mask(self, bs, num_gts, masks=None, gt_mask=None): + # assert masks is not None and gt_mask is not None, 'Make sure the input has `mask` and `gt_mask`' + # # all masks share the same set of points for efficient matching + # sample_points = torch.rand([bs, 1, self.num_sample_points, 2]) + # sample_points = 2.0 * sample_points - 1.0 + # + # out_mask = F.grid_sample(masks.detach(), sample_points, align_corners=False).squeeze(-2) + # out_mask = out_mask.flatten(0, 1) + # + # tgt_mask = torch.cat(gt_mask).unsqueeze(1) + # sample_points = torch.cat([a.repeat(b, 1, 1, 1) for a, b in zip(sample_points, num_gts) if b > 0]) + # tgt_mask = F.grid_sample(tgt_mask, sample_points, align_corners=False).squeeze([1, 2]) + # + # with torch.amp.autocast("cuda", enabled=False): + # # binary cross entropy cost + # pos_cost_mask = F.binary_cross_entropy_with_logits(out_mask, torch.ones_like(out_mask), reduction='none') + # neg_cost_mask = F.binary_cross_entropy_with_logits(out_mask, torch.zeros_like(out_mask), reduction='none') + # cost_mask = torch.matmul(pos_cost_mask, tgt_mask.T) + torch.matmul(neg_cost_mask, 1 - tgt_mask.T) + # cost_mask /= self.num_sample_points + # + # # dice cost + # out_mask = F.sigmoid(out_mask) + # numerator = 2 * torch.matmul(out_mask, tgt_mask.T) + # denominator = out_mask.sum(-1, keepdim=True) + tgt_mask.sum(-1).unsqueeze(0) + # cost_dice = 1 - (numerator + 1) / (denominator + 1) + # + # C = self.cost_gain['mask'] * cost_mask + self.cost_gain['dice'] * cost_dice + # return C + + +def get_cdn_group( + batch: dict[str, Any], + num_classes: int, + num_queries: int, + class_embed: torch.Tensor, + num_dn: int = 100, + cls_noise_ratio: float = 0.5, + box_noise_scale: float = 1.0, + training: bool = False, +) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None, dict[str, Any] | None]: + """Generate contrastive denoising training group with positive and negative samples from ground truths. + + This function creates denoising queries for contrastive denoising training by adding noise to ground truth bounding + boxes and class labels. It generates both positive and negative samples to improve model robustness. + + Args: + batch (dict[str, Any]): Batch dictionary containing 'cls' (torch.Tensor with shape (num_gts,)), 'bboxes' + (torch.Tensor with shape (num_gts, 4)), 'batch_idx' (torch.Tensor), and 'gt_groups' (list[int]) indicating + number of ground truths per image. + num_classes (int): Total number of object classes. + num_queries (int): Number of object queries. + class_embed (torch.Tensor): Class embedding weights to map labels to embedding space. + num_dn (int): Number of denoising queries to generate. + cls_noise_ratio (float): Noise ratio for class labels. + box_noise_scale (float): Noise scale for bounding box coordinates. + training (bool): Whether model is in training mode. + + Returns: + padding_cls (torch.Tensor | None): Modified class embeddings for denoising with shape (bs, num_dn, embed_dim). + padding_bbox (torch.Tensor | None): Modified bounding boxes for denoising with shape (bs, num_dn, 4). + attn_mask (torch.Tensor | None): Attention mask for denoising with shape (tgt_size, tgt_size). + dn_meta (dict[str, Any] | None): Meta information dictionary containing denoising parameters. + + Examples: + Generate denoising group for training + >>> batch = { + ... "cls": torch.tensor([0, 1, 2]), + ... "bboxes": torch.rand(3, 4), + ... "batch_idx": torch.tensor([0, 0, 1]), + ... "gt_groups": [2, 1], + ... } + >>> class_embed = torch.rand(80, 256) # 80 classes, 256 embedding dim + >>> cdn_outputs = get_cdn_group(batch, 80, 100, class_embed, training=True) + """ + if (not training) or num_dn <= 0 or batch is None: + return None, None, None, None + gt_groups = batch["gt_groups"] + max_nums = min(max(gt_groups), num_dn) + if max_nums == 0: + return None, None, None, None + + num_group = num_dn // max_nums # always >= 1, because max_nums is capped at num_dn + # Pad gt to max_num of a batch + bs = len(gt_groups) + gt_cls = batch["cls"] # (bs*num, ) + gt_bbox = batch["bboxes"] # bs*num, 4 + b_idx = batch["batch_idx"] + + # Denoise a random subset of any image carrying more than num_dn boxes. Uncapped, num_group collapses to 1 + # and a 700-box image emits 1400 denoising queries against the 2 * num_dn budget, growing decoder self-attention + # quadratically. The subset is redrawn on every call, so all boxes are still denoised across training. + gt_idx = torch.arange(sum(gt_groups), dtype=torch.long, device=gt_bbox.device) + if max(gt_groups) > max_nums: + offsets = torch.as_tensor([0, *gt_groups[:-1]]).cumsum_(0) + gt_idx = torch.cat( + [torch.randperm(n, device=gt_bbox.device)[:max_nums].sort().values + o for n, o in zip(gt_groups, offsets)] + ) + gt_cls, gt_bbox, b_idx = gt_cls[gt_idx], gt_bbox[gt_idx], b_idx[gt_idx] + gt_groups = [min(n, max_nums) for n in gt_groups] + total_num = sum(gt_groups) + + # Each group has positive and negative queries + dn_cls = gt_cls.repeat(2 * num_group) # (2*num_group*bs*num, ) + dn_bbox = gt_bbox.repeat(2 * num_group, 1) # 2*num_group*bs*num, 4 + dn_b_idx = b_idx.repeat(2 * num_group).view(-1) # (2*num_group*bs*num, ) + + # Positive and negative mask + # (bs*num*num_group, ), the second total_num*num_group part as negative samples + neg_idx = torch.arange(total_num * num_group, dtype=torch.long, device=gt_bbox.device) + num_group * total_num + + if cls_noise_ratio > 0: + # Apply class label noise to half of the samples + mask = torch.rand(dn_cls.shape) < (cls_noise_ratio * 0.5) + idx = torch.nonzero(mask).squeeze(-1) + # Randomly assign new class labels + new_label = torch.randint_like(idx, 0, num_classes, dtype=dn_cls.dtype, device=dn_cls.device) + dn_cls[idx] = new_label + + if box_noise_scale > 0: + known_bbox = xywh2xyxy(dn_bbox) + + diff = (dn_bbox[..., 2:] * 0.5).repeat(1, 2) * box_noise_scale # 2*num_group*bs*num, 4 + + rand_sign = torch.randint_like(dn_bbox, 0, 2) * 2.0 - 1.0 + rand_part = torch.rand_like(dn_bbox) + rand_part[neg_idx] += 1.0 + rand_part *= rand_sign + known_bbox += rand_part * diff + known_bbox.clip_(min=0.0, max=1.0) + dn_bbox = xyxy2xywh(known_bbox) + dn_bbox = torch.logit(dn_bbox, eps=1e-6) # inverse sigmoid + + num_dn = int(max_nums * 2 * num_group) # total denoising queries + dn_cls_embed = class_embed[dn_cls] # bs*num * 2 * num_group, 256 + padding_cls = torch.zeros(bs, num_dn, dn_cls_embed.shape[-1], device=gt_cls.device) + padding_bbox = torch.zeros(bs, num_dn, 4, device=gt_bbox.device) + + map_indices = torch.cat([torch.tensor(range(num), dtype=torch.long) for num in gt_groups]) + pos_idx = torch.stack([map_indices + max_nums * i for i in range(num_group)], dim=0) + + map_indices = torch.cat([map_indices + max_nums * i for i in range(2 * num_group)]) + padding_cls[(dn_b_idx, map_indices)] = dn_cls_embed + padding_bbox[(dn_b_idx, map_indices)] = dn_bbox + + tgt_size = num_dn + num_queries + attn_mask = torch.zeros([tgt_size, tgt_size], dtype=torch.bool) + # Match query cannot see the reconstruct + attn_mask[num_dn:, :num_dn] = True + # Reconstruct cannot see each other + for i in range(num_group): + if i == 0: + attn_mask[max_nums * 2 * i : max_nums * 2 * (i + 1), max_nums * 2 * (i + 1) : num_dn] = True + if i == num_group - 1: + attn_mask[max_nums * 2 * i : max_nums * 2 * (i + 1), : max_nums * i * 2] = True + else: + attn_mask[max_nums * 2 * i : max_nums * 2 * (i + 1), max_nums * 2 * (i + 1) : num_dn] = True + attn_mask[max_nums * 2 * i : max_nums * 2 * (i + 1), : max_nums * 2 * i] = True + dn_meta = { + "dn_pos_idx": [p.reshape(-1) for p in pos_idx.cpu().split(list(gt_groups), dim=1)], + "dn_gt_idx": list(gt_idx.cpu().split(list(gt_groups))), # gt each denoising query reconstructs + "dn_num_group": num_group, + "dn_num_split": [num_dn, num_queries], + } + + return ( + padding_cls.to(class_embed.device), + padding_bbox.to(class_embed.device), + attn_mask.to(class_embed.device), + dn_meta, + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..534de2b3c875d49c2b0f6d6464d9ffee663b8c90 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/__init__.py @@ -0,0 +1,20 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from ultralytics.models.yolo import classify, depth, detect, obb, pose, segment, semantic, world, yoloe + +from .model import YOLO, YOLOE, YOLOWorld + +__all__ = ( + "YOLO", + "YOLOE", + "YOLOWorld", + "classify", + "depth", + "detect", + "obb", + "pose", + "segment", + "semantic", + "world", + "yoloe", +) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97698dc5e9b223784b53b439c18b200c703ec3ba Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/__pycache__/model.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/__pycache__/model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ea2203de979842d9187cb866ad0061107fafed8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/__pycache__/model.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3a10629229f8a8e5769480d004bbdbe42a633e79 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__init__.py @@ -0,0 +1,7 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from ultralytics.models.yolo.classify.predict import ClassificationPredictor +from ultralytics.models.yolo.classify.train import ClassificationTrainer +from ultralytics.models.yolo.classify.val import ClassificationValidator + +__all__ = "ClassificationPredictor", "ClassificationTrainer", "ClassificationValidator" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f342fa4aa7b751aeb5ca0e347c25f605099db4b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__pycache__/predict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__pycache__/predict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7e7a62e637a63e5360827efa766d00f88dfbf8d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__pycache__/predict.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__pycache__/train.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__pycache__/train.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4ea8e669950e8b9522d36bb439d227dde6886df Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__pycache__/train.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__pycache__/val.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__pycache__/val.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a10c85a95609f0d68573c41490577f8ec2e9d0d7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/__pycache__/val.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/predict.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..d22b23c99d05b2543ced23755fcf60e443c45493 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/predict.py @@ -0,0 +1,106 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import cv2 +import numpy as np +import torch +from PIL import Image + +from ultralytics.data.augment import classify_transforms +from ultralytics.engine.predictor import BasePredictor +from ultralytics.engine.results import Results +from ultralytics.utils import DEFAULT_CFG, ops + + +class ClassificationPredictor(BasePredictor): + """A class extending the BasePredictor class for prediction based on a classification model. + + This predictor handles the specific requirements of classification models, including preprocessing images and + postprocessing predictions to generate classification results. + + Attributes: + args (dict): Configuration arguments for the predictor. + + Methods: + pre_transform: Resize and crop images on the host before the device-side conversion. + preprocess: Convert input images to model-compatible format. + postprocess: Process model predictions into Results objects. + + Examples: + >>> from ultralytics.utils import ASSETS + >>> from ultralytics.models.yolo.classify import ClassificationPredictor + >>> args = dict(model="yolo26n-cls.pt", source=ASSETS) + >>> predictor = ClassificationPredictor(overrides=args) + >>> predictor.predict_cli() + + Notes: + - Torchvision classification models can also be passed to the 'model' argument, i.e. model='resnet18'. + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks: dict | None = None): + """Initialize the ClassificationPredictor with the specified configuration and set task to 'classify'. + + This constructor initializes a ClassificationPredictor instance, which extends BasePredictor for classification + tasks. It ensures the task is set to 'classify' regardless of input configuration. + + Args: + cfg (dict): Default configuration dictionary containing prediction settings. + overrides (dict, optional): Configuration overrides that take precedence over cfg. + _callbacks (dict, optional): Dictionary of callback functions to be executed during prediction. + """ + super().__init__(cfg, overrides, _callbacks) + self.args.task = "classify" + + def setup_source(self, source): + """Set up source and inference mode and classify transforms.""" + import torchvision.transforms as T # scope for faster 'import ultralytics' + + super().setup_source(source) + transforms = getattr(self.model.model, "transforms", None) # missing on YAML-built and legacy checkpoints + size = getattr(transforms.transforms[0], "size", max(self.imgsz)) if transforms is not None else None + self.transforms = ( + transforms if size == max(self.imgsz) and self.model.format == "pt" else classify_transforms(self.imgsz) + ) + tfl = getattr(self.transforms, "transforms", ()) + split = ( + type(self.transforms) is T.Compose + and tuple(map(type, tfl)) == (T.Resize, T.CenterCrop, T.ToTensor, T.Normalize) + and getattr(self.model, "channels", 3) == 3 + ) + self.host_transforms = T.Compose(tfl[:2]) if split else None + self.device_transform = tfl[-1] if split else None + + def pre_transform(self, im: list[np.ndarray]) -> list[np.ndarray]: + """Resize and crop images on the host, leaving uint8 BGR for the device-side conversion.""" + return [np.array(self.host_transforms(Image.fromarray(x))) for x in im] + + def preprocess(self, img): + """Convert input images to model-compatible tensor format with appropriate normalization.""" + if self.device_transform is None and not isinstance(img, torch.Tensor): + img = torch.stack([self.transforms(Image.fromarray(cv2.cvtColor(x, cv2.COLOR_BGR2RGB))) for x in img], 0) + img = img.to(self.model.device) + return img.half() if self.model.fp16 else img.float() + is_tensor = isinstance(img, torch.Tensor) + img = super().preprocess(img) + return img if is_tensor else self.device_transform(img) + + def postprocess(self, preds, img, orig_imgs): + """Process predictions to return Results objects with classification probabilities. + + Args: + preds (torch.Tensor): Raw predictions from the model. + img (torch.Tensor): Input images after preprocessing. + orig_imgs (list[np.ndarray] | torch.Tensor): Original images before preprocessing. + + Returns: + (list[Results]): List of Results objects containing classification results for each image. + """ + if not isinstance(orig_imgs, list): # Input images are a torch.Tensor, not a list + orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)[..., ::-1] + + preds = preds[0] if isinstance(preds, (list, tuple)) else preds + return [ + Results(orig_img, path=img_path, names=self.model.names, probs=pred) + for pred, orig_img, img_path in zip(preds, orig_imgs, self.batch[0]) + ] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/train.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/train.py new file mode 100644 index 0000000000000000000000000000000000000000..cd838a0e6e880a963880177f184c15cfacf86e7b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/train.py @@ -0,0 +1,198 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from copy import copy +from typing import Any + +import torch + +from ultralytics.data import ClassificationDataset, build_dataloader +from ultralytics.engine.trainer import BaseTrainer +from ultralytics.models import yolo +from ultralytics.nn.tasks import ClassificationModel +from ultralytics.utils import DEFAULT_CFG, RANK +from ultralytics.utils.plotting import plot_images +from ultralytics.utils.torch_utils import is_parallel, torch_distributed_zero_first + + +class ClassificationTrainer(BaseTrainer): + """A trainer class extending BaseTrainer for training image classification models. + + This trainer handles the training process for image classification tasks, supporting both YOLO classification models + and torchvision models with comprehensive dataset handling and validation. + + Attributes: + model (ClassificationModel): The classification model to be trained. + data (dict[str, Any]): Dictionary containing dataset information including class names and number of classes. + loss_names (tuple): Names of the loss items, derived from the loss dict returned by the criterion. + validator (ClassificationValidator): Validator instance for model evaluation. + + Methods: + set_model_attributes: Set the model's class names from the loaded dataset. + get_model: Return a modified PyTorch model configured for training. + setup_model: Load, create or download model for classification. + build_dataset: Create a ClassificationDataset instance. + get_dataloader: Return PyTorch DataLoader with transforms for image preprocessing. + preprocess_batch: Preprocess a batch of images and classes. + progress_string: Return a formatted string showing training progress. + get_validator: Return an instance of ClassificationValidator. + final_eval: Evaluate trained model and save validation results. + plot_training_samples: Plot training samples with their annotations. + + Examples: + Initialize and train a classification model + >>> from ultralytics.models.yolo.classify import ClassificationTrainer + >>> args = dict(model="yolo26n-cls.pt", data="imagenet10", epochs=3) + >>> trainer = ClassificationTrainer(overrides=args) + >>> trainer.train() + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides: dict[str, Any] | None = None, _callbacks: dict | None = None): + """Initialize a ClassificationTrainer object. + + Args: + cfg (dict[str, Any], optional): Default configuration dictionary containing training parameters. + overrides (dict[str, Any], optional): Dictionary of parameter overrides for the default configuration. + _callbacks (dict, optional): Dictionary of callback functions to be executed during training. + """ + if overrides is None: + overrides = {} + overrides["task"] = "classify" + if overrides.get("imgsz") is None: + overrides["imgsz"] = 224 + super().__init__(cfg, overrides, _callbacks) + + def set_model_attributes(self): + """Set the YOLO model's class names from the loaded dataset.""" + self.model.names = self.data["names"] + + def get_model(self, cfg=None, weights=None, verbose: bool = True): + """Return a modified PyTorch model configured for training YOLO classification. + + Args: + cfg (Any, optional): Model configuration. + weights (Any, optional): Pre-trained model weights. + verbose (bool, optional): Whether to display model information. + + Returns: + (ClassificationModel): Configured PyTorch model for classification. + """ + model = ClassificationModel(cfg, nc=self.data["nc"], ch=self.data["channels"], verbose=verbose and RANK == -1) + if weights: + model.load(weights) + + for m in model.modules(): + if self.args.pretrained is False and not self.resume and hasattr(m, "reset_parameters"): + m.reset_parameters() + if isinstance(m, torch.nn.Dropout) and self.args.dropout: + m.p = self.args.dropout # set dropout + for p in model.parameters(): + p.requires_grad = True # for training + return model + + def setup_model(self): + """Load, create or download model for classification tasks. + + Returns: + (Any): Model checkpoint if applicable, otherwise None. + """ + import torchvision # scope for faster 'import ultralytics' + + if str(self.model) in torchvision.models.__dict__: + self.model = torchvision.models.__dict__[self.model]( + weights="IMAGENET1K_V1" if self.args.pretrained else None + ) + ckpt = None + else: + ckpt = super().setup_model() + ClassificationModel.reshape_outputs(self.model, self.data["nc"]) + return ckpt + + def build_dataset(self, img_path: str, mode: str = "train", batch=None): + """Create a ClassificationDataset instance given an image path and mode. + + Args: + img_path (str): Path to the dataset images. + mode (str, optional): Dataset mode ('train', 'val', or 'test'). + batch (Any, optional): Batch information (unused in this implementation). + + Returns: + (ClassificationDataset): Dataset for the specified mode. + """ + return ClassificationDataset( + img_path, + self.args, + augment=mode == "train", + prefix="train" if mode == "train" else self.args.split, + names=self.data["names"], + ) + + def get_dataloader(self, dataset_path: str, batch_size: int = 16, rank: int = 0, mode: str = "train"): + """Return PyTorch DataLoader with transforms to preprocess images. + + Args: + dataset_path (str): Path to the dataset. + batch_size (int, optional): Number of images per batch. + rank (int, optional): Process rank for distributed training. + mode (str, optional): 'train', 'val', or 'test' mode. + + Returns: + (torch.utils.data.DataLoader): DataLoader for the specified dataset and mode. + """ + with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP + dataset = self.build_dataset(dataset_path, mode) + + if not dataset.samples: + raise FileNotFoundError( + f"No images found in '{mode}' split of {dataset_path}. " + f"See https://docs.ultralytics.com/datasets/classify for cls dataset format." + ) + + drop_last = self.args.compile and mode == "train" + loader = build_dataloader( + dataset, batch_size, self.args.workers, rank=rank, drop_last=drop_last, device=self.device + ) + # Attach inference transforms + if mode != "train": + if is_parallel(self.model): + self.model.module.transforms = loader.dataset.torch_transforms + else: + self.model.transforms = loader.dataset.torch_transforms + return loader + + def preprocess_batch(self, batch: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: + """Preprocess a batch of images and classes.""" + batch["img"] = batch["img"].to(self.device, non_blocking=self.device.type not in {"cpu", "mps"}) + batch["cls"] = batch["cls"].to(self.device, non_blocking=self.device.type not in {"cpu", "mps"}) + return batch + + def progress_string(self) -> str: + """Return a formatted string showing training progress.""" + return ("\n" + "%11s" * (4 + len(self.loss_names))) % ( + "Epoch", + "GPU_mem", + *self.loss_names, + "Instances", + "Size", + ) + + def get_validator(self): + """Return an instance of ClassificationValidator for validation.""" + return yolo.classify.ClassificationValidator( + self.test_loader, self.save_dir, args=copy(self.args), _callbacks=self.callbacks + ) + + def plot_training_samples(self, batch: dict[str, torch.Tensor], ni: int): + """Plot training samples with their annotations. + + Args: + batch (dict[str, torch.Tensor]): Batch containing images and class labels. + ni (int): Batch index used for naming the output file. + """ + batch["batch_idx"] = torch.arange(batch["img"].shape[0]) # add batch index for plotting + plot_images( + labels=batch, + fname=self.save_dir / f"train_batch{ni}.jpg", + on_plot=self.on_plot, + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/val.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/val.py new file mode 100644 index 0000000000000000000000000000000000000000..da0499b9575ed3afc1e5d46ac4ea586991b93b95 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/val.py @@ -0,0 +1,218 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import torch +import torch.distributed as dist + +from ultralytics.data import ClassificationDataset, build_dataloader +from ultralytics.engine.validator import BaseValidator +from ultralytics.utils import LOGGER, RANK +from ultralytics.utils.metrics import ClassifyMetrics, ConfusionMatrix +from ultralytics.utils.plotting import plot_images + + +class ClassificationValidator(BaseValidator): + """A class extending the BaseValidator class for validation based on a classification model. + + This validator handles the validation process for classification models, including metrics calculation, confusion + matrix generation, and visualization of results. + + Attributes: + targets (list[torch.Tensor]): Ground truth class labels. + pred (list[torch.Tensor]): Model predictions. + metrics (ClassifyMetrics): Object to calculate and store classification metrics. + names (dict): Mapping of class indices to class names. + nc (int): Number of classes. + confusion_matrix (ConfusionMatrix): Matrix to evaluate model performance across classes. + + Methods: + get_desc: Return a formatted string summarizing classification metrics. + init_metrics: Initialize confusion matrix, class names, and tracking containers. + preprocess: Preprocess input batch by moving data to device. + update_metrics: Update running metrics with model predictions and batch targets. + finalize_metrics: Finalize metrics including confusion matrix and processing speed. + postprocess: Extract the primary prediction from model output. + get_stats: Calculate and return a dictionary of metrics. + build_dataset: Create a ClassificationDataset instance for validation. + get_dataloader: Build and return a data loader for classification validation. + print_results: Print evaluation metrics for the classification model. + plot_val_samples: Plot validation image samples with their ground truth labels. + plot_predictions: Plot images with their predicted class labels. + + Examples: + >>> from ultralytics.models.yolo.classify import ClassificationValidator + >>> args = dict(model="yolo26n-cls.pt", data="imagenet10") + >>> validator = ClassificationValidator(args=args) + >>> validator() + + Notes: + Torchvision classification models can also be passed to the 'model' argument, i.e. model='resnet18'. + """ + + def __init__(self, dataloader=None, save_dir=None, args=None, _callbacks: dict | None = None) -> None: + """Initialize ClassificationValidator with dataloader, save directory, and other parameters. + + Args: + dataloader (torch.utils.data.DataLoader, optional): DataLoader to use for validation. + save_dir (str | Path, optional): Directory to save results. + args (dict, optional): Arguments containing model and validation configuration. + _callbacks (dict, optional): Dictionary of callback functions to be called during validation. + """ + super().__init__(dataloader, save_dir, args, _callbacks) + self.targets = None + self.pred = None + self.args.task = "classify" + self.metrics = ClassifyMetrics() + + def get_desc(self) -> str: + """Return a formatted string summarizing classification metrics.""" + return ("%22s" + "%11s" * 2) % ("classes", "top1_acc", "top5_acc") + + def init_metrics(self, model: torch.nn.Module) -> None: + """Initialize confusion matrix, class names, and tracking containers for predictions and targets.""" + self.names = model.names + self.nc = len(model.names) + self.pred = [] + self.targets = [] + self.confusion_matrix = ConfusionMatrix(names=model.names, task="classify") + + def preprocess(self, batch: dict[str, Any]) -> dict[str, Any]: + """Preprocess input batch by moving data to device and converting to appropriate dtype.""" + batch["img"] = batch["img"].to(self.device, non_blocking=self.device.type not in {"cpu", "mps"}) + batch["img"] = batch["img"].half() if self.args.quantize == 16 else batch["img"].float() + batch["cls"] = batch["cls"].to(self.device, non_blocking=self.device.type not in {"cpu", "mps"}) + return batch + + def update_metrics(self, preds: torch.Tensor, batch: dict[str, Any]) -> None: + """Update running metrics with model predictions and batch targets. + + Args: + preds (torch.Tensor): Model predictions, typically logits or probabilities for each class. + batch (dict): Batch data containing images and class labels. + + Notes: + This method appends the top-N predictions (sorted by confidence in descending order) to the + prediction list for later evaluation. N is limited to the minimum of 5 and the number of classes. + """ + n5 = min(len(self.names), 5) + self.pred.append(preds.argsort(1, descending=True)[:, :n5].type(torch.int32).cpu()) + self.targets.append(batch["cls"].type(torch.int32).cpu()) + + def finalize_metrics(self) -> None: + """Finalize metrics including confusion matrix and processing speed. + + Examples: + >>> validator = ClassificationValidator() + >>> validator.pred = [torch.tensor([[0, 1, 2]])] # Top-3 predictions for one sample + >>> validator.targets = [torch.tensor([0])] # Ground truth class + >>> validator.finalize_metrics() + >>> print(validator.metrics.confusion_matrix) # Access the confusion matrix + + Notes: + This method processes the accumulated predictions and targets to generate the confusion matrix, + optionally plots it, and updates the metrics object with speed information. + """ + self.confusion_matrix.process_cls_preds(self.pred, self.targets) + if self.args.plots: + for normalize in True, False: + self.confusion_matrix.plot(save_dir=self.save_dir, normalize=normalize, on_plot=self.on_plot) + self.metrics.speed = self.speed + self.metrics.save_dir = self.save_dir + self.metrics.confusion_matrix = self.confusion_matrix + + def postprocess(self, preds: torch.Tensor | list[torch.Tensor] | tuple[torch.Tensor]) -> torch.Tensor: + """Extract the primary prediction from model output if it's in a list or tuple format.""" + return preds[0] if isinstance(preds, (list, tuple)) else preds + + def get_stats(self) -> dict[str, float]: + """Calculate and return a dictionary of metrics by processing targets and predictions.""" + self.metrics.process(self.targets, self.pred) + return self.metrics.results_dict + + def gather_stats(self) -> None: + """Gather stats from all GPUs.""" + if RANK == 0: + gathered_preds = [None] * dist.get_world_size() + gathered_targets = [None] * dist.get_world_size() + dist.gather_object(self.pred, gathered_preds, dst=0) + dist.gather_object(self.targets, gathered_targets, dst=0) + self.pred = [pred for rank in gathered_preds for pred in rank] + self.targets = [targets for rank in gathered_targets for targets in rank] + elif RANK > 0: + dist.gather_object(self.pred, None, dst=0) + dist.gather_object(self.targets, None, dst=0) + + def build_dataset(self, img_path: str) -> ClassificationDataset: + """Create a ClassificationDataset instance for validation.""" + return ClassificationDataset(img_path, self.args, augment=False, prefix=self.args.split, names=self.names) + + def get_dataloader(self, dataset_path: Path | str, batch_size: int) -> torch.utils.data.DataLoader: + """Build and return a data loader for classification validation. + + Args: + dataset_path (str | Path): Path to the dataset directory. + batch_size (int): Number of samples per batch. + + Returns: + (torch.utils.data.DataLoader): DataLoader object for the classification validation dataset. + """ + dataset = self.build_dataset(dataset_path) + if not dataset.samples: + raise FileNotFoundError(f"No images from the model's classes found in {dataset_path}") + return build_dataloader(dataset, batch_size, self.args.workers, rank=-1, device=self.device) + + def print_results(self) -> None: + """Print evaluation metrics for the classification model.""" + pf = "%22s" + "%11.3g" * len(self.metrics.keys) # print format + LOGGER.info(pf % ("all", self.metrics.top1, self.metrics.top5)) + + def plot_val_samples(self, batch: dict[str, Any], ni: int) -> None: + """Plot validation image samples with their ground truth labels. + + Args: + batch (dict[str, Any]): Dictionary containing batch data with 'img' (images) and 'cls' (class labels). + ni (int): Batch index used for naming the output file. + + Examples: + >>> validator = ClassificationValidator() + >>> batch = {"img": torch.rand(16, 3, 224, 224), "cls": torch.randint(0, 10, (16,))} + >>> validator.plot_val_samples(batch, 0) + """ + batch["batch_idx"] = torch.arange(batch["img"].shape[0]) # add batch index for plotting + plot_images( + labels=batch, + fname=self.save_dir / f"val_batch{ni}_labels.jpg", + names=self.names, + on_plot=self.on_plot, + ) + + def plot_predictions(self, batch: dict[str, Any], preds: torch.Tensor, ni: int) -> None: + """Plot images with their predicted class labels and save the visualization. + + Args: + batch (dict[str, Any]): Batch data containing images and other information. + preds (torch.Tensor): Model predictions with shape (batch_size, num_classes). + ni (int): Batch index used for naming the output file. + + Examples: + >>> validator = ClassificationValidator() + >>> batch = {"img": torch.rand(16, 3, 224, 224)} + >>> preds = torch.rand(16, 10) # 16 images, 10 classes + >>> validator.plot_predictions(batch, preds, 0) + """ + batched_preds = { + "img": batch["img"], + "batch_idx": torch.arange(batch["img"].shape[0]), + "cls": torch.argmax(preds, dim=1), + "conf": torch.amax(preds, dim=1), + } + plot_images( + batched_preds, + fname=self.save_dir / f"val_batch{ni}_pred.jpg", + names=self.names, + on_plot=self.on_plot, + ) # pred diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..04cdee31fc0f23efc3f7825984f0774aa8d8a999 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__init__.py @@ -0,0 +1,7 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .predict import DepthPredictor +from .train import DepthTrainer +from .val import DepthValidator + +__all__ = "DepthPredictor", "DepthTrainer", "DepthValidator" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1eadc57491ab4ea66d3235af2003df21197d11ad Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/calibrate.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/calibrate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4ddee5f007c055184d29ecaade97857ad7dd322 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/calibrate.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/predict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/predict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..407015a44294b1e679689b85a3048e4fda9039ad Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/predict.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/train.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/train.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..676b23e32361e60ba616db5d03b892e078a8150b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/train.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/val.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/val.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..312e3415ab1f86db33be075cccc447944e3a8823 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/__pycache__/val.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/calibrate.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/calibrate.py new file mode 100644 index 0000000000000000000000000000000000000000..96b22f171eadf8e494da51596a70754ab2711d8e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/calibrate.py @@ -0,0 +1,345 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Scale-only calibration for monocular depth models. + +The log-depth head predicts relative scene structure (shape); absolute scale is a separate +two-parameter log-affine ``d' = exp(a·log d + b)`` stored in the head's ``cal_a``/``cal_b`` +buffers. This module fits ``(a, b)`` by closed-form least squares against ground-truth depth +over a small set of images — no gradient training, decoder weights untouched. It powers both +the trainer's automatic post-training calibration and the ``Model.calibrate()`` API. + +Auto-calibration uses a "calibrate only if it helps" policy (:func:`select_calibration_cv`): +candidates are scored on held-out images and applied only when they beat the un-calibrated +output, so the absolute scale is fixed for cross-domain models without harming in-domain ones. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.nn.functional as F + +from ultralytics.utils import LOGGER +from ultralytics.utils.torch_utils import smart_inference_mode + + +def _depth_head(model: torch.nn.Module) -> torch.nn.Module | None: + """Return the Depth head module that carries ``cal_a``/``cal_b`` buffers, or None.""" + m = model.module if hasattr(model, "module") else model # unwrap DDP + seq = getattr(m, "model", None) + if seq is not None and not isinstance(seq, torch.nn.Sequential): + seq = getattr(seq, "model", None) + head = seq[-1] if isinstance(seq, torch.nn.Sequential) else m + return head if hasattr(head, "cal_a") else None + + +def _rewind(dataloader) -> None: + """Rewind a stateful loader to the epoch start before a partial pass. + + The trainer's InfiniteDataLoader keeps one persistent iterator across ``for`` loops, so a previous pass that broke + out early (e.g. a fit stopping at ``max_images``) leaves it mid-epoch and the next loop silently resumes there. + Every pass here that wants "the first N" must rewind first — the plot pass in particular must see the same leading + batches BaseValidator plotted as ``val_batch{ni}.jpg``. Plain DataLoaders and list fixtures restart on every + ``__iter__``. + """ + reset = getattr(dataloader, "reset", None) + if callable(reset): + reset() + + +def _delta1_none(log_pred: np.ndarray, log_gt: np.ndarray, a: float, b: float) -> float: + """δ1 under no per-image alignment after applying ``d' = exp(a·log_pred + b)``. + + δ1 is the fraction of pixels with ``max(d'/gt, gt/d') < 1.25``; in log space that is ``|a·log_pred + b − log_gt| < + log(1.25)``. This is the deployment metric (raw absolute scale, the ``align="none"`` protocol) the policy optimizes + — the val scoreboard's default ``align="median"`` is scale-invariant and cannot see calibration. + """ + ld = (a * np.asarray(log_pred, dtype=np.float64) + b) - np.asarray(log_gt, dtype=np.float64) + return float(np.mean(np.abs(ld) < np.log(1.25))) + + +def select_calibration( + lp_fit: np.ndarray, + lg_fit: np.ndarray, + lp_score: np.ndarray, + lg_score: np.ndarray, +) -> dict[str, Any]: + """Pick the calibration that best improves *held-out* raw-scale δ1 — "calibrate only if it helps". + + Two candidates are fit on the ``*_fit`` log-pixel arrays and scored on the independent ``*_score`` arrays under + :func:`_delta1_none`: + - ``identity`` (a=1, b=0): no calibration, + - ``scale-only`` (a=1, b=mean(log_gt − log_pred)): a global scale. + The winner is the highest held-out δ1, with ties favoring identity — so a calibration that does not generalize is + rejected and auto-cal does no harm. (An affine log-slope candidate was evaluated and removed: the extra parameter + overfits within-dataset cross-validation and harms cross-distribution generalization.) + + Returns: + dict with ``a``, ``b`` (floats of the winner), ``name``, and ``scores`` (per-candidate δ1). + """ + lp_fit = np.asarray(lp_fit, dtype=np.float64) + lg_fit = np.asarray(lg_fit, dtype=np.float64) + candidates = [ + ("identity", 1.0, 0.0), + ("scale-only", 1.0, float(np.mean(lg_fit - lp_fit))), + ] + scored = [(name, a, b, _delta1_none(lp_score, lg_score, a, b)) for name, a, b in candidates] + best = max(scored, key=lambda s: s[3]) # identity first, so exact ties favor it + return {"a": best[1], "b": best[2], "name": best[0], "scores": {s[0]: s[3] for s in scored}} + + +def select_calibration_cv( + pairs: list[tuple[np.ndarray, np.ndarray]], + margin: float = 0.0, + folds: int = 2, +) -> dict[str, Any]: + """Cross-validated "calibrate only if it helps": choose a candidate by K-fold held-out δ1. + + ``pairs`` is a list of per-image ``(log_pred, log_gt)`` arrays. Each candidate type is scored on every fold while + held out (fit on the rest) via :func:`select_calibration`, and the per-type held-out δ1 is averaged across folds — + so every image contributes to scoring exactly once and a candidate that only wins on one noisy split cannot be + selected. The winning *type* must beat identity's mean held-out δ1 by ``margin`` (ties favor the simpler type); the + final ``(a, b)`` is then refit on all pairs. + + Returns: + dict with ``a``, ``b`` (floats), ``name``, and ``cv_scores`` (mean held-out δ1 per type). + """ + names = ["identity", "scale-only"] + k = max(2, min(folds, len(pairs))) + per_fold = {n: [] for n in names} + for f in range(k): + fit = [pairs[i] for i in range(len(pairs)) if i % k != f] + score = [pairs[i] for i in range(len(pairs)) if i % k == f] + if not fit or not score: + continue + s = select_calibration( + np.concatenate([p[0] for p in fit]), + np.concatenate([p[1] for p in fit]), + np.concatenate([p[0] for p in score]), + np.concatenate([p[1] for p in score]), + )["scores"] + for n in names: + per_fold[n].append(s[n]) + cv = {n: float(np.mean(per_fold[n])) for n in names} + best = "identity" + for n in names[1:]: + if cv[n] > cv[best] + margin: + best = n + # refit the chosen type on all pairs (CV selects the type; all data sets the parameters) + if best == "identity": + a, b = 1.0, 0.0 + else: # scale-only + lp = np.concatenate([p[0] for p in pairs]) + lg = np.concatenate([p[1] for p in pairs]) + a, b = 1.0, float(np.mean(lg - lp)) + return {"a": a, "b": b, "name": best, "cv_scores": cv} + + +@smart_inference_mode() +def _collect_logpairs( + model: torch.nn.Module, dataloader, device: torch.device | str, max_images: int, max_depth: float = 100.0 +) -> list[tuple[np.ndarray, np.ndarray]]: + """Run the model over the loader and return a list of per-image ``(log_pred, log_gt)`` arrays. + + One entry per image (each subsampled to ≤20k valid pixels) so callers can split images into independent fit/score + sets. Only GT inside ``(0.001, max_depth)`` is collected — the same population ``DepthMetrics`` evaluates (Eigen + protocol), so invalid far GT cannot steer the fitted scale or the held-out δ1 the selection policy trusts. + Calibration buffers are reset to identity for the duration so the fit sees the raw output, then restored. + """ + head = _depth_head(model) + a0, b0 = float(head.cal_a), float(head.cal_b) + head.cal_a.fill_(1.0) + head.cal_b.fill_(0.0) + _rewind(dataloader) + rng = np.random.default_rng(0) + pairs = [] + seen = 0 + try: + for batch in dataloader: + img = batch["img"].to(device).float() / 255 + gt = batch["depth"].to(device).float() + if gt.ndim == 3: + gt = gt.unsqueeze(1) + pred = model(img).float() + if pred.ndim == 3: + pred = pred.unsqueeze(1) + if pred.shape[-2:] != gt.shape[-2:]: + pred = F.interpolate(pred, size=gt.shape[-2:], mode="bilinear", align_corners=True) + for pi, gi in zip(pred, gt): + valid = (gi > 1e-3) & (gi < max_depth) & (pi > 1e-3) & torch.isfinite(pi) + if not valid.any(): + continue + lp = torch.log(pi[valid]).detach().cpu().numpy() + lg = torch.log(gi[valid]).detach().cpu().numpy() + if lp.size > 20_000: + idx = rng.choice(lp.size, 20_000, replace=False) + lp, lg = lp[idx], lg[idx] + pairs.append((lp, lg)) + seen += img.shape[0] + if seen >= max_images: + break + finally: + # A failed pass must not wipe the model's existing calibration; callers set the chosen value explicitly. + head.cal_a.fill_(a0) + head.cal_b.fill_(b0) + return pairs + + +def fit_calibration_selective( + model: torch.nn.Module, + dataloader, + device: torch.device | str, + max_images: int = 200, + margin: float = 0.002, + max_depth: float = 100.0, +) -> dict[str, Any] | None: + """Select and apply calibration via "calibrate only if it helps" (see :func:`select_calibration_cv`). + + Collects per-image ``(log_pred, log_gt)`` over the loader, splits images into independent fit/score folds (no + leakage), chooses identity / scale-only by cross-validated raw-scale δ1, and writes the winner into the head's + ``cal_a``/``cal_b``. + + Returns: + (dict | None): The :func:`select_calibration_cv` result dict, or None if no Depth head / too few images. + """ + head = _depth_head(model) + if head is None: + LOGGER.warning("calibrate: no Depth head with cal buffers found; skipping.") + return None + pairs = _collect_logpairs(model.to(device).float().eval(), dataloader, device, max_images, max_depth) + if len(pairs) < 2: + LOGGER.warning("calibrate: fewer than 2 valid images for fit/score split; calibration skipped.") + return None + res = select_calibration_cv(pairs, margin=margin) + res["images"] = len(pairs) + head.cal_a.fill_(res["a"]) + head.cal_b.fill_(res["b"]) + scores = " ".join(f"{n}={v:.4f}" for n, v in res["cv_scores"].items()) + LOGGER.info( + f"Depth calibration selected '{res['name']}' (a={res['a']:.4f} b={res['b']:.4f}); CV held-out δ1 {scores}" + ) + return res + + +def _plot_calibrated_batches( + model: torch.nn.Module, + dataloader, + device: torch.device | str, + a: float, + b: float, + name: str, + plot_dir: str | Path, + max_batches: int = 3, + max_images: int = 4, +) -> None: + """Write ``val_batch{ni}_calibrated.jpg`` panels (RGB | GT | raw | calibrated) to ``plot_dir``. + + Runs the model with calibration buffers at identity to get the raw prediction; the calibrated column is its + deterministic affine ``exp(a·log(raw) + b)`` — no second forward. The first ``max_batches`` batches are the same + ones BaseValidator plots as ``val_batch{ni}.jpg`` (val loaders are not shuffled), so the files are directly + comparable. With the "only if it helps" policy the selected ``name`` may be ``identity``; the panels are still + written (raw == calibrated), which documents that calibration was a no-op. Buffers are restored afterwards. + """ + from ultralytics.utils.plotting import plot_depth_panels + + head = _depth_head(model) + a0, b0 = float(head.cal_a), float(head.cal_b) + head.cal_a.fill_(1.0) + head.cal_b.fill_(0.0) + model = model.to(device).eval() + titles = ["RGB", "GT", "raw", f"calibrated ({name} x{np.exp(b):.2f})"] + plot_dir = Path(plot_dir) + _rewind(dataloader) + with torch.no_grad(): + # zip stops on range exhaustion without pulling an extra batch from the stateful iterator + for ni, batch in zip(range(max_batches), dataloader): + img = batch["img"].to(device).float() / 255 + gt = batch["depth"].to(device).float() + raw = model(img).float() + if raw.ndim == 3: + raw = raw.unsqueeze(1) + cal = torch.exp(a * torch.log(raw.clamp(min=1e-3)) + b) + plot_depth_panels( + img, + [raw, cal], + plot_dir / f"val_batch{ni}_calibrated.jpg", + gt=gt, + titles=titles, + max_images=max_images, + ) + head.cal_a.fill_(a0) + head.cal_b.fill_(b0) + + +def calibrate_checkpoint( + ckpt_path: str | Path, + dataloader, + device: torch.device | str, + plot_dir: str | Path | None = None, + *, + dataset_hash: str | None = None, + validation_split: str | None = None, + max_depth: float = 100.0, +) -> dict | None: + """Fit calibration for a saved checkpoint in place (used by automatic post-training calibration). + + Loads the checkpoint, selects calibration with the "calibrate only if it helps" policy + (:func:`fit_calibration_selective`) on ``dataloader`` using a float copy on ``device``, writes the chosen buffers + into the stored model, and re-saves — preserving the rest of the checkpoint. + + Args: + ckpt_path (str | Path): Path to the ``.pt`` checkpoint file to calibrate in place. + dataloader (object): Yields batches with ``img`` (uint8, Bx3xHxW) and ``depth`` (BxHxW meters). + device (str | torch.device): Torch device to run inference on. + plot_dir (str | Path, optional): If set, also write ``val_batch{ni}_calibrated.jpg`` comparison panels (RGB | GT + | raw | calibrated) for the first val batches into this directory. + dataset_hash (str, optional): Immutable dataset manifest identity used for calibration. + validation_split (str, optional): Dataset-root-relative split used to collect calibration images. + max_depth (float): Maximum valid GT depth in meters; pixels beyond it are excluded from the fit and the held-out + δ1 scoring, matching the val metrics' Eigen protocol. + """ + from copy import deepcopy + + from ultralytics.utils.patches import torch_load + + ckpt = torch_load(ckpt_path, map_location="cpu") + saved = ckpt.get("ema") or ckpt.get("model") + if saved is None or _depth_head(saved) is None: + return + work = deepcopy(saved).float() + res = fit_calibration_selective(work, dataloader, device, max_depth=max_depth) + if res is None: + return None + a, b = res["a"], res["b"] + for key in ("ema", "model"): + m = ckpt.get(key) + if m is not None and _depth_head(m) is not None: + _depth_head(m).cal_a.fill_(a) + _depth_head(m).cal_b.fill_(b) + stored_head = _depth_head(ckpt.get("ema") or ckpt.get("model")) + a, b = float(stored_head.cal_a), float(stored_head.cal_b) + provenance = { + "status": "selected", + "candidate": res["name"], + "images": res["images"], + "a": a, + "b": b, + "dataset_hash": dataset_hash, + "validation_split": validation_split, + "strategy": "two-fold-held-out-delta1", + "scores": res["cv_scores"], + } + ckpt["depth_calibration"] = provenance + torch.save(ckpt, ckpt_path) + LOGGER.info( + f"Auto-calibration written to {getattr(ckpt_path, 'name', ckpt_path)}: '{res['name']}' a={a:.4f} b={b:.4f}" + ) + if plot_dir is not None: + try: + _plot_calibrated_batches(work, dataloader, device, a, b, res["name"], plot_dir) + LOGGER.info(f"Calibrated val_batch plots written to {plot_dir}") + except Exception as e: + LOGGER.warning(f"Calibrated val plots skipped ({type(e).__name__}: {e})") + return provenance diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/predict.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..5ad10623a4354baba87e948bd69ce9ed1e1c3c51 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/predict.py @@ -0,0 +1,53 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Depth estimation predictor for YOLO models.""" + +from __future__ import annotations + +from typing import Any + +import numpy as np +import torch + +from ultralytics.engine.predictor import BasePredictor +from ultralytics.engine.results import Results +from ultralytics.utils import DEFAULT_CFG, ops + + +class DepthPredictor(BasePredictor): + """Predictor for YOLO depth estimation models. + + Produces per-pixel depth maps from RGB images. + + Examples: + >>> from ultralytics.models.yolo.depth import DepthPredictor + >>> predictor = DepthPredictor(overrides=dict(model="yolo26n-depth.pt")) + >>> results = predictor("image.jpg") + """ + + def __init__( + self, cfg=DEFAULT_CFG, overrides: dict[str, Any] | None = None, _callbacks: dict | None = None + ) -> None: + """Initialize DepthPredictor.""" + super().__init__(cfg, overrides, _callbacks) + self.args.task = "depth" + + def postprocess( + self, preds: torch.Tensor | tuple | list, img: torch.Tensor, orig_imgs: list[np.ndarray] | torch.Tensor + ) -> list[Results]: + """Post-process depth predictions to Results objects.""" + depth_maps = preds[0] if isinstance(preds, (tuple, list)) else preds # (B, 1, H, W) + if depth_maps.ndim == 3: + depth_maps = depth_maps.unsqueeze(1) # (B, H, W) → (B, 1, H, W) + # Restore model-input resolution so all backends crop letterbox padding before scaling to the original image. + depth_maps = ops.scale_masks(depth_maps, img.shape[2:], padding=False) + + if not isinstance(orig_imgs, list): # torch.Tensor source (B, 3, H, W) + orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)[..., ::-1] + + results = [] + for i, orig_img in enumerate(orig_imgs): + img_path = self.batch[0][i] if isinstance(self.batch[0], list) else self.batch[0] + depth = ops.scale_masks(depth_maps[i : i + 1].float(), orig_img.shape[:2]) + results.append(Results(orig_img=orig_img, path=img_path, names=self.model.names, depth=depth.squeeze())) + + return results diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/train.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2d607cf5b9effbf68e9fbee8eb7147ca2acf5bb8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/train.py @@ -0,0 +1,173 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Depth estimation trainer for YOLO models.""" + +from __future__ import annotations + +from copy import copy +from pathlib import Path +from typing import Any + +from ultralytics.models import yolo +from ultralytics.models.yolo.detect import DetectionTrainer +from ultralytics.nn.tasks import DepthModel +from ultralytics.utils import DEFAULT_CFG, LOGGER, RANK +from ultralytics.utils.plotting import plt_settings + + +class DepthTrainer(DetectionTrainer): + """Trainer for YOLO depth estimation models. + + Multi-source training (list of img_paths) is handled transparently by the base DetectionTrainer/BaseDataset. + + Examples: + >>> from ultralytics.models.yolo.depth import DepthTrainer + >>> args = dict(model="yolo26s-depth.yaml", data="nyu-depth.yaml", epochs=100) + >>> trainer = DepthTrainer(overrides=args) + >>> trainer.train() + """ + + def __init__( + self, cfg=DEFAULT_CFG, overrides: dict[str, Any] | None = None, _callbacks: dict | None = None + ) -> None: + """Initialize DepthTrainer.""" + if overrides is None: + overrides = {} + overrides["task"] = "depth" + super().__init__(cfg, overrides, _callbacks) + + def get_model(self, cfg: str | None = None, weights: str | None = None, verbose: bool = True) -> DepthModel: + """Return a DepthModel initialized with the given config and weights.""" + model = DepthModel( + cfg, ch=self.data.get("channels", 3), nc=self.data["nc"], verbose=verbose and RANK in {-1, 0} + ) + if weights: + model.load(weights) + return model + + def preprocess_batch(self, batch: dict[str, Any]) -> dict[str, Any]: + """Preprocess batch: normalize images and keep depth as float32.""" + batch = super().preprocess_batch(batch) + batch["depth"] = batch["depth"].float() + return batch + + def get_validator(self) -> yolo.depth.DepthValidator: + """Return a DepthValidator for model validation.""" + return yolo.depth.DepthValidator( + self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks + ) + + @plt_settings() + def plot_training_labels(self) -> None: + """Plot the training-set GT depth distribution to ``labels.jpg``. + + The depth analog of the detection/semantic label plots. The inherited DetectionTrainer + version concatenates per-image ``bboxes``/``cls`` (all empty for depth) and hands them to + ``plot_labels``, whose reductions raise "zero-size array to reduction operation maximum + which has no identity". Instead, sample GT depth maps from the training set and plot a + histogram of valid (``> 0``) depth values, annotated with basic statistics. + """ + import matplotlib.pyplot as plt + import numpy as np + + LOGGER.info(f"Plotting labels to {self.save_dir / 'labels.jpg'}...") + dataset = self.train_loader.dataset + n = len(dataset.im_files) + if n == 0: + LOGGER.warning("No depth maps found, skipping label plot.") + return + + sample_size = min(1000, n) + indices = np.linspace(0, n - 1, sample_size).astype(int) + per_map_cap = max(1, 1_000_000 // sample_size) # bound total memory to ~1M values + values = [] + for idx in indices: + d = dataset._load_depth(idx) + if d is None: + continue + v = d[d > 0].ravel() + if v.size == 0: + continue + if v.size > per_map_cap: # uniform stride keeps the spatial distribution unbiased + v = v[np.linspace(0, v.size - 1, per_map_cap).astype(int)] + values.append(v) + + if not values: + LOGGER.warning("No valid depth values found, skipping label plot.") + return + + values = np.concatenate(values) + vmin, vmax = float(values.min()), float(np.percentile(values, 99.5)) + mean, median, std = float(values.mean()), float(np.median(values)), float(values.std()) + + _, ax = plt.subplots(1, 1, figsize=(8, 6), tight_layout=True) + ax.hist(values, bins=100, range=(vmin, max(vmax, vmin + 1e-6)), color="#3b7dd8") + ax.axvline(mean, color="#d8643b", linestyle="--", linewidth=1.5, label=f"mean {mean:.2f} m") + ax.axvline(median, color="#3bd86b", linestyle="--", linewidth=1.5, label=f"median {median:.2f} m") + ax.set_xlabel("Depth (m)") + ax.set_ylabel("Pixels") + ax.set_title("Training Labels Depth Distribution") + ax.legend(loc="upper right", frameon=False) + stats = f"images: {sample_size}\nmin: {vmin:.2f} m\nmax: {values.max():.2f} m\nstd: {std:.2f} m" + ax.text( + 0.98, + 0.7, + stats, + transform=ax.transAxes, + ha="right", + va="top", + fontsize=9, + bbox={"boxstyle": "round", "facecolor": "white", "alpha": 0.6, "edgecolor": "none"}, + ) + for spine in ax.spines.values(): + spine.set_visible(False) + + fname = self.save_dir / "labels.jpg" + plt.savefig(fname, dpi=200) + plt.close() + if self.on_plot: + self.on_plot(fname) + + def final_eval(self) -> None: + """Run the standard final evaluation, then calibrate the saved checkpoints. + + After training, fits the scale-only log-affine (``cal_a``/``cal_b``) on the validation + set and writes it into best.pt/last.pt, so the model outputs metric-scaled depth out of + the box. When ``plots`` is set, also writes ``val_batch{ni}_calibrated.jpg`` + (RGB | GT | raw | calibrated) comparison panels. + """ + super().final_eval() + if RANK not in {-1, 0}: + return + try: + from .calibrate import calibrate_checkpoint + + LOGGER.info("Calibrating depth output scale on the validation set...") + plot_ckpt = self.best if self.best.exists() else self.last + for ckpt in (self.best, self.last): + if ckpt.exists(): + plot_dir = self.save_dir if self.args.plots and ckpt == plot_ckpt else None + validation_path = self.data[self.args.split] + validation_split = None + if isinstance(validation_path, (str, Path)): + try: + validation_split = ( + Path(validation_path) + .resolve() + .relative_to(Path(self.data["path"]).resolve()) + .as_posix() + ) + except ValueError: + pass # External validation paths have no portable dataset-root-relative identifier. + provenance = calibrate_checkpoint( + ckpt, + self.test_loader, + self.device, + plot_dir=plot_dir, + dataset_hash=self.data.get("hash"), + validation_split=validation_split, + max_depth=self.data.get("max_depth") or 100.0, + ) + if ckpt == plot_ckpt and provenance is not None: + self.depth_calibration = provenance + except Exception as e: + LOGGER.warning(f"Calibration skipped ({type(e).__name__}: {e}); checkpoints left uncalibrated.") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/val.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/val.py new file mode 100644 index 0000000000000000000000000000000000000000..6b7591c066ce6e335e441ec8fb7e8342cfe5ee1e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/depth/val.py @@ -0,0 +1,135 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Depth estimation validator for YOLO models.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import torch +import torch.distributed as dist +import torch.nn.functional as F + +from ultralytics.models.yolo.detect import DetectionValidator +from ultralytics.utils import LOGGER, RANK +from ultralytics.utils.metrics import DepthMetrics +from ultralytics.utils.plotting import plot_images + + +class DepthValidator(DetectionValidator): + """Validator for YOLO depth estimation models. + + Computes standard depth metrics: delta1, abs_rel, rmse, silog. Uses validation loss as the primary training signal. + """ + + def __init__( + self, + dataloader=None, + save_dir: str | Path | None = None, + args=None, + _callbacks: dict | None = None, + ) -> None: + """Initialize DepthValidator.""" + super().__init__(dataloader, save_dir, args, _callbacks) + self.args.task = "depth" + + def init_metrics(self, model: torch.nn.Module) -> None: + """Initialize the DepthMetrics accumulator with the dataset's depth range.""" + self.metrics = DepthMetrics(max_depth=self.data.get("max_depth") or 100.0) + self.metrics.clear_stats() + + def preprocess(self, batch: dict[str, Any]) -> dict[str, Any]: + """Preprocess batch — move to device, normalize images, and keep depth as float32.""" + batch = super().preprocess(batch) + batch["depth"] = batch["depth"].float() + return batch + + def postprocess(self, preds: torch.Tensor) -> torch.Tensor: + """No NMS needed for depth — return predictions as-is.""" + return preds + + def update_metrics(self, preds: torch.Tensor, batch: dict[str, Any]) -> None: + """Accumulate depth metrics for a batch.""" + gt_depth = batch["depth"] + if gt_depth.ndim == 3: + gt_depth = gt_depth.unsqueeze(1) + if preds.ndim == 3: + preds = preds.unsqueeze(1) + if preds.shape[-2:] != gt_depth.shape[-2:]: + preds = F.interpolate(preds.float(), size=gt_depth.shape[-2:], mode="bilinear", align_corners=True) + self.metrics.update_stats(preds, gt_depth) + + def get_stats(self) -> dict[str, float]: + """Finalize and return the metrics dict. + + Cross-rank metric reduction is handled by gather_stats() (called before this on all ranks); + this runs on rank 0 with the already-summed accumulators. + """ + self.metrics.process() + return self.metrics.results_dict + + def gather_stats(self) -> None: + """Sum depth metric accumulators across DDP ranks onto rank 0. + + Validation is sharded (ContiguousDistributedSampler gives each rank a distinct chunk of the + val set), so each rank holds only its shard's summed statistics. All-reduce the sums so + rank 0's get_stats() computes metrics over the full val set instead of a single shard. + Overrides DetectionValidator.gather_stats(), which reduces detection-specific stats/box + attributes that DepthMetrics does not have. + """ + if RANK == -1 or not dist.is_initialized(): + return + totals = self.metrics._totals + totals = ( + totals.to(self.device) if totals is not None else torch.zeros(6, dtype=torch.float64, device=self.device) + ) + count = torch.tensor([self.metrics._count], dtype=torch.float64, device=self.device) + dist.all_reduce(totals, op=dist.ReduceOp.SUM) + dist.all_reduce(count, op=dist.ReduceOp.SUM) + self.metrics._totals = totals + self.metrics._count = float(count.item()) + + def print_results(self) -> None: + """Log the headline depth metrics in the detection-style aligned table format. + + Columns line up with get_desc(): Class, Images, delta1, abs_rel, rmse, silog. + Uses "depth_val" as the row label (depth has no classes, where detection prints "all"). + """ + r = self.metrics.results_dict + n_images = len(self.dataloader.dataset) if self.dataloader is not None else (self.seen or 0) + pf = "%22s" + "%11i" + "%11.4g" * 4 # label, Images, delta1, abs_rel, rmse, silog + LOGGER.info( + pf + % ( + "depth_val", + n_images, + r.get("metrics/delta1", 0.0), + r.get("metrics/abs_rel", 0.0), + r.get("metrics/rmse", 0.0), + r.get("metrics/silog", 0.0), + ) + ) + + def finalize_metrics(self) -> None: + """Set final values for metrics speed.""" + self.metrics.speed = self.speed + self.metrics.save_dir = self.save_dir + + def get_desc(self) -> str: + """Return description for progress bar.""" + return ("%22s" + "%11s" * 5) % ("Class", "Images", "delta1", "abs_rel", "rmse", "silog") + + def plot_predictions(self, batch: dict[str, Any], preds: torch.Tensor, ni: int) -> None: + """Save predicted depth overlays to val_batch{ni}_pred.jpg. + + Depth has no boxes/classes, so the detection-style plotter is replaced with a depth heatmap overlay + through the shared ``plot_images`` path, matching the semantic-segmentation visualization style. + """ + plot_images( + labels={"depth": preds}, + images=batch["img"], + paths=batch["im_file"], + fname=self.save_dir / f"val_batch{ni}_pred.jpg", + names=self.names, + on_plot=self.on_plot, + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..caece94ae0c06d51e8a4a4c5a083d74a6c731c90 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__init__.py @@ -0,0 +1,7 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .predict import DetectionPredictor +from .train import DetectionTrainer +from .val import DetectionValidator + +__all__ = "DetectionPredictor", "DetectionTrainer", "DetectionValidator" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abdfbab488066197bfe584d907426d74570ea8e8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__pycache__/predict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__pycache__/predict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e6b0a954a24267f0eb9d0eb6caf84bdb789cb84 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__pycache__/predict.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__pycache__/train.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__pycache__/train.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b27f437b06f7874fa856fe71f44e16de2c76cae Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__pycache__/train.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__pycache__/val.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__pycache__/val.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f96a9cd27d745964e6bb41dbf95d35a87142e25a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/__pycache__/val.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/predict.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..22bc68577176cd521ffef7f2f29100d4ceeebdc4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/predict.py @@ -0,0 +1,122 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from ultralytics.engine.predictor import BasePredictor +from ultralytics.engine.results import Results +from ultralytics.utils import nms, ops + + +class DetectionPredictor(BasePredictor): + """A class extending the BasePredictor class for prediction based on a detection model. + + This predictor specializes in object detection tasks, processing model outputs into meaningful detection results + with bounding boxes and class predictions. + + Attributes: + args (namespace): Configuration arguments for the predictor. + model (nn.Module): The detection model used for inference. + batch (list): Batch of images and metadata for processing. + + Methods: + postprocess: Process raw model predictions into detection results. + construct_results: Build Results objects from processed predictions. + construct_result: Create a single Result object from a prediction. + get_obj_feats: Extract object features from the feature maps. + + Examples: + >>> from ultralytics.utils import ASSETS + >>> from ultralytics.models.yolo.detect import DetectionPredictor + >>> args = dict(model="yolo26n.pt", source=ASSETS) + >>> predictor = DetectionPredictor(overrides=args) + >>> predictor.predict_cli() + """ + + def postprocess(self, preds, img, orig_imgs, **kwargs): + """Post-process predictions and return a list of Results objects. + + This method applies non-maximum suppression to raw model predictions and prepares them for visualization and + further analysis. + + Args: + preds (torch.Tensor): Raw predictions from the model. + img (torch.Tensor): Processed input image tensor in model input format. + orig_imgs (torch.Tensor | list): Original input images before preprocessing. + **kwargs (Any): Additional keyword arguments. + + Returns: + (list): List of Results objects containing the post-processed predictions. + + Examples: + >>> predictor = DetectionPredictor(overrides=dict(model="yolo26n.pt")) + >>> results = predictor.predict("path/to/image.jpg") + >>> processed_results = predictor.postprocess(preds, img, orig_imgs) + """ + save_feats = getattr(self, "_feats", None) is not None + preds = nms.non_max_suppression( + preds, + self.args.conf, + kwargs.pop("iou", self.args.iou), # allow callers (e.g. TrackTrack loose-NMS recovery) to override IoU + self.args.classes, + self.args.agnostic_nms, + max_det=self.args.max_det, + nc=0 if self.args.task == "detect" else len(self.model.names), + end2end=getattr(self.model, "end2end", False), + rotated=self.args.task == "obb", + return_idxs=save_feats, + ) + + if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list + orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)[..., ::-1] + + if save_feats: + obj_feats = self.get_obj_feats(self._feats, preds[1]) + preds = preds[0] + + results = self.construct_results(preds, img, orig_imgs, **kwargs) + + if save_feats: + for r, f in zip(results, obj_feats): + r.feats = f # add object features to results + + return results + + @staticmethod + def get_obj_feats(feat_maps, idxs): + """Extract object features from the feature maps.""" + import torch + + s = min(x.shape[1] for x in feat_maps) # find shortest vector length + obj_feats = torch.cat( + [x.permute(0, 2, 3, 1).reshape(x.shape[0], -1, s, x.shape[1] // s).mean(dim=-1) for x in feat_maps], dim=1 + ) # mean reduce all vectors to same length + return [feats[idx] if idx.shape[0] else [] for feats, idx in zip(obj_feats, idxs)] # for each img in batch + + def construct_results(self, preds, img, orig_imgs): + """Construct a list of Results objects from model predictions. + + Args: + preds (list[torch.Tensor]): List of predicted bounding boxes and scores for each image. + img (torch.Tensor): Batch of preprocessed images used for inference. + orig_imgs (list[np.ndarray]): List of original images before preprocessing. + + Returns: + (list[Results]): List of Results objects containing detection information for each image. + """ + return [ + self.construct_result(pred, img, orig_img, img_path) + for pred, orig_img, img_path in zip(preds, orig_imgs, self.batch[0]) + ] + + def construct_result(self, pred, img, orig_img, img_path): + """Construct a single Results object from one image prediction. + + Args: + pred (torch.Tensor): Predicted boxes and scores with shape (N, 6) where N is the number of detections. + img (torch.Tensor): Preprocessed image tensor used for inference. + orig_img (np.ndarray): Original image before preprocessing. + img_path (str): Path to the original image file. + + Returns: + (Results): Results object containing the original image, image path, class names, and scaled bounding boxes. + """ + pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape) + return Results(orig_img, path=img_path, names=self.model.names, boxes=pred[:, :6]) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/train.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/train.py new file mode 100644 index 0000000000000000000000000000000000000000..f73c575b5cbbf28248ae63735ceee351ce5ca2c7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/train.py @@ -0,0 +1,259 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import math +import random +from copy import copy +from typing import Any + +import numpy as np +import torch +from torch import nn + +from ultralytics.data import build_dataloader, build_yolo_dataset +from ultralytics.engine.trainer import BaseTrainer +from ultralytics.models import yolo +from ultralytics.nn.tasks import DetectionModel +from ultralytics.utils import DEFAULT_CFG, LOGGER, RANK +from ultralytics.utils.patches import override_configs +from ultralytics.utils.plotting import plot_images, plot_labels +from ultralytics.utils.torch_utils import torch_distributed_zero_first, unwrap_model + + +class DetectionTrainer(BaseTrainer): + """A class extending the BaseTrainer class for training based on a detection model. + + This trainer specializes in object detection tasks, handling the specific requirements for training YOLO models for + object detection including dataset building, data loading, preprocessing, and model configuration. + + Attributes: + model (DetectionModel): The YOLO detection model being trained. + data (dict): Dictionary containing dataset information including class names and number of classes. + loss_names (tuple): Names of the loss components, derived from the loss dict returned by the criterion. + + Methods: + build_dataset: Build YOLO dataset for training or validation. + get_dataloader: Construct and return dataloader for the specified mode. + preprocess_batch: Preprocess a batch of images by scaling and converting to float. + set_model_attributes: Set model attributes based on dataset information. + get_model: Return a YOLO detection model. + get_validator: Return a validator for model evaluation. + progress_string: Return a formatted string of training progress. + plot_training_samples: Plot training samples with their annotations. + plot_training_labels: Create a labeled training plot of the YOLO model. + auto_batch: Calculate optimal batch size based on model memory requirements. + + Examples: + >>> from ultralytics.models.yolo.detect import DetectionTrainer + >>> args = dict(model="yolo26n.pt", data="coco8.yaml", epochs=3) + >>> trainer = DetectionTrainer(overrides=args) + >>> trainer.train() + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides: dict[str, Any] | None = None, _callbacks: dict | None = None): + """Initialize a DetectionTrainer object for training YOLO object detection models. + + Args: + cfg (dict, optional): Default configuration dictionary containing training parameters. + overrides (dict, optional): Dictionary of parameter overrides for the default configuration. + _callbacks (dict, optional): Dictionary of callback functions to be executed during training. + """ + super().__init__(cfg, overrides, _callbacks) + + def build_dataset(self, img_path: str, mode: str = "train", batch: int | None = None): + """Build YOLO Dataset for training or validation. + + Args: + img_path (str): Path to the folder containing images. + mode (str): 'train' mode or 'val' mode, users are able to customize different augmentations for each mode. + batch (int, optional): Size of batches, this is for 'rect' mode. + + Returns: + (Dataset): YOLO dataset object configured for the specified mode. + """ + gs = max(int(unwrap_model(self.model).stride.max()), 32) + return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, rect=mode == "val", stride=gs) + + def get_dataloader(self, dataset_path: str, batch_size: int = 16, rank: int = 0, mode: str = "train"): + """Construct and return dataloader for the specified mode. + + Args: + dataset_path (str): Path to the dataset. + batch_size (int): Number of images per batch. + rank (int): Process rank for distributed training. + mode (str): 'train' for training dataloader, 'val' for validation dataloader. + + Returns: + (DataLoader): PyTorch dataloader object. + """ + assert mode in {"train", "val"}, f"Mode must be 'train' or 'val', not {mode}." + with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP + dataset = self.build_dataset(dataset_path, mode, batch_size) + shuffle = mode == "train" + if getattr(dataset, "rect", False) and shuffle and not np.all(dataset.batch_shapes == dataset.batch_shapes[0]): + LOGGER.warning("'rect=True' is incompatible with DataLoader shuffle, setting shuffle=False") + shuffle = False + return build_dataloader( + dataset, + batch=batch_size, + workers=self.args.workers if mode == "train" else self.args.workers * 2, + shuffle=shuffle, + rank=rank, + drop_last=self.args.compile and mode == "train", + device=self.device, + ) + + def preprocess_batch(self, batch: dict) -> dict: + """Preprocess a batch of images by scaling and converting to float. + + Args: + batch (dict): Dictionary containing batch data with 'img' tensor. + + Returns: + (dict): Preprocessed batch with normalized images. + """ + for k, v in batch.items(): + if isinstance(v, torch.Tensor): + batch[k] = v.to(self.device, non_blocking=self.device.type not in {"cpu", "mps"}) + batch["img"] = batch["img"].float() / 255 + if self.args.multi_scale > 0.0: + imgs = batch["img"] + sz = ( + random.randrange( + max(self.stride, int(self.args.imgsz * (1.0 - self.args.multi_scale))), # min imgsz + int(self.args.imgsz * (1.0 + self.args.multi_scale) + self.stride), # max imgsz + ) + // self.stride + * self.stride + ) # size + sf = sz / max(imgs.shape[2:]) # scale factor + if sf != 1: + ns = [ + math.ceil(x * sf / self.stride) * self.stride for x in imgs.shape[2:] + ] # new shape (stretched to gs-multiple) + imgs = nn.functional.interpolate(imgs, size=ns, mode="bilinear", align_corners=False) + batch["img"] = imgs + return batch + + def set_model_attributes(self): + """Set model attributes based on dataset information.""" + # Nl = de_parallel(self.model).model[-1].nl # number of detection layers (to scale hyps) + # self.args.box *= 3 / nl # scale to layers + # self.args.cls *= self.data["nc"] / 80 * 3 / nl # scale to classes and layers + # self.args.cls *= (self.args.imgsz / 640) ** 2 * 3 / nl # scale to image size and layers + self.model.nc = self.data["nc"] # attach number of classes to model + self.model.names = self.data["names"] # attach class names to model + self.model.args = self.args # attach hyperparameters to model + + def set_model_names_for_load(self, model): + """Set target dataset names before loading weights so cls heads can remap by name.""" + if getattr(self.args, "cls_remap", True) and self.data.get("names"): + model.names = self.data["names"] + return model + + def get_class_counts(self): + """Return per-class instance counts from the training dataset labels.""" + classes = np.concatenate([lb["cls"].flatten() for lb in self.train_loader.dataset.labels], 0) + return np.bincount(classes.astype(int), minlength=self.data["nc"]).astype(np.float32) + + def compute_class_weights(self, class_counts): + """Convert class counts to inverse-frequency weights raised to the power of cls_pw.""" + class_counts = np.where(class_counts == 0, 1.0, class_counts) + return (1.0 / class_counts) ** self.args.cls_pw # apply power directly + + def set_class_weights(self): + """Compute and set class weights for handling class imbalance. + + Class weights are computed based on inverse class frequency in the training dataset, + raised to the power of cls_pw (0 < cls_pw <= 1 dampens; values are restricted to the range [0, 1]). + Final weights are normalized so their mean equals 1.0. + """ + assert 0 <= self.args.cls_pw <= 1.0, "cls_pw must be in the range [0, 1]" + if self.args.cls_pw == 0.0: + return + class_counts = self.get_class_counts() + if not class_counts.any(): # nothing counted (e.g. missing/unreadable masks); keep default weights + return + weights = self.compute_class_weights(class_counts) + weights = weights / weights.mean() # normalize so mean equals 1.0 + model = unwrap_model(self.model) + if hasattr(model, "student_model"): + model = model.student_model # distillation: the student model builds the loss criterion + model.class_weights = torch.from_numpy(weights).to(self.device) + LOGGER.info(f"Class weights: {model.class_weights.cpu().numpy().round(3)}") + + def get_model(self, cfg: str | None = None, weights: str | None = None, verbose: bool = True): + """Return a YOLO detection model. + + Args: + cfg (str, optional): Path to model configuration file. + weights (str, optional): Path to model weights. + verbose (bool): Whether to display model information. + + Returns: + (DetectionModel): YOLO detection model. + """ + model = self.set_model_names_for_load( + DetectionModel(cfg, nc=self.data["nc"], ch=self.data["channels"], verbose=verbose and RANK == -1) + ) + if weights: + model.load(weights) + return model + + def get_validator(self): + """Return a DetectionValidator for YOLO model validation.""" + return yolo.detect.DetectionValidator( + self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks + ) + + def _build_train_pipeline(self): + """Build the training pipeline and align the default detection limit with observed dataset object counts.""" + super()._build_train_pipeline() + if self.args.task in {"detect", "segment", "pose", "obb"}: + datasets = {"train": self.train_loader.dataset, "val": self.test_loader.dataset} + yolo.detect.DetectionValidator._check_max_det(self.args, datasets) + unwrap_model(self.model).set_head_attr(max_det=self.args.max_det) + + def progress_string(self): + """Return a formatted string of training progress with epoch, GPU memory, loss, instances and size.""" + return ("\n" + "%11s" * (4 + len(self.loss_names))) % ( + "Epoch", + "GPU_mem", + *self.loss_names, + "Instances", + "Size", + ) + + def plot_training_samples(self, batch: dict[str, Any], ni: int) -> None: + """Plot training samples with their annotations. + + Args: + batch (dict[str, Any]): Dictionary containing batch data. + ni (int): Batch index used for naming the output file. + """ + plot_images( + labels=batch, + paths=batch["im_file"], + fname=self.save_dir / f"train_batch{ni}.jpg", + on_plot=self.on_plot, + ) + + def plot_training_labels(self): + """Create a labeled training plot of the YOLO model.""" + boxes = np.concatenate([lb["bboxes"] for lb in self.train_loader.dataset.labels], 0) + cls = np.concatenate([lb["cls"] for lb in self.train_loader.dataset.labels], 0) + plot_labels(boxes, cls.squeeze(), names=self.data["names"], save_dir=self.save_dir, on_plot=self.on_plot) + + def auto_batch(self): + """Get optimal batch size by calculating memory occupation of model. + + Returns: + (int): Optimal batch size. + """ + with override_configs(self.args, overrides={"cache": False}) as self.args: + train_dataset = self.build_dataset(self.data["train"], mode="train", batch=16) + max_num_obj = max(len(label["cls"]) for label in train_dataset.labels) * 4 # 4 for mosaic augmentation + n = len(train_dataset) + del train_dataset # free memory + return super().auto_batch(max_num_obj, dataset_size=n) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/val.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/val.py new file mode 100644 index 0000000000000000000000000000000000000000..e08e369851fb80156525451a3641cf2dfc61c7ba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/val.py @@ -0,0 +1,628 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import os +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.distributed as dist + +from ultralytics.data import build_dataloader, build_yolo_dataset, converter +from ultralytics.data.utils import get_split_fraction +from ultralytics.engine.validator import BaseValidator +from ultralytics.utils import DEFAULT_CFG, LOGGER, RANK, nms, ops +from ultralytics.utils.checks import check_requirements +from ultralytics.utils.metrics import ConfusionMatrix, DetMetrics, box_iou +from ultralytics.utils.plotting import plot_images + + +class DetectionValidator(BaseValidator): + """A class extending the BaseValidator class for validation based on a detection model. + + This class implements validation functionality specific to object detection tasks, including metrics calculation, + prediction processing, and visualization of results. + + Attributes: + is_coco (bool): Whether the dataset is COCO. + is_lvis (bool): Whether the dataset is LVIS. + class_map (list[int]): Mapping from model class indices to dataset class indices. + metrics (DetMetrics): Object detection metrics calculator. + iouv (torch.Tensor): IoU thresholds for mAP calculation. + niou (int): Number of IoU thresholds. + jdict (list[dict[str, Any]]): List for storing JSON detection results. + stats (dict[str, list[torch.Tensor]]): Dictionary for storing statistics during validation. + + Examples: + >>> from ultralytics.models.yolo.detect import DetectionValidator + >>> args = dict(model="yolo26n.pt", data="coco8.yaml") + >>> validator = DetectionValidator(args=args) + >>> validator() + """ + + def __init__(self, dataloader=None, save_dir=None, args=None, _callbacks: dict | None = None) -> None: + """Initialize detection validator with necessary variables and settings. + + Args: + dataloader (torch.utils.data.DataLoader, optional): DataLoader to use for validation. + save_dir (Path, optional): Directory to save results. + args (dict[str, Any], optional): Arguments for the validator. + _callbacks (dict, optional): Dictionary of callback functions. + """ + conf = args.get("conf") if isinstance(args, dict) else getattr(args, "conf", None) + self.confusion_matrix_conf = 0.25 if conf is None else conf + super().__init__(dataloader, save_dir, args, _callbacks) + self.is_coco = False + self.is_lvis = False + self.class_map = None + self.args.task = "detect" + self.iouv = torch.linspace(0.5, 0.95, 10) # IoU vector for mAP@0.5:0.95 + self.niou = self.iouv.numel() + self.metrics = DetMetrics() + + @staticmethod + def _check_max_det(args, datasets: dict[str, torch.utils.data.Dataset]) -> None: + """Warn when dataset object counts exceed max_det and raise the default limit to the observed maximum.""" + maxima = { + split: max( + ( + len(label["cls"]) + for subset in getattr(dataset, "datasets", [dataset]) + if hasattr(subset, "labels") + for label in subset.labels + if isinstance(label, dict) and getattr(label.get("cls"), "ndim", 0) > 0 + ), + default=0, + ) + for split, dataset in datasets.items() + } + observed = max(maxima.values()) + if observed <= args.max_det: + return + + split_counts = ", ".join(f"{split}={count}" for split, count in maxima.items()) + message = ( + f"Dataset images contain up to {observed} objects ({split_counts}), but max_det={args.max_det}. " + "This mismatch can cap recall and produce invalid validation metrics." + " Raising it may increase validation cost but cannot increase model or export capacity, which may cap recall." + ) + if args.max_det == DEFAULT_CFG.max_det: + args.max_det = observed + message += f" Setting max_det={observed} to match the observed maximum." + else: + message += f" Keeping the user-specified max_det={args.max_det}." + if RANK in {-1, 0}: + LOGGER.warning(message) + + def preprocess(self, batch: dict[str, Any]) -> dict[str, Any]: + """Preprocess batch of images for YOLO validation. + + Args: + batch (dict[str, Any]): Batch containing images and annotations. + + Returns: + (dict[str, Any]): Preprocessed batch. + """ + for k, v in batch.items(): + if isinstance(v, torch.Tensor): + batch[k] = v.to(self.device, non_blocking=self.device.type not in {"cpu", "mps"}) + batch["img"] = (batch["img"].half() if self.args.quantize == 16 else batch["img"].float()) / 255 + return batch + + def init_metrics(self, model: torch.nn.Module) -> None: + """Initialize evaluation metrics for YOLO detection validation. + + Args: + model (torch.nn.Module): Model to validate. + """ + if not self.training: + self._check_max_det(self.args, {self.args.split or "val": self.dataloader.dataset}) + val = self.data.get(self.args.split, "") # validation path + self.is_coco = ( + isinstance(val, str) + and "coco" in val + and (val.endswith((f"{os.sep}val2017.txt", f"{os.sep}test-dev2017.txt"))) + ) + self.is_lvis = isinstance(val, str) and "lvis" in val and not self.is_coco # is LVIS + self.class_map = converter.coco80_to_coco91_class() if self.is_coco else list(range(1, len(model.names) + 1)) + self.args.save_json |= self.args.val and (self.is_coco or self.is_lvis) and not self.training # run final val + self.names = model.names + self.nc = len(model.names) + self.end2end = getattr(model, "end2end", False) + native_model = model.model if getattr(model, "format", None) == "pt" else model + if self.end2end and hasattr(native_model, "set_head_attr"): + native_model.set_head_attr(max_det=self.args.max_det, agnostic_nms=self.args.agnostic_nms) + self.seen = 0 + self.jdict = [] + self.is_custom_json = self.args.save_json and self.args.task == "detect" and not (self.is_coco or self.is_lvis) + self.gdict = getattr(self, "gdict", None) if self.is_custom_json else None + self.build_gdict = self.is_custom_json and self.gdict is None + self.eval_ids = list(self.dataloader.sampler) if self.is_custom_json else None + self.pred_counts = [] + if self.build_gdict: + self.gdict = {"images": [], "annotations": [], "categories": [{"id": x} for x in self.class_map]} + self.metrics.names = model.names + self.metrics.clear_stats() + self.metrics.clear_image_metrics() + self.confusion_matrix = ConfusionMatrix(names=model.names, save_matches=self.args.plots and self.args.visualize) + + def get_desc(self) -> str: + """Return a formatted string summarizing class metrics of YOLO model.""" + return ("%22s" + "%11s" * 6) % ("Class", "Images", "Instances", "Box(P", "R", "mAP50", "mAP50-95)") + + def postprocess(self, preds: torch.Tensor) -> list[dict[str, torch.Tensor]]: + """Apply Non-maximum suppression to prediction outputs. + + Args: + preds (torch.Tensor): Raw predictions from the model. + + Returns: + (list[dict[str, torch.Tensor]]): Processed predictions after NMS, where each dict contains 'bboxes', 'conf', + 'cls', and 'extra' tensors. + """ + outputs = nms.non_max_suppression( + preds, + self.args.conf, + self.args.iou, + nc=0 if self.args.task == "detect" else self.nc, + multi_label=True, + agnostic=self.args.single_cls or self.args.agnostic_nms, + max_det=self.args.max_det, + end2end=self.end2end, + rotated=self.args.task == "obb", + ) + return [{"bboxes": x[:, :4], "conf": x[:, 4], "cls": x[:, 5], "extra": x[:, 6:]} for x in outputs] + + def _prepare_batch(self, si: int, batch: dict[str, Any]) -> dict[str, Any]: + """Prepare a batch of images and annotations for validation. + + Args: + si (int): Sample index within the batch. + batch (dict[str, Any]): Batch data containing images and annotations. + + Returns: + (dict[str, Any]): Prepared batch with processed annotations. + """ + idx = batch["batch_idx"] == si + cls = batch["cls"][idx].squeeze(-1) + bbox = batch["bboxes"][idx] + ori_shape = batch["ori_shape"][si] + imgsz = batch["img"].shape[2:] + ratio_pad = batch["ratio_pad"][si] + if cls.shape[0]: + bbox = ops.xywh2xyxy(bbox) * torch.tensor(imgsz, device=self.device)[[1, 0, 1, 0]] # target boxes + return { + "cls": cls, + "bboxes": bbox, + "ori_shape": ori_shape, + "imgsz": imgsz, + "ratio_pad": ratio_pad, + "im_file": batch["im_file"][si], + } + + def _prepare_pred(self, pred: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: + """Prepare predictions for evaluation against ground truth. + + Args: + pred (dict[str, torch.Tensor]): Post-processed predictions from the model. + + Returns: + (dict[str, torch.Tensor]): Prepared predictions in native space. + """ + if self.args.single_cls: + pred["cls"] *= 0 + return pred + + def update_metrics(self, preds: list[dict[str, torch.Tensor]], batch: dict[str, Any]) -> None: + """Update metrics with new predictions and ground truth. + + Args: + preds (list[dict[str, torch.Tensor]]): List of predictions from the model. + batch (dict[str, Any]): Batch data containing ground truth. + """ + for si, pred in enumerate(preds): + self.seen += 1 + pbatch = self._prepare_batch(si, batch) + cls = pbatch["cls"].cpu().numpy() + im_idx = self.eval_ids[self.seen - 1] if self.is_custom_json else None + if self.build_gdict: + boxes = ops.xyxy2ltwh( + ops.scale_boxes(pbatch["imgsz"], pbatch["bboxes"].clone(), pbatch["ori_shape"], pbatch["ratio_pad"]) + ).tolist() + self.gdict["images"].append({"id": im_idx}) + self.gdict["annotations"].extend( + { + "id": (im_idx << 32 | i) + 1, + "image_id": im_idx, + "category_id": self.class_map[int(c)], + "bbox": b, + "area": b[2] * b[3], + "iscrowd": 0, + } + for i, (b, c) in enumerate(zip(boxes, cls)) + ) + predn = self._prepare_pred(pred) + if self.is_custom_json: + self.pred_counts.append(len(predn["cls"])) + + no_pred = predn["cls"].shape[0] == 0 + self.metrics.update_stats( + { + **self._process_batch(predn, pbatch), + "target_cls": cls, + "target_img": np.unique(cls), + "conf": np.zeros(0) if no_pred else predn["conf"].cpu().numpy(), + "pred_cls": np.zeros(0) if no_pred else predn["cls"].cpu().numpy(), + "im_name": Path(pbatch["im_file"]).name, + } + ) + if self.args.plots: + self.confusion_matrix.process_batch(predn, pbatch, conf=self.confusion_matrix_conf) + if self.args.visualize: + self.confusion_matrix.plot_matches( + batch["img"][si], + pbatch["im_file"], + self.save_dir, + self.args.show_labels, + self.args.show_conf, + ) + + if no_pred: + continue + + if self.args.save_json or self.args.save_txt: + predn_scaled = self.scale_preds(predn, pbatch) + if self.args.save_json: + self.pred_to_json(predn_scaled, pbatch) + if self.args.save_txt: + self.save_one_txt( + predn_scaled, + self.args.save_conf, + pbatch["ori_shape"], + self.save_dir / "labels" / f"{Path(pbatch['im_file']).stem}.txt", + ) + + def finalize_metrics(self) -> None: + """Set final values for metrics speed and confusion matrix.""" + if self.args.plots: + for normalize in True, False: + self.confusion_matrix.plot(save_dir=self.save_dir, normalize=normalize, on_plot=self.on_plot) + self.metrics.speed = self.speed + self.metrics.confusion_matrix = self.confusion_matrix + self.metrics.save_dir = self.save_dir + + def _gather_image_metrics(self, metric) -> None: + """Gather per-image metrics from all GPUs for a single metric object.""" + if RANK == 0: + gathered_image_metrics = [None] * dist.get_world_size() + dist.gather_object(metric.image_metrics, gathered_image_metrics, dst=0) + metric.clear_image_metrics() + for image_metrics in gathered_image_metrics: + if image_metrics: + metric.image_metrics.update(image_metrics) + elif RANK > 0: + dist.gather_object(metric.image_metrics, None, dst=0) + metric.clear_image_metrics() + + def gather_stats(self) -> None: + """Gather stats from all GPUs.""" + if RANK == 0: + gathered_stats = [None] * dist.get_world_size() + dist.gather_object(self.metrics.stats, gathered_stats, dst=0) + merged_stats = {key: [] for key in self.metrics.stats} + for stats_dict in gathered_stats: + for key, value in stats_dict.items(): + merged_stats[key].extend(value) + gathered_json = [None] * dist.get_world_size() + dist.gather_object( + (self.jdict, self.gdict if self.build_gdict else None, self.pred_counts), gathered_json, dst=0 + ) + self.jdict = [x for jdict, _, _ in gathered_json for x in jdict] + self.pred_counts = [x for _, _, counts in gathered_json for x in counts] + if self.build_gdict: + for key in "images", "annotations": + self.gdict[key] = [x for _, gdict, _ in gathered_json for x in gdict[key]] + self.metrics.stats = merged_stats + self._gather_image_metrics(self.metrics.box) + self.seen = len(self.dataloader.dataset) # total image count from dataset + elif RANK > 0: + dist.gather_object(self.metrics.stats, None, dst=0) + dist.gather_object((self.jdict, self.gdict if self.build_gdict else None, self.pred_counts), None, dst=0) + self._gather_image_metrics(self.metrics.box) + self.jdict = [] + self.metrics.clear_stats() + if self.args.plots and RANK > -1: + matrix = torch.as_tensor(self.confusion_matrix.matrix, device=self.device) + dist.reduce(matrix, dst=0, op=dist.ReduceOp.SUM) + if RANK == 0: + self.confusion_matrix.matrix = matrix.cpu().numpy() + + def get_stats(self) -> dict[str, Any]: + """Calculate and return metrics statistics. + + Returns: + (dict[str, Any]): Dictionary containing metrics results. + """ + self.metrics.process(save_dir=self.save_dir, plot=self.args.plots, on_plot=self.on_plot) + stats = self.metrics.results_dict + if self.args.save_json and self.args.task == "detect": + stats.update({f"metrics/mAP_{x}(B)": 0.0 for x in ("small", "medium", "large")}) + if self.training: + stats = self.eval_json(stats) + self.metrics.clear_stats() + return stats + + def print_results(self) -> None: + """Print training/validation set metrics per class.""" + pf = "%22s" + "%11i" * 2 + "%11.3g" * len(self.metrics.keys) # print format + LOGGER.info(pf % ("all", self.seen, self.metrics.nt_per_class.sum(), *self.metrics.mean_results())) + if self.metrics.nt_per_class.sum() == 0: + LOGGER.warning(f"no labels found in {self.args.task} set, cannot compute metrics without labels") + + # Print results per class + if self.args.verbose and not self.training and self.nc > 1: + for i, c in enumerate(self.metrics.ap_class_index): + LOGGER.info( + pf + % ( + self.names[c], + self.metrics.nt_per_image[c], + self.metrics.nt_per_class[c], + *self.metrics.class_result(i), + ) + ) + + def _process_batch(self, preds: dict[str, torch.Tensor], batch: dict[str, Any]) -> dict[str, np.ndarray]: + """Return correct prediction matrix. + + Args: + preds (dict[str, torch.Tensor]): Dictionary containing prediction data with 'bboxes' and 'cls' keys. + batch (dict[str, Any]): Batch dictionary containing ground truth data with 'bboxes' and 'cls' keys. + + Returns: + (dict[str, np.ndarray]): Dictionary containing 'tp' key with correct prediction matrix of shape (N, 10) for + 10 IoU levels. + """ + if batch["cls"].shape[0] == 0 or preds["cls"].shape[0] == 0: + return {"tp": np.zeros((preds["cls"].shape[0], self.niou), dtype=bool)} + iou = box_iou(batch["bboxes"], preds["bboxes"]) + return {"tp": self.match_predictions(preds["cls"], batch["cls"], iou).cpu().numpy()} + + def build_dataset(self, img_path: str, mode: str = "val", batch: int | None = None) -> torch.utils.data.Dataset: + """Build YOLO Dataset. + + Args: + img_path (str): Path to the folder containing images. + mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode. + batch (int, optional): Size of batches, this is for `rect`. + + Returns: + (Dataset): YOLO dataset. + """ + fraction = get_split_fraction(self.args.fraction, self.args.split or "val") + return build_yolo_dataset( + self.args, img_path, batch, self.data, mode=mode, stride=self.stride, fraction=fraction + ) + + def get_dataloader(self, dataset_path: str, batch_size: int) -> torch.utils.data.DataLoader: + """Construct and return dataloader. + + Args: + dataset_path (str): Path to the dataset. + batch_size (int): Size of each batch. + + Returns: + (torch.utils.data.DataLoader): DataLoader for validation. + """ + dataset = self.build_dataset(dataset_path, batch=batch_size, mode="val") + if self.names and len(self.names) < self.data["nc"]: # standalone val of a model with fewer classes + LOGGER.warning(f"Skipping labels of classes the model (nc={len(self.names)}) cannot predict.") + dataset.update_labels(list(range(len(self.names)))) + return build_dataloader( + dataset, + batch_size, + self.args.workers, + shuffle=False, + rank=-1, + drop_last=self.args.compile, + pin_memory=self.training, + device=self.device, + ) + + def plot_val_samples(self, batch: dict[str, Any], ni: int) -> None: + """Plot validation image samples. + + Args: + batch (dict[str, Any]): Batch containing images and annotations. + ni (int): Batch index. + """ + plot_images( + labels=batch, + paths=batch["im_file"], + fname=self.save_dir / f"val_batch{ni}_labels.jpg", + names=self.names, + on_plot=self.on_plot, + ) + + def plot_predictions( + self, batch: dict[str, Any], preds: list[dict[str, torch.Tensor]], ni: int, max_det: int | None = None + ) -> None: + """Plot predicted bounding boxes on input images and save the result. + + Args: + batch (dict[str, Any]): Batch containing images and annotations. + preds (list[dict[str, torch.Tensor]]): List of predictions from the model. + ni (int): Batch index. + max_det (int | None): Maximum number of detections to plot. + """ + if not preds: + return + for i, pred in enumerate(preds): + pred["batch_idx"] = torch.ones_like(pred["conf"]) * i # add batch index to predictions + keys = preds[0].keys() + max_det = max_det or self.args.max_det + batched_preds = {k: torch.cat([x[k][:max_det] for x in preds], dim=0) for k in keys} + batched_preds["bboxes"] = ops.xyxy2xywh(batched_preds["bboxes"]) # convert to xywh format + plot_images( + images=batch["img"], + labels=batched_preds, + paths=batch["im_file"], + fname=self.save_dir / f"val_batch{ni}_pred.jpg", + names=self.names, + on_plot=self.on_plot, + ) # pred + + def save_one_txt(self, predn: dict[str, torch.Tensor], save_conf: bool, shape: tuple[int, int], file: Path) -> None: + """Save YOLO detections to a txt file in normalized coordinates in a specific format. + + Args: + predn (dict[str, torch.Tensor]): Dictionary containing predictions with keys 'bboxes', 'conf', and 'cls'. + save_conf (bool): Whether to save confidence scores. + shape (tuple[int, int]): Shape of the original image (height, width). + file (Path): File path to save the detections. + """ + from ultralytics.engine.results import Results + + Results( + np.zeros((shape[0], shape[1]), dtype=np.uint8), + path=None, + names=self.names, + boxes=torch.cat([predn["bboxes"], predn["conf"].unsqueeze(-1), predn["cls"].unsqueeze(-1)], dim=1), + ).save_txt(file, save_conf=save_conf) + + def pred_to_json(self, predn: dict[str, torch.Tensor], pbatch: dict[str, Any]) -> None: + """Serialize YOLO predictions to COCO json format. + + Args: + predn (dict[str, torch.Tensor]): Predictions dictionary containing 'bboxes', 'conf', and 'cls' keys with + bounding box coordinates, confidence scores, and class predictions. + pbatch (dict[str, Any]): Batch dictionary containing 'imgsz', 'ori_shape', 'ratio_pad', and 'im_file'. + + Examples: + >>> result = { + ... "image_id": 42, + ... "file_name": "42.jpg", + ... "category_id": 18, + ... "bbox": [258.15, 41.29, 348.26, 243.78], + ... "score": 0.236, + ... } + """ + path = Path(pbatch["im_file"]) + stem = path.stem + image_id = int(stem) if stem.isnumeric() else stem + box = ops.xyxy2xywh(predn["bboxes"]) # xywh + box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner + for b, s, c in zip(box.tolist(), predn["conf"].tolist(), predn["cls"].tolist()): + self.jdict.append( + { + "image_id": image_id, + "file_name": path.name, + "category_id": self.class_map[int(c)], + "bbox": [round(x, 3) for x in b], + "score": round(s, 5), + } + ) + + def scale_preds(self, predn: dict[str, torch.Tensor], pbatch: dict[str, Any]) -> dict[str, torch.Tensor]: + """Scales predictions to the original image size.""" + return { + **predn, + "bboxes": ops.scale_boxes( + pbatch["imgsz"], + predn["bboxes"].clone(), + pbatch["ori_shape"], + ratio_pad=pbatch["ratio_pad"], + ), + } + + def eval_json(self, stats: dict[str, Any]) -> dict[str, Any]: + """Evaluate YOLO output in JSON format and return performance statistics. + + Args: + stats (dict[str, Any]): Current statistics dictionary. + + Returns: + (dict[str, Any]): Updated statistics dictionary with COCO/LVIS evaluation results. + """ + if self.gdict: + predictions = iter(self.jdict) + pred_json = [ + {**next(predictions), "image_id": image["id"]} + for image, count in zip(self.gdict["images"], self.pred_counts) + for _ in range(count) + ] + else: + pred_json = self.jdict if self.training else self.save_dir / "predictions.json" + anno_json = self.gdict or ( + self.data["path"] + / "annotations" + / ("instances_val2017.json" if self.is_coco else f"lvis_v1_{self.args.split}.json") + ) + return self.coco_evaluate(stats, pred_json, anno_json) + + def coco_evaluate( + self, + stats: dict[str, Any], + pred_json: str | Path | list, + anno_json: str | Path | dict, + iou_types: str | list[str] = "bbox", + suffix: str | list[str] = "Box", + ) -> dict[str, Any]: + """Evaluate COCO/LVIS or custom COCO-format detection metrics using faster-coco-eval. + + Args: + stats (dict[str, Any]): Dictionary to store computed metrics and statistics. + pred_json (str | Path | list): Path or in-memory predictions in COCO format. + anno_json (str | Path | dict): Path or in-memory ground truth in COCO format. + iou_types (str | list[str]): IoU types to evaluate, such as "bbox", "segm", or "keypoints". + suffix (str | list[str]): Metric suffixes corresponding to the IoU types. + + Returns: + (dict[str, Any]): Updated stats dictionary containing the computed COCO-format evaluation metrics. + """ + if self.args.save_json and len(self.jdict) and (self.is_coco or self.is_lvis or self.gdict): + LOGGER.info("\nEvaluating faster-coco-eval mAP...") + try: + for x in pred_json, anno_json: + if isinstance(x, (str, Path)): + assert Path(x).is_file(), f"{x} file not found" + iou_types = [iou_types] if isinstance(iou_types, str) else iou_types + suffix = [suffix] if isinstance(suffix, str) else suffix + check_requirements("faster-coco-eval>=1.6.7") + from faster_coco_eval import COCO, COCOeval_faster + + anno = getattr(self, "_coco_api", None) or COCO(anno_json) + self._coco_api = anno + pred = anno.loadRes(pred_json) + for i, iou_type in enumerate(iou_types): + val = COCOeval_faster( + anno, pred, iouType=iou_type, lvis_style=self.is_lvis, print_function=LOGGER.info + ) + val.params.imgIds = ( + anno.getImgIds() + if self.gdict + else [int(Path(x).stem) for x in self.dataloader.dataset.im_files] + ) + val.evaluate() + val.accumulate() + val.summarize() + + if not self.training and (self.is_coco or self.is_lvis): + stats[f"metrics/mAP50({suffix[i][0]})"] = val.stats_as_dict["AP_50"] + stats[f"metrics/mAP50-95({suffix[i][0]})"] = val.stats_as_dict["AP_all"] + stats["fitness"] = 0.9 * val.stats_as_dict["AP_all"] + 0.1 * val.stats_as_dict["AP_50"] + for x in "small", "medium", "large": + if f"AP_{x}" in val.stats_as_dict: # COCO keypoint evaluation has no small area range + stats[f"metrics/mAP_{x}({suffix[i][0]})"] = val.stats_as_dict[f"AP_{x}"] + if not self.training and self.is_lvis: + stats[f"metrics/APr({suffix[i][0]})"] = val.stats_as_dict["APr"] + stats[f"metrics/APc({suffix[i][0]})"] = val.stats_as_dict["APc"] + stats[f"metrics/APf({suffix[i][0]})"] = val.stats_as_dict["APf"] + + if self.is_lvis: + stats["fitness"] = stats["metrics/mAP50-95(B)"] # always use box mAP50-95 for fitness + except Exception as e: + LOGGER.warning(f"faster-coco-eval unable to run: {e}") + return stats diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/model.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/model.py new file mode 100644 index 0000000000000000000000000000000000000000..0d0cbc82edf06819efa5539b2dd264f499a22b39 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/model.py @@ -0,0 +1,561 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from ultralytics.cfg import get_cfg +from ultralytics.data.build import load_inference_source +from ultralytics.engine.model import Model +from ultralytics.models import yolo +from ultralytics.nn.autobackend import check_class_names +from ultralytics.nn.backends.base import BaseBackend +from ultralytics.nn.tasks import ( + ClassificationModel, + DepthModel, + DetectionModel, + OBBModel, + PoseModel, + SegmentationModel, + SemanticSegmentationModel, + WorldModel, + YOLOEModel, + YOLOESegModel, +) +from ultralytics.utils import ROOT, YAML + + +class YOLO(Model): + """YOLO (You Only Look Once) object detection model. + + This class provides a unified interface for YOLO models, automatically switching to specialized model types + (YOLOWorld or YOLOE) based on the model filename. It supports various computer vision tasks including object + detection, instance segmentation, semantic segmentation, depth estimation, classification, pose estimation, and + oriented bounding box detection. + + Attributes: + model: The loaded YOLO model instance. + task: The task type (detect, segment, semantic, depth, classify, pose, obb). + overrides: Configuration overrides for the model. + + Methods: + __init__: Initialize a YOLO model with automatic type detection. + task_map: Map tasks to their corresponding model, trainer, validator, and predictor classes. + + Examples: + Load a pretrained YOLO26n detection model + >>> model = YOLO("yolo26n.pt") + + Load a pretrained YOLO26n segmentation model + >>> model = YOLO("yolo26n-seg.pt") + + Initialize from a YAML configuration + >>> model = YOLO("yolo26n.yaml") + """ + + def __init__(self, model: str | Path = "yolo26n.pt", task: str | None = None, verbose: bool = False): + """Initialize a YOLO model. + + This constructor initializes a YOLO model, automatically switching to specialized model types (YOLOWorld or + YOLOE) based on the model filename. + + Args: + model (str | Path): Model name or path to model file, i.e. 'yolo26n.pt', 'yolo26n.yaml'. + task (str, optional): YOLO task specification, i.e. 'detect', 'segment', 'semantic', 'depth', 'classify', + 'pose', 'obb'. Defaults to auto-detection based on model. + verbose (bool): Display model info on load. + """ + path = Path(model if isinstance(model, (str, Path)) else "") + if "-world" in path.stem and path.suffix in {".pt", ".yaml", ".yml"}: # if YOLOWorld PyTorch model + new_instance = YOLOWorld(path, verbose=verbose) + self.__class__ = type(new_instance) + self.__dict__ = new_instance.__dict__ + elif "yoloe" in path.stem and path.suffix in {".pt", ".yaml", ".yml"}: # if YOLOE PyTorch model + new_instance = YOLOE(path, task=task, verbose=verbose) + self.__class__ = type(new_instance) + self.__dict__ = new_instance.__dict__ + else: + # Continue with default YOLO initialization + super().__init__(model=model, task=task, verbose=verbose) + head = self.model.model[-1]._get_name() if hasattr(self.model, "model") else "" + if not head and isinstance(self.model, (str, Path)): # an exported model keeps its head name in metadata + head = BaseBackend.read_metadata(self.model).get("head", "") + if "RTDETR" in head: # if RTDETR head + from ultralytics import RTDETR + + new_instance = RTDETR(self) + self.__class__ = type(new_instance) + self.__dict__ = new_instance.__dict__ + elif isinstance(self.model, WorldModel): # e.g. `ul://…/yolov8l-worldv2`, no suffix for the filename test + new_instance = YOLOWorld(self) + self.__class__ = type(new_instance) + self.__dict__ = new_instance.__dict__ + + @property + def task_map(self) -> dict[str, dict[str, Any]]: + """Map head to model, trainer, validator, and predictor classes.""" + return { + "classify": { + "model": ClassificationModel, + "trainer": yolo.classify.ClassificationTrainer, + "validator": yolo.classify.ClassificationValidator, + "predictor": yolo.classify.ClassificationPredictor, + }, + "detect": { + "model": DetectionModel, + "trainer": yolo.detect.DetectionTrainer, + "validator": yolo.detect.DetectionValidator, + "predictor": yolo.detect.DetectionPredictor, + }, + "segment": { + "model": SegmentationModel, + "trainer": yolo.segment.SegmentationTrainer, + "validator": yolo.segment.SegmentationValidator, + "predictor": yolo.segment.SegmentationPredictor, + }, + "pose": { + "model": PoseModel, + "trainer": yolo.pose.PoseTrainer, + "validator": yolo.pose.PoseValidator, + "predictor": yolo.pose.PosePredictor, + }, + "obb": { + "model": OBBModel, + "trainer": yolo.obb.OBBTrainer, + "validator": yolo.obb.OBBValidator, + "predictor": yolo.obb.OBBPredictor, + }, + "depth": { + "model": DepthModel, + "trainer": yolo.depth.DepthTrainer, + "validator": yolo.depth.DepthValidator, + "predictor": yolo.depth.DepthPredictor, + }, + "semantic": { + "model": SemanticSegmentationModel, + "trainer": yolo.semantic.SemanticSegmentationTrainer, + "validator": yolo.semantic.SemanticSegmentationValidator, + "predictor": yolo.semantic.SemanticSegmentationPredictor, + }, + } + + +class YOLOWorld(Model): + """YOLO-World object detection model. + + YOLO-World is an open-vocabulary object detection model that can detect objects based on text descriptions without + requiring training on specific classes. It extends the YOLO architecture to support real-time open-vocabulary + detection. + + Attributes: + model: The loaded YOLO-World model instance. + task: Always set to 'detect' for object detection. + overrides: Configuration overrides for the model. + + Methods: + __init__: Initialize YOLOv8-World model with a pre-trained model file. + task_map: Map tasks to their corresponding model, trainer, validator, and predictor classes. + set_classes: Set the model's class names for detection. + + Examples: + Load a YOLOv8-World model + >>> model = YOLOWorld("yolov8s-world.pt") + + Set custom classes for detection + >>> model.set_classes(["person", "car", "bicycle"]) + """ + + def __init__(self, model: str | Path = "yolov8s-world.pt", verbose: bool = False) -> None: + """Initialize YOLOv8-World model with a pre-trained model file. + + Loads a YOLOv8-World model for object detection. If no custom class names are provided, it assigns default COCO + class names. + + Args: + model (str | Path): Path to the pre-trained model file. Supports *.pt and *.yaml formats. + verbose (bool): If True, prints additional information during initialization. + """ + super().__init__(model=model, task="detect", verbose=verbose) + + # Assign default COCO class names when there are no custom names + if not hasattr(self.model, "names"): + self.model.names = YAML.load(ROOT / "cfg/datasets/coco8.yaml").get("names") + + @property + def task_map(self) -> dict[str, dict[str, Any]]: + """Map head to model, trainer, validator, and predictor classes.""" + return { + "detect": { + "model": WorldModel, + "validator": yolo.world.WorldValidator, + "predictor": yolo.detect.DetectionPredictor, + "trainer": yolo.world.WorldTrainer, + } + } + + def set_classes(self, classes: list[str]) -> None: + """Set the model's class names for detection. + + Args: + classes (list[str]): A list of categories i.e. ["person"]. + """ + self.model.set_classes(classes) + # Remove background if it's given + background = " " + if background in classes: + classes.remove(background) + self.model.names = classes + + self.predictor = None + + +class YOLOE(Model): + """YOLOE object detection and segmentation model. + + YOLOE is an enhanced YOLO model that supports both object detection and instance segmentation tasks with improved + performance and additional features like visual and text positional embeddings. + + Attributes: + model: The loaded YOLOE model instance. + task: The task type (detect or segment). + overrides: Configuration overrides for the model. + + Methods: + __init__: Initialize YOLOE model with a pre-trained model file. + task_map: Map tasks to their corresponding model, trainer, validator, and predictor classes. + get_text_pe: Get text positional embeddings for the given texts. + get_visual_pe: Get visual positional embeddings for the given image and visual features. + set_vocab: Set vocabulary and class names for the YOLOE model. + get_vocab: Get the vocabulary for the given class names, which become the model's classes as the head is fused. + set_classes: Set the model's class names and embeddings for detection. + save_prompt_embeddings: Save the current prompt embeddings and class names to an NPZ file. + load_prompt_embeddings: Load prompt embeddings and class names from an NPZ file. + val: Validate the model using text or visual prompts. + predict: Run prediction on images, videos, directories, streams, etc. + + Examples: + Load a YOLOE segmentation model + >>> model = YOLOE("yoloe-11s-seg.pt") + + Predict with visual prompts, whose 'cls' holds one class index per box + >>> from ultralytics.models.yolo.yoloe import YOLOEVPSegPredictor + >>> prompts = {"bboxes": np.array([[10, 20, 100, 200]]), "cls": np.array([0])} + >>> results = model.predict("image.jpg", visual_prompts=prompts, predictor=YOLOEVPSegPredictor) + + Re-parameterize into a prompt-free model, which no longer accepts prompts + >>> names = ["person", "car", "dog"] + >>> model.set_vocab(model.get_vocab(names), names) + """ + + def __init__(self, model: str | Path = "yoloe-11s-seg.pt", task: str | None = None, verbose: bool = False) -> None: + """Initialize YOLOE model with a pre-trained model file. + + Args: + model (str | Path): Path to the pre-trained model file. Supports *.pt and *.yaml formats. + task (str, optional): Task type for the model. Auto-detected if None. + verbose (bool): If True, prints additional information during initialization. + """ + super().__init__(model=model, task=task, verbose=verbose) + + @property + def task_map(self) -> dict[str, dict[str, Any]]: + """Map head to model, trainer, validator, and predictor classes.""" + return { + "detect": { + "model": YOLOEModel, + "validator": yolo.yoloe.YOLOEDetectValidator, + "predictor": yolo.detect.DetectionPredictor, + "trainer": yolo.yoloe.YOLOETrainer, + }, + "segment": { + "model": YOLOESegModel, + "validator": yolo.yoloe.YOLOESegValidator, + "predictor": yolo.segment.SegmentationPredictor, + "trainer": yolo.yoloe.YOLOESegTrainer, + }, + } + + def get_text_pe(self, texts): + """Get text positional embeddings for the given texts.""" + assert isinstance(self.model, YOLOEModel) + return self.model.get_text_pe(texts) + + def get_visual_pe(self, img, visual): + """Get visual positional embeddings for the given image and visual features. + + This method extracts positional embeddings from visual features based on the input image. It requires that the + model is an instance of YOLOEModel. + + Args: + img (torch.Tensor): Input image tensor. + visual (torch.Tensor): Visual features extracted from the image. + + Returns: + (torch.Tensor): Visual positional embeddings. + + Examples: + >>> model = YOLOE("yoloe-11s-seg.pt") + >>> img = torch.rand(1, 3, 640, 640) + >>> visual_features = torch.rand(1, 1, 80, 80) + >>> pe = model.get_visual_pe(img, visual_features) + """ + assert isinstance(self.model, YOLOEModel) + return self.model.get_visual_pe(img, visual) + + def set_vocab( + self, vocab: torch.nn.ModuleList, names: list[str], one2one_vocab: torch.nn.ModuleList | None = None + ) -> None: + """Re-parameterize the model into a prompt-free one over the given class names. + + The vocabulary is the fused classification layer `get_vocab` returns for the same names, not the names + themselves. The model must be an instance of YOLOEModel. + + Args: + vocab (torch.nn.ModuleList): One-to-many fused classification layers returned by `get_vocab` for `names`. + names (list[str]): List of class names that the model can detect or classify. + one2one_vocab (torch.nn.ModuleList | None): One-to-one fused classification layers. When provided, both + heads are built and `nms` keeps selecting between them; otherwise only the current head is built. + + Raises: + AssertionError: If the model is not an instance of YOLOEModel. + + Examples: + >>> model = YOLOE("yoloe-11s-seg.pt") + >>> names = ["person", "car", "dog"] + >>> model.set_vocab(model.get_vocab(names), names) + """ + assert isinstance(self.model, YOLOEModel) + names = check_class_names(names) + self.predictor = None # the delegate destructively re-parameterizes the head + self.model.set_vocab(vocab, names=names, one2one_vocab=one2one_vocab) + + def get_vocab(self, names): + """Get the vocabulary for the given class names, which become the model's classes as the head is fused.""" + assert isinstance(self.model, YOLOEModel) + self.predictor = None # the delegate destructively fuses the promptable head + return self.model.get_vocab(names) + + def set_classes(self, classes: list[str], embeddings: torch.Tensor | None = None) -> None: + """Set the model's class names and embeddings for detection. + + Args: + classes (list[str]): A list of categories i.e. ["person"]. + embeddings (torch.Tensor, optional): Embeddings corresponding to the classes. + """ + # Verify no background class is present + assert " " not in classes + assert isinstance(self.model, YOLOEModel) + names = list(self.model.names.values()) if isinstance(self.model.names, dict) else list(self.model.names) + if embeddings is not None or names != classes: + if embeddings is None: + embeddings = self.get_text_pe(classes) # generate text embeddings if not provided + self.model.set_classes(classes, embeddings) + self.predictor = None + + def _prompt_embedding_model(self) -> str: + """Return the checkpoint identifier used to bind prompt embeddings to this model.""" + source = getattr(self.model, "pt_path", None) or self.ckpt_path + source = source if isinstance(source, (str, Path)) else self.model.yaml["yaml_file"] + model = Path(source).stem + return model[:-4] if model.endswith("-seg") else model + + def save_prompt_embeddings(self, file: str | Path) -> Path: + """Save the current prompt embeddings and class names to an NPZ file. + + Args: + file (str | Path): Destination NPZ file path. + + Returns: + (Path): Path to the saved NPZ file. + + Raises: + ValueError: If prompt embeddings have not been set or are invalid. + """ + assert isinstance(self.model, YOLOEModel) + embeddings = getattr(self.model, "pe", None) + if not isinstance(embeddings, torch.Tensor) or embeddings.ndim != 3 or embeddings.shape[0] != 1: + raise ValueError("Prompt embeddings must be set before they can be saved.") + names = list(self.model.names.values()) if isinstance(self.model.names, dict) else list(self.model.names) + if embeddings.shape[1] != len(names) or not torch.isfinite(embeddings).all(): + raise ValueError("Prompt embeddings must be finite and match the number of class names.") + + file = Path(file) + if file.suffix.lower() != ".npz": + raise ValueError(f"Prompt embedding file must have an '.npz' suffix, not '{file.suffix}'.") + np.savez_compressed( + file, + embeddings=embeddings.detach().cpu().float().numpy(), + names=np.asarray(names, dtype=np.str_), + model=np.asarray(self._prompt_embedding_model(), dtype=np.str_), + ) + return file + + def load_prompt_embeddings(self, file: str | Path) -> None: + """Load prompt embeddings and class names from a model-bound NPZ file. + + Args: + file (str | Path): Source NPZ file path created by :meth:`save_prompt_embeddings`. + + Raises: + ValueError: If the file is invalid or belongs to a different YOLOE architecture. + """ + assert isinstance(self.model, YOLOEModel) + with np.load(file, allow_pickle=False) as data: + if set(data.files) != {"embeddings", "names", "model"}: + raise ValueError("Prompt embedding file must contain 'embeddings', 'names', and 'model'.") + embeddings, names, model = data["embeddings"], data["names"], data["model"] + + if model.ndim != 0 or model.dtype.kind != "U": + raise ValueError("Prompt embedding model identifier must be a scalar string.") + model_name = str(model.item()) + if model_name != self._prompt_embedding_model(): + raise ValueError( + f"Prompt embeddings for model '{model_name}' cannot be loaded into '{self._prompt_embedding_model()}'." + ) + if names.ndim != 1 or names.dtype.kind != "U": + raise ValueError("Prompt embedding class names must be a one-dimensional string array.") + if embeddings.dtype != np.float32 or embeddings.ndim != 3 or embeddings.shape[0] != 1: + raise ValueError("Prompt embeddings must be a float32 array with shape (1, classes, dimensions).") + if embeddings.shape[1] != len(names) or embeddings.shape[2] != self.model.model[-1].embed: + raise ValueError("Prompt embedding shape does not match the class names or model embedding dimension.") + if not np.isfinite(embeddings).all(): + raise ValueError("Prompt embeddings must contain only finite values.") + self.set_classes(names.tolist(), torch.from_numpy(embeddings.copy()).to(next(self.model.parameters()).device)) + + def val( + self, + validator=None, + load_vp: bool = False, + refer_data: str | None = None, + **kwargs, + ): + """Validate the model using text or visual prompts. + + Args: + validator (callable, optional): A callable validator function. If None, a default validator is loaded. + load_vp (bool): Whether to load visual prompts. If False, text prompts are used. + refer_data (str, optional): Path to the reference data for visual prompts. + **kwargs (Any): Additional keyword arguments to override default settings. + + Returns: + (dict): Validation statistics containing metrics computed during validation. + """ + custom = {"rect": not load_vp} # method defaults + if kwargs.get("data") is None: + kwargs["data"] = self._val_data() + args = {**self.overrides, **custom, **kwargs, "mode": "val"} # highest priority args on the right + + validator = (validator or self._smart_load("validator"))(args=args, _callbacks=self.callbacks) + validator(model=self.model, load_vp=load_vp, refer_data=refer_data) + self.metrics = validator.metrics + return validator.metrics + + def predict( + self, + source=None, + stream: bool = False, + visual_prompts: dict[str, np.ndarray | list[np.ndarray]] | None = None, + refer_image=None, + predictor=yolo.yoloe.YOLOEVPDetectPredictor, + **kwargs, + ): + """Run prediction on images, videos, directories, streams, etc. + + Args: + source (str | int | PIL.Image | np.ndarray, optional): Source for prediction. Accepts image paths, directory + paths, URL/YouTube streams, PIL images, numpy arrays, or webcam indices. + stream (bool): Whether to stream the prediction results. If True, results are yielded as a generator as they + are computed. + visual_prompts (dict[str, np.ndarray | list[np.ndarray]]): Dictionary containing visual prompts for the + model. Must include 'bboxes' and 'cls' keys when non-empty, holding either flat arrays or one array per + image for an explicit list, tuple, or 4-D tensor source with no refer_image. + refer_image (str | PIL.Image | np.ndarray, optional): Reference image for visual prompts. + predictor (callable): Custom predictor class for visual prompt predictions. Defaults to + YOLOEVPDetectPredictor. + **kwargs (Any): Additional keyword arguments passed to the predictor. + + Returns: + (list | generator): List of Results objects or generator of Results objects if stream=True. + + Examples: + >>> model = YOLOE("yoloe-11s-seg.pt") + >>> results = model.predict("path/to/image.jpg") + >>> # With visual prompts, whose 'cls' holds one class index per box + >>> from ultralytics.models.yolo.yoloe import YOLOEVPSegPredictor + >>> prompts = {"bboxes": np.array([[10, 20, 100, 200]]), "cls": np.array([0])} + >>> results = model.predict("path/to/image.jpg", visual_prompts=prompts, predictor=YOLOEVPSegPredictor) + """ + visual_prompts = visual_prompts if visual_prompts is not None else {} + if len(visual_prompts): + assert "bboxes" in visual_prompts and "cls" in visual_prompts, ( + f"Expected 'bboxes' and 'cls' in visual prompts, but got {visual_prompts.keys()}" + ) + bboxes, classes = visual_prompts["bboxes"], visual_prompts["cls"] + assert all(hasattr(x, "__len__") and getattr(x, "ndim", 1) > 0 for x in (bboxes, classes)), ( + "Expected non-scalar 'bboxes' and 'cls' visual prompts" + ) + assert len(bboxes) == len(classes) > 0, "Expected an equal, non-zero number of boxes and classes" + nested = yolo.yoloe.YOLOEVPDetectPredictor.is_per_image(visual_prompts) # one prompt array per image + assert not isinstance(source, np.ndarray) or source.ndim != 4, "4-D NumPy sources are not supported" + per_image_source = isinstance(source, (list, tuple)) or ( + isinstance(source, torch.Tensor) and source.ndim == 4 + ) + assert not nested or (refer_image is None and per_image_source), ( + "Expected flat 'bboxes' and 'cls' arrays for a non-sequence source or when refer_image is set" + ) + multi = nested + pairs = list(zip(bboxes, classes)) if multi else [(bboxes, classes)] + assert not multi or len(pairs) == len(source), ( + f"Expected one prompt per source image, but got {len(pairs)} prompts for {len(source)} images" + ) + assert all( + getattr(b, "ndim", 2) == 2 + and (not multi or b.shape[1:] == (4,)) + and getattr(c, "ndim", 1) == 1 + and len(b) == len(c) + and all(np.isscalar(x) and not isinstance(x, (str, bytes)) for x in c) + for b, c in pairs + ), "Expected non-string scalar class indices for each bounding box" + per_image = [len(set(c.tolist() if isinstance(c, np.ndarray) else c)) for _, c in pairs] + assert all(per_image), "Expected at least one class per image" + num_cls = max(per_image) + if type(self.predictor) is not predictor: + args = get_cfg(overrides={**self.overrides, **kwargs}) + self.predictor = predictor( + overrides={ + "task": self.model.task, + "mode": "predict", + "save": False, + "verbose": kwargs.get("verbose", self.overrides.get("verbose", refer_image is None)), + "batch": 1, + "device": args.device, + "quantize": args.quantize, + "imgsz": args.imgsz, + }, + _callbacks=self.callbacks, + ) + + self.model.model[-1].nc = num_cls + self.model.names = [f"object{i}" for i in range(num_cls)] + self.predictor.set_prompts(visual_prompts.copy()) + self.predictor.setup_model(model=self.model, verbose=self.predictor.args.verbose) + + if refer_image is None and source is not None: + dataset = load_inference_source(source) + if dataset.mode in {"video", "stream"}: + # NOTE: set the first frame as refer image for videos/streams inference + refer_image = next(iter(dataset))[1][0] + if refer_image is not None: + vpe = self.predictor.get_vpe(refer_image) + self.model.set_classes(self.model.names, vpe) + self.task = "segment" if isinstance(self.predictor, yolo.segment.SegmentationPredictor) else "detect" + self.predictor = None # reset predictor + elif isinstance(self.predictor, yolo.yoloe.YOLOEVPDetectPredictor): + self.predictor = None # reset predictor if no visual prompts + self.overrides["agnostic_nms"] = True # use agnostic nms for YOLOE default + + return super().predict(source, stream, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..61e3e3c6a82b9addf0206bfe0bab63fa34c26108 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__init__.py @@ -0,0 +1,7 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .predict import OBBPredictor +from .train import OBBTrainer +from .val import OBBValidator + +__all__ = "OBBPredictor", "OBBTrainer", "OBBValidator" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96ff77df8f8538b010005666e62266afc1941cef Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__pycache__/predict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__pycache__/predict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d64d8c76814429166211d863f9ff0545fdd035a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__pycache__/predict.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__pycache__/train.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__pycache__/train.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..820d9a9733604bbfbf4ec18475a894bccb8ba200 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__pycache__/train.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__pycache__/val.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__pycache__/val.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10ea5b190f2d69fe3be11afaa5cd02c61b918bb5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/__pycache__/val.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/predict.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..86de5ee88c7f7fe223a3e7a93d8108bb9a677f43 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/predict.py @@ -0,0 +1,58 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import torch + +from ultralytics.engine.results import Results +from ultralytics.models.yolo.detect.predict import DetectionPredictor +from ultralytics.utils import DEFAULT_CFG, ops + + +class OBBPredictor(DetectionPredictor): + """A class extending the DetectionPredictor class for prediction based on an Oriented Bounding Box (OBB) model. + + This predictor handles oriented bounding box detection tasks, processing images and returning results with rotated + bounding boxes. + + Attributes: + args (namespace): Configuration arguments for the predictor. + model (torch.nn.Module): The loaded YOLO OBB model. + + Examples: + >>> from ultralytics.utils import ASSETS + >>> from ultralytics.models.yolo.obb import OBBPredictor + >>> args = dict(model="yolo26n-obb.pt", source=ASSETS) + >>> predictor = OBBPredictor(overrides=args) + >>> predictor.predict_cli() + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks: dict | None = None): + """Initialize OBBPredictor with optional model and data configuration overrides. + + Args: + cfg (dict, optional): Default configuration for the predictor. + overrides (dict, optional): Configuration overrides that take precedence over the default config. + _callbacks (dict, optional): Dictionary of callback functions to be invoked during prediction. + """ + super().__init__(cfg, overrides, _callbacks) + self.args.task = "obb" + + def construct_result(self, pred, img, orig_img, img_path): + """Construct the result object from the prediction. + + Args: + pred (torch.Tensor): The predicted bounding boxes, scores, and rotation angles with shape (N, 7) where the + last dimension contains [x, y, w, h, confidence, class_id, angle]. + img (torch.Tensor): The image after preprocessing with shape (B, C, H, W). + orig_img (np.ndarray): The original image before preprocessing. + img_path (str): The path to the original image. + + Returns: + (Results): The result object containing the original image, image path, class names, and oriented bounding + boxes. + """ + rboxes = torch.cat([pred[:, :4], pred[:, -1:]], dim=-1) + rboxes[:, :4] = ops.scale_boxes(img.shape[2:], rboxes[:, :4], orig_img.shape, xywh=True) + obb = torch.cat([rboxes, pred[:, 4:6]], dim=-1) + return Results(orig_img, path=img_path, names=self.model.names, obb=obb) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/train.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/train.py new file mode 100644 index 0000000000000000000000000000000000000000..7b2623d4bcf948b815dfb80182a38eaf46d9ff9f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/train.py @@ -0,0 +1,78 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from copy import copy +from pathlib import Path + +from ultralytics.models import yolo +from ultralytics.nn.tasks import OBBModel +from ultralytics.utils import DEFAULT_CFG, RANK + + +class OBBTrainer(yolo.detect.DetectionTrainer): + """A class extending the DetectionTrainer class for training based on an Oriented Bounding Box (OBB) model. + + This trainer specializes in training YOLO models that detect oriented bounding boxes, which are useful for detecting + objects at arbitrary angles rather than just axis-aligned rectangles. + + Attributes: + loss_names (tuple): Names of the loss components, derived from the loss dict returned by the criterion. + + Methods: + get_model: Return OBBModel initialized with specified config and weights. + get_validator: Return an instance of OBBValidator for validation of YOLO model. + + Examples: + >>> from ultralytics.models.yolo.obb import OBBTrainer + >>> args = dict(model="yolo26n-obb.pt", data="dota8.yaml", epochs=3) + >>> trainer = OBBTrainer(overrides=args) + >>> trainer.train() + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides: dict | None = None, _callbacks: dict | None = None): + """Initialize an OBBTrainer object for training Oriented Bounding Box (OBB) models. + + Args: + cfg (dict, optional): Configuration dictionary for the trainer. Contains training parameters and model + configuration. + overrides (dict, optional): Dictionary of parameter overrides for the configuration. Any values here will + take precedence over those in cfg. + _callbacks (dict, optional): Dictionary of callback functions to be invoked during training. + """ + if overrides is None: + overrides = {} + overrides["task"] = "obb" + super().__init__(cfg, overrides, _callbacks) + + def get_model( + self, cfg: str | dict | None = None, weights: str | Path | None = None, verbose: bool = True + ) -> OBBModel: + """Return OBBModel initialized with specified config and weights. + + Args: + cfg (str | dict, optional): Model configuration. Can be a path to a YAML config file, a dictionary + containing configuration parameters, or None to use default configuration. + weights (str | Path, optional): Path to pretrained weights file. If None, random initialization is used. + verbose (bool): Whether to display model information during initialization. + + Returns: + (OBBModel): Initialized OBBModel with the specified configuration and weights. + + Examples: + >>> trainer = OBBTrainer() + >>> model = trainer.get_model(cfg="yolo26n-obb.yaml", weights="yolo26n-obb.pt") + """ + model = self.set_model_names_for_load( + OBBModel(cfg, nc=self.data["nc"], ch=self.data["channels"], verbose=verbose and RANK == -1) + ) + if weights: + model.load(weights) + + return model + + def get_validator(self): + """Return an instance of OBBValidator for validation of YOLO model.""" + return yolo.obb.OBBValidator( + self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/val.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/val.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd645a3a571dec0b568fece8f7a30d503999546 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/obb/val.py @@ -0,0 +1,306 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from ultralytics.models.yolo.detect import DetectionValidator +from ultralytics.utils import LOGGER, ops +from ultralytics.utils.metrics import OBBMetrics, batch_probiou +from ultralytics.utils.nms import TorchNMS +from ultralytics.utils.plotting import plot_images + + +class OBBValidator(DetectionValidator): + """A class extending the DetectionValidator class for validation based on an Oriented Bounding Box (OBB) model. + + This validator specializes in evaluating models that predict rotated bounding boxes, commonly used for aerial and + satellite imagery where objects can appear at various orientations. + + Attributes: + args (dict): Configuration arguments for the validator. + metrics (OBBMetrics): Metrics object for evaluating OBB model performance. + is_dota (bool): Flag indicating whether the validation dataset is in DOTA format. + + Methods: + init_metrics: Initialize evaluation metrics for YOLO. + _process_batch: Process batch of detections and ground truth boxes to compute IoU matrix. + _prepare_batch: Prepare batch data for OBB validation. + _prepare_pred: Prepare predictions for evaluation against ground truth. + plot_predictions: Plot predicted bounding boxes on input images. + pred_to_json: Serialize YOLO predictions to COCO json format. + save_one_txt: Save YOLO detections to a txt file in normalized coordinates. + eval_json: Evaluate YOLO output in JSON format and return performance statistics. + + Examples: + >>> from ultralytics.models.yolo.obb import OBBValidator + >>> args = dict(model="yolo26n-obb.pt", data="dota8.yaml") + >>> validator = OBBValidator(args=args) + >>> validator(model=args["model"]) + """ + + def __init__(self, dataloader=None, save_dir=None, args=None, _callbacks: dict | None = None) -> None: + """Initialize OBBValidator and set task to 'obb', metrics to OBBMetrics. + + This constructor initializes an OBBValidator instance for validating Oriented Bounding Box (OBB) models. It + extends the DetectionValidator class and configures it specifically for the OBB task. + + Args: + dataloader (torch.utils.data.DataLoader, optional): DataLoader to be used for validation. + save_dir (str | Path, optional): Directory to save results. + args (dict, optional): Arguments containing validation parameters. + _callbacks (dict, optional): Dictionary of callback functions to be called during validation. + """ + super().__init__(dataloader, save_dir, args, _callbacks) + self.args.task = "obb" + self.metrics = OBBMetrics() + + def init_metrics(self, model: torch.nn.Module) -> None: + """Initialize evaluation metrics for YOLO obb validation. + + Args: + model (torch.nn.Module): Model to validate. + """ + super().init_metrics(model) + val = self.data.get(self.args.split, "") # validation path + self.is_dota = isinstance(val, str) and "DOTA" in val # check if dataset is DOTA format + self.confusion_matrix.task = "obb" # set confusion matrix task to 'obb' + + def _process_batch(self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> dict[str, np.ndarray]: + """Compute the correct prediction matrix for a batch of detections and ground truth bounding boxes. + + Args: + preds (dict[str, torch.Tensor]): Prediction dictionary containing 'cls' and 'bboxes' keys with detected + class labels and bounding boxes. + batch (dict[str, torch.Tensor]): Batch dictionary containing 'cls' and 'bboxes' keys with ground truth class + labels and bounding boxes. + + Returns: + (dict[str, np.ndarray]): Dictionary containing 'tp' key with the correct prediction matrix as a numpy array + with shape (N, 10), which includes 10 IoU levels for each detection, indicating the accuracy of + predictions compared to the ground truth. + + Examples: + >>> preds = {"cls": torch.randint(0, 5, (100,)), "bboxes": torch.rand(100, 5)} + >>> batch = {"cls": torch.randint(0, 5, (50,)), "bboxes": torch.rand(50, 5)} + >>> correct_matrix = validator._process_batch(preds, batch) + """ + if batch["cls"].shape[0] == 0 or preds["cls"].shape[0] == 0: + return {"tp": np.zeros((preds["cls"].shape[0], self.niou), dtype=bool)} + iou = batch_probiou(batch["bboxes"], preds["bboxes"]) + return {"tp": self.match_predictions(preds["cls"], batch["cls"], iou).cpu().numpy()} + + def postprocess(self, preds: torch.Tensor) -> list[dict[str, torch.Tensor]]: + """Postprocess OBB predictions. + + Args: + preds (torch.Tensor): Raw predictions from the model. + + Returns: + (list[dict[str, torch.Tensor]]): Processed predictions with angle information concatenated to bboxes. + """ + preds = super().postprocess(preds) + for pred in preds: + pred["bboxes"] = torch.cat([pred["bboxes"], pred.pop("extra")], dim=-1) # concatenate angle + return preds + + def _prepare_batch(self, si: int, batch: dict[str, Any]) -> dict[str, Any]: + """Prepare batch data for OBB validation with proper scaling and formatting. + + Args: + si (int): Sample index within the batch. + batch (dict[str, Any]): Dictionary containing batch data with keys: + - batch_idx: Tensor of batch indices + - cls: Tensor of class labels + - bboxes: Tensor of bounding boxes + - ori_shape: Original image shapes + - img: Batch of images + - ratio_pad: Ratio and padding information + + Returns: + (dict[str, Any]): Prepared batch data with scaled bounding boxes and metadata. + """ + idx = batch["batch_idx"] == si + cls = batch["cls"][idx].squeeze(-1) + bbox = batch["bboxes"][idx] + ori_shape = batch["ori_shape"][si] + imgsz = batch["img"].shape[2:] + ratio_pad = batch["ratio_pad"][si] + if cls.shape[0]: + bbox[..., :4].mul_(torch.tensor(imgsz, device=self.device)[[1, 0, 1, 0]]) # target boxes + return { + "cls": cls, + "bboxes": bbox, + "ori_shape": ori_shape, + "imgsz": imgsz, + "ratio_pad": ratio_pad, + "im_file": batch["im_file"][si], + } + + def plot_predictions(self, batch: dict[str, Any], preds: list[dict[str, torch.Tensor]], ni: int) -> None: + """Plot predicted bounding boxes on input images and save the result. + + Args: + batch (dict[str, Any]): Batch data containing images, file paths, and other metadata. + preds (list[dict[str, torch.Tensor]]): List of prediction dictionaries for each image in the batch. + ni (int): Batch index used for naming the output file. + + Examples: + >>> validator = OBBValidator() + >>> batch = {"img": images, "im_file": paths} + >>> preds = [{"bboxes": torch.rand(10, 5), "cls": torch.zeros(10), "conf": torch.rand(10)}] + >>> validator.plot_predictions(batch, preds, 0) + """ + if not preds: + return + for i, pred in enumerate(preds): + pred["batch_idx"] = torch.ones_like(pred["conf"]) * i + keys = preds[0].keys() + batched_preds = {k: torch.cat([x[k] for x in preds], dim=0) for k in keys} + plot_images( + images=batch["img"], + labels=batched_preds, + paths=batch["im_file"], + fname=self.save_dir / f"val_batch{ni}_pred.jpg", + names=self.names, + on_plot=self.on_plot, + ) + + def pred_to_json(self, predn: dict[str, torch.Tensor], pbatch: dict[str, Any]) -> None: + """Convert YOLO predictions to COCO JSON format with rotated bounding box information. + + Args: + predn (dict[str, torch.Tensor]): Prediction dictionary containing 'bboxes', 'conf', and 'cls' keys with + bounding box coordinates, confidence scores, and class predictions. + pbatch (dict[str, Any]): Batch dictionary containing 'imgsz', 'ori_shape', 'ratio_pad', and 'im_file'. + + Notes: + This method processes rotated bounding box predictions and converts them to both rbox format + (x, y, w, h, angle) and polygon format (x1, y1, x2, y2, x3, y3, x4, y4) before adding them + to the JSON dictionary. + """ + path = Path(pbatch["im_file"]) + stem = path.stem + image_id = int(stem) if stem.isnumeric() else stem + rbox = predn["bboxes"] + poly = ops.xywhr2xyxyxyxy(rbox).view(-1, 8) + for r, b, s, c in zip(rbox.tolist(), poly.tolist(), predn["conf"].tolist(), predn["cls"].tolist()): + self.jdict.append( + { + "image_id": image_id, + "file_name": path.name, + "category_id": self.class_map[int(c)], + "score": round(s, 5), + "rbox": [round(x, 3) for x in r], + "poly": [round(x, 3) for x in b], + } + ) + + def save_one_txt(self, predn: dict[str, torch.Tensor], save_conf: bool, shape: tuple[int, int], file: Path) -> None: + """Save YOLO OBB detections to a text file in normalized coordinates. + + Args: + predn (dict[str, torch.Tensor]): Prediction dictionary containing 'bboxes', 'conf', and 'cls' keys with + bounding box coordinates (including angle), confidence scores, and class predictions. + save_conf (bool): Whether to save confidence scores in the text file. + shape (tuple[int, int]): Original image shape in format (height, width). + file (Path): Output file path to save detections. + + Examples: + >>> validator = OBBValidator() + >>> predn = { + ... "bboxes": torch.tensor([[100, 100, 50, 30, 45]]), + ... "conf": torch.tensor([0.9]), + ... "cls": torch.tensor([0]), + ... } + >>> validator.save_one_txt(predn, True, (640, 480), Path("detection.txt")) + """ + import numpy as np + + from ultralytics.engine.results import Results + + Results( + np.zeros((shape[0], shape[1]), dtype=np.uint8), + path=None, + names=self.names, + obb=torch.cat([predn["bboxes"], predn["conf"].unsqueeze(-1), predn["cls"].unsqueeze(-1)], dim=1), + ).save_txt(file, save_conf=save_conf) + + def scale_preds(self, predn: dict[str, torch.Tensor], pbatch: dict[str, Any]) -> dict[str, torch.Tensor]: + """Scales predictions to the original image size.""" + return { + **predn, + "bboxes": ops.scale_boxes( + pbatch["imgsz"], predn["bboxes"].clone(), pbatch["ori_shape"], ratio_pad=pbatch["ratio_pad"], xywh=True + ), + } + + def eval_json(self, stats: dict[str, Any]) -> dict[str, Any]: + """Evaluate YOLO output in JSON format and save predictions in DOTA format. + + Args: + stats (dict[str, Any]): Performance statistics dictionary. + + Returns: + (dict[str, Any]): Updated performance statistics. + """ + if self.args.save_json and self.is_dota and len(self.jdict): + import json + import re + from collections import defaultdict + + pred_json = self.save_dir / "predictions.json" # predictions + pred_txt = self.save_dir / "predictions_txt" # predictions + pred_txt.mkdir(parents=True, exist_ok=True) + with open(pred_json) as f: + data = json.load(f) + # Save split results + LOGGER.info(f"Saving predictions with DOTA format to {pred_txt}...") + for d in data: + image_id = d["image_id"] + score = d["score"] + classname = self.names[d["category_id"] - 1].replace(" ", "-") + p = d["poly"] + + with open(f"{pred_txt / f'Task1_{classname}'}.txt", "a", encoding="utf-8") as f: + f.writelines(f"{image_id} {score} {p[0]} {p[1]} {p[2]} {p[3]} {p[4]} {p[5]} {p[6]} {p[7]}\n") + # Save merged results, this could result slightly lower map than using official merging script, + # because of the probiou calculation. + pred_merged_txt = self.save_dir / "predictions_merged_txt" # predictions + pred_merged_txt.mkdir(parents=True, exist_ok=True) + merged_results = defaultdict(list) + LOGGER.info(f"Saving merged predictions with DOTA format to {pred_merged_txt}...") + for d in data: + image_id = d["image_id"].split("__", 1)[0] + pattern = re.compile(r"\d+___\d+") + x, y = (int(c) for c in re.findall(pattern, d["image_id"])[0].split("___")) + bbox, score, cls = d["rbox"], d["score"], d["category_id"] - 1 + bbox[0] += x + bbox[1] += y + bbox.extend([score, cls]) + merged_results[image_id].append(bbox) + for image_id, bbox in merged_results.items(): + bbox = torch.tensor(bbox) + max_wh = torch.max(bbox[:, :2]).item() * 2 + c = bbox[:, 6:7] * max_wh # classes + scores = bbox[:, 5] # scores + b = bbox[:, :5].clone() + b[:, :2] += c + # 0.3 could get results close to the ones from official merging script, even slightly better. + i = TorchNMS.fast_nms(b, scores, 0.3, iou_func=batch_probiou) + bbox = bbox[i] + + b = ops.xywhr2xyxyxyxy(bbox[:, :5]).view(-1, 8) + for x in torch.cat([b, bbox[:, 5:7]], dim=-1).tolist(): + classname = self.names[int(x[-1])].replace(" ", "-") + p = [round(i, 3) for i in x[:-2]] # poly + score = round(x[-2], 3) + + with open(f"{pred_merged_txt / f'Task1_{classname}'}.txt", "a", encoding="utf-8") as f: + f.writelines(f"{image_id} {score} {p[0]} {p[1]} {p[2]} {p[3]} {p[4]} {p[5]} {p[6]} {p[7]}\n") + + return stats diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..958b0a96ebb22d278af11c02afd254e0a5d091fd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__init__.py @@ -0,0 +1,7 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .predict import PosePredictor +from .train import PoseTrainer +from .val import PoseValidator + +__all__ = "PosePredictor", "PoseTrainer", "PoseValidator" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ebcc200335196d409a6a7f403c12d21cd82284b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__pycache__/predict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__pycache__/predict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca830ddd16bbff03ef057302c8b6358368515f45 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__pycache__/predict.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__pycache__/train.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__pycache__/train.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..101fe51b861b4f127e73476ac170dc976cf47139 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__pycache__/train.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__pycache__/val.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__pycache__/val.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f221ab3130ead0be190b93519409226a0f05c3c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/__pycache__/val.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/predict.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..d2e87b0ef832b0de007176dce927b91f914b8d54 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/predict.py @@ -0,0 +1,67 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from ultralytics.models.yolo.detect.predict import DetectionPredictor +from ultralytics.utils import DEFAULT_CFG, ops + + +class PosePredictor(DetectionPredictor): + """A class extending the DetectionPredictor class for prediction based on a pose model. + + This class specializes in pose estimation, handling keypoints detection alongside standard object detection + capabilities inherited from DetectionPredictor. + + Attributes: + args (namespace): Configuration arguments for the predictor. + model (torch.nn.Module): The loaded YOLO pose model with keypoint detection capabilities. + + Methods: + construct_result: Construct the result object from the prediction, including keypoints. + + Examples: + >>> from ultralytics.utils import ASSETS + >>> from ultralytics.models.yolo.pose import PosePredictor + >>> args = dict(model="yolo26n-pose.pt", source=ASSETS) + >>> predictor = PosePredictor(overrides=args) + >>> predictor.predict_cli() + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks: dict | None = None): + """Initialize PosePredictor for pose estimation tasks. + + Sets up a PosePredictor instance, configuring it for pose detection tasks and handling device-specific warnings + for Apple MPS. + + Args: + cfg (Any): Configuration for the predictor. + overrides (dict, optional): Configuration overrides that take precedence over cfg. + _callbacks (dict, optional): Dictionary of callback functions to be invoked during prediction. + """ + super().__init__(cfg, overrides, _callbacks) + self.args.task = "pose" + + def construct_result(self, pred, img, orig_img, img_path): + """Construct the result object from the prediction, including keypoints. + + Extends the parent class implementation by extracting keypoint data from predictions and adding them to the + result object. + + Args: + pred (torch.Tensor): The predicted bounding boxes, scores, and keypoints with shape (N, 6+K*D) where N is + the number of detections, K is the number of keypoints, and D is the keypoint dimension. + img (torch.Tensor): The processed input image tensor with shape (B, C, H, W). + orig_img (np.ndarray): The original unprocessed image as a numpy array. + img_path (str): The path to the original image file. + + Returns: + (Results): The result object containing the original image, image path, class names, bounding boxes, and + keypoints. + """ + result = super().construct_result(pred, img, orig_img, img_path) + # Extract keypoints from prediction and reshape according to model's keypoint shape + pred_kpts = pred[:, 6:].view(pred.shape[0], *self.model.kpt_shape) + # Scale keypoints coordinates to match the original image dimensions + pred_kpts = ops.scale_coords(img.shape[2:], pred_kpts, orig_img.shape) + result.update(keypoints=pred_kpts) + return result diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/train.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/train.py new file mode 100644 index 0000000000000000000000000000000000000000..30c18131bfb0788574a41253aaf83c74ca9faf23 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/train.py @@ -0,0 +1,116 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from copy import copy +from pathlib import Path +from typing import Any + +from ultralytics.models import yolo +from ultralytics.nn.tasks import PoseModel +from ultralytics.utils import DEFAULT_CFG, RANK + + +class PoseTrainer(yolo.detect.DetectionTrainer): + """A class extending the DetectionTrainer class for training YOLO pose estimation models. + + This trainer specializes in handling pose estimation tasks, managing model training, validation, and visualization + of pose keypoints alongside bounding boxes. + + Attributes: + args (dict): Configuration arguments for training. + model (PoseModel): The pose estimation model being trained. + data (dict): Dataset configuration including keypoint shape information. + loss_names (tuple): Names of the loss components, derived from the loss dict returned by the criterion. + + Methods: + get_model: Retrieve a pose estimation model with specified configuration. + set_model_attributes: Set keypoints shape attribute on the model. + get_validator: Create a validator instance for model evaluation. + plot_training_samples: Visualize training samples with keypoints. + get_dataset: Retrieve the dataset and ensure it contains required kpt_shape key. + + Examples: + >>> from ultralytics.models.yolo.pose import PoseTrainer + >>> args = dict(model="yolo26n-pose.pt", data="coco8-pose.yaml", epochs=3) + >>> trainer = PoseTrainer(overrides=args) + >>> trainer.train() + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides: dict[str, Any] | None = None, _callbacks: dict | None = None): + """Initialize a PoseTrainer object for training YOLO pose estimation models. + + Args: + cfg (dict, optional): Default configuration dictionary containing training parameters. + overrides (dict, optional): Dictionary of parameter overrides for the default configuration. + _callbacks (dict, optional): Dictionary of callback functions to be executed during training. + + Notes: + This trainer will automatically set the task to 'pose' regardless of what is provided in overrides. + A warning is issued when using Apple MPS device due to known bugs with pose models. + """ + if overrides is None: + overrides = {} + overrides["task"] = "pose" + super().__init__(cfg, overrides, _callbacks) + + def get_model( + self, + cfg: str | Path | dict[str, Any] | None = None, + weights: str | Path | None = None, + verbose: bool = True, + ) -> PoseModel: + """Get pose estimation model with specified configuration and weights. + + Args: + cfg (str | Path | dict, optional): Model configuration file path or dictionary. + weights (str | Path, optional): Path to the model weights file. + verbose (bool): Whether to display model information. + + Returns: + (PoseModel): Initialized pose estimation model. + """ + model = self.set_model_names_for_load( + PoseModel( + cfg, + nc=self.data["nc"], + ch=self.data["channels"], + data_kpt_shape=self.data["kpt_shape"], + verbose=verbose and RANK == -1, + ) + ) + if weights: + model.load(weights) + + return model + + def set_model_attributes(self): + """Set keypoints shape attribute of PoseModel.""" + super().set_model_attributes() + self.model.kpt_shape = self.data["kpt_shape"] + self.model.kpt_oks_sigmas = self.data.get("kpt_oks_sigmas") + kpt_names = self.data.get("kpt_names") + if not kpt_names: + names = list(map(str, range(self.model.kpt_shape[0]))) + kpt_names = {i: names for i in range(self.model.nc)} + self.model.kpt_names = kpt_names + + def get_validator(self): + """Return an instance of the PoseValidator class for validation.""" + return yolo.pose.PoseValidator( + self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks + ) + + def get_dataset(self) -> dict[str, Any]: + """Retrieve the dataset and ensure it contains the required `kpt_shape` key. + + Returns: + (dict): A dictionary containing the training/validation/test dataset and category names. + + Raises: + KeyError: If the `kpt_shape` key is not present in the dataset. + """ + data = super().get_dataset() + if "kpt_shape" not in data: + raise KeyError(f"No `kpt_shape` in the {self.args.data}. See https://docs.ultralytics.com/datasets/pose") + return data diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/val.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/val.py new file mode 100644 index 0000000000000000000000000000000000000000..c2400dea3ea78b2be71ce15852eeb3e69aa37ad2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/val.py @@ -0,0 +1,257 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from ultralytics.models.yolo.detect import DetectionValidator +from ultralytics.utils import ops +from ultralytics.utils.metrics import OKS_SIGMA, PoseMetrics, kpt_iou + + +class PoseValidator(DetectionValidator): + """A class extending the DetectionValidator class for validation based on a pose model. + + This validator is specifically designed for pose estimation tasks, handling keypoints and implementing specialized + metrics for pose evaluation. + + Attributes: + sigma (np.ndarray): Sigma values for OKS calculation, either OKS_SIGMA or ones divided by number of keypoints. + kpt_shape (list[int]): Shape of the keypoints, typically [17, 3] for COCO format. + args (dict): Arguments for the validator including task set to "pose". + metrics (PoseMetrics): Metrics object for pose evaluation. + + Methods: + preprocess: Preprocess batch by converting keypoints data to float and moving it to the device. + get_desc: Return description of evaluation metrics in string format. + init_metrics: Initialize pose estimation metrics for YOLO model. + postprocess: Postprocess YOLO predictions to extract and reshape keypoints for pose estimation. + _prepare_batch: Prepare a batch for processing by converting keypoints to float and scaling to original + dimensions. + _process_batch: Return correct prediction matrix by computing Intersection over Union (IoU) between detections + and ground truth. + gather_stats: Gather stats from all GPUs. + scale_preds: Scale predictions to the original image size. + save_one_txt: Save YOLO pose detections to a text file in normalized coordinates. + pred_to_json: Convert YOLO predictions to COCO JSON format. + eval_json: Evaluate object detection model using COCO JSON format. + + Examples: + >>> from ultralytics.models.yolo.pose import PoseValidator + >>> args = dict(model="yolo26n-pose.pt", data="coco8-pose.yaml") + >>> validator = PoseValidator(args=args) + >>> validator() + + Notes: + This class extends DetectionValidator with pose-specific functionality. It initializes with sigma values + for OKS calculation and sets up PoseMetrics for evaluation. A warning is displayed when using Apple MPS + due to a known bug with pose models. + """ + + def __init__(self, dataloader=None, save_dir=None, args=None, _callbacks: dict | None = None) -> None: + """Initialize a PoseValidator object for pose estimation validation. + + This validator is specifically designed for pose estimation tasks, handling keypoints and implementing + specialized metrics for pose evaluation. + + Args: + dataloader (torch.utils.data.DataLoader, optional): DataLoader to be used for validation. + save_dir (Path | str, optional): Directory to save results. + args (dict, optional): Arguments for the validator including task set to "pose". + _callbacks (dict, optional): Dictionary of callback functions to be executed during validation. + """ + super().__init__(dataloader, save_dir, args, _callbacks) + self.sigma = None + self.kpt_shape = None + self.args.task = "pose" + self.metrics = PoseMetrics() + + def preprocess(self, batch: dict[str, Any]) -> dict[str, Any]: + """Preprocess batch by converting keypoints data to float and moving it to the device.""" + batch = super().preprocess(batch) + batch["keypoints"] = batch["keypoints"].float() + return batch + + def get_desc(self) -> str: + """Return description of evaluation metrics in string format.""" + return ("%22s" + "%11s" * 10) % ( + "Class", + "Images", + "Instances", + "Box(P", + "R", + "mAP50", + "mAP50-95)", + "Pose(P", + "R", + "mAP50", + "mAP50-95)", + ) + + def init_metrics(self, model: torch.nn.Module) -> None: + """Initialize evaluation metrics for YOLO pose validation. + + Args: + model (torch.nn.Module): Model to validate. + """ + super().init_metrics(model) + self.kpt_shape = self.data["kpt_shape"] + is_pose = self.kpt_shape == [17, 3] + nkpt = self.kpt_shape[0] + if sigmas := self.data.get("kpt_oks_sigmas"): # optional custom OKS sigmas from the dataset YAML + self.sigma = np.array(sigmas, dtype=np.float32).flatten() + if len(self.sigma) != nkpt or not np.all(self.sigma > 0): + raise ValueError(f"'kpt_oks_sigmas' must be {nkpt} positive values, got {sigmas}") + else: + self.sigma = OKS_SIGMA if is_pose else np.ones(nkpt) / nkpt + + def postprocess(self, preds: torch.Tensor) -> list[dict[str, torch.Tensor]]: + """Postprocess YOLO predictions to extract and reshape keypoints for pose estimation. + + This method extends the parent class postprocessing by extracting keypoints from the 'extra' field of + predictions and reshaping them according to the keypoint shape configuration. The keypoints are reshaped from a + flattened format to the proper dimensional structure (typically [N, 17, 3] for COCO pose format). + + Args: + preds (torch.Tensor): Raw prediction tensor from the YOLO pose model containing bounding boxes, confidence + scores, class predictions, and keypoint data. + + Returns: + (list[dict[str, torch.Tensor]]): List of processed prediction dictionaries, each containing: + - 'bboxes': Bounding box coordinates + - 'conf': Confidence scores + - 'cls': Class predictions + - 'keypoints': Reshaped keypoint coordinates with shape (-1, *self.kpt_shape) + + Notes: + The keypoints are extracted from the 'extra' field which contains additional task-specific data beyond + basic detection. + """ + preds = super().postprocess(preds) + for pred in preds: + pred["keypoints"] = pred.pop("extra").view(-1, *self.kpt_shape) # remove extra if exists + return preds + + def _prepare_batch(self, si: int, batch: dict[str, Any]) -> dict[str, Any]: + """Prepare a batch for processing by converting keypoints to float and scaling to original dimensions. + + Args: + si (int): Sample index within the batch. + batch (dict[str, Any]): Dictionary containing batch data with keys like 'keypoints', 'batch_idx', etc. + + Returns: + (dict[str, Any]): Prepared batch with keypoints scaled to model input (letterboxed) image dimensions. + + Notes: + This method extends the parent class's _prepare_batch method by adding keypoint processing. + Keypoints are scaled from normalized coordinates to the model input (letterboxed) image dimensions. + """ + pbatch = super()._prepare_batch(si, batch) + kpts = batch["keypoints"][batch["batch_idx"] == si] + h, w = pbatch["imgsz"] + kpts = kpts.clone() + kpts[..., 0] *= w + kpts[..., 1] *= h + pbatch["keypoints"] = kpts + return pbatch + + def _process_batch(self, preds: dict[str, torch.Tensor], batch: dict[str, Any]) -> dict[str, np.ndarray]: + """Return correct prediction matrix by computing Intersection over Union (IoU) between detections and ground + truth. + + Args: + preds (dict[str, torch.Tensor]): Dictionary containing prediction data with keys 'cls' for class predictions + and 'keypoints' for keypoint predictions. + batch (dict[str, Any]): Dictionary containing ground truth data with keys 'cls' for class labels, 'bboxes' + for bounding boxes, and 'keypoints' for keypoint annotations. + + Returns: + (dict[str, np.ndarray]): Dictionary containing the correct prediction matrix including 'tp_p' for pose true + positives across 10 IoU levels. + + Notes: + `0.53` scale factor used in area computation is referenced from + https://github.com/jin-s13/xtcocoapi/blob/master/xtcocotools/cocoeval.py#L384. + """ + tp = super()._process_batch(preds, batch) + gt_cls = batch["cls"] + if gt_cls.shape[0] == 0 or preds["cls"].shape[0] == 0: + tp_p = np.zeros((preds["cls"].shape[0], self.niou), dtype=bool) + else: + # `0.53` is from https://github.com/jin-s13/xtcocoapi/blob/master/xtcocotools/cocoeval.py#L384 + area = ops.xyxy2xywh(batch["bboxes"])[:, 2:].prod(1) * 0.53 + iou = kpt_iou(batch["keypoints"], preds["keypoints"], sigma=self.sigma, area=area) + tp_p = self.match_predictions(preds["cls"], gt_cls, iou).cpu().numpy() + tp.update({"tp_p": tp_p}) # update tp with kpts IoU + return tp + + def gather_stats(self) -> None: + """Gather stats from all GPUs.""" + super().gather_stats() # gather stats from DetectionValidator + self._gather_image_metrics(self.metrics.pose) + + def save_one_txt(self, predn: dict[str, torch.Tensor], save_conf: bool, shape: tuple[int, int], file: Path) -> None: + """Save YOLO pose detections to a text file in normalized coordinates. + + Args: + predn (dict[str, torch.Tensor]): Prediction dict with keys 'bboxes', 'conf', 'cls', and 'keypoints'. + save_conf (bool): Whether to save confidence scores. + shape (tuple[int, int]): Shape of the original image (height, width). + file (Path): Output file path to save detections. + + Notes: + The output format is: class_id x_center y_center width height confidence keypoints where keypoints are + normalized (x, y, visibility) values for each point. + """ + from ultralytics.engine.results import Results + + Results( + np.zeros((shape[0], shape[1]), dtype=np.uint8), + path=None, + names=self.names, + boxes=torch.cat([predn["bboxes"], predn["conf"].unsqueeze(-1), predn["cls"].unsqueeze(-1)], dim=1), + keypoints=predn["keypoints"], + ).save_txt(file, save_conf=save_conf) + + def pred_to_json(self, predn: dict[str, torch.Tensor], pbatch: dict[str, Any]) -> None: + """Convert YOLO predictions to COCO JSON format. + + This method takes prediction tensors and batch data, converts the bounding boxes from YOLO format to COCO + format, and appends the results with keypoints to the internal JSON dictionary (self.jdict). + + Args: + predn (dict[str, torch.Tensor]): Prediction dictionary containing 'bboxes', 'conf', 'cls', and 'keypoints' + tensors. + pbatch (dict[str, Any]): Batch dictionary containing 'imgsz', 'ori_shape', 'ratio_pad', and 'im_file'. + + Notes: + The method extracts the image ID from the filename stem (either as an integer if numeric, or as a string), + converts bounding boxes from xyxy to xywh format, and adjusts coordinates from center to top-left corner + before saving to the JSON dictionary. + """ + super().pred_to_json(predn, pbatch) + kpts = predn["keypoints"] + for i, k in enumerate(kpts.flatten(1, 2).tolist()): + self.jdict[-len(kpts) + i]["keypoints"] = k # keypoints + + def scale_preds(self, predn: dict[str, torch.Tensor], pbatch: dict[str, Any]) -> dict[str, torch.Tensor]: + """Scales predictions to the original image size.""" + return { + **super().scale_preds(predn, pbatch), + "keypoints": ops.scale_coords( + pbatch["imgsz"], + predn["keypoints"].clone(), + pbatch["ori_shape"], + ratio_pad=pbatch["ratio_pad"], + ), + } + + def eval_json(self, stats: dict[str, Any]) -> dict[str, Any]: + """Evaluate object detection model using COCO JSON format.""" + anno_json = self.data["path"] / "annotations/person_keypoints_val2017.json" # annotations + pred_json = self.save_dir / "predictions.json" # predictions + return super().coco_evaluate(stats, pred_json, anno_json, ["bbox", "keypoints"], suffix=["Box", "Pose"]) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..36a921a9a36a0f0a0bf1bf03be9014c6886f6c6e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__init__.py @@ -0,0 +1,7 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .predict import SegmentationPredictor +from .train import SegmentationTrainer +from .val import SegmentationValidator + +__all__ = "SegmentationPredictor", "SegmentationTrainer", "SegmentationValidator" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfe004138506a4bfc2d0ce092fcda60ace2c42c4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__pycache__/predict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__pycache__/predict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7dd93ab8822d9767cf2bc3ffc1322a539324622e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__pycache__/predict.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__pycache__/train.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__pycache__/train.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10b7825359c9f9d75bac5bbfc743b919d1c4967e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__pycache__/train.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__pycache__/val.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__pycache__/val.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf8c3a6d5bb496b137066e96bb2cf8f7a7a36820 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/__pycache__/val.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/predict.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..99f4dcce203163308e1fd2ed9ff7338b04cebf29 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/predict.py @@ -0,0 +1,111 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from ultralytics.engine.results import Results +from ultralytics.models.yolo.detect.predict import DetectionPredictor +from ultralytics.utils import DEFAULT_CFG, ops + + +class SegmentationPredictor(DetectionPredictor): + """A class extending the DetectionPredictor class for prediction based on a segmentation model. + + This class specializes in processing segmentation model outputs, handling both bounding boxes and masks in the + prediction results. + + Attributes: + args (dict): Configuration arguments for the predictor. + model (torch.nn.Module): The loaded YOLO segmentation model. + batch (list): Current batch of images being processed. + + Methods: + postprocess: Apply non-max suppression and process segmentation detections. + construct_results: Construct a list of result objects from predictions. + construct_result: Construct a single result object from a prediction. + + Examples: + >>> from ultralytics.utils import ASSETS + >>> from ultralytics.models.yolo.segment import SegmentationPredictor + >>> args = dict(model="yolo26n-seg.pt", source=ASSETS) + >>> predictor = SegmentationPredictor(overrides=args) + >>> predictor.predict_cli() + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks: dict | None = None): + """Initialize the SegmentationPredictor with configuration, overrides, and callbacks. + + This class specializes in processing segmentation model outputs, handling both bounding boxes and masks in the + prediction results. + + Args: + cfg (dict): Configuration for the predictor. + overrides (dict, optional): Configuration overrides that take precedence over cfg. + _callbacks (dict, optional): Dictionary of callback functions to be invoked during prediction. + """ + super().__init__(cfg, overrides, _callbacks) + self.args.task = "segment" + + def postprocess(self, preds, img, orig_imgs): + """Apply non-max suppression and process segmentation detections for each image in the input batch. + + Args: + preds (tuple): Model predictions, containing bounding boxes, scores, classes, and mask coefficients. + img (torch.Tensor): Input image tensor in model format, with shape (B, C, H, W). + orig_imgs (list | torch.Tensor | np.ndarray): Original image or batch of images. + + Returns: + (list): List of Results objects containing the segmentation predictions for each image in the batch. Each + Results object includes both bounding boxes and segmentation masks. + + Examples: + >>> predictor = SegmentationPredictor(overrides=dict(model="yolo26n-seg.pt")) + >>> results = predictor.postprocess(preds, img, orig_img) + """ + # Extract protos - tuple if PyTorch model or array if exported + protos = preds[0][1] if isinstance(preds[0], tuple) else preds[1] + return super().postprocess(preds[0], img, orig_imgs, protos=protos) + + def construct_results(self, preds, img, orig_imgs, protos): + """Construct a list of result objects from the predictions. + + Args: + preds (list[torch.Tensor]): List of predicted bounding boxes, scores, and masks. + img (torch.Tensor): The image after preprocessing. + orig_imgs (list[np.ndarray]): List of original images before preprocessing. + protos (torch.Tensor): Prototype masks tensor with shape (B, C, H, W). + + Returns: + (list[Results]): List of result objects containing the original images, image paths, class names, bounding + boxes, and masks. + """ + return [ + self.construct_result(pred, img, orig_img, img_path, proto) + for pred, orig_img, img_path, proto in zip(preds, orig_imgs, self.batch[0], protos) + ] + + def construct_result(self, pred, img, orig_img, img_path, proto): + """Construct a single result object from the prediction. + + Args: + pred (torch.Tensor): The predicted bounding boxes, scores, and masks. + img (torch.Tensor): The image after preprocessing. + orig_img (np.ndarray): The original image before preprocessing. + img_path (str): The path to the original image. + proto (torch.Tensor): The prototype masks. + + Returns: + (Results): Result object containing the original image, image path, class names, bounding boxes, and masks. + """ + if pred.shape[0] == 0: # save empty boxes + masks = None + elif self.args.retina_masks: + pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape) + masks = ops.process_mask_native(proto, pred[:, 6:], pred[:, :4], orig_img.shape[:2]) # NHW + else: + masks = ops.process_mask(proto, pred[:, 6:], pred[:, :4], img.shape[2:], upsample=True) # NHW + pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape) + if masks is not None: + keep = masks.amax((-2, -1)) > 0 # only keep predictions with masks + if not (all(keep) or getattr(self, "_feats", None) is not None): # skip filter if native ReID enabled + pred, masks = pred[keep], masks[keep] # indexing is slow + return Results(orig_img, path=img_path, names=self.model.names, boxes=pred[:, :6], masks=masks) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/train.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/train.py new file mode 100644 index 0000000000000000000000000000000000000000..447027167f8ec0ed209e7158685ae296757d7f8d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/train.py @@ -0,0 +1,70 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from copy import copy +from pathlib import Path + +from ultralytics.models import yolo +from ultralytics.nn.tasks import SegmentationModel +from ultralytics.utils import DEFAULT_CFG, RANK + + +class SegmentationTrainer(yolo.detect.DetectionTrainer): + """A class extending the DetectionTrainer class for training based on a segmentation model. + + This trainer specializes in handling segmentation tasks, extending the detection trainer with segmentation-specific + functionality including model initialization, validation, and visualization. + + Attributes: + loss_names (tuple[str]): Names of the loss components, derived from the loss dict returned by the criterion. + + Examples: + >>> from ultralytics.models.yolo.segment import SegmentationTrainer + >>> args = dict(model="yolo26n-seg.pt", data="coco8-seg.yaml", epochs=3) + >>> trainer = SegmentationTrainer(overrides=args) + >>> trainer.train() + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides: dict | None = None, _callbacks: dict | None = None): + """Initialize a SegmentationTrainer object. + + Args: + cfg (dict): Configuration dictionary with default training settings. + overrides (dict, optional): Dictionary of parameter overrides for the default configuration. + _callbacks (dict, optional): Dictionary of callback functions to be executed during training. + """ + if overrides is None: + overrides = {} + overrides["task"] = "segment" + super().__init__(cfg, overrides, _callbacks) + + def get_model(self, cfg: dict | str | None = None, weights: str | Path | None = None, verbose: bool = True): + """Initialize and return a SegmentationModel with specified configuration and weights. + + Args: + cfg (dict | str, optional): Model configuration. Can be a dictionary, a path to a YAML file, or None. + weights (str | Path, optional): Path to pretrained weights file. + verbose (bool): Whether to display model information during initialization. + + Returns: + (SegmentationModel): Initialized segmentation model with loaded weights if specified. + + Examples: + >>> trainer = SegmentationTrainer() + >>> model = trainer.get_model(cfg="yolo26n-seg.yaml") + >>> model = trainer.get_model(weights="yolo26n-seg.pt", verbose=False) + """ + model = self.set_model_names_for_load( + SegmentationModel(cfg, nc=self.data["nc"], ch=self.data["channels"], verbose=verbose and RANK == -1) + ) + if weights: + model.load(weights) + + return model + + def get_validator(self): + """Return an instance of SegmentationValidator for validation of YOLO model.""" + return yolo.segment.SegmentationValidator( + self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/val.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/val.py new file mode 100644 index 0000000000000000000000000000000000000000..577ec0bc4a5aabe6ab057b48f3a2c1d8f0885842 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/val.py @@ -0,0 +1,310 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.nn.functional as F + +from ultralytics.models.yolo.detect import DetectionValidator +from ultralytics.utils import LOGGER, ops +from ultralytics.utils.checks import check_requirements +from ultralytics.utils.metrics import SegmentMetrics, mask_iou + + +class SegmentationValidator(DetectionValidator): + """A class extending the DetectionValidator class for validation based on a segmentation model. + + This validator handles the evaluation of segmentation models, processing both bounding box and mask predictions to + compute metrics such as mAP for both detection and segmentation tasks. + + Attributes: + process (callable): Function to process masks based on save_json and save_txt flags. + args (SimpleNamespace): Arguments for the validator. + metrics (SegmentMetrics): Metrics calculator for segmentation tasks. + stats (dict): Dictionary to store statistics during validation. + + Examples: + >>> from ultralytics.models.yolo.segment import SegmentationValidator + >>> args = dict(model="yolo26n-seg.pt", data="coco8-seg.yaml") + >>> validator = SegmentationValidator(args=args) + >>> validator() + """ + + def __init__(self, dataloader=None, save_dir=None, args=None, _callbacks: dict | None = None) -> None: + """Initialize SegmentationValidator and set task to 'segment', metrics to SegmentMetrics. + + Args: + dataloader (torch.utils.data.DataLoader, optional): DataLoader to use for validation. + save_dir (Path, optional): Directory to save results. + args (dict, optional): Arguments for the validator. + _callbacks (dict, optional): Dictionary of callback functions. + """ + super().__init__(dataloader, save_dir, args, _callbacks) + self.process = None + self.args.task = "segment" + self.metrics = SegmentMetrics() + + def preprocess(self, batch: dict[str, Any]) -> dict[str, Any]: + """Preprocess batch of images for YOLO segmentation validation. + + Args: + batch (dict[str, Any]): Batch containing images and annotations. + + Returns: + (dict[str, Any]): Preprocessed batch. + """ + batch = super().preprocess(batch) + batch["masks"] = batch["masks"].float() + return batch + + def init_metrics(self, model: torch.nn.Module) -> None: + """Initialize metrics and select mask processing function based on save_json flag. + + Args: + model (torch.nn.Module): Model to validate. + """ + super().init_metrics(model) + if self.args.save_json: + check_requirements("faster-coco-eval>=1.6.7") + # More accurate vs faster + self.process = ops.process_mask_native if self.args.save_json or self.args.save_txt else ops.process_mask + + def get_desc(self) -> str: + """Return a formatted description of evaluation metrics.""" + return ("%22s" + "%11s" * 10) % ( + "Class", + "Images", + "Instances", + "Box(P", + "R", + "mAP50", + "mAP50-95)", + "Mask(P", + "R", + "mAP50", + "mAP50-95)", + ) + + def postprocess(self, preds: list[torch.Tensor]) -> list[dict[str, torch.Tensor]]: + """Post-process YOLO predictions and return output detections with proto. + + Args: + preds (list[torch.Tensor]): Raw predictions from the model. + + Returns: + (list[dict[str, torch.Tensor]]): Processed detection predictions with masks. + """ + proto = preds[0][1] if isinstance(preds[0], tuple) else preds[1] + preds = super().postprocess(preds[0]) + imgsz = [4 * x for x in proto.shape[2:]] # get image size from proto + for i, pred in enumerate(preds): + coefficient = pred.pop("extra") + pred["masks"] = self.process(proto[i], coefficient, pred["bboxes"], shape=imgsz) + return preds + + def _prepare_batch(self, si: int, batch: dict[str, Any]) -> dict[str, Any]: + """Prepare a batch for validation by processing images and targets. + + Args: + si (int): Sample index within the batch. + batch (dict[str, Any]): Batch data containing images and annotations. + + Returns: + (dict[str, Any]): Prepared batch with processed annotations. + """ + prepared_batch = super()._prepare_batch(si, batch) + nl = prepared_batch["cls"].shape[0] + if self.args.overlap_mask: + masks = batch["masks"][si] + index = torch.arange(1, nl + 1, device=masks.device).view(nl, 1, 1) + masks = (masks == index).float() + else: + masks = batch["masks"][batch["batch_idx"] == si] + if nl: + mask_size = [s if self.process is ops.process_mask_native else s // 4 for s in prepared_batch["imgsz"]] + if masks.shape[1:] != mask_size: + masks = F.interpolate(masks[None], mask_size, mode="bilinear", align_corners=False)[0] + masks = masks.gt_(0.5) + prepared_batch["masks"] = masks + return prepared_batch + + def gather_stats(self) -> None: + """Gather stats from all GPUs.""" + super().gather_stats() # gather stats from DetectionValidator + self._gather_image_metrics(self.metrics.seg) + + def _process_batch(self, preds: dict[str, torch.Tensor], batch: dict[str, Any]) -> dict[str, np.ndarray]: + """Compute correct prediction matrix for a batch based on bounding boxes and optional masks. + + Args: + preds (dict[str, torch.Tensor]): Dictionary containing predictions with keys like 'cls' and 'masks'. + batch (dict[str, Any]): Dictionary containing batch data with keys like 'cls' and 'masks'. + + Returns: + (dict[str, np.ndarray]): A dictionary containing correct prediction matrices including 'tp_m' for mask IoU. + + Examples: + >>> preds = {"cls": torch.tensor([1, 0]), "masks": torch.rand(2, 640, 640), "bboxes": torch.rand(2, 4)} + >>> batch = {"cls": torch.tensor([1, 0]), "masks": torch.rand(2, 640, 640), "bboxes": torch.rand(2, 4)} + >>> correct_preds = validator._process_batch(preds, batch) + + Notes: + - This method computes IoU between predicted and ground truth masks. + - Overlapping masks are handled based on the overlap_mask argument setting. + """ + tp = super()._process_batch(preds, batch) + gt_cls = batch["cls"] + if gt_cls.shape[0] == 0 or preds["cls"].shape[0] == 0: + tp_m = np.zeros((preds["cls"].shape[0], self.niou), dtype=bool) + else: + iou = mask_iou(batch["masks"].flatten(1), preds["masks"].flatten(1).float()) # float, uint8 + tp_m = self.match_predictions(preds["cls"], gt_cls, iou).cpu().numpy() + tp.update({"tp_m": tp_m}) # update tp with mask IoU + return tp + + def plot_predictions(self, batch: dict[str, Any], preds: list[dict[str, torch.Tensor]], ni: int) -> None: + """Plot batch predictions with masks and bounding boxes. + + Args: + batch (dict[str, Any]): Batch containing images and annotations. + preds (list[dict[str, torch.Tensor]]): List of predictions from the model. + ni (int): Batch index. + """ + for p in preds: + masks = p["masks"] + if masks.shape[0] > self.args.max_det: + LOGGER.warning(f"Limiting validation plots to 'max_det={self.args.max_det}' items.") + p["masks"] = torch.as_tensor(masks[: self.args.max_det], dtype=torch.uint8).cpu() + super().plot_predictions(batch, preds, ni, max_det=self.args.max_det) # plot bboxes + + def save_one_txt(self, predn: dict[str, torch.Tensor], save_conf: bool, shape: tuple[int, int], file: Path) -> None: + """Save YOLO detections to a txt file in normalized coordinates in a specific format. + + Args: + predn (dict[str, torch.Tensor]): Prediction dictionary containing 'bboxes', 'conf', 'cls', and 'masks' keys. + save_conf (bool): Whether to save confidence scores. + shape (tuple[int, int]): Shape of the original image. + file (Path): File path to save the detections. + """ + from ultralytics.engine.results import Results + + Results( + np.zeros((shape[0], shape[1]), dtype=np.uint8), + path=None, + names=self.names, + boxes=torch.cat([predn["bboxes"], predn["conf"].unsqueeze(-1), predn["cls"].unsqueeze(-1)], dim=1), + masks=torch.as_tensor(predn["masks"], dtype=torch.uint8), + ).save_txt(file, save_conf=save_conf) + + def pred_to_json(self, predn: dict[str, torch.Tensor], pbatch: dict[str, Any]) -> None: + """Save one JSON result for COCO evaluation. + + Args: + predn (dict[str, torch.Tensor]): Predictions containing bboxes, masks, confidence scores, and classes. + pbatch (dict[str, Any]): Batch dictionary containing 'imgsz', 'ori_shape', 'ratio_pad', and 'im_file'. + """ + + def to_string(counts: list[int]) -> str: + """Converts the RLE object into a compact string representation. Each count is delta-encoded and + variable-length encoded as a string. + + Args: + counts (list[int]): List of RLE counts. + """ + result = [] + + for i in range(len(counts)): + x = int(counts[i]) + + # Apply delta encoding for all counts after the second entry + if i > 2: + x -= int(counts[i - 2]) + + # Variable-length encode the value + while True: + c = x & 0x1F # Take 5 bits + x >>= 5 + + # If the sign bit (0x10) is set, continue if x != -1; + # otherwise, continue if x != 0 + more = (x != -1) if (c & 0x10) else (x != 0) + if more: + c |= 0x20 # Set continuation bit + c += 48 # Shift to ASCII + result.append(chr(c)) + if not more: + break + + return "".join(result) + + def multi_encode(pixels: torch.Tensor) -> list[int]: + """Convert multiple binary masks using Run-Length Encoding (RLE). + + Args: + pixels (torch.Tensor): A 2D tensor where each row represents a flattened binary mask with shape [N, + H*W]. + + Returns: + (list[list[int]]): A list of RLE counts for each mask. + """ + num_masks, width = pixels.shape + transitions = pixels[:, 1:] != pixels[:, :-1] + row_idx, col_idx = torch.where(transitions) + n = len(row_idx) + # Pack each (mask, position) pair into one integer for a compact, single device-to-host transfer. + row_idx.mul_(width).add_(col_idx).add_(1) + del col_idx + packed = torch.cat((row_idx, pixels[:, 0].to(row_idx.dtype))).cpu().numpy() + positions, starts = np.split(packed, (n,)) + boundaries = np.searchsorted(positions, np.arange(num_masks + 1) * width) + + # Compute run lengths + counts = [] + for i in range(num_masks): + mask_positions = positions[boundaries[i] : boundaries[i + 1]] - i * width + if mask_positions.size: + count = np.diff(mask_positions).tolist() + count.insert(0, mask_positions[0]) + count.append(width - mask_positions[-1]) + else: + count = [width] + + # Ensure starting with background (0) count + if starts[i] == 1: + count = [0, *count] + counts.append(count) + + return counts + + pred_masks = predn["masks"].transpose(2, 1).contiguous().view(len(predn["masks"]), -1) # N, H*W + h, w = predn["masks"].shape[1:3] + counts = multi_encode(pred_masks) + rles = [] + for c in counts: + rles.append({"size": [h, w], "counts": to_string(c)}) + super().pred_to_json(predn, pbatch) + for i, r in enumerate(rles): + self.jdict[-len(rles) + i]["segmentation"] = r # segmentation + + def scale_preds(self, predn: dict[str, torch.Tensor], pbatch: dict[str, Any]) -> dict[str, torch.Tensor]: + """Scales predictions to the original image size.""" + return { + **super().scale_preds(predn, pbatch), + "masks": ops.scale_masks(predn["masks"][None], pbatch["ori_shape"], ratio_pad=pbatch["ratio_pad"])[ + 0 + ].byte(), + } + + def eval_json(self, stats: dict[str, Any]) -> dict[str, Any]: + """Return COCO-style instance segmentation evaluation metrics.""" + pred_json = self.save_dir / "predictions.json" # predictions + anno_json = ( + self.data["path"] + / "annotations" + / ("instances_val2017.json" if self.is_coco else f"lvis_v1_{self.args.split}.json") + ) # annotations + return super().coco_evaluate(stats, pred_json, anno_json, ["bbox", "segm"], suffix=["Box", "Mask"]) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5a64044f3d8198f82e465d7096c399b076ea9f36 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__init__.py @@ -0,0 +1,7 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .predict import SemanticSegmentationPredictor +from .train import SemanticSegmentationTrainer +from .val import SemanticSegmentationValidator + +__all__ = "SemanticSegmentationPredictor", "SemanticSegmentationTrainer", "SemanticSegmentationValidator" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7da58548c4e2d6e6590116be5cdd3bd027200e45 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__pycache__/predict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__pycache__/predict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8a0baf06b173a3f7308149149ab09f08b3f2417 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__pycache__/predict.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__pycache__/train.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__pycache__/train.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..717c8dc0a88782ce2795de1c5de1ec3b28febf60 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__pycache__/train.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__pycache__/val.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__pycache__/val.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9c507003ec9e146ef0702cbbe1fffbdd50b74b3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/__pycache__/val.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/predict.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..cc738ec22c3c44ccc0e066cbca5ff8dc9b64d6e5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/predict.py @@ -0,0 +1,89 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import torch +import torch.nn.functional as F + +from ultralytics.engine.predictor import BasePredictor +from ultralytics.engine.results import Results +from ultralytics.utils import DEFAULT_CFG, ops + + +class SemanticSegmentationPredictor(BasePredictor): + """Predictor for semantic segmentation models. + + This predictor processes model outputs to produce per-pixel class label maps. + + Examples: + >>> from ultralytics.models.yolo.semantic import SemanticSegmentationPredictor + >>> args = dict(model="yolo26n-sem.pt", source="path/to/image.jpg") + >>> predictor = SemanticSegmentationPredictor(overrides=args) + >>> predictor.predict_cli() + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None): + """Initialize SemanticSegmentationPredictor. + + Args: + cfg (dict): Configuration for the predictor. + overrides (dict, optional): Configuration overrides. + _callbacks (dict, optional): Callback functions. + """ + super().__init__(cfg, overrides, _callbacks) + self.args.task = "semantic" + + @staticmethod + def _class_map_dtype(num_classes: int) -> torch.dtype: + """Return the smallest practical integer dtype for semantic class IDs.""" + return torch.uint8 if num_classes <= 256 else torch.int16 if num_classes <= 32768 else torch.int32 + + def postprocess(self, preds, img, orig_imgs): + """Convert model output to semantic segmentation results. + + Args: + preds (torch.Tensor | tuple): Model output logits [B, nc, H, W] or baked class map [B, H, W]. + img (torch.Tensor): Preprocessed input image tensor. + orig_imgs (list | torch.Tensor): Original images. + + Returns: + (list[Results]): List of Results objects with semantic masks. + """ + if isinstance(preds, (tuple, list)): + preds = preds[0] + + if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list + orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)[..., ::-1] + + classes = ( + torch.as_tensor(self.args.classes, device=preds.device).flatten() + if self.args.classes is not None and len(self.model.names) > 1 + else None + ) + + results = [] + for i, (pred, orig_img) in enumerate(zip(preds, orig_imgs)): + img_path = self.batch[0][i] if isinstance(self.batch[0], list) else self.batch[0] + class_map_input = pred.ndim == 2 # exports with in-graph ArgMax emit a [H, W] class map directly + pred = (pred[None, None] if class_map_input else pred[None]).float() + if class_map_input: + # Class maps may arrive as float from OpenCV DNN, but they are still discrete IDs. Nearest-resize only. + if pred.shape[2:] != img.shape[2:]: + pred = F.interpolate(pred, img.shape[2:], mode="nearest") + class_map = ops.scale_masks(pred, orig_img.shape[:2], mode="nearest")[0, 0] + class_map = class_map.to(self._class_map_dtype(int(class_map.max().item()) + 1)) + else: + # pred: [1, nc, H, W] logits. Upsample to the input resolution first so LetterBox padding is integer. + if pred.shape[2:] != img.shape[2:]: + pred = F.interpolate(pred, img.shape[2:], mode="bilinear") + # Remove letterbox padding, then resize to original image. + pred = ops.scale_masks(pred, orig_img.shape[:2])[0] + dtype = self._class_map_dtype(max(pred.shape[0], 2)) + if pred.shape[0] > 1: # CPU argmax over the outermost dim runs as a per-output loop; max(dim) streams + class_map = (pred.max(0).indices if pred.device.type == "cpu" else pred.argmax(0)).to(dtype) + else: + class_map = pred.gt(0).squeeze(0).to(dtype) + if classes is not None: # keep only selected classes, mark the rest as ignore + class_map[~(class_map.unsqueeze(-1) == classes).any(-1)] = 255 + results.append(Results(orig_img, path=img_path, names=self.model.names, semantic_mask=class_map)) + return results diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/train.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/train.py new file mode 100644 index 0000000000000000000000000000000000000000..df45b577446d389584f808b7fc226cb218f621a2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/train.py @@ -0,0 +1,152 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from copy import copy +from typing import Any + +import numpy as np + +from ultralytics.data.utils import add_polygon_background +from ultralytics.models import yolo +from ultralytics.models.yolo.detect import DetectionTrainer +from ultralytics.nn.tasks import SemanticSegmentationModel +from ultralytics.utils import DEFAULT_CFG, LOGGER, RANK +from ultralytics.utils.plotting import colors, plt_settings + + +class SemanticSegmentationTrainer(DetectionTrainer): + """Trainer for YOLO semantic segmentation models. + + This trainer handles semantic segmentation training, including dataset building, model initialization, and + validation setup. + + Examples: + >>> from ultralytics.models.yolo.semantic import SemanticSegmentationTrainer + >>> args = dict(model="yolo26n-sem.yaml", data="cityscapes8.yaml", epochs=3) + >>> trainer = SemanticSegmentationTrainer(overrides=args) + >>> trainer.train() + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides: dict[str, Any] | None = None, _callbacks: dict | None = None): + """Initialize SemanticSegmentationTrainer. + + Args: + cfg (dict): Configuration dictionary with default training settings. + overrides (dict, optional): Dictionary of parameter overrides. + _callbacks (dict, optional): Callback functions. + """ + if overrides is None: + overrides = {} + overrides["task"] = "semantic" + super().__init__(cfg, overrides, _callbacks) + + def get_dataset(self): + """Parse the dataset YAML and add background metadata for polygon labels when required.""" + return add_polygon_background(super().get_dataset()) + + def get_model(self, cfg: str | None = None, weights: str | None = None, verbose: bool = True): + """Return a SemanticSegmentationModel with optional pretrained backbone. + + Args: + cfg (str, optional): Path to model configuration file. + weights (str | Path, optional): Path to model weights. + verbose (bool): Whether to display model information. + + Returns: + (SemanticSegmentationModel): Semantic segmentation model. + """ + model = SemanticSegmentationModel( + cfg, nc=self.data["nc"], ch=self.data["channels"], verbose=verbose and RANK == -1 + ) + if weights: + model.load(weights) + + return model + + def get_validator(self): + """Return a SemanticSegmentationValidator for model evaluation.""" + return yolo.semantic.SemanticSegmentationValidator( + self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks + ) + + def set_class_weights(self): + """Compute pixel-frequency class weights; skipped for binary (nc==1, unweighted BCE in the loss).""" + if self.data["nc"] > 1: + super().set_class_weights() + + def get_class_counts(self, max_masks=None): + """Return per-class pixel counts from training masks, optionally sampled to max_masks.""" + nc = self.data["nc"] + pixel_counts = np.zeros(nc, dtype=np.float32) + dataset = self.train_loader.dataset + labels = getattr(dataset, "labels", []) + if not labels: + return pixel_counts + indices = np.arange(len(labels)) + if max_masks and len(indices) > max_masks: + indices = np.linspace(0, len(labels) - 1, max_masks).astype(int) + include_class = getattr(dataset, "include_class", None) + for idx in indices: + shape = labels[idx].get("shape") + try: + mask = dataset.load_mask(idx, image_shape=tuple(shape) if shape is not None else None) + except Exception: # noqa: S112 + continue + if include_class is not None: + mask[~np.isin(mask, include_class)] = 255 + valid = (mask >= 0) & (mask < nc) & (mask != 255) + if valid.any(): + classes, counts = np.unique(mask[valid], return_counts=True) + pixel_counts[classes.astype(int)] += counts + return pixel_counts + + def compute_class_weights(self, class_counts): + """Compute ENet inverse-log `(1/ln(1.02 + p))**cls_pw` weights (Paszke et al., 2016, arXiv:1606.02147).""" + p = class_counts / max(class_counts.sum(), 1.0) # pixel frequency, bounded for rare classes unlike detection + return (1.0 / np.log(1.02 + p)) ** self.args.cls_pw + + @plt_settings() + def plot_training_labels(self): + """Plot training labels class distribution for semantic segmentation. + + Samples up to 1000 mask files from the training dataset, accumulates per-class pixel + counts, and plots a bar chart of class distribution saved to 'labels.jpg'. + """ + import matplotlib.pyplot as plt + + LOGGER.info(f"Plotting labels to {self.save_dir / 'labels.jpg'}...") + nc = self.data["nc"] + names = self.data["names"] + pixel_counts = self.get_class_counts(max_masks=1000) + if not pixel_counts.any(): + LOGGER.warning("No semantic mask files found, skipping label plot.") + return + + _, ax = plt.subplots(1, 1, figsize=(8, 6), tight_layout=True) + bars = ax.bar(range(nc), pixel_counts, color=[[c / 255.0 for c in colors(i, False)] for i in range(nc)]) + ax.set_xlabel("Class") + ax.set_ylabel("Pixels") + ax.set_title("Training Labels Class Distribution") + if 0 < len(names) < 30: + ax.set_xticks(range(len(names))) + ax.set_xticklabels(list(names.values()), rotation=90, fontsize=10) + for bar in bars: + height = bar.get_height() + if height > 0: + ax.text( + bar.get_x() + bar.get_width() / 2.0, + height, + f"{int(height):,}", + ha="center", + va="bottom", + fontsize=8, + ) + for spine in ax.spines.values(): + spine.set_visible(False) + + fname = self.save_dir / "labels.jpg" + plt.savefig(fname, dpi=200) + plt.close() + if self.on_plot: + self.on_plot(fname) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/val.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/val.py new file mode 100644 index 0000000000000000000000000000000000000000..b9c89175f8dfeeece0bcffaff345206c8e9ef4b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/semantic/val.py @@ -0,0 +1,197 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import torch.distributed as dist +import torch.nn.functional as F +from PIL import Image + +from ultralytics.data.dataset import SemanticDataset +from ultralytics.models.yolo.detect import DetectionValidator +from ultralytics.utils import LOGGER, RANK +from ultralytics.utils.metrics import ConfusionMatrix, SemanticMetrics +from ultralytics.utils.plotting import plot_images + + +class SemanticSegmentationValidator(DetectionValidator): + """Validator for semantic segmentation models. + + This validator evaluates semantic segmentation models using mIoU and pixel accuracy metrics. + + Attributes: + metrics (SemanticMetrics): Metrics calculator for semantic segmentation. + + Examples: + >>> from ultralytics.models.yolo.semantic import SemanticSegmentationValidator + >>> args = dict(model="yolo26n-sem.pt", data="cityscapes8.yaml") + >>> validator = SemanticSegmentationValidator(args=args) + >>> validator() + """ + + def __init__(self, dataloader=None, save_dir=None, args=None, _callbacks=None): + """Initialize SemanticSegmentationValidator. + + Args: + dataloader (DataLoader, optional): DataLoader for validation. + save_dir (Path, optional): Directory to save results. + args (dict, optional): Arguments for the validator. + _callbacks (dict, optional): Callback functions. + """ + super().__init__(dataloader, save_dir, args, _callbacks) + self.args.task = "semantic" + self.dataset = None + self.results_dir = None + self.metrics = SemanticMetrics() + self.image_shapes = {} + self._semantic_target_shape = None + + def init_metrics(self, model): + """Initialize metrics with model class names. + + Args: + model (nn.Module): Model to validate. + """ + self.names = model.names + self.nc = len(self.names) + self.metrics = SemanticMetrics(names=self.names) + self.seen = 0 + self.dataset = getattr(self.dataloader, "dataset", None) + labels = getattr(self.dataset, "labels", []) if self.dataset is not None else [] + self.image_shapes = {lb["im_file"]: tuple(lb["shape"]) for lb in labels if "im_file" in lb and "shape" in lb} + self.results_dir = None + if self.args.save_json: + self.results_dir = self.save_dir / "results" + self.results_dir.mkdir(parents=True, exist_ok=True) + cm_nc = self.metrics.cm_nc + if cm_nc == 2 and len(self.names) == 1: # binary segmentation, expand to include background + cm_names = {0: "background", 1: next(iter(self.names.values()))} + else: + base = list(self.names.values()) + [str(i) for i in range(len(self.names), cm_nc)] + cm_names = {i: base[i] for i in range(cm_nc)} + self.confusion_matrix = ConfusionMatrix(names=cm_names, task="semantic") + + def preprocess(self, batch): + """Preprocess a batch of images and masks. + + Args: + batch (dict): Batch data containing images and masks. + + Returns: + (dict): Preprocessed batch. + """ + batch = super().preprocess(batch) + batch["semantic_mask"] = batch["semantic_mask"].to(self.device, dtype=torch.int32) + self._semantic_target_shape = tuple(batch["semantic_mask"].shape[-2:]) + return batch + + def postprocess(self, preds): + """Convert logits or baked class maps to class predictions. + + Args: + preds (torch.Tensor): Raw model output logits [B, nc, H, W] or baked class map [B, H, W]. + + Returns: + (torch.Tensor): Predicted class IDs [B, H, W]. + """ + if isinstance(preds, (tuple, list)): + preds = preds[0] + if preds.ndim == 3: + # [B, H, W] class map with argmax already baked into the graph. Nearest-resize only. + if tuple(preds.shape[-2:]) != self._semantic_target_shape: + preds = F.interpolate(preds[:, None].float(), size=self._semantic_target_shape, mode="nearest")[:, 0] + return preds.to(torch.int32) + pred_hw = preds.shape[2:] + if pred_hw[0] != self._semantic_target_shape[0] or pred_hw[1] != self._semantic_target_shape[1]: + preds = F.interpolate(preds, size=self._semantic_target_shape, mode="bilinear", align_corners=False) + if self.nc > 1: # CPU argmax over a non-innermost dim runs as a per-output loop; max(dim) streams + return (preds.max(dim=1).indices if preds.device.type == "cpu" else preds.argmax(dim=1)).to(torch.int32) + return preds.gt(0).squeeze(1).to(torch.int32) + + def update_metrics(self, preds, batch): + """Update metrics with predictions and ground truth. + + Args: + preds (torch.Tensor): Predicted class IDs [B, H, W]. + batch (dict): Batch containing 'semantic_mask'. + """ + if self.args.save_json: + self.save_pred_masks(preds, batch) + self.metrics.update_stats(preds, batch["semantic_mask"]) + self.seen += preds.shape[0] + + def gather_stats(self): + """Reduce semantic confusion matrix to rank 0 during DDP validation.""" + if RANK == -1 or not dist.is_available() or not dist.is_initialized(): + return + if self.metrics.matrix is None: + cm_nc = self.metrics.cm_nc + self.metrics.matrix = torch.zeros((cm_nc, cm_nc), device=self.device, dtype=torch.float32) + dist.reduce(self.metrics.matrix, dst=0, op=dist.ReduceOp.SUM) + # Gather nt_per_image across ranks + if RANK == 0: + gathered_nt = [None] * dist.get_world_size() + dist.gather_object(self.metrics.nt_per_image, gathered_nt, dst=0) + self.metrics.nt_per_image = np.sum(gathered_nt, axis=0) + elif RANK > 0: + dist.gather_object(self.metrics.nt_per_image, None, dst=0) + + def save_pred_masks(self, preds: torch.Tensor, batch: dict[str, Any]) -> None: + """Save semantic predictions as single-channel PNG masks.""" + if self.results_dir is None: + return + im_files = batch.get("im_file", []) + if not im_files: + return + preds = preds.cpu().numpy() + if isinstance(self.dataset, SemanticDataset) and self.dataset.label_mapping: + preds = self.dataset.convert_label(preds, inverse=True) + preds = preds.astype(np.uint8, copy=False) + for pred, im_file in zip(preds, im_files): + orig_shape = self.image_shapes.get(im_file) + if orig_shape and pred.shape != orig_shape: + pred = cv2.resize(pred, (orig_shape[1], orig_shape[0]), interpolation=cv2.INTER_NEAREST) + save_path = self.results_dir / Path(im_file).with_suffix(".png").name + Image.fromarray(pred).save(save_path) + + def get_stats(self): + """Return validation statistics. + + Returns: + (dict): Dictionary of validation metrics. + """ + self.metrics.process(save_dir=self.save_dir, plot=self.args.plots, on_plot=self.on_plot) + if self.metrics.matrix is not None: + # Internal layout is [gt, pred]; transpose to [pred, gt] for ConfusionMatrix export format. + self.confusion_matrix.matrix = self.metrics.matrix.detach().cpu().numpy().T.astype(float) + return self.metrics.results_dict + + def get_desc(self): + """Return a formatted description of evaluation metrics. + + Returns: + (str): Formatted string with metric names. + """ + return ("%22s" + "%11s" * 4) % ("Class", "Images", "Pixels", "mIoU", "PixAcc") + + def print_results(self) -> None: + """Print training/validation set metrics per class.""" + super().print_results() + if self.args.save_json and self.results_dir is not None: + LOGGER.info(f"Semantic prediction masks saved to {self.results_dir}") + + def plot_predictions(self, batch, preds, ni): + """Plot predicted semantic masks on input images.""" + plot_images( + images=batch["img"], + labels={"semantic_mask": preds}, + paths=batch["im_file"], + fname=self.save_dir / f"val_batch{ni}_pred.jpg", + names=self.names, + on_plot=self.on_plot, + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6dc22144d6926a9ee3b9fbb4f52ed7261847bf74 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__init__.py @@ -0,0 +1,6 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .train import WorldTrainer +from .val import WorldValidator + +__all__ = ["WorldTrainer", "WorldValidator"] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82b791f1c44d557622183fb5af8c320aa386dd75 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__pycache__/train.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__pycache__/train.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1945b0c2c40c695f2618af72f3502bee57bf5bdb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__pycache__/train.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__pycache__/train_world.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__pycache__/train_world.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..853cd17293cf11b09ca6067062c68863933887e9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__pycache__/train_world.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__pycache__/val.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__pycache__/val.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f76fe3f0026523426d300784ba158bb5194d7bb5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/__pycache__/val.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/train.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/train.py new file mode 100644 index 0000000000000000000000000000000000000000..920ce36dfb27ae5f0e10ca5c6625e40e9ea92924 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/train.py @@ -0,0 +1,174 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import itertools +from pathlib import Path +from typing import Any + +import torch + +from ultralytics.data import build_yolo_dataset +from ultralytics.models.yolo.detect import DetectionTrainer +from ultralytics.nn.tasks import WorldModel +from ultralytics.utils import DEFAULT_CFG, LOGGER, RANK +from ultralytics.utils.torch_utils import unwrap_model + + +def on_pretrain_routine_end(trainer) -> None: + """Set up model classes and text encoder at the end of the pretrain routine.""" + # Set on all ranks: validation runs on every rank, but txt_feats/nc are not DDP buffers so they don't sync + names = [name.split("/", 1)[0] for name in list(trainer.test_loader.dataset.data["names"].values())] + trainer.ema.ema.set_classes(names, cache_clip_model=False) + + +class WorldTrainer(DetectionTrainer): + """A trainer class for fine-tuning YOLO World models on close-set datasets. + + This trainer extends the DetectionTrainer to support training YOLO World models, which combine visual and textual + features for improved object detection and understanding. It handles text embedding generation and caching to + accelerate training with multi-modal data. + + Attributes: + text_embeddings (dict[str, torch.Tensor] | None): Cached text embeddings for category names to accelerate + training. + model (WorldModel): The YOLO World model being trained. + data (dict[str, Any]): Dataset configuration containing class information. + args (Any): Training arguments and configuration. + + Methods: + get_model: Return WorldModel initialized with specified config and weights. + build_dataset: Build YOLO Dataset for training or validation. + set_text_embeddings: Set text embeddings for datasets to accelerate training. + generate_text_embeddings: Generate text embeddings for a list of text samples. + preprocess_batch: Preprocess a batch of images and text for YOLOWorld training. + + Examples: + Initialize and train a YOLO World model + >>> from ultralytics.models.yolo.world import WorldTrainer + >>> args = dict(model="yolov8s-world.pt", data="coco8.yaml", epochs=3) + >>> trainer = WorldTrainer(overrides=args) + >>> trainer.train() + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides: dict[str, Any] | None = None, _callbacks: dict | None = None): + """Initialize a WorldTrainer object with given arguments. + + Args: + cfg (dict[str, Any]): Configuration for the trainer. + overrides (dict[str, Any], optional): Configuration overrides. + _callbacks (dict, optional): Dictionary of callback functions. + """ + if overrides is None: + overrides = {} + assert not overrides.get("compile"), f"Training with 'model={overrides['model']}' requires 'compile=False'" + super().__init__(cfg, overrides, _callbacks) + self.text_embeddings = None + + def get_model(self, cfg=None, weights: str | None = None, verbose: bool = True) -> WorldModel: + """Return WorldModel initialized with specified config and weights. + + Args: + cfg (dict[str, Any] | str, optional): Model configuration. + weights (str, optional): Path to pretrained weights. + verbose (bool): Whether to display model info. + + Returns: + (WorldModel): Initialized WorldModel. + """ + # NOTE: This `nc` here is the max number of different text samples in one image, rather than the actual `nc`. + # NOTE: Following the official config, nc hard-coded to 80 for now. + model = WorldModel( + cfg["yaml_file"] if isinstance(cfg, dict) else cfg, + ch=self.data["channels"], + nc=min(self.data["nc"], 80), + verbose=verbose and RANK == -1, + ) + if weights: + model.load(weights) + # the caller's Model shares this dict, so a bare append outlives the trainer and stacks on every later one + if on_pretrain_routine_end not in self.callbacks["on_pretrain_routine_end"]: + self.add_callback("on_pretrain_routine_end", on_pretrain_routine_end) + + return model + + def build_dataset(self, img_path: str, mode: str = "train", batch: int | None = None): + """Build YOLO Dataset for training or validation. + + Args: + img_path (str): Path to the folder containing images. + mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode. + batch (int, optional): Size of batches, this is for `rect`. + + Returns: + (Any): YOLO dataset configured for training or validation. + """ + gs = max(int(unwrap_model(self.model).stride.max() if self.model else 0), 32) + dataset = build_yolo_dataset( + self.args, img_path, batch, self.data, mode=mode, rect=mode == "val", stride=gs, multi_modal=mode == "train" + ) + if mode == "train": + self.set_text_embeddings([dataset], batch) # cache text embeddings to accelerate training + return dataset + + def set_text_embeddings(self, datasets: list[Any], batch: int | None) -> None: + """Set text embeddings for datasets to accelerate training by caching category names. + + This method collects unique category names from all datasets, then generates and caches text embeddings for + these categories to improve training efficiency. + + Args: + datasets (list[Any]): List of datasets from which to extract category names. + batch (int | None): Batch size used for processing. + + Notes: + This method collects category names from datasets that have the 'category_names' attribute, + then uses the first dataset's image path to determine where to cache the generated text embeddings. + """ + text_embeddings = {} + for dataset in datasets: + if not hasattr(dataset, "category_names"): + continue + text_embeddings.update( + self.generate_text_embeddings( + list(dataset.category_names), batch, cache_dir=Path(dataset.img_path).parent + ) + ) + self.text_embeddings = text_embeddings + + def generate_text_embeddings(self, texts: list[str], batch: int, cache_dir: Path) -> dict[str, torch.Tensor]: + """Generate text embeddings for a list of text samples. + + Args: + texts (list[str]): List of text samples to encode. + batch (int): Batch size for processing. + cache_dir (Path): Directory to save/load cached embeddings. + + Returns: + (dict[str, torch.Tensor]): Dictionary mapping text samples to their embeddings. + """ + model = "clip:ViT-B/32" + cache_path = cache_dir / f"text_embeddings_{model.replace(':', '_').replace('/', '_')}.pt" + if cache_path.exists(): + LOGGER.info(f"Reading existed cache from '{cache_path}'") + txt_map = torch.load(cache_path, map_location=self.device) + if sorted(txt_map.keys()) == sorted(texts): + return txt_map + LOGGER.info(f"Caching text embeddings to '{cache_path}'") + assert self.model is not None + txt_feats = unwrap_model(self.model).get_text_pe(texts, batch, cache_clip_model=False) + txt_map = dict(zip(texts, txt_feats.squeeze(0))) + torch.save(txt_map, cache_path) + return txt_map + + def preprocess_batch(self, batch: dict[str, Any]) -> dict[str, Any]: + """Preprocess a batch of images and text for YOLOWorld training.""" + batch = DetectionTrainer.preprocess_batch(self, batch) + + # Add text features + texts = list(itertools.chain(*batch["texts"])) + txt_feats = torch.stack([self.text_embeddings[text] for text in texts]).to( + self.device, non_blocking=self.device.type not in {"cpu", "mps"} + ) + batch["txt_feats"] = txt_feats.reshape(len(batch["texts"]), -1, txt_feats.shape[-1]) + return batch diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/train_world.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/train_world.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3124935f0674551343ce1472e5176df4507aea --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/train_world.py @@ -0,0 +1,196 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +from ultralytics.data import YOLOConcatDataset, build_grounding, build_yolo_dataset +from ultralytics.data.utils import check_det_dataset +from ultralytics.models.yolo.world import WorldTrainer +from ultralytics.utils import DATASETS_DIR, DEFAULT_CFG, LOGGER +from ultralytics.utils.checks import check_file +from ultralytics.utils.torch_utils import unwrap_model + + +class WorldTrainerFromScratch(WorldTrainer): + """A class extending the WorldTrainer for training a world model from scratch on open-set datasets. + + This trainer specializes in handling mixed datasets including both object detection and grounding datasets, + supporting training YOLO-World models with combined vision-language capabilities. + + Attributes: + cfg (dict): Configuration dictionary with default parameters for model training. + overrides (dict): Dictionary of parameter overrides to customize the configuration. + _callbacks (dict): Dictionary of callback functions to be executed during different stages of training. + data (dict): Final processed data configuration containing train/val paths and metadata. + training_data (dict): Dictionary mapping training dataset paths to their configurations. + + Methods: + build_dataset: Build YOLO Dataset for training or validation with mixed dataset support. + get_dataset: Get train and validation paths from data dictionary. + plot_training_labels: Skip label plotting for YOLO-World training. + final_eval: Perform final evaluation and validation for the YOLO-World model. + + Examples: + >>> from ultralytics.models.yolo.world.train_world import WorldTrainerFromScratch + >>> from ultralytics import YOLOWorld + >>> data = dict( + ... train=dict( + ... yolo_data=["Objects365.yaml"], + ... grounding_data=[ + ... dict( + ... img_path="flickr30k/images", + ... json_file="flickr30k/final_flickr_separateGT_train.json", + ... ), + ... dict( + ... img_path="GQA/images", + ... json_file="GQA/final_mixed_train_no_coco.json", + ... ), + ... ], + ... ), + ... val=dict(yolo_data=["lvis.yaml"]), + ... ) + >>> model = YOLOWorld("yolov8s-worldv2.yaml") + >>> model.train(data=data, trainer=WorldTrainerFromScratch) + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks: dict | None = None): + """Initialize a WorldTrainerFromScratch object. + + This initializes a trainer for YOLO-World models from scratch, supporting mixed datasets including both object + detection and grounding datasets for vision-language capabilities. + + Args: + cfg (dict): Configuration dictionary with default parameters for model training. + overrides (dict, optional): Dictionary of parameter overrides to customize the configuration. + _callbacks (dict, optional): Dictionary of callback functions to run during different stages of training. + """ + if overrides is None: + overrides = {} + super().__init__(cfg, overrides, _callbacks) + + def build_dataset(self, img_path, mode="train", batch=None): + """Build YOLO Dataset for training or validation. + + This method constructs appropriate datasets based on the mode and input paths, handling both standard YOLO + datasets and grounding datasets with different formats. + + Args: + img_path (list[str] | str): Path to the folder containing images or list of paths. + mode (str): 'train' mode or 'val' mode, allowing customized augmentations for each mode. + batch (int, optional): Size of batches, used for rectangular training/validation. + + Returns: + (YOLOConcatDataset | Dataset): The constructed dataset for training or validation. + """ + gs = max(int(unwrap_model(self.model).stride.max() if self.model else 0), 32) + if mode != "train": + return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, rect=False, stride=gs) + datasets = [ + build_yolo_dataset(self.args, im_path, batch, self.training_data[im_path], stride=gs, multi_modal=True) + if isinstance(im_path, str) + else build_grounding( + # assign `nc` from validation set to max number of text samples for training consistency + self.args, + im_path["img_path"], + im_path["json_file"], + batch, + stride=gs, + max_samples=self.data["nc"], + ) + for im_path in img_path + ] + self.set_text_embeddings(datasets, batch) # cache text embeddings to accelerate training + return YOLOConcatDataset(datasets) if len(datasets) > 1 else datasets[0] + + @staticmethod + def check_data_config(data: dict | str | Path) -> dict: + """Check and load the data configuration from a YAML file or dictionary. + + Args: + data (dict | str | Path): Data configuration as a dictionary or path to a YAML file. + + Returns: + (dict): Data configuration dictionary loaded from YAML file or passed directly. + """ + # If string, load from YAML file + if not isinstance(data, dict): + from ultralytics.utils import YAML + + return YAML.load(check_file(data)) + return data + + def get_dataset(self): + """Get train and validation paths from data dictionary. + + Processes the data configuration to extract paths for training and validation datasets, handling both YOLO + detection datasets and grounding datasets. + + Returns: + (dict): Final processed data configuration containing train/val paths and metadata. + + Raises: + AssertionError: If train or validation datasets are not found, or if validation has multiple datasets. + """ + final_data = {} + self.args.data = data_yaml = self.check_data_config(self.args.data) + assert data_yaml.get("train", False), "train dataset not found" # object365.yaml + assert data_yaml.get("val", False), "validation dataset not found" # lvis.yaml + data = {k: [check_det_dataset(d) for d in v.get("yolo_data", [])] for k, v in data_yaml.items()} + assert len(data["val"]) == 1, f"Only support validating on 1 dataset for now, but got {len(data['val'])}." + val_split = "minival" if "lvis" in data["val"][0]["val"] else "val" + for d in data["val"]: + if d.get("minival") is None: # for lvis dataset + continue + d["minival"] = str(d["path"] / d["minival"]) + for s in ("train", "val"): + final_data[s] = [d["train" if s == "train" else val_split] for d in data[s]] + # save grounding data if there's one + grounding_data = data_yaml[s].get("grounding_data") + if grounding_data is None: + continue + grounding_data = grounding_data if isinstance(grounding_data, list) else [grounding_data] + for g in grounding_data: + assert isinstance(g, dict), f"Grounding data should be provided in dict format, but got {type(g)}" + for k in ("img_path", "json_file"): + path = Path(g[k]) + if not path.exists() and not path.is_absolute(): + g[k] = str((DATASETS_DIR / g[k]).resolve()) # path relative to DATASETS_DIR + final_data[s] += grounding_data + # assign the first val dataset as currently only one validation set is supported + data["val"] = data["val"][0] + final_data["val"] = final_data["val"][0] + # NOTE: to make training work properly, set `nc` and `names` + final_data["nc"] = data["val"]["nc"] + final_data["names"] = data["val"]["names"] + # NOTE: add path with lvis path + final_data["path"] = data["val"]["path"] + final_data["channels"] = data["val"]["channels"] + self.data = final_data + if self.args.single_cls: # consistent with base trainer + LOGGER.info("Overriding class names with single class.") + self.data["names"] = {0: "object"} + self.data["nc"] = 1 + self.training_data = {} + for d in data["train"]: + if self.args.single_cls: + d["names"] = {0: "object"} + d["nc"] = 1 + self.training_data[d["train"]] = d + return final_data + + def plot_training_labels(self): + """Skip label plotting for YOLO-World training.""" + + def final_eval(self): + """Perform final evaluation and validation for the YOLO-World model. + + Configures the validator with appropriate dataset and split information before running evaluation. + + Returns: + (dict): Dictionary containing evaluation metrics and results. + """ + val = self.args.data["val"]["yolo_data"][0] + self.validator.args.data = val + self.validator.args.split = "minival" if isinstance(val, str) and "lvis" in val else "val" + return super().final_eval() diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/val.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/val.py new file mode 100644 index 0000000000000000000000000000000000000000..d910b6e542b6a040851da0e51a2e4ab5c6cfe503 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/world/val.py @@ -0,0 +1,40 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import torch + +from ultralytics.data.utils import check_det_dataset, convert_ndjson_to_yolo_if_needed +from ultralytics.models.yolo.detect import DetectionValidator +from ultralytics.utils.torch_utils import select_device + + +class WorldValidator(DetectionValidator): + """A validator for YOLO-World models that sets dataset class names before validation. + + Open-vocabulary YOLO-World models default to 80 COCO classes, so validating on a dataset with different classes + (e.g. LVIS) fails or yields zero metrics. This validator generates text embeddings for the dataset's class names so + standalone `model.val()` works. During training, classes are set via the `on_pretrain_routine_end` callback instead. + """ + + def __call__(self, trainer=None, model=None): + """Set dataset classes for standalone validation, then run validation.""" + if trainer is None: # standalone val; training sets classes via on_pretrain_routine_end callback + self.device = select_device(self.args.device, verbose=False) + if not isinstance(model, torch.nn.Module): + from ultralytics.nn.tasks import load_checkpoint + + model = load_checkpoint(model or self.args.model, device=self.device)[0] + model.eval().to(self.device) + self.args.data = convert_ndjson_to_yolo_if_needed(self.args.data, self.args.fraction) + names = [name.split("/", 1)[0] for name in check_det_dataset(self.args.data)["names"].values()] + current = model.names.values() if isinstance(model.names, dict) else model.names # names may be a list + if list(current) != names: # regenerate prompts only if class order differs from dataset + state = (model.names, model.txt_feats, model.model[-1].nc) # restore after to avoid leak to caller + model.set_classes(names, cache_clip_model=False) + model.names = dict(enumerate(names)) # set_classes updates embeddings/nc but not names + try: + return super().__call__(trainer, model) + finally: + model.names, model.txt_feats, model.model[-1].nc = state + return super().__call__(trainer, model) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cc2b12c003387cb9c8b32a23f1010526b69c67c8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__init__.py @@ -0,0 +1,22 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .predict import YOLOEVPDetectPredictor, YOLOEVPSegPredictor +from .train import YOLOEPEFreeTrainer, YOLOEPETrainer, YOLOETrainer, YOLOETrainerFromScratch, YOLOEVPTrainer +from .train_seg import YOLOEPESegTrainer, YOLOESegTrainer, YOLOESegTrainerFromScratch, YOLOESegVPTrainer +from .val import YOLOEDetectValidator, YOLOESegValidator + +__all__ = [ + "YOLOEDetectValidator", + "YOLOEPEFreeTrainer", + "YOLOEPESegTrainer", + "YOLOEPETrainer", + "YOLOESegTrainer", + "YOLOESegTrainerFromScratch", + "YOLOESegVPTrainer", + "YOLOESegValidator", + "YOLOETrainer", + "YOLOETrainerFromScratch", + "YOLOEVPDetectPredictor", + "YOLOEVPSegPredictor", + "YOLOEVPTrainer", +] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b840e62681d1fb675c017412b3bf49654d69f85 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/predict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/predict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e08fad697c03cecfcb5e214d5f8f42260d4c00b2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/predict.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/train.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/train.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bc67bfc37b28b3b071f0a2692e269733d45c17e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/train.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/train_seg.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/train_seg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..373ed56c90c772fed0589102b3fd15e9a931daf0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/train_seg.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/val.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/val.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ce6e4fa3987c057b1841736556af81b7cb3e285 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/__pycache__/val.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/predict.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..bf2be3d279ad9c7a6ba5a57e99f6cf5ddad207fe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/predict.py @@ -0,0 +1,120 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import numpy as np +import torch + +from ultralytics.data.augment import LoadVisualPrompt +from ultralytics.models.yolo.detect import DetectionPredictor +from ultralytics.models.yolo.segment import SegmentationPredictor + + +class YOLOEVPDetectPredictor(DetectionPredictor): + """A class extending DetectionPredictor for YOLO-EVP (Enhanced Visual Prompting) predictions. + + This class provides common functionality for YOLO models that use visual prompting, including model setup, prompt + handling, and preprocessing transformations. + + Attributes: + model (torch.nn.Module): The YOLO model for inference. + device (torch.device): Device to run the model on (CPU or CUDA). + prompts (dict): Visual prompts containing class indices and bounding boxes or masks. + visuals (torch.Tensor): The prompts rasterized against the shapes of the batch being preprocessed. + + Methods: + setup_model: Initialize the YOLO model and set it to evaluation mode. + set_prompts: Set the visual prompts for the model. + is_per_image: Report whether the prompts hold one array per image. + preprocess: Preprocess a batch of images and rasterize its visual prompts. + inference: Run inference with visual prompts. + get_vpe: Process source to get visual prompt embeddings. + """ + + def setup_model(self, model, verbose: bool = True): + """Set up the model for prediction. + + Args: + model (torch.nn.Module): Model to load or use. + verbose (bool, optional): If True, provides detailed logging. + """ + super().setup_model(model, verbose=verbose) + self.done_warmup = True + + def set_prompts(self, prompts): + """Set the visual prompts for the model. + + Args: + prompts (dict): Dictionary containing class indices and bounding boxes or masks. Must include a 'cls' key + with class indices. + """ + self.prompts = prompts + + @staticmethod + def is_per_image(prompts: dict) -> bool: + """Return True if 'bboxes' and 'cls' hold one array per image rather than one set applied to every image.""" + return all( + isinstance(prompts.get(k), list) and all(isinstance(x, np.ndarray) for x in prompts[k]) + for k in ("bboxes", "cls") + ) + + def preprocess(self, im): + """Preprocess a batch and rasterize its visual prompts.""" + imgs = super().preprocess(im) + dst_shape = tuple(imgs.shape[2:]) # one letterboxed shape per batch, since preprocess stacks the images + # tensor sources skip letterboxing, so their src and dst shapes are identical + src_shapes = [dst_shape] * len(im) if isinstance(im, torch.Tensor) else [x.shape[:2] for x in im] + self.visuals = self._prompts_to_tensor(dst_shape, src_shapes) + return imgs + + def _prompts_to_tensor(self, dst_shape, src_shapes): + """Rasterize prompts into a batched tensor on the model device.""" + bboxes, category = self.prompts.get("bboxes", None), self.prompts["cls"] + if not self.is_per_image(self.prompts): # one flat set, rasterized against every image in the batch + masks = self.prompts.get("masks", None) + visuals = [self._process_single_image(dst_shape, src, category, bboxes, masks) for src in src_shapes] + else: + assert len(src_shapes) == len(category) == len(bboxes), ( + f"Expected same length for all inputs, but got {len(src_shapes)}vs{len(category)}vs{len(bboxes)}!" + ) + visuals = [ + self._process_single_image(dst_shape, src, category[i], bboxes[i]) for i, src in enumerate(src_shapes) + ] + prompts = torch.nn.utils.rnn.pad_sequence(visuals, batch_first=True).to(self.device) # (B, N, H, W) + return prompts.half() if self.model.fp16 else prompts.float() + + def _process_single_image(self, dst_shape, src_shape, category, bboxes=None, masks=None): + """Resize one image's prompts and generate its visuals.""" + if bboxes is not None and len(bboxes): + bboxes = np.array(bboxes, dtype=np.float32) + if bboxes.ndim == 1: + bboxes = bboxes[None, :] + # Calculate scaling factor and adjust bounding boxes + gain = min(dst_shape[0] / src_shape[0], dst_shape[1] / src_shape[1]) # gain = old / new + bboxes *= gain + bboxes[..., 0::2] += round((dst_shape[1] - round(src_shape[1] * gain)) / 2 - 0.1) + bboxes[..., 1::2] += round((dst_shape[0] - round(src_shape[0] * gain)) / 2 - 0.1) + elif masks is not None: + # Resize and process masks + resized_masks = super().pre_transform(masks) + masks = np.stack(resized_masks) # (N, H, W) + masks[masks == 114] = 0 # Reset padding values to 0 + else: + raise ValueError("Please provide valid bboxes or masks") + + # Generate visuals using the visual prompt loader + return LoadVisualPrompt().get_visuals(category, dst_shape, bboxes, masks) + + def inference(self, im, *args, **kwargs): + """Run inference with visual prompts.""" + return super().inference(im, *args, vpe=self.visuals, **kwargs) + + def get_vpe(self, source): + """Extract visual prompt embeddings from one source image.""" + self.setup_source(source) + assert len(self.dataset) == 1, "get_vpe only supports one image!" + for _, im0s, _ in self.dataset: + im = self.preprocess(im0s) + return self.model(im, vpe=self.visuals, return_vpe=True) + + +class YOLOEVPSegPredictor(YOLOEVPDetectPredictor, SegmentationPredictor): + """Predictor for YOLO-EVP segmentation tasks combining detection and segmentation capabilities.""" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/train.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/train.py new file mode 100644 index 0000000000000000000000000000000000000000..ff4e140779f296eb9a52e780c7a2d9551e988d57 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/train.py @@ -0,0 +1,277 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from copy import copy, deepcopy +from pathlib import Path + +import torch + +from ultralytics.data import YOLOConcatDataset, build_yolo_dataset +from ultralytics.data.augment import LoadVisualPrompt +from ultralytics.models.yolo.detect import DetectionTrainer, DetectionValidator +from ultralytics.models.yolo.segment import SegmentationValidator +from ultralytics.nn.tasks import YOLOEModel, YOLOESegModel +from ultralytics.utils import DEFAULT_CFG, LOGGER, RANK +from ultralytics.utils.torch_utils import unwrap_model + +from ..world.train_world import WorldTrainerFromScratch +from .val import YOLOEDetectValidator, YOLOESegValidator + + +class YOLOETrainer(DetectionTrainer): + """A trainer class for YOLOE object detection models. + + This class extends DetectionTrainer to provide specialized training functionality for YOLOE models, including custom + model initialization, validation, and dataset building with multi-modal support. + + Attributes: + loss_names (tuple): Names of loss components, derived from the loss dict returned by the criterion. + + Methods: + get_model: Initialize and return a task-appropriate YOLOE model. + get_validator: Return a task-appropriate YOLOE validator. + build_dataset: Build YOLO dataset with multi-modal support for training. + """ + + def __init__(self, cfg=DEFAULT_CFG, overrides: dict | None = None, _callbacks: dict | None = None): + """Initialize the YOLOE Trainer with specified configurations. + + Args: + cfg (dict): Configuration dictionary with default training settings from DEFAULT_CFG. + overrides (dict, optional): Dictionary of parameter overrides for the default configuration. + _callbacks (dict, optional): Dictionary of callback functions to be applied during training. + """ + if overrides is None: + overrides = {} + assert not overrides.get("compile"), f"Training with 'model={overrides['model']}' requires 'compile=False'" + overrides["overlap_mask"] = False + super().__init__(cfg, overrides, _callbacks) + + def get_model(self, cfg=None, weights=None, verbose: bool = True): + """Return a task-appropriate YOLOE model initialized with the specified configuration and weights. + + Args: + cfg (dict | str, optional): Model configuration. Can be a dictionary containing a 'yaml_file' key, a direct + path to a YAML file, or None to use default configuration. + weights (str | Path, optional): Path to pretrained weights file to load into the model. + verbose (bool): Whether to display model information during initialization. + + Returns: + (YOLOEModel | YOLOESegModel): The initialized YOLOE model. + + Notes: + - The number of classes (nc) is hard-coded to a maximum of 80 following the official configuration. + - The nc parameter here represents the maximum number of different text samples in one image, + rather than the actual number of classes. + """ + # NOTE: This `nc` here is the max number of different text samples in one image, rather than the actual `nc`. + # NOTE: Following the official config, nc hard-coded to 80 for now. + model = (YOLOESegModel if self.args.task == "segment" else YOLOEModel)( + cfg["yaml_file"] if isinstance(cfg, dict) else cfg, + ch=self.data["channels"], + nc=min(self.data["nc"], 80), + verbose=verbose and RANK == -1, + ) + if weights: + model.load(weights) + + return model + + def get_validator(self): + """Return a task-appropriate YOLOE validator.""" + validator = YOLOESegValidator if self.args.task == "segment" else YOLOEDetectValidator + return validator(self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks) + + def build_dataset(self, img_path: str, mode: str = "train", batch: int | None = None): + """Build YOLO Dataset. + + Args: + img_path (str): Path to the folder containing images. + mode (str): 'train' mode or 'val' mode, users are able to customize different augmentations for each mode. + batch (int, optional): Size of batches, this is for rectangular training. + + Returns: + (Dataset): YOLO dataset configured for training or validation. + """ + gs = max(int(unwrap_model(self.model).stride.max() if self.model else 0), 32) + return build_yolo_dataset( + self.args, img_path, batch, self.data, mode=mode, rect=mode == "val", stride=gs, multi_modal=mode == "train" + ) + + +class YOLOEPETrainer(DetectionTrainer): + """Fine-tune YOLOE model using linear probing approach. + + This trainer freezes most model layers and only trains specific projection layers for efficient fine-tuning on new + datasets while preserving pretrained features. + + Methods: + get_model: Initialize a YOLOE model with frozen layers except projection layers. + get_validator: Return a task-appropriate validator. + """ + + def get_model(self, cfg=None, weights=None, verbose: bool = True): + """Return a task-appropriate YOLOE model initialized with specified config and weights. + + Args: + cfg (dict | str, optional): Model configuration. + weights (str, optional): Path to pretrained weights. + verbose (bool): Whether to display model information. + + Returns: + (YOLOEModel | YOLOESegModel): Initialized model with frozen layers except for specific projection layers. + """ + model = (YOLOESegModel if self.args.task == "segment" else YOLOEModel)( + cfg["yaml_file"] if isinstance(cfg, dict) else cfg, + ch=self.data["channels"], + nc=self.data["nc"], + verbose=verbose and RANK == -1, + ) + + del model.model[-1].savpe + + assert weights is not None, "Pretrained weights must be provided for linear probing." + if weights: + model.load(weights) + + model.eval() + names = list(self.data["names"].values()) + # NOTE: `get_text_pe` related to text model and YOLOEDetect.reprta, + # it'd get correct results as long as loading proper pretrained weights. + tpe = model.get_text_pe(names) + model.set_classes(names, tpe) + model.model[-1].fuse(model.pe) # fuse text embeddings to classify head + model.model[-1].cv3[0][2] = deepcopy(model.model[-1].cv3[0][2]).requires_grad_(True) + model.model[-1].cv3[1][2] = deepcopy(model.model[-1].cv3[1][2]).requires_grad_(True) + model.model[-1].cv3[2][2] = deepcopy(model.model[-1].cv3[2][2]).requires_grad_(True) + + if getattr(model.model[-1], "one2one_cv3", None) is not None: + model.model[-1].one2one_cv3[0][2] = deepcopy(model.model[-1].one2one_cv3[0][2]).requires_grad_(True) + model.model[-1].one2one_cv3[1][2] = deepcopy(model.model[-1].one2one_cv3[1][2]).requires_grad_(True) + model.model[-1].one2one_cv3[2][2] = deepcopy(model.model[-1].one2one_cv3[2][2]).requires_grad_(True) + + model.train() + + return model + + def get_validator(self): + """Return a task-appropriate validator without the text prompts the YOLOE validators require.""" + validator = SegmentationValidator if self.args.task == "segment" else DetectionValidator + return validator(self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks) + + +class YOLOETrainerFromScratch(YOLOETrainer, WorldTrainerFromScratch): + """Train YOLOE models from scratch with text embedding support. + + This trainer combines YOLOE training capabilities with world training features, enabling training from scratch with + text embeddings and grounding datasets. + + Methods: + build_dataset: Build datasets for training with grounding support. + generate_text_embeddings: Generate and cache text embeddings for training. + """ + + def build_dataset(self, img_path: list[str] | str, mode: str = "train", batch: int | None = None): + """Build YOLO Dataset for training or validation. + + This method constructs appropriate datasets based on the mode and input paths, handling both standard YOLO + datasets and grounding datasets with different formats. + + Args: + img_path (list[str] | str): Path to the folder containing images or list of paths. + mode (str): 'train' mode or 'val' mode, allowing customized augmentations for each mode. + batch (int, optional): Size of batches, used for rectangular training/validation. + + Returns: + (YOLOConcatDataset | Dataset): The constructed dataset for training or validation. + """ + return WorldTrainerFromScratch.build_dataset(self, img_path, mode, batch) + + def generate_text_embeddings(self, texts: list[str], batch: int, cache_dir: Path): + """Generate text embeddings for a list of text samples. + + Args: + texts (list[str]): List of text samples to encode. + batch (int): Batch size for processing. + cache_dir (Path): Directory to save/load cached embeddings. + + Returns: + (dict): Dictionary mapping text samples to their embeddings. + """ + model = unwrap_model(self.model).text_model + cache_path = cache_dir / f"text_embeddings_{model.replace(':', '_').replace('/', '_')}.pt" + if cache_path.exists(): + LOGGER.info(f"Reading existed cache from '{cache_path}'") + txt_map = torch.load(cache_path, map_location=self.device) + if sorted(txt_map.keys()) == sorted(texts): + return txt_map + LOGGER.info(f"Caching text embeddings to '{cache_path}'") + txt_feats = unwrap_model(self.model).get_text_pe(texts, batch, without_reprta=True, cache_clip_model=False) + txt_map = dict(zip(texts, txt_feats.squeeze(0))) + torch.save(txt_map, cache_path) + return txt_map + + +class YOLOEPEFreeTrainer(YOLOEPETrainer, YOLOETrainerFromScratch): + """Train prompt-free YOLOE model. + + This trainer combines linear probing capabilities with from-scratch training for prompt-free YOLOE models that don't + require text prompts during inference. + + Methods: + preprocess_batch: Preprocess batches without text features. + set_text_embeddings: Set text embeddings for datasets (no-op for prompt-free). + """ + + def preprocess_batch(self, batch): + """Preprocess a batch of images for YOLOE training, adjusting formatting and dimensions as needed.""" + return DetectionTrainer.preprocess_batch(self, batch) + + def set_text_embeddings(self, datasets, batch: int): + """No-op override for prompt-free training that does not require text embeddings. + + Args: + datasets (list[Dataset]): List of datasets containing category names to process. + batch (int): Batch size for processing text embeddings. + """ + + +class YOLOEVPTrainer(YOLOETrainerFromScratch): + """Train YOLOE model with visual prompts. + + This trainer extends YOLOETrainerFromScratch to support visual prompt-based training, where visual cues are provided + alongside images to guide the detection process. + + Methods: + build_dataset: Build dataset with visual prompt loading transforms. + """ + + def build_dataset(self, img_path: list[str] | str, mode: str = "train", batch: int | None = None): + """Build YOLO Dataset for training or validation with visual prompts. + + Args: + img_path (list[str] | str): Path to the folder containing images or list of paths. + mode (str): 'train' mode or 'val' mode, allowing customized augmentations for each mode. + batch (int, optional): Size of batches, used for rectangular training/validation. + + Returns: + (YOLOConcatDataset | Dataset): YOLO dataset configured for training or validation, with visual prompts for + training mode. + """ + dataset = super().build_dataset(img_path, mode, batch) + if isinstance(dataset, YOLOConcatDataset): + for d in dataset.datasets: + d.transforms.append(LoadVisualPrompt()) + else: + dataset.transforms.append(LoadVisualPrompt()) + return dataset + + def _close_dataloader_mosaic(self): + """Close mosaic augmentation and add visual prompt loading to the training dataset.""" + super()._close_dataloader_mosaic() + if isinstance(self.train_loader.dataset, YOLOConcatDataset): + for d in self.train_loader.dataset.datasets: + d.transforms.append(LoadVisualPrompt()) + else: + self.train_loader.dataset.transforms.append(LoadVisualPrompt()) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/train_seg.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/train_seg.py new file mode 100644 index 0000000000000000000000000000000000000000..9f5011e6c687034a2c8f7d25ee583ba6ff4db025 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/train_seg.py @@ -0,0 +1,23 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from ultralytics.models.yolo.segment import SegmentationTrainer + +from .train import YOLOEPETrainer, YOLOETrainer, YOLOETrainerFromScratch, YOLOEVPTrainer + + +class YOLOESegTrainer(YOLOETrainer, SegmentationTrainer): + """Trainer class for YOLOE segmentation models.""" + + +class YOLOEPESegTrainer(SegmentationTrainer): + """Fine-tune YOLOE segmentation models in linear probing way.""" + + get_model = YOLOEPETrainer.get_model # shared linear-probing builder; SegmentationTrainer stays the sole base + + +class YOLOESegTrainerFromScratch(YOLOETrainerFromScratch, YOLOESegTrainer): + """Trainer for YOLOE segmentation models trained from scratch without pretrained weights.""" + + +class YOLOESegVPTrainer(YOLOEVPTrainer, YOLOESegTrainerFromScratch): + """Trainer for YOLOE segmentation models with Vision Prompt (VP) capabilities.""" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/val.py b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/val.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0cb93c8f52d1bd518c24b1dabd23b4c76bb59e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/val.py @@ -0,0 +1,203 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import torch +from torch.nn import functional as F + +from ultralytics.data import YOLOConcatDataset, build_dataloader, build_yolo_dataset +from ultralytics.data.augment import LoadVisualPrompt +from ultralytics.data.utils import check_det_dataset, get_split_fraction +from ultralytics.models.yolo.detect import DetectionValidator +from ultralytics.models.yolo.segment import SegmentationValidator +from ultralytics.nn.modules.head import YOLOEDetect +from ultralytics.nn.tasks import YOLOEModel +from ultralytics.utils import LOGGER, TQDM +from ultralytics.utils.torch_utils import select_device, smart_inference_mode + + +class YOLOEDetectValidator(DetectionValidator): + """A validator class for YOLOE detection models that handles both text and visual prompt embeddings. + + This class extends DetectionValidator to provide specialized validation functionality for YOLOE models. It supports + validation using either text prompts or visual prompt embeddings extracted from training samples, enabling flexible + evaluation strategies for prompt-based object detection. + + Attributes: + device (torch.device): The device on which validation is performed. + args (namespace): Configuration arguments for validation. + dataloader (DataLoader): DataLoader for validation data. + + Methods: + get_visual_pe: Extract visual prompt embeddings from training samples. + preprocess: Preprocess batch data ensuring visuals are on the same device as images. + get_vpe_dataloader: Create a dataloader for LVIS training visual prompt samples. + get_model: Prepare a validation model with text or visual prompt embeddings. + + Examples: + Validate with text prompts + >>> validator = YOLOEDetectValidator() + >>> stats = validator(model=model, load_vp=False) + + Validate with visual prompts + >>> stats = validator(model=model, refer_data="path/to/data.yaml", load_vp=True) + """ + + @smart_inference_mode() + def get_visual_pe(self, dataloader: torch.utils.data.DataLoader, model: YOLOEModel) -> torch.Tensor: + """Extract visual prompt embeddings from training samples. + + This method processes a dataloader to compute visual prompt embeddings for each class using a YOLOE model. It + normalizes the embeddings and handles cases where no samples exist for a class by setting their embeddings to + zero. + + Args: + dataloader (torch.utils.data.DataLoader): The dataloader providing training samples. + model (YOLOEModel): The YOLOE model from which to extract visual prompt embeddings. + + Returns: + (torch.Tensor): Visual prompt embeddings with shape (1, num_classes, embed_dim). + """ + assert isinstance(model, YOLOEModel) + names = [name.split("/", 1)[0] for name in list(dataloader.dataset.data["names"].values())] + visual_pe = torch.zeros(len(names), model.model[-1].embed, device=self.device) + cls_visual_num = torch.zeros(len(names)) + + desc = "Get visual prompt embeddings from samples" + + # Count samples per class + for batch in dataloader: + cls = batch["cls"].squeeze(-1).to(torch.int).unique() + count = torch.bincount(cls, minlength=len(names)) + cls_visual_num += count + + cls_visual_num = cls_visual_num.to(self.device) + + # Extract visual prompt embeddings + pbar = TQDM(dataloader, total=len(dataloader), desc=desc) + for batch in pbar: + batch = self.preprocess(batch) + preds = model.get_visual_pe(batch["img"], visual=batch["visuals"]) # (B, max_n, embed_dim) + + batch_idx = batch["batch_idx"] + for i in range(preds.shape[0]): + cls = batch["cls"][batch_idx == i].squeeze(-1).to(torch.int).unique(sorted=True) + pad_cls = torch.ones(preds.shape[1], device=self.device) * -1 + pad_cls[: cls.shape[0]] = cls + for c in cls: + visual_pe[c] += preds[i][pad_cls == c].sum(0) / cls_visual_num[c] + + # Normalize embeddings for classes with samples, set others to zero + visual_pe[cls_visual_num != 0] = F.normalize(visual_pe[cls_visual_num != 0], dim=-1, p=2) + visual_pe[cls_visual_num == 0] = 0 + return visual_pe.unsqueeze(0) + + def get_vpe_dataloader(self, data: dict[str, Any]) -> torch.utils.data.DataLoader: + """Create a dataloader for LVIS training visual prompt samples. + + This method prepares a dataloader for visual prompt embeddings (VPE) using the specified dataset. It applies + necessary transformations including LoadVisualPrompt and configurations to the dataset for validation purposes. + + Args: + data (dict): Dataset configuration dictionary containing paths and settings. + + Returns: + (torch.utils.data.DataLoader): The dataloader for visual prompt samples. + """ + dataset = build_yolo_dataset( + self.args, + data.get(self.args.split, data.get("val")), + self.args.batch, + data, + mode="val", + rect=False, + fraction=get_split_fraction(self.args.fraction, self.args.split or "val"), + ) + if isinstance(dataset, YOLOConcatDataset): + for d in dataset.datasets: + d.transforms.append(LoadVisualPrompt()) + else: + dataset.transforms.append(LoadVisualPrompt()) + return build_dataloader( + dataset, + self.args.batch, + self.args.workers, + shuffle=False, + rank=-1, + device=self.device, + ) + + @smart_inference_mode(False) + def get_model( + self, + model: YOLOEModel | str | None = None, + trainer: Any | None = None, + refer_data: str | None = None, + load_vp: bool = False, + ) -> YOLOEModel: + """Prepare text, visual, or prompt-free models before validation inference setup. + + Args: + trainer (object, optional): Trainer object containing the model and device. + model (YOLOEModel | str, optional): Model to validate. Required if trainer is not provided. + refer_data (str, optional): Path to reference data for visual prompts. + load_vp (bool): Whether to load visual prompts. If False, text prompts are used. + + Returns: + (YOLOEModel): Model with prompts prepared for validation. + """ + model = super().get_model(model, trainer) + if trainer is not None: + self.device = trainer.device + names = [name.split("/", 1)[0] for name in list(self.dataloader.dataset.data["names"].values())] + + if load_vp: + LOGGER.info("Validate using the visual prompt.") + self.args.quantize = None + # Directly use the same dataloader for visual embeddings extracted during training + vpe = self.get_visual_pe(self.dataloader, model) + model.set_classes(names, vpe) + else: + LOGGER.info("Validate using the text prompt.") + tpe = model.get_text_pe(names) + model.set_classes(names, tpe) + else: + if refer_data is not None: + assert load_vp, "Refer data is only used for visual prompt validation." + self.device = select_device(self.args.device, verbose=False) + + if isinstance(model, (str, Path)): + from ultralytics.nn.tasks import load_checkpoint + + model, _ = load_checkpoint(model, device=self.device) # model, ckpt + model.eval().to(self.device) + data = check_det_dataset(refer_data or self.args.data) + names = [name.split("/", 1)[0] for name in list(data["names"].values())] + + if refer_data is not None: + eval_data = check_det_dataset(self.args.data) + eval_names = [name.split("/", 1)[0] for name in list(eval_data["names"].values())] + if names != eval_names: + LOGGER.warning( + f"Class names from refer data {names} do not match evaluation dataset {eval_names}. " + f"This may lead to incorrect validation results." + ) + + if load_vp: + LOGGER.info("Validate using the visual prompt.") + self.args.quantize = None + dataloader = self.get_vpe_dataloader(data) + vpe = self.get_visual_pe(dataloader, model) + model.set_classes(names, vpe) + elif not (isinstance(model.model[-1], YOLOEDetect) and hasattr(model.model[-1], "lrpc")): # text prompts + LOGGER.info("Validate using the text prompt.") + tpe = model.get_text_pe(names) + model.set_classes(names, tpe) + return model + + +class YOLOESegValidator(YOLOEDetectValidator, SegmentationValidator): + """YOLOE segmentation validator that supports both text and visual prompt embeddings.""" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a49ce0521c25ead13ab52b62641610ac361608a8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/__init__.py @@ -0,0 +1,27 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .tasks import ( + BaseModel, + ClassificationModel, + DetectionModel, + SegmentationModel, + guess_model_scale, + guess_model_task, + load_checkpoint, + parse_model, + torch_safe_load, + yaml_model_load, +) + +__all__ = ( + "BaseModel", + "ClassificationModel", + "DetectionModel", + "SegmentationModel", + "guess_model_scale", + "guess_model_task", + "load_checkpoint", + "parse_model", + "torch_safe_load", + "yaml_model_load", +) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ea3953c7fa3786fdf82c53b5ddc4c40064eba13 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/autobackend.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/autobackend.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cd96596a977f10d7c27c24185f07ffd08fd67d9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/autobackend.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/distill_model.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/distill_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dde52bb7160a83079ac457fa92e72c77b1378963 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/distill_model.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/tasks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/tasks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37714bcdbbeb517b402e6f7e6a3f0285558c7785 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/tasks.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:745cfb3699b343fdce7fbd51549961923b5ac2cd2a75189524bd98c7913c7c5c +size 123702 diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/text_model.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/text_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8155a4508e3f132fb0ffaf6f5eb115216a6b215e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/__pycache__/text_model.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/autobackend.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/autobackend.py new file mode 100644 index 0000000000000000000000000000000000000000..f99efffcfff5cdec7d0ba5c20f12e4dda8d76913 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/autobackend.py @@ -0,0 +1,437 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import platform +from copy import deepcopy +from pathlib import Path +from typing import Any + +import numpy as np +import torch +from torch import nn + +from ultralytics.utils import LINUX, LOGGER, WINDOWS +from ultralytics.utils.checks import check_suffix +from ultralytics.utils.downloads import is_url +from ultralytics.utils.torch_utils import TORCH_1_10, TORCH_1_13, smart_inference_mode + +from .backends import ( + AscendBackend, + AxeleraBackend, + CoreAIBackend, + CoreMLBackend, + DeepXBackend, + ExecuTorchBackend, + HailoBackend, + LiteRTBackend, + MNNBackend, + NCNNBackend, + ONNXBackend, + ONNXIMXBackend, + OpenVINOBackend, + PaddleBackend, + PyTorchBackend, + QNNBackend, + RKNNBackend, + TensorFlowBackend, + TensorRTBackend, + TorchScriptBackend, + TritonBackend, +) + + +def check_class_names(names: list | dict) -> dict[int, str]: + """Check class names and convert to dict format if needed. + + Args: + names (list | dict): Class names as list or dict format. + + Returns: + (dict): Class names in dict format with integer keys and string values. + + Raises: + KeyError: If class indices are invalid for the dataset size. + """ + if isinstance(names, list): # names is a list + names = dict(enumerate(names)) # convert to dict + if isinstance(names, dict): + # Convert 1) string keys to int, i.e. '0' to 0, and non-string values to strings, i.e. True to 'True' + names = {int(k): str(v) for k, v in names.items()} + n = len(names) + if not n: + raise KeyError("0-class dataset, at least one class name is required in your dataset YAML.") + if max(names.keys()) >= n: + raise KeyError( + f"{n}-class dataset requires class indices 0-{n - 1}, but you have invalid class indices " + f"{min(names.keys())}-{max(names.keys())} defined in your dataset YAML." + ) + if isinstance(names[0], str) and names[0].startswith("n0"): # imagenet class codes, i.e. 'n01440764' + from ultralytics.utils import ROOT, YAML + + names_map = YAML.load(ROOT / "cfg/datasets/ImageNet.yaml")["map"] # human-readable names + names = {k: names_map[v] for k, v in names.items()} + return names + + +def default_class_names(data: str | Path | None = None, nc: int = 999) -> dict[int, str]: + """Load class names from a YAML file or return numerical class names. + + Args: + data (str | Path, optional): Path to YAML file containing class names. + nc (int): Number of names to generate when the YAML is missing or unreadable. + + Returns: + (dict): Dictionary mapping class indices to class names. + """ + if data: + try: + from ultralytics.utils import YAML + from ultralytics.utils.checks import check_yaml + + return YAML.load(check_yaml(data))["names"] + except Exception: + pass + return {i: f"class{i}" for i in range(nc)} # return default if above errors + + +class AutoBackend(nn.Module): + """Handle dynamic backend selection for running inference using Ultralytics YOLO models. + + The AutoBackend class is designed to provide an abstraction layer for various inference engines. It supports a wide + range of formats, each with specific naming conventions as outlined below: + + Supported Formats and Naming Conventions: + | Format | File Suffix | + | --------------------- | ----------------- | + | PyTorch | *.pt | + | TorchScript | *.torchscript | + | ONNX Runtime | *.onnx | + | ONNX OpenCV DNN | *.onnx (dnn=True) | + | OpenVINO | *openvino_model/ | + | CoreML | *.mlpackage | + | TensorRT | *.engine | + | TensorFlow SavedModel | *_saved_model/ | + | TensorFlow GraphDef | *.pb | + | TensorFlow Edge TPU | *_edgetpu.tflite | + | PaddlePaddle | *_paddle_model/ | + | MNN | *.mnn | + | NCNN | *_ncnn_model/ | + | IMX | *_imx_model/ | + | RKNN | *_rknn_model/ | + | Triton Inference | triton://model | + | ExecuTorch | *.pte | + | Axelera AI | *_axelera_model/ | + | DEEPX | *_deepx_model/ | + | Qualcomm QNN | *_qnn.onnx | + | LiteRT | *.tflite | + | Hailo | *_hailo_model/ | + | Huawei Ascend | *_ascend_model/ | + + Attributes: + backend (BaseBackend): The loaded inference backend instance. + format (str): The model format (e.g., 'pt', 'onnx', 'engine'). + model: The underlying model (nn.Module for PyTorch backends, backend instance otherwise). + device (torch.device): The device (CPU or GPU) on which the model is loaded. + task (str): The type of task the model performs (detect, segment, semantic, classify, pose, obb). + names (dict): A dictionary of class names that the model can detect. + stride (int): The model stride, typically 32 for YOLO models. + fp16 (bool): Whether the model uses half-precision (FP16) inference. + nhwc (bool): Whether the model expects NHWC input format instead of NCHW. + + Methods: + forward: Run inference on an input image. + from_numpy: Convert NumPy arrays to tensors on the model device. + warmup: Warm up the model with a dummy input. + _model_type: Determine the model type from file path. + + Examples: + >>> model = AutoBackend(model="yolo26n.pt", device="cuda") + >>> results = model(img) + """ + + _BACKEND_MAP = { + "pt": PyTorchBackend, + "torchscript": TorchScriptBackend, + "onnx": ONNXBackend, + "dnn": ONNXBackend, # Special case: ONNX with DNN + "openvino": OpenVINOBackend, + "engine": TensorRTBackend, + "coreml": CoreMLBackend, + "saved_model": TensorFlowBackend, + "pb": TensorFlowBackend, + "edgetpu": TensorFlowBackend, + "paddle": PaddleBackend, + "mnn": MNNBackend, + "ncnn": NCNNBackend, + "imx": ONNXIMXBackend, + "rknn": RKNNBackend, + "triton": TritonBackend, + "executorch": ExecuTorchBackend, + "axelera": AxeleraBackend, + "deepx": DeepXBackend, + "qnn": QNNBackend, + "litert": LiteRTBackend, + "hailo": HailoBackend, + "ascend": AscendBackend, + "coreai": CoreAIBackend, + } + + @smart_inference_mode(False) + def __init__( + self, + model: str | torch.nn.Module = "yolo26n.pt", + device: torch.device | None = None, + dnn: bool = False, + data: str | Path | None = None, + fp16: bool = False, + fuse: bool = True, + verbose: bool = True, + channels_last: bool | None = None, + end2end: bool | None = None, + ): + """Initialize the AutoBackend for inference. + + Args: + model (str | torch.nn.Module): Path to the model weights file or a module instance. + device (torch.device): Device to run the model on. + dnn (bool): Use OpenCV DNN module for ONNX inference. + data (str | Path, optional): Path to the additional data.yaml file containing class names. + fp16 (bool): Enable half-precision inference. Supported only on specific backends. + fuse (bool): Fuse Conv2D + BatchNorm layers for optimization. + verbose (bool): Enable verbose logging. + channels_last (bool, optional): Use channels-last memory format, or auto-enable it on supported x86 CPUs. + end2end (bool, optional): Select the native detection head before fusion; None preserves its current mode. + """ + super().__init__() + device = device or torch.device("cpu") + # Determine model format from path/URL + format = "pt" if isinstance(model, nn.Module) else self._model_type(model, dnn) + if ( + isinstance(model, nn.Module) + and TORCH_1_10 + and any(x.is_inference() for x in (*model.parameters(), *model.buffers())) + ): + model = deepcopy(model) # retained backends require normal tensors for fusion and later mutation + + # Check if format supports FP16 + fp16 &= format in {"pt", "torchscript", "onnx", "openvino", "engine"} + + # Set device + if ( + isinstance(device, torch.device) + and torch.cuda.is_available() + and device.type != "cpu" + and format not in {"pt", "torchscript", "engine", "onnx", "paddle"} + ): + device = torch.device("cpu") + + # Select and initialize the appropriate backend + backend_kwargs = {"device": device, "fp16": fp16} + + if format not in self._BACKEND_MAP: + from ultralytics.engine.exporter import export_formats + + raise TypeError( + f"model='{model}' is not a supported model format. " + f"Ultralytics supports: {export_formats()['Format']}\n" + f"See https://docs.ultralytics.com/modes/predict for help." + ) + if format == "pt": + backend_kwargs["fuse"] = fuse + backend_kwargs["verbose"] = verbose + backend_kwargs["end2end"] = end2end + elif format in {"saved_model", "pb", "edgetpu", "dnn"}: + backend_kwargs["format"] = format + self.backend = self._BACKEND_MAP[format](model, **backend_kwargs) + + if format == "pt": + device_type = torch.device(self.backend.device).type + supported = device_type == "cuda" or ( + TORCH_1_13 + and device_type == "cpu" + and platform.machine() in {"AMD64", "x86_64"} + and torch.backends.mkldnn.is_available() + and torch.backends.mkldnn.enabled + ) + if channels_last is None: + channels_last = device_type == "cpu" and supported and (LINUX or WINDOWS) + if channels_last and not supported: + LOGGER.warning(f"'channels_last=True' is not supported on '{device_type}', ignoring.") + self.backend.model.to( + memory_format=torch.channels_last if channels_last and supported else torch.contiguous_format + ) + elif channels_last: + LOGGER.warning(f"'channels_last=True' applies only to native PyTorch models, ignoring format='{format}'.") + + self.nhwc = format in {"coreml", "saved_model", "pb", "edgetpu", "rknn"} + self.format = format + + # Ensure backend has names (fallback to default if not set by metadata) + if not self.backend.names: + self.backend.names = default_class_names(data) + self.backend.names = check_class_names(self.backend.names) + empty = [k for k, v in self.backend.names.items() if not v.strip()] + if empty: + LOGGER.warning(f"Empty class name string(s) at class indices {empty} will display as blank labels.") + + def __getattr__(self, name: str) -> Any: + """Delegate attribute access to the backend. + + This allows AutoBackend to transparently expose backend attributes + without explicit copying. + + Args: + name: Attribute name to look up. + + Returns: + The attribute value from the backend. + + Raises: + AttributeError: If the attribute is not found in backend. + """ + if "backend" in self.__dict__ and hasattr(self.backend, name): + return getattr(self.backend, name) + return super().__getattr__(name) + + def forward( + self, + im: torch.Tensor, + augment: bool = False, + embed: list | None = None, + **kwargs: Any, + ) -> Any: + """Run inference on an AutoBackend model. + + Args: + im (torch.Tensor): The image tensor to perform inference on. + augment (bool): Whether to perform data augmentation during inference. + embed (list, optional): A list of layer indices to return embeddings from. + **kwargs (Any): Additional keyword arguments for model configuration. + + Returns: + (Any): The raw model output, with NumPy arrays converted to tensors on `self.device`. + """ + if self.nhwc: + im = im.permute(0, 2, 3, 1) # torch BCHW to numpy BHWC shape(1,320,192,3) + if self.backend.fp16 and im.dtype != torch.float16: + im = im.half() + + # Build forward kwargs based on backend type + forward_kwargs = {} + if self.format == "pt": + forward_kwargs = {"augment": augment, "embed": embed, **kwargs} + + y = self.backend.forward(im, **forward_kwargs) + + if isinstance(y, (list, tuple)): + if len(self.names) == 999 and (self.task == "segment" or len(y) == 2): # segments and names not defined + nc = y[0].shape[1] - y[1].shape[1] - 4 # y = (1, 116, 8400), (1, 32, 160, 160) + self.names = {i: f"class{i}" for i in range(nc)} + return self.from_numpy(y[0]) if len(y) == 1 else [self.from_numpy(x) for x in y] + else: + return self.from_numpy(y) + + def from_numpy(self, x: Any) -> Any: + """Normalize a backend output to the model device when possible. + + Args: + x (Any): Backend output to normalize. + + Returns: + (Any): Tensor on `self.device`, or the unchanged non-tensor output. + """ + if isinstance(x, np.ndarray): + return torch.as_tensor(x, device=self.device) # shares memory on CPU, one fused copy to accelerators + return x.to(self.device) if isinstance(x, torch.Tensor) else x + + def warmup(self, imgsz: tuple[int, int, int, int] = (1, 3, 640, 640), im: torch.Tensor | None = None) -> None: + """Warm up the model by running forward pass(es). + + Args: + imgsz (tuple[int, int, int, int]): Dummy input shape in (batch, channels, height, width) format. + im (torch.Tensor, optional): Input tensor to reuse instead of allocating a dummy. + """ + from ultralytics.utils.nms import non_max_suppression + + if not self.end2end: + import torchvision # noqa (import here triggers torchvision NMS use in nms.py) + if self.format in {"pt", "torchscript", "onnx", "engine", "saved_model", "pb", "triton"} and ( + self.device.type != "cpu" or self.format == "triton" + ): + im = ( + im + if im is not None + else torch.empty(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) + ) + for _ in range(2 if self.format == "torchscript" else 1): + self.forward(im) # warmup model + warmup_boxes = torch.rand(1, 84, 16, device=self.device) # 16 boxes works best empirically + warmup_boxes[:, :4] *= im.shape[-1] + non_max_suppression(warmup_boxes) # warmup NMS + + @staticmethod + def _model_type(p: str = "path/to/model.pt", dnn: bool = False) -> str: + """Take a path to a model file and return the model format string. + + Args: + p (str): Path to the model file. + dnn (bool): Whether to use OpenCV DNN module for ONNX inference. + + Returns: + (str): Model format string (e.g., 'pt', 'onnx', 'engine', 'triton'). + + Examples: + >>> fmt = AutoBackend._model_type("path/to/model.onnx") + >>> assert fmt == "onnx" + """ + from ultralytics.engine.exporter import export_formats + + sf = export_formats()["Suffix"] + if not is_url(p) and not isinstance(p, str): + check_suffix(p, sf) + name = Path(p).name + types = [s in name for s in sf] + types[5] |= name.endswith(".mlmodel") + format = next((f for i, f in enumerate(export_formats()["Argument"]) if types[i]), None) + if name.endswith("_qnn.onnx"): # QNN context-binary file otherwise matches the plain '.onnx' suffix + format = "qnn" + elif name.endswith(".tflite") and not name.endswith("_edgetpu.tflite"): + format = "litert" # bare .tflite files (incl. legacy TFLite exports) load via LiteRT + elif format == "-": + format = "pt" + elif format == "onnx" and dnn: + format = "dnn" + elif not any(types): + from urllib.parse import urlsplit + + url = urlsplit(p) + if bool(url.netloc) and bool(url.path) and url.scheme in {"http", "grpc"}: + format = "triton" + return format + + def eval(self) -> AutoBackend: + """Set the backend model to evaluation mode if supported.""" + if hasattr(self.backend, "model") and hasattr(self.backend.model, "eval"): + self.backend.model.eval() + return super().eval() + + def _apply(self, fn) -> AutoBackend: + """Apply a function to backend.model parameters, buffers, and tensors. + + This method extends the functionality of the parent class's _apply method by additionally applying the + function to the backend model and updating the backend device. It's typically used for operations like moving + the model to a different device or changing its precision. + + Args: + fn (Callable): A function to be applied to the model's tensors. This is typically a method like to(), cpu(), + cuda(), half(), or float(). + + Returns: + (AutoBackend): The model instance with the function applied and updated attributes. + """ + super()._apply(fn) + if hasattr(self.backend, "model") and isinstance(self.backend.model, nn.Module): + self.backend.model._apply(fn) + self.backend.device = next(self.backend.model.parameters()).device # update device after move + return self diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f78188d0bdc094caa8b63a931d9ad30a255db5de --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__init__.py @@ -0,0 +1,53 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Ultralytics YOLO inference backends. + +This package provides modular inference backends for various deep learning frameworks and hardware accelerators. +Each backend implements the `BaseBackend` interface and can be used independently or through the unified +`AutoBackend` dispatcher for automatic format detection and inference routing. +""" + +from .ascend import AscendBackend +from .axelera import AxeleraBackend +from .base import BaseBackend +from .coreai import CoreAIBackend +from .coreml import CoreMLBackend +from .deepx import DeepXBackend +from .executorch import ExecuTorchBackend +from .hailo import HailoBackend +from .litert import LiteRTBackend +from .mnn import MNNBackend +from .ncnn import NCNNBackend +from .onnx import ONNXBackend, ONNXIMXBackend +from .openvino import OpenVINOBackend +from .paddle import PaddleBackend +from .pytorch import PyTorchBackend, TorchScriptBackend +from .qnn import QNNBackend +from .rknn import RKNNBackend +from .tensorflow import TensorFlowBackend +from .tensorrt import TensorRTBackend +from .triton import TritonBackend + +__all__ = [ + "AscendBackend", + "AxeleraBackend", + "BaseBackend", + "CoreAIBackend", + "CoreMLBackend", + "DeepXBackend", + "ExecuTorchBackend", + "HailoBackend", + "LiteRTBackend", + "MNNBackend", + "NCNNBackend", + "ONNXBackend", + "ONNXIMXBackend", + "OpenVINOBackend", + "PaddleBackend", + "PyTorchBackend", + "QNNBackend", + "RKNNBackend", + "TensorFlowBackend", + "TensorRTBackend", + "TorchScriptBackend", + "TritonBackend", +] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9833d5f10164eb0e56d27892d7c26fb552ca662 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/ascend.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/ascend.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d76b3a0424dcfa0ac8e860d8921b1b1117a71ed Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/ascend.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/axelera.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/axelera.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c3fc66c95bcdfbad32d672322f48e9e40b737f1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/axelera.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6c4a5595d20e07ed4b2e71a7296dff2777fc590 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/base.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/coreai.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/coreai.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..570942a6425a7eb86352987a613a1d2db03ca23d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/coreai.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/coreml.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/coreml.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88aa56566365e8baf2db54654b66c6e97ccbf67f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/coreml.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/deepx.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/deepx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd291d692f4a048320de5cf4ddb3f95f578e26c0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/deepx.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/executorch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/executorch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cbad9679139d3e80188b1ef09dc6ab32911c3e3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/executorch.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/hailo.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/hailo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e80abddd7bfb629b484b28b906dbb33bb8b04eee Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/hailo.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/litert.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/litert.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9654f310eec1a79600c9b1986fa4111239adc554 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/litert.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/mnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/mnn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0031ee44260fd46399dfdb79af6af6c4a69f91f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/mnn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/ncnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/ncnn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bf1841f56dad10f95854c62ae7c820a6adbca9c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/ncnn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/onnx.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/onnx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bec3c2ed75b1423acaec260144989d4f635d746 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/onnx.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/openvino.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/openvino.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d50e91be4a8ffc000be120cd52c554c19a778452 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/openvino.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/paddle.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/paddle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4060013e2f859f153a2ae88f9c8a0e7b11978bd3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/paddle.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/pytorch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/pytorch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa4f7477eea9b688ca29371f851793dff3c04ba4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/pytorch.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/qnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/qnn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f13ed0c7219ffb37ebb6c0eb112a84854ef0f93 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/qnn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/rknn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/rknn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01b4a7e70e55ce89e0b07b66dfb6d710594cd55a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/rknn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/tensorflow.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/tensorflow.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80edde00c908f5fae3b45c46f98cb6124351a8c4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/tensorflow.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/tensorrt.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/tensorrt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb3db9458b1258f323152139681e742f8b397115 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/tensorrt.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/triton.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/triton.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb2bfbf33a8f18dbe92f0b0623374b8938a08712 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/__pycache__/triton.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/ascend.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/ascend.py new file mode 100644 index 0000000000000000000000000000000000000000..d5cb99e3fff238ec6d3b4bb4edbf0de7e9a433be --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/ascend.py @@ -0,0 +1,66 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import torch + +from ultralytics.utils import LOGGER + +from .base import BaseBackend + + +class AscendBackend(BaseBackend): + """Huawei Ascend NPU inference backend for CANN offline models. + + Loads a compiled .om offline model and runs inference on the Ascend AI Processor through the ais_bench runtime, + which wraps CANN's pyACL bindings. + """ + + def load_model(self, weight: str | Path) -> None: + """Load an Ascend model from a directory containing a .om file. + + Args: + weight (str | Path): Path to the Ascend model directory containing the .om offline model. + + Raises: + ImportError: If the ``ais_bench`` Python package is not installed. + FileNotFoundError: If no .om file is found in the given directory. + """ + try: + from ais_bench.infer.interface import InferSession + except ImportError as e: + raise ImportError( + "Ascend inference requires the CANN runtime and `ais_bench` Python package. " + "See https://docs.ultralytics.com/integrations/ascend#runtime-installation for instructions." + ) from e + + LOGGER.info(f"Loading {weight} for Huawei Ascend inference...") + + w = Path(weight) + found = next(w.rglob("*.om"), None) + if found is None: + raise FileNotFoundError(f"No .om file found in: {w}") + + self.model = InferSession(getattr(self.device, "index", None) or 0, str(found)) + + self.apply_metadata(self.read_metadata(found)) + + def __del__(self): + """Release the Ascend device-side resources held by the inference session.""" + if model := getattr(self, "model", None): + model.free_resource() + + def forward(self, im: torch.Tensor) -> np.ndarray | list[np.ndarray]: + """Run inference on the Ascend NPU. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (np.ndarray | list[np.ndarray]): Model predictions as a single array or list of arrays. + """ + y = self.model.infer([im.cpu().numpy()]) + return y[0] if len(y) == 1 else y diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/axelera.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/axelera.py new file mode 100644 index 0000000000000000000000000000000000000000..45775fd214801144154e5ab521a718b0f432773e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/axelera.py @@ -0,0 +1,68 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import torch + +from ultralytics.utils.checks import check_requirements + +from .base import BaseBackend + + +class AxeleraBackend(BaseBackend): + """Axelera AI inference backend for Axelera Metis AI accelerators. + + Loads compiled Axelera models (.axm files) and runs inference using the Axelera AI runtime SDK. + """ + + def load_model(self, weight: str | Path) -> None: + """Load an Axelera model from a directory containing a .axm file. + + Args: + weight (str | Path): Path to the Axelera model directory containing the .axm binary. + """ + from ultralytics.utils.export.axelera import AXELERA_SDK + + if not check_requirements( + f"axelera-rt=={AXELERA_SDK}", + cmds="--extra-index-url https://software.axelera.ai/artifactory/api/pypi/axelera-pypi/simple", + ): + raise ModuleNotFoundError(f"Axelera inference requires axelera-rt=={AXELERA_SDK}.") + from axelera.runtime import op + + w = Path(weight) + found = next(w.rglob("*.axm"), None) + if found is None: + raise FileNotFoundError(f"No .axm file found in: {w}") + + self.model = op.load(str(found)).optimized() + + self.apply_metadata(self.read_metadata(found)) + + def forward(self, im: torch.Tensor) -> np.ndarray | list[np.ndarray]: + """Run inference on the Axelera hardware accelerator. + + A compiled model accepts a single image, so batches go through the Axelera scheduler, which + overlaps host-side quantization with execution on the device. `batch()` takes the whole tensor + as one argument and expands its leading dimension: its `*inputs` varargs mean one entry per + model input, not per image, and passing one image per argument is rejected. It returns one + result per image in input order, each keeping its singleton batch dimension, hence the + concatenate below rather than a stack. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (np.ndarray | list[np.ndarray]): Model predictions, one array per model output. + """ + im = im.cpu() + if im.shape[0] == 1: + return self.model(im) + + outputs = self.model.batch(im) + if isinstance(outputs[0], (list, tuple)): # multi-output head, e.g. detections plus masks + return [np.concatenate(o, axis=0) for o in zip(*outputs)] + return np.concatenate(outputs, axis=0) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/base.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/base.py new file mode 100644 index 0000000000000000000000000000000000000000..6f2c70950460a23bdeb9e893c36e92967057e113 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/base.py @@ -0,0 +1,222 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import ast +import contextlib +import json +from abc import ABC, abstractmethod +from pathlib import Path +from typing import Any + +import torch + +from ultralytics.utils import YAML + + +def _read_proto_map(file: Path, path: tuple[int, ...]) -> dict: + """Read a protobuf ``map`` at a nested field path, without importing the format's framework. + + Args: + file (Path): Path to the protobuf file, i.e. an ONNX or CoreML model. + path (tuple[int, ...]): Field numbers to descend, the last holding the repeated ``key``/``value`` entries. + + Returns: + (dict): Map entries as string key-value pairs. + """ + import mmap + + def fields(buf): + """Yield ``(number, payload)`` for each length-delimited field of a message, stepping over varint fields.""" + i = 0 + + def varint(): + """Decode the base-128 varint at the current offset.""" + nonlocal i + v = shift = 0 + while buf[i] & 0x80: + v, i, shift = v | (buf[i] & 0x7F) << shift, i + 1, shift + 7 + v, i = v | buf[i] << shift, i + 1 + return v + + while i < len(buf): + tag = varint() + if tag & 7 == 0: # varint field, i.e. ONNX ir_version + varint() + elif tag & 7 == 2: # length-delimited field, i.e. a nested message, string or weights blob + n = varint() + yield tag >> 3, buf[i : i + n] # a memoryview slice, so a large payload is never copied + i += n + else: + return # these protos carry no fixed-width fields + + with open(file, "rb") as f: + messages = [memoryview(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ))] + for number in path: + messages = [payload for m in messages for n, payload in fields(m) if n == number] + return {bytes(e[1]).decode(): bytes(e.get(2, b"")).decode() for e in map(dict, map(fields, messages))} + + +class BaseBackend(ABC): + """Base class for all inference backends. + + This abstract class defines the interface that all inference backends must implement. It provides common + functionality for model loading, metadata processing, and device management. + + Attributes: + model: The underlying inference model or runtime session. + device (torch.device): The device to run inference on. + fp16 (bool): Whether to use FP16 (half-precision) inference. + nhwc (bool): Whether the model expects NHWC input format instead of NCHW. + stride (int): Model stride, typically 32 for YOLO models. + names (dict): Dictionary mapping class indices to class names. + task (str | None): The task type (detect, segment, semantic, classify, pose, obb). + batch (int): Batch size for inference. + imgsz (tuple): Input image size as (height, width). + channels (int): Number of input channels, typically 3 for RGB. + end2end (bool): Whether the model includes end-to-end NMS post-processing. + dynamic (bool): Whether the model supports dynamic input shapes. + base_model (bool): Whether the loaded model is an Ultralytics `BaseModel`, and so implements the `augment` and + `embed` forward arguments. + metadata (dict): Model metadata dictionary containing export configuration. + """ + + def __init__(self, weight: str | torch.nn.Module, device: torch.device | str, fp16: bool = False): + """Initialize the base backend with common attributes and load the model. + + Args: + weight (str | torch.nn.Module): Path to the model weights file or a PyTorch module instance. + device (torch.device | str): Device to run inference on (e.g., 'cpu', 'cuda:0'). + fp16 (bool): Whether to use FP16 half-precision inference. + """ + self.device = device + self.fp16 = fp16 + self.nhwc = False + self.stride = 32 + self.names = {} + self.task = None + self.batch = 1 + self.channels = 3 + self.end2end = False + self.dynamic = False + self.base_model = False + self.metadata = {} + self.model = None + self.load_model(weight) + + @abstractmethod + def load_model(self, weight: str | torch.nn.Module) -> None: + """Load the model from a weights file or module instance. + + Args: + weight (str | torch.nn.Module): Path to model weights or a PyTorch module. + """ + raise NotImplementedError + + @abstractmethod + def forward(self, im: torch.Tensor) -> Any: + """Run inference on the input image tensor. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (Any): The raw output from the model's forward pass, which may require post-processing. + """ + raise NotImplementedError + + def __call__(self, *args, **kwargs) -> Any: + """Allow the backend instance to be called directly to perform inference, forwarding arguments to the `forward` + method. + """ + return self.forward(*args, **kwargs) + + @staticmethod + def engine_header(file: str | Path) -> tuple[int, dict]: + """Read the metadata header an Ultralytics ``.engine`` export writes ahead of its serialized engine. + + Args: + file (str | Path): Path to the TensorRT engine file. + + Returns: + (tuple[int, dict]): Byte offset of the engine bytes and the header metadata, ``(0, {})`` without a header. + """ + with open(file, "rb") as f: + n = int.from_bytes(f.read(4), byteorder="little") # 4-byte little-endian JSON length, if a header exists + if 0 < n <= f.seek(0, 2) - 4: # a length overrunning the file is not a header + f.seek(4) + with contextlib.suppress(ValueError): # engine bytes are not JSON, so a real header parses + return 4 + n, json.loads(f.read(n)) + return 0, {} + + @staticmethod + def read_metadata(file: str | Path) -> dict: + """Read Ultralytics metadata from an export without loading it or importing its framework. + + Single-file formats embed metadata in a length-prefixed JSON header (``.engine``), a zip entry + (``.torchscript``, ``.tflite``) or protobuf string map entries (``.onnx``, ``.mlpackage``), and every other + format writes a ``metadata.yaml`` sidecar beside or inside the export. Core AI has its own + ``metadata.json`` inside the ``.aimodel`` asset. MNN keeps it in a flatbuffer + ``bizCode`` field and Triton serves it over HTTP, so neither is read here. + + Args: + file (str | Path): Path to an exported model file or directory. + + Returns: + (dict): Parsed metadata, empty for a third-party export or one predating metadata embedding. + """ + import zipfile + + p = Path(file) + try: + if p.suffix == ".engine": # 4-byte little-endian length then that many bytes of JSON + return BaseBackend.engine_header(p)[1] + if p.suffix in {".tflite", ".torchscript"}: # metadata appended to or saved inside the model zip + with zipfile.ZipFile(p) as z: + names = z.namelist() + if "metadata.json" in names: # litert-torch and single-file tflite exports + return json.loads(z.read("metadata.json")) + name = next((n for n in names if n.endswith("extra/config.txt")), None) # torch.jit extra file + return json.loads(z.read(name)) if name else ast.literal_eval(z.read(names[0]).decode()) + if p.suffix == ".onnx" or p.name.endswith("_imx_model"): # IMX packages its ONNX in a directory + return _read_proto_map(next(p.glob("*.onnx")) if p.is_dir() else p, (14,)) # metadata_props + if p.suffix in {".mlpackage", ".mlmodel"}: # description.metadata.userDefined + return _read_proto_map(next(p.rglob("*.mlmodel")) if p.is_dir() else p, (2, 100, 100)) + if p.suffix == ".aimodel": # Core AI keeps it in the asset's own metadata.json + return json.loads((p / "metadata.json").read_text()).get("creatorDefinedMetadata", {}) + sidecar = (p if p.is_dir() else p.parent) / "metadata.yaml" # openvino, ncnn, paddle, saved_model, ... + if p.suffix == ".pb": # a frozen graph keeps its metadata in the sibling saved_model directory + sidecar = next(p.resolve().parent.rglob(f"{p.stem}_saved_model*/metadata.yaml"), sidecar) + return YAML.load(sidecar) if sidecar.exists() else {} + except Exception: # a third-party, truncated or metadata-less artifact + return {} + + def apply_metadata(self, metadata: dict | None) -> None: + """Process and apply model metadata to backend attributes. + + Handles type conversions for common metadata fields (e.g., stride, batch, names) and sets them as + instance attributes. Also resolves end-to-end NMS and dynamic shape settings from export args. + + Args: + metadata (dict | None): Dictionary containing metadata key-value pairs from model export. + """ + if not metadata: + return + + # Store raw metadata + self.metadata = metadata + + # Process type conversions for known fields + for k, v in metadata.items(): + if k in {"stride", "batch", "channels"}: + metadata[k] = int(v) + elif k in {"imgsz", "names", "kpt_shape", "kpt_names", "args", "end2end"} and isinstance(v, str): + metadata[k] = ast.literal_eval(v) + + # Handle models exported with end-to-end NMS + metadata["end2end"] = bool(metadata.get("end2end", False) or metadata.get("args", {}).get("nms", False)) + metadata["dynamic"] = metadata.get("args", {}).get("dynamic", self.dynamic) + + # Apply all metadata fields as backend attributes + for k, v in metadata.items(): + setattr(self, k, v) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/coreai.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/coreai.py new file mode 100644 index 0000000000000000000000000000000000000000..1cbdf9abfb0983d00a2ea76b96b8999df37c9f9c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/coreai.py @@ -0,0 +1,64 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import asyncio +from pathlib import Path + +import torch + +from ultralytics.utils import LOGGER +from ultralytics.utils.checks import check_requirements + +from .base import BaseBackend + + +class CoreAIBackend(BaseBackend): + """Apple Core AI inference backend for macOS 26+ on Apple silicon. + + Loads a `.aimodel` asset and runs it through the Core AI runtime. That runtime's Python API is async, so this + backend owns a private event loop and drives every call through it. + """ + + def load_model(self, weight: str | Path) -> None: + """Load a Core AI `.aimodel` asset. + + Args: + weight (str | Path): Path to the `.aimodel` asset directory. + """ + LOGGER.info(f"Loading {weight} for Apple Core AI inference...") + check_requirements("coreai-torch>=0.4.2") + from coreai.runtime import AIModel + + w = Path(weight) + self._loop = asyncio.new_event_loop() + model = self._loop.run_until_complete(_await(AIModel.load(w))) + self._function = self._loop.run_until_complete(_await(model.load_function("main"))) + descriptor = self._function.desc + self._input_name = descriptor.input_names[0] + self._output_names = list(descriptor.output_names) + self.fp16 = "float16" in str(descriptor.input_descriptor(self._input_name).dtype) + self.apply_metadata(self.read_metadata(w)) + + def forward(self, im: torch.Tensor) -> list: + """Run inference through the Core AI runtime. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (list): Model outputs as torch tensors, in declared output order. + """ + from coreai.runtime import NDArray + + inputs = {self._input_name: NDArray(im.cpu().numpy())} + out = self._loop.run_until_complete(_await(self._function(inputs))) + values = [out[n] for n in self._output_names] if isinstance(out, dict) else list(out) + return [torch.from_numpy(v.numpy() if hasattr(v, "numpy") else v).float() for v in values] + + +async def _await(value): + """Await `value` when the runtime returned a coroutine, and pass it straight through when it did not.""" + import inspect + + return await value if inspect.isawaitable(value) else value diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/coreml.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/coreml.py new file mode 100644 index 0000000000000000000000000000000000000000..e9c4bf771f8dc9ea04c967bc4d0240299a861cc2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/coreml.py @@ -0,0 +1,84 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import torch +from PIL import Image + +from ultralytics.utils import LOGGER +from ultralytics.utils.checks import check_requirements + +from .base import BaseBackend + + +class CoreMLBackend(BaseBackend): + """CoreML inference backend for Apple hardware. + + Loads and runs inference with CoreML models (.mlpackage files) using the coremltools library. Supports both static + and dynamic input shapes and handles NMS-included model outputs. + """ + + def load_model(self, weight: str | Path) -> None: + """Load a CoreML model from a .mlpackage file. + + Args: + weight (str | Path): Path to the .mlpackage model file. + """ + check_requirements(["coremltools>=9.0", "numpy>=1.14.5,<=2.3.5"]) + import coremltools as ct + + LOGGER.info(f"Loading {weight} for CoreML inference...") + # Run on the Neural Engine (CPU_AND_NE): ~3x faster than CPU, and the default ComputeUnit.ALL / CPU_AND_GPU + # abort the process via an MPSGraph compiler bug on macOS hosts (coremltools 9.x). CPU_AND_NE needs macOS >= 13, + # so fall back to CPU_ONLY below that. CoreML inference is macOS-only, so this applies wherever the backend runs. + # Exception: RT-DETR loses FP16 accuracy and runs slower on the Neural Engine alone, so route it through ALL. + meta = self.read_metadata(weight) + default_unit = ct.ComputeUnit.ALL if meta.get("head") == "RTDETRDecoder" else ct.ComputeUnit.CPU_AND_NE + try: + self.model = ct.models.MLModel(weight, compute_units=default_unit) + except Exception: + self.model = ct.models.MLModel(weight, compute_units=ct.ComputeUnit.CPU_ONLY) + spec = self.model.get_spec() + self.input_name = spec.description.input[0].name + self.dynamic = spec.description.input[0].type.HasField("multiArrayType") + + self.apply_metadata(meta) + + def forward(self, im: torch.Tensor) -> np.ndarray | list[np.ndarray]: + """Run CoreML inference with automatic input format handling. + + Args: + im (torch.Tensor): Input image tensor in BHWC format (converted from BCHW by AutoBackend). + + Returns: + (np.ndarray | list[np.ndarray]): Model predictions as numpy array(s). + """ + im = im.cpu().numpy() + h, w = im.shape[1:3] + + if self.dynamic: + y = list(self.model.predict({self.input_name: im.transpose(0, 3, 1, 2)}).values()) + else: # static exports take one image per request: predict the batch as a list and stack the outputs + y = self.model.predict([{self.input_name: Image.fromarray((x * 255).astype("uint8"))} for x in im]) + if "confidence" in y[0]: # NMS included: zero-pad per image, return (B, n, 6) before the swap below + from ultralytics.utils.ops import xywh2xyxy + + y = [(xywh2xyxy(d["coordinates"] * [[w, h, w, h]]), d["confidence"]) for d in y] + y = [ + np.concatenate((box, conf.max(1, keepdims=True), conf.argmax(1, keepdims=True)), 1) + for box, conf in y + ] + n = max(map(len, y)) + return np.stack([np.pad(d, ((0, n - len(d)), (0, 0))) for d in y]) + arrays = [k for k, v in y[0].items() if isinstance(v, np.ndarray)] + if arrays: + y = [np.concatenate([d[k] for d in y]) for k in arrays] + else: # neuralnetwork classifiers emit only the label and a name-to-probability dict + probs = next(k for k, v in y[0].items() if isinstance(v, dict)) + y = [np.array([[d[probs][n] for n in self.names.values()] for d in y])] + if len(y) == 2 and len(y[1].shape) != 4: # segmentation model + y = list(reversed(y)) + return y diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/deepx.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/deepx.py new file mode 100644 index 0000000000000000000000000000000000000000..aa8d7e79c316bc8506ca720c5624e3d592770b99 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/deepx.py @@ -0,0 +1,70 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import torch + +from ultralytics.utils import LOGGER + +from .base import BaseBackend + + +class DeepXBackend(BaseBackend): + """DEEPX NPU inference backend for DEEPX hardware accelerators. + + Loads compiled DEEPX models (.dxnn files) and runs inference using the DEEPX DX-Runtime. + """ + + def load_model(self, weight: str | Path) -> None: + """Load a DEEPX model from a directory containing a .dxnn file. + + Args: + weight (str | Path): Path to the DEEPX model directory containing the .dxnn binary. + + Raises: + ImportError: If the ``dx_engine`` Python package is not installed. + FileNotFoundError: If no .dxnn file is found in the given directory. + """ + try: + from dx_engine import InferenceEngine + except ImportError as e: + raise ImportError( + "DEEPX inference requires the DEEPX DX-Runtime and `dx_engine` Python package. " + "See https://docs.ultralytics.com/integrations/deepx#runtime-installation for installation instructions." + ) from e + + LOGGER.info(f"Loading {weight} for DEEPX inference...") + + w = Path(weight) + found = next(w.rglob("*.dxnn"), None) + if found is None: + raise FileNotFoundError(f"No .dxnn file found in: {w}") + + self.model = InferenceEngine(str(found)) + + self.apply_metadata(self.read_metadata(found)) + + def forward(self, im: torch.Tensor) -> np.ndarray | list[np.ndarray]: + """Run inference on the DEEPX NPU. + + Converts each image from BCHW float [0, 1] to HWC uint8 [0, 255] per the DEEPX runtime contract, + runs the engine per image, then stacks outputs along the batch dimension. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (np.ndarray | list[np.ndarray]): Model predictions as a single array or list of arrays. + """ + outputs = [] + for sample in im.cpu().numpy(): + sample = np.ascontiguousarray(np.clip(np.transpose(sample, (1, 2, 0)) * 255, 0, 255).astype(np.uint8)) + for i, out in enumerate(map(np.asarray, self.model.run([sample]))): + if i == len(outputs): + outputs.append([]) + outputs[i].append(out if out.ndim and out.shape[0] == 1 else out[None]) + y = [np.concatenate(x, axis=0) for x in outputs] + return y[0] if len(y) == 1 else y diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/executorch.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/executorch.py new file mode 100644 index 0000000000000000000000000000000000000000..06d1f845b0690eafe0568a9366c6d91f924a67d6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/executorch.py @@ -0,0 +1,47 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import torch + +from ultralytics.utils import LOGGER +from ultralytics.utils.checks import check_executorch_requirements + +from .base import BaseBackend + + +class ExecuTorchBackend(BaseBackend): + """Meta ExecuTorch inference backend for on-device deployment. + + Loads and runs inference with Meta ExecuTorch models (.pte files) using the ExecuTorch runtime. Supports both + standalone .pte files and directory-based model packages with metadata. + """ + + def load_model(self, weight: str | Path) -> None: + """Load an ExecuTorch model from a .pte file or directory. + + Args: + weight (str | Path): Path to the .pte model file or directory containing the model. + """ + LOGGER.info(f"Loading {weight} for ExecuTorch inference...") + check_executorch_requirements() + + from executorch.runtime import Runtime + + w = Path(weight) + program = Runtime.get().load_program(str(next(w.rglob("*.pte")) if w.is_dir() else w)) + self.model = program.load_method("forward") + self.apply_metadata(self.read_metadata(w)) + + def forward(self, im: torch.Tensor) -> list: + """Run inference using the ExecuTorch runtime. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (list): Model predictions as a list of ExecuTorch output values. + """ + return self.model.execute([im]) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/hailo.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/hailo.py new file mode 100644 index 0000000000000000000000000000000000000000..169e88cb8963ed6fc5ac06d20fb7154b3b94237a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/hailo.py @@ -0,0 +1,206 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import math +from contextlib import ExitStack +from pathlib import Path + +import numpy as np +import torch + +from ultralytics.utils import LOGGER + +from .base import BaseBackend + + +class HailoBackend(BaseBackend): + """HailoRT inference backend for Ultralytics Hailo HEF models.""" + + def load_model(self, weight: str | Path) -> None: + """Load a Hailo export directory and its Ultralytics metadata.""" + try: + from hailo_platform import ( + HEF, + ConfigureParams, + FormatType, + HailoStreamInterface, + InferVStreams, + InputVStreamParams, + OutputVStreamParams, + VDevice, + ) + except ImportError as e: + raise ImportError( + "Hailo inference requires HailoRT. " + "See https://docs.ultralytics.com/integrations/hailo#run-hailo-inference" + ) from e + + w = Path(weight) + hef_file = next(w.rglob("*.hef"), None) + if hef_file is None or not hef_file.is_file(): + raise FileNotFoundError(f"No .hef file found in: {w}") + + LOGGER.info(f"Loading {hef_file} for Hailo inference...") + self.apply_metadata(self.read_metadata(hef_file)) + if self.task and self.task not in {"detect", "segment", "pose", "obb", "classify", "semantic", "depth"}: + raise ValueError( + f"Hailo inference only supports detect, segment, pose, obb, classify, semantic and depth tasks, " + f"not task='{self.task}'." + ) + + self.hef = HEF(str(hef_file)) + self.input_info = self.hef.get_input_vstream_infos()[0] + self.output_infos = self.hef.get_output_vstream_infos() + with ExitStack() as stack: + target = stack.enter_context(VDevice()) + configure_params = ConfigureParams.create_from_hef(self.hef, interface=HailoStreamInterface.PCIe) + network_group = target.configure(self.hef, configure_params)[0] + stack.enter_context(network_group.activate(network_group.create_params())) + input_params = InputVStreamParams.make(network_group, format_type=FormatType.UINT8) + output_params = OutputVStreamParams.make(network_group, format_type=FormatType.FLOAT32) + self.model = stack.enter_context(InferVStreams(network_group, input_params, output_params)) + self._stack = stack.pop_all() + self._anchors = None + if self.task in {"segment", "pose", "obb"}: + from ultralytics.nn.modules import DFL + + self._dfl = DFL() + self.end2end = self.end2end or self.metadata.get("nms", False) # head selection or HailoRT NMS + + def __del__(self): + """Release the Hailo pipeline and device.""" + if stack := getattr(self, "_stack", None): + stack.close() + + def forward(self, im: torch.Tensor) -> np.ndarray | list[torch.Tensor]: + """Run Hailo inference and return decoded detections, or dense outputs and prototypes for segmentation.""" + im = np.ascontiguousarray(np.clip(im.permute(0, 2, 3, 1).cpu().numpy() * 255, 0, 255).astype(np.uint8)) + results = self.model.infer({self.input_info.name: im}) + outputs = [results[x.name] for x in self.output_infos] + if self.task == "segment": + return self._decode_segment(outputs) + if self.task == "pose": + return self._decode_pose(outputs) + if self.task == "obb": + return self._decode_obb(outputs) + if self.task == "classify": + return torch.from_numpy(outputs[0]).reshape(outputs[0].shape[0], -1) # on-chip softmax probabilities + if self.task == "semantic": + out = torch.from_numpy(outputs[0]) + if self.metadata.get("semantic_baked"): + # Multi-class Hailo-10/15 baked the upsample and argmax on chip; return the class map. + return out.reshape(out.shape[0], out.shape[1], out.shape[2]) + # Hailo-8/8L and single-class heads return raw stride-8 logits; hand them to the predictor's existing + # bilinear upsample, letterbox removal, and class reduction so results match the PyTorch model exactly. + return out.permute(0, 3, 1, 2) + if self.task == "depth": + return self._decode_depth(outputs[0]) + return self._decode_raw(outputs) if not self.metadata.get("nms", False) else self._decode_nms(outputs[0]) + + def _decode_nms(self, output: list) -> np.ndarray: + """Convert Hailo per-class NMS output from normalized ``yxyx`` to pixel ``xyxy`` coordinates.""" + height, width = self.input_info.shape[:2] + scale = np.array([width, height, width, height], dtype=np.float32) + frames = [] + for detections in output: + rows = [] + for class_id, class_detections in enumerate(detections): + if len(class_detections): + class_detections = np.asarray(class_detections) + boxes = class_detections[:, [1, 0, 3, 2]] * scale + classes = np.full((len(boxes), 1), class_id, dtype=np.float32) + rows.append(np.concatenate((boxes, class_detections[:, 4:5], classes), axis=1)) + frame = np.concatenate(rows) if rows else np.empty((0, 6), dtype=np.float32) + frames.append(frame[np.argsort(-frame[:, 4])[:300]]) + count = max(map(len, frames), default=0) + predictions = np.zeros((len(frames), count, 6), dtype=np.float32) + for i, frame in enumerate(frames): + predictions[i, : len(frame)] = frame + return predictions + + def _decode_boxes(self, reg_maps: list[torch.Tensor], angle: torch.Tensor | None = None) -> torch.Tensor: + """Run DFL and box decoding on cached anchors, returning (B, A, 4) xywh boxes (rotated if angle given).""" + from ultralytics.utils.tal import dist2bbox, dist2rbox, make_anchors + + if self._anchors is None: + strides = [self.input_info.shape[0] / m.shape[2] for m in reg_maps] + self._anchors = make_anchors(reg_maps, strides) + anchors, stride_tensor = self._anchors + dist = self._dfl(torch.cat([m.flatten(2) for m in reg_maps], 2)).transpose(1, 2) + if angle is not None: + return dist2rbox(dist, angle, anchors) * stride_tensor + return dist2bbox(dist, anchors, xywh=True) * stride_tensor + + def _decode_segment(self, outputs: list[np.ndarray]) -> list[torch.Tensor]: + """Decode raw segmentation tensors (reg, cls, coeff per scale + prototypes) for the predictor's NMS.""" + proto = torch.from_numpy(outputs[-1]).permute(0, 3, 1, 2) + k = len(outputs) - 1 + reg_maps = [torch.from_numpy(x).permute(0, 3, 1, 2) for x in outputs[0:k:3]] + cls_maps = [torch.from_numpy(x).permute(0, 3, 1, 2) for x in outputs[1:k:3]] + cof_maps = [torch.from_numpy(x).permute(0, 3, 1, 2) for x in outputs[2:k:3]] + boxes = self._decode_boxes(reg_maps) + cls = torch.cat([x.flatten(2) for x in cls_maps], 2).transpose(1, 2) # sigmoid baked in at export + cof = torch.cat([x.flatten(2) for x in cof_maps], 2).transpose(1, 2) + return [torch.cat((boxes, cls, cof), 2).transpose(1, 2), proto] + + def _decode_pose(self, outputs: list[np.ndarray]) -> torch.Tensor: + """Decode raw pose tensors (reg, cls, kpt per scale) into the dense output the predictor's NMS expects.""" + maps = [torch.from_numpy(x).permute(0, 3, 1, 2) for x in outputs] + reg_maps, cls_maps, kpt_maps = maps[0::3], maps[1::3], maps[2::3] + boxes = self._decode_boxes(reg_maps) + anchors, stride_tensor = self._anchors + cls = torch.cat([m.flatten(2) for m in cls_maps], 2).transpose(1, 2) # sigmoid baked in at export + kpts = torch.cat([m.flatten(2) for m in kpt_maps], 2).transpose(1, 2) # (B, A, nk) raw + n_kpt, ndim = self.kpt_shape + b, a, _ = kpts.shape + y = kpts.view(b, a, n_kpt, ndim) + # Pose.kpts_decode: xy = (raw * 2 + (anchor - 0.5)) * stride; visibility sigmoid is applied on the host + xy = (y[..., :2] * 2.0 + (anchors.view(a, 1, 2) - 0.5)) * stride_tensor.view(a, 1, 1) + kpts = torch.cat((xy, y[..., 2:3].sigmoid()), -1) if ndim == 3 else xy + return torch.cat((boxes, cls, kpts.view(b, a, -1)), 2).transpose(1, 2) + + def _decode_obb(self, outputs: list[np.ndarray]) -> torch.Tensor: + """Decode raw OBB tensors (reg, cls, angle per scale) into the dense output the rotated NMS expects.""" + maps = [torch.from_numpy(x).permute(0, 3, 1, 2) for x in outputs] + reg_maps, cls_maps, ang_maps = maps[0::3], maps[1::3], maps[2::3] + angle = torch.cat([m.flatten(2) for m in ang_maps], 2).transpose(1, 2) # (B, A, 1) raw + angle = (angle.sigmoid() - 0.25) * math.pi # OBB head angle squash, applied on the host + boxes = self._decode_boxes(reg_maps, angle) # rotated xywh + cls = torch.cat([m.flatten(2) for m in cls_maps], 2).transpose(1, 2) # sigmoid baked in at export + return torch.cat((boxes, cls, angle), 2).transpose(1, 2) + + def _decode_raw(self, outputs: list[np.ndarray]) -> np.ndarray: + """Decode branch-first YOLO26 regression and class outputs.""" + from ultralytics.utils.tal import dist2bbox, make_anchors + + split = len(outputs) // 2 + box_maps = [torch.from_numpy(x).permute(0, 3, 1, 2) for x in outputs[:split]] + cls_maps = [torch.from_numpy(x).permute(0, 3, 1, 2) for x in outputs[split:]] + if self._anchors is None: + strides = [self.input_info.shape[0] / x.shape[2] for x in box_maps] + self._anchors = make_anchors(box_maps, strides) + anchors, stride_tensor = self._anchors + boxes = torch.cat([x.flatten(2) for x in box_maps], 2).transpose(1, 2) + boxes = dist2bbox(boxes, anchors, xywh=not self.end2end) * stride_tensor + scores = torch.cat([x.flatten(2) for x in cls_maps], 2).transpose(1, 2).sigmoid() + if not self.end2end: + return torch.cat((boxes, scores), 2).transpose(1, 2).numpy() + classes = scores.shape[2] + anchor_index = scores.amax(-1).topk(min(300, scores.shape[1]), dim=1).indices[..., None] + boxes = boxes.gather(1, anchor_index.expand(-1, -1, 4)) + scores = scores.gather(1, anchor_index.expand(-1, -1, classes)) + scores, index = scores.flatten(1).topk(min(300, scores.shape[1] * classes), dim=1) + boxes = boxes.gather(1, (index // classes)[..., None].expand(-1, -1, 4)) + return torch.cat((boxes, scores[..., None], (index % classes)[..., None].float()), 2).numpy() + + def _decode_depth(self, output: np.ndarray) -> torch.Tensor: + """Decode the raw depth logit into a metric depth map, mirroring ``Depth.forward`` on the host. + + The HEF is cut at the head's final logit conv, so the clamp/exp and learned log-affine calibration that + follow it in the head run here. The map stays at head resolution (H/4, W/4); ``DepthPredictor.postprocess`` + resizes it to the image with ``scale_masks``, the same path the PyTorch model takes at inference. + """ + logit = torch.from_numpy(output).permute(0, 3, 1, 2) # (B, H/4, W/4, 1) -> (B, 1, H/4, W/4) + depth = logit.clamp(-4.0, 5.0).exp() + return depth.pow(self.metadata.get("cal_a", 1.0)) * math.exp(self.metadata.get("cal_b", 0.0)) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/litert.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/litert.py new file mode 100644 index 0000000000000000000000000000000000000000..674841664df05e533fe68dc40c72d901676e64d1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/litert.py @@ -0,0 +1,110 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import torch + +from ultralytics.utils import LOGGER, NUM_THREADS +from ultralytics.utils.checks import check_requirements + +from .base import BaseBackend + + +class LiteRTBackend(BaseBackend): + """Google LiteRT (formerly TensorFlow Lite) inference backend. + + Loads and runs inference with LiteRT models (.tflite files) exported via ai-edge-litert/litert-torch. Ultralytics + exports keep float graph I/O (weights/activations may be int8/int16 internally); full-integer .tflite (legacy + onnx2tf or third-party) with int8/int16 graph I/O are also handled by (de)quantizing at the boundary. Box and + keypoint coordinates are denormalized by image size. + """ + + def load_model(self, weight: str | Path) -> None: + """Load a LiteRT model from a .tflite file. + + Args: + weight (str | Path): Path to the .tflite model file (metadata embedded as a metadata.json entry). + """ + check_requirements("ai-edge-litert>=2.1.4") + from ai_edge_litert.interpreter import Interpreter + + tflite_file = Path(weight) + + LOGGER.info(f"Loading {tflite_file} for LiteRT inference...") + self.interpreter = Interpreter(str(tflite_file), num_threads=NUM_THREADS) # Enable multi-core inference + self.interpreter.allocate_tensors() + self.input_details = self.interpreter.get_input_details() + self.output_details = self.interpreter.get_output_details() + # Legacy onnx2tf TFLite exports are NHWC; litert-torch exports are NCHW. Detect from the input tensor so both + # load through this backend (the detection/proto outputs share the same layout for either export path). + self.nhwc = self.input_details[0]["shape"][-1] == 3 + + self.apply_metadata(self.read_metadata(tflite_file)) + + def forward(self, im: torch.Tensor) -> list[np.ndarray]: + """Run inference using the LiteRT interpreter. + + Box and pose keypoint coordinates are exported normalized to [0, 1] (so INT8 quantization preserves class + score resolution) and denormalized here by the input image size, mirroring the TensorFlow Lite backend. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (list[np.ndarray]): Model predictions as a list of numpy arrays. + """ + im = im.cpu().numpy() # BCHW + if self.nhwc: + im = im.transpose(0, 2, 3, 1) # BCHW to BHWC for legacy onnx2tf TFLite + h, w = im.shape[1:3] if self.nhwc else im.shape[2:4] + details = self.input_details[0] + # Ultralytics exports keep float I/O, but quantize here too for full-integer .tflite (legacy onnx2tf or + # third-party) whose graph input is int8/int16. + if details["dtype"] in {np.int8, np.int16}: + scale, zero_point = details["quantization"] + im = (im / scale + zero_point).astype(details["dtype"]) + self.interpreter.set_tensor(details["index"], im) + self.interpreter.invoke() + + kpt_start = 4 + len(self.names) # pose keypoints follow the box (4) and class-score (nc) channels + y = [] + for output in self.output_details: + x = self.interpreter.get_tensor(output["index"]) + if self.task == "semantic" and x.ndim == 3: + # Legacy onnx2tf baked argmax class map [B, H, W] of integer IDs: skip xywh denorm, which would + # corrupt and overflow the indices. + y.append(x) + continue + if output["dtype"] in {np.int8, np.int16}: # dequantize full-integer .tflite outputs (see input note) + scale, zero_point = output["quantization"] + x = (x.astype(np.float32) - zero_point) * scale + # Denormalize xywh (and pose keypoints) by image size. litert-torch end2end output is already post-NMS + # pixel coordinates (batch, max_det, 6+), so it is left as-is; legacy onnx2tf TFLite normalizes even the + # end2end output, so it is denormalized on the last axis. + if x.ndim == 3 and not self.end2end and getattr(self, "head", None) != "RTDETRDecoder": + x[:, [0, 2]] *= w + x[:, [1, 3]] *= h + if self.task == "pose": + x[:, kpt_start::3] *= w + x[:, kpt_start + 1 :: 3] *= h + elif x.ndim == 3 and self.end2end and self.nhwc: + x[:, :, [0, 2]] *= w + x[:, :, [1, 3]] *= h + if self.task == "pose": # post-NMS [B, N, box(4)+conf+cls+kpts], keypoints start at 6 + x[:, :, 6::3] *= w + x[:, :, 7::3] *= h + y.append(x) + + if self.task == "segment" and y[0].ndim == 4: # order as (detections, protos) + y = [y[1], y[0]] + # litert-torch exports are NCHW; legacy onnx2tf masks/logits are NHWC and need a channels-last→first transpose. + if self.nhwc: + if self.task == "segment" and len(y) > 1 and y[1].ndim == 4: + y[1] = np.transpose(y[1], (0, 3, 1, 2)) # protos NHWC → NCHW + elif self.task in {"semantic", "depth"} and len(y) == 1 and y[0].ndim == 4: + y[0] = np.transpose(y[0], (0, 3, 1, 2)) # logits NHWC → NCHW + + return y diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/mnn.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/mnn.py new file mode 100644 index 0000000000000000000000000000000000000000..1282b66fe182be47687ab49aca3965fbcd959da3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/mnn.py @@ -0,0 +1,64 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import json +import os +from pathlib import Path + +import numpy as np +import torch + +from ultralytics.utils import LOGGER +from ultralytics.utils.checks import check_requirements + +from .base import BaseBackend + + +class MNNBackend(BaseBackend): + """MNN (Mobile Neural Network) inference backend. + + Loads and runs inference with MNN models (.mnn files) using the Alibaba MNN framework. Optimized for mobile and edge + deployment with configurable thread count and precision. + """ + + def load_model(self, weight: str | Path) -> None: + """Load an Alibaba MNN model from a .mnn file. + + Args: + weight (str | Path): Path to the .mnn model file. + """ + LOGGER.info(f"Loading {weight} for MNN inference...") + check_requirements("MNN") + import MNN + + config = {"precision": "low", "backend": "CPU", "numThread": (os.cpu_count() + 1) // 2} + rt = MNN.nn.create_runtime_manager((config,)) + self.net = MNN.nn.load_module_from_file(weight, [], [], runtime_manager=rt, rearrange=True) + self.expr = MNN.expr + + # Load metadata from bizCode + info = self.net.get_info() + if "bizCode" in info: + try: + self.apply_metadata(json.loads(info["bizCode"])) + except json.JSONDecodeError: + pass + + def forward(self, im: torch.Tensor) -> list: + """Run inference using the MNN runtime. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (list): Model predictions as a list of numpy arrays. + """ + input_var = self.expr.const(im.data_ptr(), im.shape) + output_var = self.net.onForward([input_var]) + # NOTE: need this copy(), or it'd get incorrect results on ARM devices + if output_var: + return [x.read().copy() for x in output_var] + if self.metadata.get("args", {}).get("nms") and self.task in {"detect", "pose"}: + return [np.empty((im.shape[0], 0, 6))] + raise RuntimeError("Alibaba MNN inference returned no output tensors.") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/ncnn.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/ncnn.py new file mode 100644 index 0000000000000000000000000000000000000000..61d34a5d16165c33059dc8297d45b6cc3b912d38 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/ncnn.py @@ -0,0 +1,68 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import torch + +from ultralytics.utils import LOGGER +from ultralytics.utils.checks import check_requirements + +from .base import BaseBackend + + +class NCNNBackend(BaseBackend): + """Tencent NCNN inference backend for mobile and embedded deployment. + + Loads and runs inference with Tencent NCNN models (*_ncnn_model/ directories). Optimized for mobile platforms with + optional Vulkan GPU acceleration when available. + """ + + def load_model(self, weight: str | Path) -> None: + """Load an NCNN model from a .param/.bin file pair or model directory. + + Args: + weight (str | Path): Path to the .param file or directory containing NCNN model files. + """ + LOGGER.info(f"Loading {weight} for NCNN inference...") + check_requirements("ncnn", cmds="--no-deps") + import ncnn as pyncnn + + self.pyncnn = pyncnn + self.net = pyncnn.Net() + + # Setup Vulkan if available + if isinstance(self.device, str) and self.device.startswith("vulkan"): + self.net.opt.use_vulkan_compute = True + self.net.set_vulkan_device(int(self.device.split(":")[1])) + self.device = torch.device("cpu") + else: + self.net.opt.use_vulkan_compute = False + + w = Path(weight) + if not w.is_file(): + w = next(w.glob("*.param")) + + self.net.load_param(str(w)) + self.net.load_model(str(w.with_suffix(".bin"))) + + self.apply_metadata(self.read_metadata(w)) + + def forward(self, im: torch.Tensor) -> list[np.ndarray]: + """Run inference using the NCNN runtime. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (list[np.ndarray]): Model predictions as a list of numpy arrays, one per output layer. + """ + outputs = [] + for sample in im.cpu().numpy(): + with self.net.create_extractor() as ex: + ex.input(self.net.input_names()[0], self.pyncnn.Mat(sample)) + # Sort output names as temporary fix for pnnx issue + outputs.append([np.array(ex.extract(x)[1]) for x in sorted(self.net.output_names())]) + return [np.stack(y) for y in zip(*outputs)] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/onnx.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..20ad7f1b9978e98e5daa4b621062026918f88138 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/onnx.py @@ -0,0 +1,225 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import torch + +from ultralytics.utils import LOGGER +from ultralytics.utils.checks import check_requirements + +from .base import BaseBackend + +# ONNX Runtime output type string -> (torch dtype, numpy dtype) for IO binding. +_ORT_DTYPES = { + "tensor(float16)": (torch.float16, np.float16), + "tensor(float)": (torch.float32, np.float32), + "tensor(double)": (torch.float64, np.float64), + "tensor(uint8)": (torch.uint8, np.uint8), + "tensor(int8)": (torch.int8, np.int8), + "tensor(int32)": (torch.int32, np.int32), + "tensor(int64)": (torch.int64, np.int64), +} + + +class ONNXBackend(BaseBackend): + """Microsoft ONNX Runtime inference backend with optional OpenCV DNN support. + + Loads and runs inference with ONNX models (.onnx files) using either Microsoft ONNX Runtime with CUDA/CoreML + execution providers, or OpenCV DNN for lightweight CPU inference. Supports IO binding for optimized GPU inference + with static input shapes. + """ + + def __init__( + self, + weight: str | Path, + device: torch.device, + fp16: bool = False, + format: str = "onnx", + session_options: object | None = None, + ): + """Initialize the ONNX backend. + + Args: + weight (str | Path): Path to the .onnx model file. + device (torch.device): Device to run inference on. + fp16 (bool): Whether to use FP16 half-precision inference. + format (str): Inference engine, either "onnx" for ONNX Runtime or "dnn" for OpenCV DNN. + session_options (object | None): Optional ONNX Runtime session options. + """ + assert format in {"onnx", "dnn"}, f"Unsupported ONNX format: {format}." + self.format = format + self.session_options = session_options + super().__init__(weight, device, fp16) + + def load_model(self, weight: str | Path) -> None: + """Load an ONNX model using ONNX Runtime or OpenCV DNN. + + Args: + weight (str | Path): Path to the .onnx model file. + """ + cuda = isinstance(self.device, torch.device) and torch.cuda.is_available() and self.device.type != "cpu" + + self.apply_metadata(self.read_metadata(weight)) + + if self.format == "dnn": + # OpenCV DNN + LOGGER.info(f"Loading {weight} for ONNX OpenCV DNN inference...") + import cv2 + + self.net = cv2.dnn.readNetFromONNX(weight) + else: + # ONNX Runtime + LOGGER.info(f"Loading {weight} for ONNX Runtime inference...") + check_requirements(("onnx", "onnxruntime-gpu" if cuda else "onnxruntime")) + import onnxruntime + + # Select execution provider + available = onnxruntime.get_available_providers() + if cuda and "CUDAExecutionProvider" in available: + providers = [("CUDAExecutionProvider", {"device_id": self.device.index}), "CPUExecutionProvider"] + elif self.device.type == "mps" and "CoreMLExecutionProvider" in available: + providers = ["CoreMLExecutionProvider", "CPUExecutionProvider"] + else: + providers = ["CPUExecutionProvider"] + + LOGGER.info( + f"Using ONNX Runtime {onnxruntime.__version__} with " + f"{providers[0] if isinstance(providers[0], str) else providers[0][0]}" + ) + + try: + self.session = onnxruntime.InferenceSession(weight, self.session_options, providers=providers) + except onnxruntime.capi.onnxruntime_pybind11_state.InvalidProtobuf as e: + # ONNX Runtime reports an unparsable graph as a raw protobuf error naming neither the problem + # nor a remedy. Only this one type is caught: other load failures are execution-provider or + # model-support issues, where the runtime's own message is the useful one. + raise TypeError( + f"ERROR ❌️ {weight} is not a loadable ONNX model — the file is empty, truncated or corrupted " + f"({type(e).__name__}: {e}).\nRecommend fixes are to re-export it with " + f"'yolo export model=yolo26n.pt format=onnx', or to re-download the file." + ) from e + if cuda and "CUDAExecutionProvider" not in self.session.get_providers(): + LOGGER.warning("CUDA requested but CUDAExecutionProvider not available. Using CPU...") + self.device = torch.device("cpu") + cuda = False + self.output_names = [x.name for x in self.session.get_outputs()] + + # Check if dynamic shapes + self.dynamic = isinstance(self.session.get_outputs()[0].shape[0], str) + self.fp16 = "float16" in self.session.get_inputs()[0].type + + # Setup IO binding for CUDA + self.use_io_binding = not self.dynamic and cuda + if self.use_io_binding: + self.io = self.session.io_binding() + self.bindings = [] + for output in self.session.get_outputs(): + torch_dtype, np_dtype = _ORT_DTYPES.get(output.type, (torch.float32, np.float32)) + y_tensor = torch.empty(output.shape, dtype=torch_dtype).to(self.device) + self.io.bind_output( + name=output.name, + device_type=self.device.type, + device_id=self.device.index if cuda else 0, + element_type=np_dtype, + shape=tuple(y_tensor.shape), + buffer_ptr=y_tensor.data_ptr(), + ) + self.bindings.append(y_tensor) + + def forward( + self, im: torch.Tensor | dict[str, torch.Tensor | np.ndarray] + ) -> torch.Tensor | list[torch.Tensor] | np.ndarray: + """Run ONNX inference using IO binding (CUDA) or standard session execution. + + Args: + im (torch.Tensor | dict): Input image tensor in BCHW format, normalized to [0, 1], or a dictionary mapping + input names to tensors/arrays for multi-input ONNX Runtime models. + + Returns: + (torch.Tensor | list[torch.Tensor] | np.ndarray): Model predictions as tensor(s) or numpy array(s). + """ + if self.format == "dnn": + # OpenCV DNN + self.net.setInput(im.cpu().numpy()) + return self.net.forward() + + # ONNX Runtime + if isinstance(im, dict): # multi-input model + im = {k: v.cpu().numpy() if isinstance(v, torch.Tensor) else v for k, v in im.items()} + return self.session.run(self.output_names, im) + + if self.use_io_binding: + if self.device.type == "cpu": + im = im.cpu() + self.io.bind_input( + name="images", + device_type=im.device.type, + device_id=im.device.index if im.device.type == "cuda" else 0, + element_type=np.float16 if self.fp16 else np.float32, + shape=tuple(im.shape), + buffer_ptr=im.data_ptr(), + ) + self.session.run_with_iobinding(self.io) + return self.bindings + else: + return self.session.run(self.output_names, {self.session.get_inputs()[0].name: im.cpu().numpy()}) + + +class ONNXIMXBackend(ONNXBackend): + """ONNX IMX inference backend for NXP i.MX processors. + + Extends `ONNXBackend` with support for quantized models targeting NXP i.MX edge devices. Uses MCT (Model Compression + Toolkit) quantizers and custom NMS operations for optimized inference. + """ + + def load_model(self, weight: str | Path) -> None: + """Load a quantized ONNX model from an IMX model directory. + + Args: + weight (str | Path): Path to the IMX model directory containing the .onnx file. + """ + check_requirements(("model-compression-toolkit>=2.4.1", "edge-mdt-cl<1.1.0", "onnxruntime-extensions")) + check_requirements(("onnx", "onnxruntime")) + import mct_quantizers as mctq + import onnxruntime + from edgemdt_cl.pytorch.nms import nms_ort # noqa - register custom NMS ops + + w = Path(weight) + onnx_file = next(w.glob("*.onnx")) + LOGGER.info(f"Loading {onnx_file} for ONNX IMX inference...") + + session_options = mctq.get_ort_session_options() + session_options.enable_mem_reuse = False + + self.session = onnxruntime.InferenceSession(onnx_file, session_options, providers=["CPUExecutionProvider"]) + self.output_names = [x.name for x in self.session.get_outputs()] + self.dynamic = isinstance(self.session.get_outputs()[0].shape[0], str) + self.fp16 = "float16" in self.session.get_inputs()[0].type + self.apply_metadata(self.read_metadata(w)) + + def forward(self, im: torch.Tensor) -> np.ndarray | list[np.ndarray] | tuple[np.ndarray, ...]: + """Run IMX inference with task-specific output concatenation for detect, pose, and segment tasks. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (np.ndarray | list[np.ndarray] | tuple[np.ndarray, ...]): Task-formatted model predictions. + """ + y = self.session.run(self.output_names, {self.session.get_inputs()[0].name: im.cpu().numpy()}) + + if self.task == "detect": + # boxes, conf, cls + return np.concatenate([y[0], y[1][:, :, None], y[2][:, :, None]], axis=-1) + elif self.task == "pose": + # boxes, conf, kpts + return np.concatenate([y[0], y[1][:, :, None], y[2][:, :, None], y[3]], axis=-1, dtype=y[0].dtype) + elif self.task == "segment": + return ( + np.concatenate([y[0], y[1][:, :, None], y[2][:, :, None], y[3]], axis=-1, dtype=y[0].dtype), + y[4], + ) + return y diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/openvino.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/openvino.py new file mode 100644 index 0000000000000000000000000000000000000000..643d6d6f7289bbbf41dae4554d990b80eed730ba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/openvino.py @@ -0,0 +1,135 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from functools import partial +from pathlib import Path + +import numpy as np +import torch + +from ultralytics.utils import ARM64, LINUX, LOGGER, WINDOWS +from ultralytics.utils.checks import check_requirements + +from .base import BaseBackend + + +class OpenVINOBackend(BaseBackend): + """Intel OpenVINO inference backend for Intel hardware acceleration. + + Loads and runs inference with Intel OpenVINO IR models (*_openvino_model/ directories). Supports automatic device + selection and Intel-specific device targeting. + """ + + def load_model(self, weight: str | Path) -> None: + """Load an Intel OpenVINO IR model from a .xml/.bin file pair or model directory. + + Args: + weight (str | Path): Path to the .xml file or directory containing OpenVINO model files. + """ + LOGGER.info(f"Loading {weight} for OpenVINO inference...") + check_requirements("openvino>=2024.0.0") + import openvino as ov + + core = ov.Core() + if WINDOWS: # Avoid reduced-precision CPU kernel failures without restricting native FP32 instructions + core.set_property("CPU", {"INFERENCE_PRECISION_HINT": ov.Type.f32}) + fallback_device = "CPU" if core.available_devices == ["CPU"] else "AUTO" + device_name = fallback_device + + if isinstance(self.device, str) and self.device.startswith("intel"): + device_name = self.device.split(":")[1].upper() + self.device = torch.device("cpu") + if not any(d == device_name or d.startswith(f"{device_name}.") for d in core.available_devices): + LOGGER.warning(f"OpenVINO device '{device_name}' not available. Using '{fallback_device}' instead.") + device_name = fallback_device + + w = Path(weight) + if not w.is_file(): + w = next(w.glob("*.xml")) + + ov_model = core.read_model(model=str(w), weights=w.with_suffix(".bin")) + if ov_model.get_parameters()[0].get_layout().empty: + ov_model.get_parameters()[0].set_layout(ov.Layout("NCHW")) + + self.apply_metadata(self.read_metadata(w)) + + # OpenVINO CPU plugin segfaults running INT8 models with dynamic shapes on Intel AMX CPUs (Sapphire Rapids and + # newer), see https://github.com/openvinotoolkit/openvino/issues/37577, so run those as static models by + # reshaping and recompiling per input shape in forward() instead + cpuinfo = Path("/proc/cpuinfo") + self.read_model = ( + partial(core.read_model, model=str(w), weights=w.with_suffix(".bin")) + if LINUX + and device_name in {"CPU", "AUTO"} + and ov_model.input().get_partial_shape().is_dynamic + and any(op.get_type_name() == "FakeQuantize" for op in ov_model.get_ops()) + and cpuinfo.exists() + and "amx_int8" in cpuinfo.read_text() + else None + ) + if self.read_model is not None: + self.dynamic = False # fixed letterbox shapes so recompiles stay rare + + # Force sync inference because AsyncInferQueue can hang indefinitely on Intel and AMD CPUs, see + # https://github.com/ultralytics/ultralytics/issues/25923. + self.inference_mode = "LATENCY" + config = {"PERFORMANCE_HINT": self.inference_mode} + if LINUX and ARM64 and device_name == "CPU": + config["EXECUTION_MODE_HINT"] = ov.properties.hint.ExecutionMode.ACCURACY + config["INFERENCE_PRECISION_HINT"] = ov.Type.f32 + if ( + self.task == "classify" + and device_name.startswith("NPU") + and "NPU_TURBO" in core.get_property(device_name, "SUPPORTED_PROPERTIES") + ): + config["NPU_TURBO"] = "YES" + + self.compile_model = partial(core.compile_model, device_name=device_name, config=config) + self.ov_compiled_model = self.compile_model(ov_model) + LOGGER.info( + f"Using OpenVINO {self.inference_mode} mode for batch={self.batch} inference on " + f"{', '.join(self.ov_compiled_model.get_property('EXECUTION_DEVICES'))}..." + ) + self.input_name = self.ov_compiled_model.input().get_any_name() + self.ov = ov + + def forward(self, im: torch.Tensor) -> list[np.ndarray]: + """Run Intel OpenVINO inference. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (list[np.ndarray]): Model predictions as a list of numpy arrays, one per output layer. + """ + im = im.cpu().numpy().astype(np.float32, copy=False) + if self.read_model is not None and self.ov_compiled_model.input().get_partial_shape() != self.ov.PartialShape( + im.shape + ): + ov_model = self.read_model() + ov_model.reshape(list(im.shape)) + self.ov_compiled_model = self.compile_model(ov_model) + + if self.inference_mode in {"THROUGHPUT", "CUMULATIVE_THROUGHPUT"}: + # Async inference for larger batch sizes + n = im.shape[0] + results = [None] * n + + def callback(request, userdata): + """Store async inference result in the preallocated results list at the given index.""" + results[userdata] = request.results + + async_queue = self.ov.AsyncInferQueue(self.ov_compiled_model) + async_queue.set_callback(callback) + + for i in range(n): + async_queue.start_async(inputs={self.input_name: im[i : i + 1]}, userdata=i) + async_queue.wait_all() + + y = [list(r.values()) for r in results] + y = [np.concatenate(x) for x in zip(*y)] + else: + # Sync inference for LATENCY mode + y = list(self.ov_compiled_model(im).values()) + return y diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/paddle.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/paddle.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6ab325af490cf84cd20ebadeb2b0c8a3cd7b58 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/paddle.py @@ -0,0 +1,74 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import torch + +from ultralytics.utils import ARM64, LOGGER +from ultralytics.utils.checks import check_requirements + +from .base import BaseBackend + + +class PaddleBackend(BaseBackend): + """Baidu PaddlePaddle inference backend. + + Loads and runs inference with Baidu PaddlePaddle models (*_paddle_model/ directories). Supports both CPU and GPU + execution with automatic device configuration and memory pool initialization. + """ + + def load_model(self, weight: str | Path) -> None: + """Load a Baidu PaddlePaddle model from a directory containing .json and .pdiparams files. + + Args: + weight (str | Path): Path to the model directory or .pdiparams file. + """ + cuda = isinstance(self.device, torch.device) and torch.cuda.is_available() and self.device.type != "cpu" + LOGGER.info(f"Loading {weight} for PaddlePaddle inference...") + if cuda: + check_requirements("paddlepaddle-gpu>=3.0.0,<3.3.0") + elif ARM64: + check_requirements("paddlepaddle==3.0.0") + else: + check_requirements("paddlepaddle>=3.0.0,<3.3.0") + + import paddle.inference as pdi + + w = Path(weight) + model_file, params_file = None, None + + if w.is_dir(): + model_file = next(w.rglob("*.json"), None) + params_file = next(w.rglob("*.pdiparams"), None) + elif w.suffix == ".pdiparams": + model_file = w.with_name("model.json") + params_file = w + + if not (model_file and params_file and model_file.is_file() and params_file.is_file()): + raise FileNotFoundError(f"Paddle model not found in {w}. Both .json and .pdiparams files are required.") + + config = pdi.Config(str(model_file), str(params_file)) + if cuda: + config.enable_use_gpu(memory_pool_init_size_mb=2048, device_id=self.device.index or 0) + + self.predictor = pdi.create_predictor(config) + self.input_handle = self.predictor.get_input_handle(self.predictor.get_input_names()[0]) + self.output_names = self.predictor.get_output_names() + + self.apply_metadata(self.read_metadata(w)) + + def forward(self, im: torch.Tensor) -> list[np.ndarray]: + """Run Baidu PaddlePaddle inference. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (list[np.ndarray]): Model predictions as a list of numpy arrays, one per output handle. + """ + self.input_handle.copy_from_cpu(im.cpu().numpy().astype(np.float32, copy=False)) + self.predictor.run() + return [self.predictor.get_output_handle(x).copy_to_cpu() for x in self.output_names] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/pytorch.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/pytorch.py new file mode 100644 index 0000000000000000000000000000000000000000..ea1798ef28ee24cb8efbdff94886503df6faa7eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/pytorch.py @@ -0,0 +1,143 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import torch +from torch import nn + +from ultralytics.utils import IS_JETSON, LOGGER, is_jetson +from ultralytics.utils.torch_utils import TORCH_1_10, TORCH_2_1, unwrap_model + +from .base import BaseBackend + + +class PyTorchBackend(BaseBackend): + """PyTorch inference backend for native model execution. + + Loads and runs inference with native PyTorch models (.pt checkpoint files) or pre-loaded nn.Module + instances. Supports model layer fusion, FP16 precision, and NVIDIA Jetson compatibility. + """ + + def __init__( + self, + weight: str | Path | nn.Module, + device: torch.device, + fp16: bool = False, + fuse: bool = True, + verbose: bool = True, + end2end: bool | None = None, + ): + """Initialize the PyTorch backend. + + Args: + weight (str | Path | nn.Module): Path to the .pt model file or a pre-loaded nn.Module instance. + device (torch.device): Device to run inference on (e.g., 'cpu', 'cuda:0'). + fp16 (bool): Whether to use FP16 half-precision inference. + fuse (bool): Whether to fuse Conv2D + BatchNorm layers for optimization. + verbose (bool): Whether to print verbose model loading messages. + end2end (bool, optional): Select the detection head before fusion; None preserves its current mode. + """ + self.fuse = fuse + self.verbose = verbose + self.end2end_override = end2end + super().__init__(weight, device, fp16) + + def load_model(self, weight: str | torch.nn.Module) -> None: + """Load a PyTorch model from a checkpoint file or nn.Module instance. + + Args: + weight (str | torch.nn.Module): Path to the .pt checkpoint or a pre-loaded module. + """ + from ultralytics.nn.tasks import BaseModel, load_checkpoint + + model = weight if isinstance(weight, torch.nn.Module) else load_checkpoint(weight, device=self.device)[0] + if self.end2end_override is not None and hasattr(model, "end2end"): + model.end2end = self.end2end_override + if self.fuse and hasattr(model, "fuse"): + if IS_JETSON and is_jetson(jetpack=5): + model = model.to(self.device) + model = model.fuse(verbose=self.verbose) if isinstance(model, BaseModel) else model.fuse() + model = model.to(self.device) + + # Extract model attributes + if hasattr(model, "kpt_shape"): + self.kpt_shape = model.kpt_shape + self.stride = max(int(model.stride.max()), 32) if hasattr(model, "stride") else 32 + self.names = model.module.names if hasattr(model, "module") else getattr(model, "names", {}) + self.channels = model.yaml.get("channels", 3) if hasattr(model, "yaml") else 3 + model.half() if self.fp16 else model.float() + + for p in model.parameters(): + p.requires_grad = False + + self.model = model + self.end2end = getattr(model, "end2end", False) + self.base_model = isinstance(unwrap_model(model), BaseModel) + + def forward( + self, im: torch.Tensor, augment: bool = False, embed: list | None = None, **kwargs: Any + ) -> torch.Tensor | list[torch.Tensor]: + """Run native PyTorch inference with support for augmentation and embeddings. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + augment (bool): Whether to apply test-time augmentation. + embed (list | None): List of layer indices to extract embeddings from, or None. + **kwargs (Any): Additional keyword arguments passed to the model forward method. + + Returns: + (torch.Tensor | list[torch.Tensor]): Model predictions as tensor(s). + """ + if not self.base_model: # a foreign nn.Module defines no `augment`/`embed` contract to honor + return self.model(im, **kwargs) + return self.model(im, augment=augment, embed=embed, **kwargs) + + +class TorchScriptBackend(BaseBackend): + """PyTorch TorchScript inference backend for serialized model execution. + + Loads and runs inference with TorchScript models (.torchscript files) created via torch.jit.trace or + torch.jit.script. Supports FP16 precision and embedded metadata extraction. + """ + + def __init__(self, weight: str | Path, device: torch.device, fp16: bool = False): + """Initialize the TorchScript backend. + + Args: + weight (str | Path): Path to the .torchscript model file. + device (torch.device): Device to run inference on (e.g., 'cpu', 'cuda:0'). + fp16 (bool): Whether to use FP16 half-precision inference. + """ + super().__init__(weight, device, fp16) + + def load_model(self, weight: str) -> None: + """Load a TorchScript model from a .torchscript file with optional embedded metadata. + + Args: + weight (str): Path to the .torchscript model file. + """ + import torchvision # noqa - required for TorchScript model deserialization + + LOGGER.info(f"Loading {weight} for TorchScript inference...") + # NNC builds no shape expression for a traced constant, so a repeat forward raises "RuntimeError: + # _Map_base::at" or segfaults. Never restored: this setter is global, so restoring it races concurrent + # forwards, and the optimization it disables is the broken one on these versions. + if TORCH_1_10 and not TORCH_2_1: + torch._C._jit_set_texpr_fuser_enabled(False) + self.model = torch.jit.load(weight, map_location=self.device) + self.model.half() if self.fp16 else self.model.float() + self.apply_metadata(self.read_metadata(weight)) + + def forward(self, im: torch.Tensor) -> torch.Tensor | list[torch.Tensor]: + """Run TorchScript inference. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (torch.Tensor | list[torch.Tensor]): Model predictions as tensor(s). + """ + return self.model(im) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/qnn.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/qnn.py new file mode 100644 index 0000000000000000000000000000000000000000..7fc0f8288cad8fa08024d9c7dc7a47029d7f3b76 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/qnn.py @@ -0,0 +1,76 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import torch + +from ultralytics.utils import LOGGER +from ultralytics.utils.checks import check_requirements + +from .base import BaseBackend + + +class QNNBackend(BaseBackend): + """Qualcomm QNN inference backend for Snapdragon hardware. + + Loads and runs the QNN context binary produced by the Ultralytics QNN export (`*_qnn.onnx`) using ONNX Runtime with + the QNN Execution Provider plugin (`onnxruntime-qnn`). Inference runs on Qualcomm Snapdragon devices (Android, + Windows on Snapdragon, or Qualcomm Linux boards) via the HTP (NPU) backend. + """ + + def load_model(self, weight: str | Path) -> None: + """Load a QNN context-binary model with ONNX Runtime's QNN Execution Provider plugin. + + Args: + weight (str | Path): Path to the `*_qnn.onnx` file. + + Raises: + OSError: If the QNN Execution Provider cannot be registered (e.g. not on Snapdragon hardware). + """ + check_requirements("onnxruntime-qnn") + import onnxruntime + + from ultralytics.utils.export.qnn import qnn_library_paths + + onnx_file = Path(weight) + LOGGER.info(f"Loading {onnx_file} for Qualcomm QNN inference...") + + # Register the QNN EP (libraries resolved from the plugin helper or the onnxruntime/capi bundle) and select + # it; ep_library is None when QNN is already built into ONNX Runtime and needs no plugin registration + ep_name = "QNNExecutionProvider" + ep_library, htp_backend = qnn_library_paths() + ep_options = {"backend_path": htp_backend} + options = onnxruntime.SessionOptions() + if ep_library: + onnxruntime.register_execution_provider_library(ep_name, ep_library) + devices = [d for d in onnxruntime.get_ep_devices() if d.ep_name == ep_name] + if not devices: + raise OSError( + "QNN Execution Provider registered but no QNN devices were found. Run on a Qualcomm Snapdragon " + "device with 'onnxruntime-qnn' installed." + ) + options.add_provider_for_devices(devices, ep_options) + self.session = onnxruntime.InferenceSession(str(onnx_file), sess_options=options) + else: + self.session = onnxruntime.InferenceSession( + str(onnx_file), sess_options=options, providers=[ep_name], provider_options=[ep_options] + ) + self.output_names = [x.name for x in self.session.get_outputs()] + shape = self.session.get_inputs()[0].shape # channel-last exports take [N, H, W, C] input + self.nhwc = len(shape) == 4 and shape[3] in {1, 3} and shape[1] not in {1, 3} + self.apply_metadata(self.read_metadata(onnx_file)) + + def forward(self, im: torch.Tensor) -> list: + """Run inference on the Qualcomm QNN runtime. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (list): Model predictions as a list of output arrays. + """ + if self.nhwc: + im = im.permute(0, 2, 3, 1) + return self.session.run(self.output_names, {self.session.get_inputs()[0].name: im.cpu().numpy()}) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/rknn.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/rknn.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2857adbd0dca59f52e412748c8818fd1e4f07c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/rknn.py @@ -0,0 +1,81 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import torch + +from ultralytics.utils import LOGGER +from ultralytics.utils.checks import check_requirements, is_rockchip + +from .base import BaseBackend + + +class RKNNBackend(BaseBackend): + """Rockchip RKNN inference backend for Rockchip NPU hardware. + + Loads and runs inference with RKNN models (.rknn files) using the RKNN-Toolkit-Lite2 runtime. Only supported on + Rockchip devices with NPU hardware (e.g., RK3588, RK3566). + """ + + def load_model(self, weight: str | Path) -> None: + """Load a Rockchip RKNN model from a .rknn file or model directory. + + Args: + weight (str | Path): Path to the .rknn file or directory containing the model. + + Raises: + OSError: If not running on a Rockchip device. + RuntimeError: If model loading or runtime initialization fails. + """ + if not is_rockchip(): + raise OSError("RKNN inference is only supported on Rockchip devices.") + + LOGGER.info(f"Loading {weight} for RKNN inference...") + check_requirements("rknn-toolkit-lite2") + from rknnlite.api import RKNNLite + + w = Path(weight) + if not w.is_file(): + w = next(w.rglob("*.rknn")) + + self.model = RKNNLite() + ret = self.model.load_rknn(str(w)) + if ret != 0: + raise RuntimeError(f"Failed to load RKNN model: {ret}") + + ret = self.model.init_runtime() + if ret != 0: + raise RuntimeError(f"Failed to init RKNN runtime: {ret}") + + self.apply_metadata(self.read_metadata(w)) + + def forward(self, im: torch.Tensor) -> list: + """Run inference on the Rockchip NPU. + + Args: + im (torch.Tensor): Input image tensor in BHWC format, normalized to [0, 1]. + + Returns: + (list): Model predictions as a list of output arrays. + """ + h, w = im.shape[1:3] + im = (im.cpu().numpy() * 255).astype("uint8") + im = im if isinstance(im, (list, tuple)) else [im] + y = self.model.inference(inputs=im) + # INT8 exports use input-relative coordinates so a single per-tensor scale preserves class scores. + if ( + self.metadata.get("args", {}).get("quantize") == 8 + and self.task in {"detect", "segment", "pose", "obb"} + and not self.end2end + ): + kpt_start = 4 + len(self.names) # pose keypoints follow the box (4) and class-score (nc) channels + for x in y: + if x.ndim == 3: + x[:, [0, 2]] *= w + x[:, [1, 3]] *= h + if self.task == "pose": + x[:, kpt_start::3] *= w + x[:, kpt_start + 1 :: 3] *= h + return y diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/tensorflow.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/tensorflow.py new file mode 100644 index 0000000000000000000000000000000000000000..8b02c82b67903e6e6822a8191c94c871e9282cc9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/tensorflow.py @@ -0,0 +1,159 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import platform +from pathlib import Path + +import numpy as np +import torch + +from ultralytics.utils import LOGGER + +from .base import BaseBackend + + +class TensorFlowBackend(BaseBackend): + """Google TensorFlow inference backend supporting multiple serialization formats. + + Loads and runs inference with Google TensorFlow models in SavedModel, GraphDef (.pb), and Edge TPU formats. Handles + quantized model dequantization and task-specific output formatting. + """ + + def __init__(self, weight: str | Path, device: torch.device, fp16: bool = False, format: str = "saved_model"): + """Initialize the Google TensorFlow backend. + + Args: + weight (str | Path): Path to the SavedModel directory, .pb file, or Edge TPU .tflite file. + device (torch.device): Device to run inference on. + fp16 (bool): Whether to use FP16 half-precision inference. + format (str): Model format, one of "saved_model", "pb", or "edgetpu". + """ + assert format in {"saved_model", "pb", "edgetpu"}, f"Unsupported TensorFlow format: {format}." + self.format = format + super().__init__(weight, device, fp16) + + def load_model(self, weight: str | Path) -> None: + """Load a Google TensorFlow model in SavedModel, GraphDef, or Edge TPU format. + + Args: + weight (str | Path): Path to the model file or directory. + """ + if self.format in {"saved_model", "pb"}: + import tensorflow as tf + + if self.format == "saved_model": + LOGGER.info(f"Loading {weight} for TensorFlow SavedModel inference...") + self.model = tf.saved_model.load(weight) + self.apply_metadata(self.read_metadata(weight)) + elif self.format == "pb": + LOGGER.info(f"Loading {weight} for TensorFlow GraphDef inference...") + from ultralytics.utils.export.tensorflow import gd_outputs + + def wrap_frozen_graph(gd, inputs, outputs): + """Wrap a TensorFlow frozen graph for inference by pruning to specified input/output nodes.""" + x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) + ge = x.graph.as_graph_element + return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs)) + + gd = tf.Graph().as_graph_def() + with open(weight, "rb") as f: + gd.ParseFromString(f.read()) + self.frozen_func = wrap_frozen_graph(gd, inputs="x:0", outputs=gd_outputs(gd)) + self.apply_metadata(self.read_metadata(weight)) + else: # edgetpu + try: + from tflite_runtime.interpreter import Interpreter, load_delegate + + self.tf = None + except ImportError: + import tensorflow as tf + + self.tf = tf + Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate + + device = self.device[3:] if str(self.device).startswith("tpu") else ":0" + LOGGER.info(f"Loading {weight} on device {device[1:]} for TensorFlow Lite Edge TPU inference...") + delegate = {"Linux": "libedgetpu.so.1", "Darwin": "libedgetpu.1.dylib", "Windows": "edgetpu.dll"}[ + platform.system() + ] + self.interpreter = Interpreter( + model_path=str(weight), + experimental_delegates=[load_delegate(delegate, options={"device": device})], + ) + self.device = torch.device("cpu") # Edge TPU runs on CPU from PyTorch's perspective + + self.interpreter.allocate_tensors() + self.input_details = self.interpreter.get_input_details() + self.output_details = self.interpreter.get_output_details() + + self.apply_metadata(self.read_metadata(weight)) + + def forward(self, im: torch.Tensor) -> list[np.ndarray]: + """Run Google TensorFlow inference with format-specific execution and output post-processing. + + Args: + im (torch.Tensor): Input image tensor in BHWC format (converted from BCHW by AutoBackend). + + Returns: + (list[np.ndarray]): Model predictions as a list of numpy arrays. + """ + im = im.cpu().numpy() + if self.format == "saved_model": + y = self.model.serving_default(im) + if not isinstance(y, list): + y = [y] + elif self.format == "pb": + import tensorflow as tf + + y = self.frozen_func(x=tf.constant(im)) + else: + h, w = im.shape[1:3] + + details = self.input_details[0] + is_int = details["dtype"] in {np.int8, np.int16} + + if is_int: + scale, zero_point = details["quantization"] + im = (im / scale + zero_point).astype(details["dtype"]) + + self.interpreter.set_tensor(details["index"], im) + self.interpreter.invoke() + + y = [] + for output in self.output_details: + x = self.interpreter.get_tensor(output["index"]) + if self.task == "semantic" and x.ndim == 3: + # Baked argmax class map [B, H, W] of integer class IDs, not boxes or quantized logits: + # skip dequantization and xywh denormalization, which would corrupt and overflow the indices. + y.append(x) + continue + if is_int: + scale, zero_point = output["quantization"] + x = (x.astype(np.float32) - zero_point) * scale + if x.ndim == 3: + # Denormalize xywh by image size + if x.shape[-1] == 6 or self.end2end: + x[:, :, [0, 2]] *= w + x[:, :, [1, 3]] *= h + if self.task == "pose": + x[:, :, 6::3] *= w + x[:, :, 7::3] *= h + else: + x[:, [0, 2]] *= w + x[:, [1, 3]] *= h + if self.task == "pose": + x[:, 5::3] *= w + x[:, 6::3] *= h + y.append(x) + + if self.task == "segment": # segment with (det, proto) output order reversed + if len(y[1].shape) != 4: + y = list(reversed(y)) # should be y = (1, 116, 8400), (1, 160, 160, 32) + if y[1].shape[-1] == 6: # end-to-end model + y = [y[1]] + else: + y[1] = np.transpose(y[1], (0, 3, 1, 2)) # should be y = (1, 116, 8400), (1, 32, 160, 160) + elif self.task in {"semantic", "depth"} and len(y) == 1 and y[0].ndim == 4: + y[0] = np.transpose(y[0], (0, 3, 1, 2)) # NHWC → NCHW for semantic segmentation and depth anything logits + return [x if isinstance(x, np.ndarray) else x.numpy() for x in y] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/tensorrt.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/tensorrt.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b1e4cebf3190dce438a1471381191376d732a4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/tensorrt.py @@ -0,0 +1,161 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from collections import OrderedDict, namedtuple +from pathlib import Path + +import numpy as np +import torch + +from ultralytics.utils import IS_JETSON, LOGGER, PYTHON_VERSION +from ultralytics.utils.checks import check_requirements, check_tensorrt, check_version +from ultralytics.utils.torch_utils import TORCH_1_10 + +from .base import BaseBackend + + +class TensorRTBackend(BaseBackend): + """NVIDIA TensorRT inference backend for GPU-accelerated deployment. + + Loads and runs inference with NVIDIA TensorRT serialized engines (.engine files). Supports both TensorRT 7-9 and + TensorRT 10/11 APIs, dynamic input shapes, FP16 precision, and DLA core offloading. + """ + + def load_model(self, weight: str | Path) -> None: + """Load an NVIDIA TensorRT engine from a serialized .engine file. + + Args: + weight (str | Path): Path to the .engine file with optional embedded metadata. + """ + LOGGER.info(f"Loading {weight} for TensorRT inference...") + + if IS_JETSON and check_version(PYTHON_VERSION, "<=3.8.10"): + check_requirements("numpy==1.23.5") + + try: + import tensorrt as trt + except ImportError: + check_tensorrt() + import tensorrt as trt + + check_version(trt.__version__, ">=7.0.0", hard=True) + check_version(trt.__version__, "!=10.2.0", msg="https://github.com/ultralytics/ultralytics/pull/24367") + + if self.device.type == "cpu": + self.device = torch.device("cuda:0") + + Binding = namedtuple("Binding", ("name", "dtype", "shape", "data")) + logger = trt.Logger(trt.Logger.INFO) + + # Read engine file + offset, metadata = self.engine_header(weight) + with open(weight, "rb") as f, trt.Runtime(logger) as runtime, torch.cuda.device(self.device): + f.seek(offset) # skip the metadata header, if any, that precedes the engine + if (dla := metadata.get("dla")) is not None: + runtime.DLA_core = int(dla) + engine = runtime.deserialize_cuda_engine(f.read()) + self.apply_metadata(metadata) + try: + self.context = engine.create_execution_context() # TensorRT binds this to the current device + except Exception: + LOGGER.error("TensorRT model exported with a different version than expected\n") + raise + + # Setup bindings + self.bindings = OrderedDict() + self.output_names = [] + self.fp16 = False + self.dynamic = False + # TensorRT 10 and 11 both drop the legacy binding API in favor of named I/O tensors + self.is_trt10 = not hasattr(engine, "num_bindings") + num = range(engine.num_io_tensors) if self.is_trt10 else range(engine.num_bindings) + + for i in num: + if self.is_trt10: + name = engine.get_tensor_name(i) + dtype = trt.nptype(engine.get_tensor_dtype(name)) + is_input = engine.get_tensor_mode(name) == trt.TensorIOMode.INPUT + shape = tuple(engine.get_tensor_shape(name)) + profile_shape = tuple(engine.get_tensor_profile_shape(name, 0)[2]) if is_input else None + else: + name = engine.get_binding_name(i) + dtype = trt.nptype(engine.get_binding_dtype(i)) + is_input = engine.binding_is_input(i) + shape = tuple(engine.get_binding_shape(i)) + profile_shape = tuple(engine.get_profile_shape(0, i)[1]) if is_input else None + + if is_input: + if -1 in shape: + self.dynamic = True + if self.is_trt10: + self.context.set_input_shape(name, profile_shape) + else: + self.context.set_binding_shape(i, profile_shape) + if dtype == np.float16: + self.fp16 = True + else: + self.output_names.append(name) + + shape = ( + tuple(self.context.get_tensor_shape(name)) + if self.is_trt10 + else tuple(self.context.get_binding_shape(i)) + ) + im = torch.from_numpy(np.empty(shape, dtype=dtype)).to(self.device) + self.bindings[name] = Binding(name, dtype, shape, im) + + # Replay the engine from one captured CUDA graph instead of relaunching every kernel, worth ~50 us per call. + # A dynamic engine would recapture on every shape change, and DLA or an embedded NMS does host work mid-stream + # that cannot be captured, so both keep `execute_v2`. + host = dla is not None or metadata.get("args", {}).get("nms", False) + self.graph = None + if TORCH_1_10 and self.is_trt10 and not self.dynamic and not host: + for name, binding in self.bindings.items(): + self.context.set_tensor_address(name, binding.data.data_ptr()) + stream, graph = torch.cuda.Stream(self.device), torch.cuda.CUDAGraph() + with torch.cuda.stream(stream): # selects the engine's device as well, which the capture records on + ok = self.context.execute_async_v3(stream.cuda_stream) # TensorRT allocates on its first run + stream.synchronize() + with torch.cuda.graph(graph, stream=stream): + ok &= self.context.execute_async_v3(stream.cuda_stream) + self.graph = graph if ok else None # a refused enqueue records nothing and would replay stale outputs + + self.model = engine + + def forward(self, im: torch.Tensor) -> list[torch.Tensor]: + """Run NVIDIA TensorRT inference with dynamic shape handling. + + Args: + im (torch.Tensor): Input image tensor in BCHW format on the CUDA device. + + Returns: + (list[torch.Tensor]): Model predictions as a list of tensors on the CUDA device. + """ + if self.dynamic and im.shape != self.bindings["images"].shape: + if self.is_trt10: + ok = self.context.set_input_shape("images", im.shape) + else: + ok = self.context.set_binding_shape(self.model.get_binding_index("images"), im.shape) + if not ok: # the profile refused the shape, so the bindings below would describe the wrong engine state + raise ValueError(f"input size {tuple(im.shape)} is outside the TensorRT optimization profile") + self.bindings["images"] = self.bindings["images"]._replace(shape=im.shape) + for name in self.output_names: + shape = ( + self.context.get_tensor_shape(name) + if self.is_trt10 + else self.context.get_binding_shape(self.model.get_binding_index(name)) + ) + self.bindings[name].data.resize_(tuple(shape)) + + s = self.bindings["images"].shape + assert im.shape == s, f"input size {im.shape} {'>' if self.dynamic else 'not equal to'} max model size {s}" + + if self.graph is None: + self.bindings["images"] = self.bindings["images"]._replace(data=im) + if not self.context.execute_v2([binding.data.data_ptr() for binding in self.bindings.values()]): + raise RuntimeError("TensorRT inference execution failed") + else: + self.bindings["images"].data.copy_(im) # the capture reads this address, so the input must land in it + self.graph.replay() + return [self.bindings[x].data for x in sorted(self.output_names)] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/triton.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/triton.py new file mode 100644 index 0000000000000000000000000000000000000000..741c83da2047d1d84691316e8e85e79626b326b6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/backends/triton.py @@ -0,0 +1,45 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import torch + +from ultralytics.utils.checks import check_requirements + +from .base import BaseBackend + + +class TritonBackend(BaseBackend): + """NVIDIA Triton Inference Server backend for remote model serving. + + Connects to and runs inference with models hosted on an NVIDIA Triton Inference Server instance via HTTP or gRPC + protocols. The model is specified using a triton:// URL scheme. + """ + + def load_model(self, weight: str | Path) -> None: + """Connect to a remote model on an NVIDIA Triton Inference Server. + + Args: + weight (str | Path): Triton model URL (e.g., 'triton://host:8000/model_name'). + """ + check_requirements("tritonclient[all]") + from ultralytics.utils.triton import TritonRemoteModel + + self.model = TritonRemoteModel(weight) + + # Copy metadata from Triton model + if hasattr(self.model, "metadata"): + self.apply_metadata(self.model.metadata) + + def forward(self, im: torch.Tensor) -> list: + """Run inference via the NVIDIA Triton Inference Server. + + Args: + im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1]. + + Returns: + (list): Model predictions as a list of numpy arrays from the Triton server. + """ + return self.model(im.cpu().numpy()) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/distill_model.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/distill_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b05ffd94d1ace0835c40bfd8c2f2dd3f8c546a32 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/distill_model.py @@ -0,0 +1,319 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import torch +import torch.nn.functional as F +from torch import nn + +from ultralytics.nn.modules.head import Detect +from ultralytics.utils.torch_utils import copy_attr + +from .tasks import load_checkpoint + + +class FeatureHook: + """Picklable forward hook that stores layer output into a shared dict.""" + + def __init__(self, feat_dict: dict, idx: int) -> None: + """Initialize the hook with the shared feature dict and the layer index to store outputs under.""" + self.feat_dict = feat_dict + self.idx = idx + + def __call__(self, module: nn.Module, inputs: tuple, output) -> None: + """Store the layer's forward output into the shared feature dict under its index. + + The output is a tensor for neck layers but a tuple/dict for the Detect head, so it is left untyped. + """ + self.feat_dict[self.idx] = output + + +class DistillationModel(nn.Module): + """YOLO knowledge distillation model. + + This class wraps a teacher-student pair for knowledge distillation training. Features are extracted from both models + via forward hooks for distillation. + + Attributes: + teacher_model (nn.Module): Frozen teacher model providing features. + student_model (nn.Module): Trainable student model being distilled. + feats_idx (list): Layer indices for feature extraction. + projector (nn.ModuleList): MLP projector aligning student features to teacher dimensions. + dis (float): Distillation loss weight factor. + + Methods: + get_distill_layers: Auto-detect distillation feature layers from the Detect head. + forward: Run the student model, or compute the combined loss when given a training batch. + loss: Compute combined detection and distillation loss. + loss_sl2: Compute score-weighted L2 distillation loss for a feature pair. + decouple_outputs: Normalize teacher/student head outputs across train/val formats. + fuse: Fuse and return the student model for inference and export. + train: Set training mode while keeping teacher frozen. + + Examples: + Train a student model with knowledge distillation from a larger teacher (the trainer builds the + DistillationModel internally when the ``distill_model`` argument is set) + >>> from ultralytics import YOLO + >>> model = YOLO("yolo26n.pt") + >>> model.train(data="coco8.yaml", distill_model="yolo26s.pt") + """ + + def __init__(self, teacher_model: str | Path | nn.Module, student_model: nn.Module): + """Initialize the distillation model with teacher, student, and feature extraction hooks. + + Args: + teacher_model (str | Path | nn.Module): Teacher model checkpoint path or module. + student_model (nn.Module): Student model module to be trained. + """ + super().__init__() + ch = student_model.yaml.get("channels", 3) + if isinstance(teacher_model, (str, Path)): + teacher_model = load_checkpoint(teacher_model)[0] + if teacher_model.yaml.get("channels", 3) != ch: + weights = teacher_model + teacher_model = type(weights)(weights.yaml.copy(), ch=ch, nc=weights.yaml["nc"], verbose=False) + teacher_model.load(weights) + device = next(student_model.parameters()).device + self.teacher_model = teacher_model.to(device) + self._freeze_teacher() + self.student_model = student_model + self.feats_idx = self.get_distill_layers(student_model) + + # Hook-based feature capture: identical for teacher and student + self._teacher_feats: dict[int, torch.Tensor] = {} + self._student_feats: dict[int, torch.Tensor] = {} + self._teacher_hooks: list = [] + self._student_hooks: list = [] + self._register_feature_hooks() + + # Get feature dimensions via dummy forward pass (hooks capture outputs) + imgsz = student_model.args.imgsz + student_model.eval() + with torch.no_grad(): + im = torch.zeros(2, ch, imgsz, imgsz, device=device) + teacher_model(im) + student_model(im) + student_model.train() + teacher_output = [self._teacher_feats[idx] for idx in self.feats_idx] + student_output = [self._student_feats[idx] for idx in self.feats_idx] + + copy_attr(self, student_model) + self.dis = self.student_model.args.dis + projectors = [] + for student_out, teacher_out in zip(student_output[:-1], teacher_output[:-1]): + student_dim = self.decouple_outputs(student_out).shape[1] + teacher_dim = self.decouple_outputs(teacher_out).shape[1] + projectors.append( + nn.Sequential( + nn.Conv2d(student_dim, teacher_dim, kernel_size=1, stride=1, padding=0), + nn.ReLU(inplace=True), + nn.Conv2d(teacher_dim, teacher_dim, kernel_size=1, stride=1, padding=0), + ) + ) + self.projector = nn.ModuleList(projectors).to(device) + + def __getstate__(self): + """Return a copy of state for pickling without captured features or hook handles. + + Clears the feature dicts in place (rather than replacing the attributes) because the registered + FeatureHooks share these exact dict objects; otherwise a deepcopy/pickle of a mid-training model would + still reach the hook-held tensors (which carry grad_fn and cannot be deep-copied). + """ + self._teacher_feats.clear() + self._student_feats.clear() + state = self.__dict__.copy() + state["_teacher_hooks"] = [] + state["_student_hooks"] = [] + return state + + def __setstate__(self, state): + """Clear stale features and hooks, and re-register forward hooks after unpickling.""" + self.__dict__.update(state) + self._teacher_feats = {} + self._student_feats = {} + self._register_feature_hooks() + + def _remove_feature_hooks(self) -> None: + """Remove any previously registered feature-capture hooks.""" + for handle in self._student_hooks: + handle.remove() + self._student_hooks.clear() + if self.teacher_model is not None: + for handle in self._teacher_hooks: + handle.remove() + self._teacher_hooks.clear() + + @staticmethod + def _clear_feature_hooks(module: nn.Module) -> None: + """Remove any FeatureHook instances from a module's forward hooks.""" + for handle_id, hook in list(module._forward_hooks.items()): + if isinstance(hook, FeatureHook): + del module._forward_hooks[handle_id] + + def _register_feature_hooks(self) -> None: + """Register feature-capture hooks, removing stale FeatureHook instances first.""" + self._remove_feature_hooks() + for idx in self.feats_idx: + self._clear_feature_hooks(self.student_model.model[idx]) + self._student_hooks.append( + self.student_model.model[idx].register_forward_hook(FeatureHook(self._student_feats, idx)) + ) + if self.teacher_model is not None: + self._clear_feature_hooks(self.teacher_model.model[idx]) + self._teacher_hooks.append( + self.teacher_model.model[idx].register_forward_hook(FeatureHook(self._teacher_feats, idx)) + ) + + @staticmethod + def get_distill_layers(model: nn.Module) -> list[int]: + """Auto-detect distillation feature layers from the model's Detect head. + + Returns the Detect head's input layer indices plus the head layer index itself. + E.g. YOLO26 -> [16, 19, 22, 23], YOLOv8 -> [15, 18, 21, 22]. + """ + for m in model.model: + if isinstance(m, Detect): + return [*list(m.f), m.i] + raise ValueError("No Detect head found in model") + + def _freeze_teacher(self): + """Keep teacher fixed for distillation.""" + if self.teacher_model is None: + return + self.teacher_model.eval() + for v in self.teacher_model.parameters(): + if v.requires_grad: + v.requires_grad = False + + def train(self, mode: bool = True): + """Set model train mode while keeping teacher frozen in eval mode.""" + super().train(mode) + self._freeze_teacher() + return self + + def forward(self, x, *args, **kwargs): + """Forward pass through the student model.""" + if isinstance(x, dict): # for cases of training and validating while training. + return self.loss(x, *args, **kwargs) + return self.student_model.predict(x, *args, **kwargs) + + def fuse(self, verbose: bool = True, imgsz: int | list[int, int] = 640): + """Fuse and return the student model, dropping the training-only distillation wrapper.""" + self._remove_feature_hooks() + return self.student_model.fuse(verbose=verbose, imgsz=imgsz) + + def loss(self, batch, preds=None): + """Compute loss. + + Args: + batch (dict): Batch to compute loss on. + preds (torch.Tensor | list[torch.Tensor], optional): Predictions. + """ + loss_distill = torch.zeros(1, device=batch["img"].device) + if not self.training: # for loss calculation during validation while training + if preds is None: + preds = self.student_model(batch["img"]) + regular_loss, loss_items = self.student_model.loss(batch, preds) + loss_items["dis_loss"] = loss_distill.detach() + return torch.cat([regular_loss, loss_distill]), loss_items + + # Clear feature dicts before forward passes + self._teacher_feats.clear() + self._student_feats.clear() + + with torch.no_grad(): + self.teacher_model(batch["img"]) # hooks capture teacher features + preds = self.student_model(batch["img"]) # hooks capture student features + + regular_loss, loss_items = self.student_model.loss(batch, preds) + teacher_head_feat = self._teacher_feats[self.feats_idx[-1]] + teacher_scores = ( + self.decouple_outputs(teacher_head_feat, branch="one2many")["scores"] + + self.decouple_outputs(teacher_head_feat, branch="one2one")["scores"] + ) / 2 + # neck feature sizes vary per batch (e.g. multi_scale), so split scores by the live teacher feats + neck_feats = [self._teacher_feats[idx] for idx in self.feats_idx[:-1]] + parts = torch.split(teacher_scores, [f.shape[-2] * f.shape[-1] for f in neck_feats], dim=-1) + teacher_scores = tuple(p.sigmoid().max(dim=1, keepdim=True).values for p in parts) + for i, feat_idx in enumerate(self.feats_idx[:-1]): + teacher_feat = self.decouple_outputs(self._teacher_feats[feat_idx]) + student_feat = self.projector[i](self.decouple_outputs(self._student_feats[feat_idx])) + loss_distill += ( + self.loss_sl2(student_feat, teacher_feat, feat_idx=i, teacher_scores=teacher_scores) * self.dis + ) + + loss_items["dis_loss"] = loss_distill.detach() + loss_distill = loss_distill * batch["img"].shape[0] + return torch.cat([regular_loss, loss_distill]), loss_items + + def loss_sl2( + self, student_feat: torch.Tensor, teacher_feat: torch.Tensor, feat_idx: int, teacher_scores: tuple + ) -> torch.Tensor: + """Compute score-weighted L2 distillation loss for a feature pair. + + Args: + student_feat (torch.Tensor): Student feature tensor of shape (N, C, H, W). + teacher_feat (torch.Tensor): Teacher feature tensor of shape (N, C, H, W). + feat_idx (int): Index of the feature level for selecting teacher scores. + teacher_scores (tuple): Tuple of score tensors for each feature level. + + Returns: + (torch.Tensor): The computed score-weighted L2 loss. + """ + teacher_score = teacher_scores[feat_idx] + n, c = student_feat.shape[:2] + student_feat = student_feat.view(n, c, -1) + teacher_feat = teacher_feat.view(n, c, -1) + mse = F.mse_loss(student_feat, teacher_feat, reduction="none") + weighted_mse = (mse * teacher_score).sum() / (teacher_score.sum() * c + 1e-9) + return weighted_mse + + @property + def criterion(self): + """Get the criterion from the student model.""" + return self.student_model.criterion + + @criterion.setter + def criterion(self, value) -> None: + """Set value for student criterion.""" + self.student_model.criterion = value + + def init_criterion(self): + """Initialize the loss criterion via the student model.""" + return self.student_model.init_criterion() + + @property + def end2end(self): + """Expose student end-to-end mode for validator/predictor control.""" + return getattr(self.student_model, "end2end", False) + + @end2end.setter + def end2end(self, value): + """Forward end-to-end mode update to the student model.""" + self.student_model.end2end = value + + def set_head_attr(self, **kwargs): + """Forward head-attribute updates (e.g. max_det, agnostic_nms, end2end) to the student model.""" + self.student_model.set_head_attr(**kwargs) + + def decouple_outputs(self, preds, branch: str = "one2one"): + """Decouple outputs for teacher/student models. + + This method handles different output formats from YOLO models, including + tuple outputs (train/val mode), dict outputs with branches (one2one/one2many), + and direct tensor outputs. + + Args: + preds (torch.Tensor | tuple | dict): Model predictions in various formats. + branch (str): Which branch to extract from dict outputs ("one2one" or "one2many"). + + Returns: + (torch.Tensor | dict): The decoupled predictions. + """ + if isinstance(preds, tuple): # decouple for val mode + preds = preds[1] + if isinstance(preds, dict) and branch in preds: + preds = preds[branch] + return preds diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03582ae589d962fa860f1ce69149a5a2c01cac11 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__init__.py @@ -0,0 +1,194 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Ultralytics neural network modules. + +This module provides access to various neural network components used in Ultralytics models, including convolution +blocks, attention mechanisms, transformer components, and detection/segmentation heads. + +Examples: + Visualize a module with Netron + >>> from ultralytics.nn.modules import Conv + >>> import torch + >>> import subprocess + >>> x = torch.ones(1, 128, 40, 40) + >>> m = Conv(128, 128) + >>> f = f"{m._get_name()}.onnx" + >>> torch.onnx.export(m, x, f) + >>> subprocess.run(f"onnxslim {f} {f} && open {f}", shell=True, check=True) # pip install onnxslim +""" + +from .block import ( + C1, + C2, + C2PSA, + C3, + C3TR, + CIB, + DFL, + ELAN1, + PSA, + SPP, + SPPELAN, + SPPF, + A2C2f, + AConv, + ADown, + Attention, + BNContrastiveHead, + Bottleneck, + BottleneckCSP, + C2f, + C2fAttn, + C2fCIB, + C2fPSA, + C3Ghost, + C3k2, + C3x, + CBFuse, + CBLinear, + ContrastiveHead, + GhostBottleneck, + HGBlock, + HGStem, + ImagePoolingAttn, + MaxSigmoidAttnBlock, + Proto, + RepC3, + RepNCSPELAN4, + RepVGGDW, + ResNetLayer, + SCDown, + TorchVision, +) +from .conv import ( + CBAM, + ChannelAttention, + Concat, + Conv, + Conv2, + ConvTranspose, + DWConv, + DWConvTranspose2d, + Focus, + GhostConv, + Index, + LightConv, + RepConv, + SpatialAttention, +) +from .head import ( + OBB, + OBB26, + Classify, + Depth, + Detect, + LRPCHead, + Pose, + Pose26, + RTDETRDecoder, + Segment, + Segment26, + SemanticSegment, + WorldDetect, + YOLOEDetect, + YOLOESegment, + YOLOESegment26, + v10Detect, +) +from .transformer import ( + AIFI, + MLP, + DeformableTransformerDecoder, + DeformableTransformerDecoderLayer, + LayerNorm2d, + MLPBlock, + MSDeformAttn, + TransformerBlock, + TransformerEncoderLayer, + TransformerLayer, +) + +__all__ = ( + "AIFI", + "C1", + "C2", + "C2PSA", + "C3", + "C3TR", + "CBAM", + "CIB", + "DFL", + "ELAN1", + "MLP", + "OBB", + "OBB26", + "PSA", + "SPP", + "SPPELAN", + "SPPF", + "A2C2f", + "AConv", + "ADown", + "Attention", + "BNContrastiveHead", + "Bottleneck", + "BottleneckCSP", + "C2f", + "C2fAttn", + "C2fCIB", + "C2fPSA", + "C3Ghost", + "C3k2", + "C3x", + "CBFuse", + "CBLinear", + "ChannelAttention", + "Classify", + "Concat", + "ContrastiveHead", + "Conv", + "Conv2", + "ConvTranspose", + "DWConv", + "DWConvTranspose2d", + "DeformableTransformerDecoder", + "DeformableTransformerDecoderLayer", + "Depth", + "Detect", + "Focus", + "GhostBottleneck", + "GhostConv", + "HGBlock", + "HGStem", + "ImagePoolingAttn", + "Index", + "LRPCHead", + "LayerNorm2d", + "LightConv", + "MLPBlock", + "MSDeformAttn", + "MaxSigmoidAttnBlock", + "Pose", + "Pose26", + "Proto", + "RTDETRDecoder", + "RepC3", + "RepConv", + "RepNCSPELAN4", + "RepVGGDW", + "ResNetLayer", + "SCDown", + "Segment", + "Segment26", + "SemanticSegment", + "SpatialAttention", + "TorchVision", + "TransformerBlock", + "TransformerEncoderLayer", + "TransformerLayer", + "WorldDetect", + "YOLOEDetect", + "YOLOESegment", + "YOLOESegment26", + "v10Detect", +) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df186cd14daddd67b152a156cb3240e9921c9c38 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/activation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/activation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..477cd1131afb68bce87fea87b7c5c3f80f1bbb63 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/activation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/block.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..157b2d6b6bd66548559fb4c19ccbf343e7296a57 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/block.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:729f29a7aec577c6a051ffb0df85e0a5276cd59a49498329db066c24f0a50c93 +size 124349 diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/conv.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/conv.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f1957913d120add82f151bab4994257095e13a8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/conv.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/head.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/head.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ea0e769d6e1d65f65b39c7a7f0a48b1cc65608d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/head.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef520a0950a768e038f3a27baf4451a9da6a107c7c44384d803f345224abf76a +size 112675 diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/transformer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/transformer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a411c67fa695ce1b5211680a48c4cfb5fd3fbd4f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/transformer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..867246d64cc1bb367db36680a1fe9c4d14421a03 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/activation.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/activation.py new file mode 100644 index 0000000000000000000000000000000000000000..8b2051b45507f7fd9d7e9c47674e014d12f78f77 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/activation.py @@ -0,0 +1,54 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Activation modules.""" + +import torch +from torch import nn + + +class AGLU(nn.Module): + """Unified activation function module from AGLU. + + This class implements a parameterized activation function with learnable parameters lambda and kappa, based on the + AGLU (Adaptive Gated Linear Unit) approach. + + Attributes: + act (nn.Softplus): Softplus activation function with negative beta. + lambd (nn.Parameter): Learnable lambda parameter initialized with uniform distribution. + kappa (nn.Parameter): Learnable kappa parameter initialized with uniform distribution. + + Methods: + forward: Compute the forward pass of the Unified activation function. + + Examples: + >>> import torch + >>> m = AGLU() + >>> input = torch.randn(2) + >>> output = m(input) + >>> print(output.shape) + torch.Size([2]) + + References: + https://github.com/kostas1515/AGLU + """ + + def __init__(self, device=None, dtype=None) -> None: + """Initialize the Unified activation function with learnable parameters.""" + super().__init__() + self.act = nn.Softplus(beta=-1.0) + self.lambd = nn.Parameter(nn.init.uniform_(torch.empty(1, device=device, dtype=dtype))) # lambda parameter + self.kappa = nn.Parameter(nn.init.uniform_(torch.empty(1, device=device, dtype=dtype))) # kappa parameter + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply the Adaptive Gated Linear Unit (AGLU) activation function. + + This forward method implements the AGLU activation function with learnable parameters lambda and kappa. The + function applies a transformation that adaptively combines linear and non-linear components. + + Args: + x (torch.Tensor): Input tensor to apply the activation function to. + + Returns: + (torch.Tensor): Output tensor after applying the AGLU activation function, with the same shape as the input. + """ + lam = torch.clamp(self.lambd, min=0.0001) # Clamp lambda to avoid division by zero + return torch.exp((1 / lam) * self.act((self.kappa * x) - torch.log(lam))) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/block.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/block.py new file mode 100644 index 0000000000000000000000000000000000000000..4adb66533458effe21796353314771305ca6cd4b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/block.py @@ -0,0 +1,2080 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Block modules.""" + +from __future__ import annotations + +import math + +import torch +import torch.nn.functional as F +from torch import nn + +from ultralytics.utils.torch_utils import fuse_conv_and_bn + +from .conv import Conv, DWConv, GhostConv, LightConv, RepConv, autopad +from .transformer import TransformerBlock + +__all__ = ( + "C1", + "C2", + "C2PSA", + "C3", + "C3TR", + "CIB", + "DFL", + "ELAN1", + "PSA", + "SPP", + "SPPELAN", + "SPPF", + "AConv", + "ADown", + "Attention", + "BNContrastiveHead", + "Bottleneck", + "BottleneckCSP", + "C2f", + "C2fAttn", + "C2fCIB", + "C2fPSA", + "C3Ghost", + "C3k2", + "C3x", + "CBFuse", + "CBLinear", + "ContrastiveHead", + "GhostBottleneck", + "HGBlock", + "HGStem", + "ImagePoolingAttn", + "Proto", + "RepC3", + "RepNCSPELAN4", + "RepVGGDW", + "ResNetLayer", + "SCDown", + "TorchVision", +) + + +class DFL(nn.Module): + """Integral module of Distribution Focal Loss (DFL). + + Proposed in Generalized Focal Loss https://arxiv.org/abs/2006.04388 + """ + + def __init__(self, c1: int = 16): + """Initialize a convolutional layer with a given number of input channels. + + Args: + c1 (int): Number of input channels. + """ + super().__init__() + self.conv = nn.Conv2d(c1, 1, 1, bias=False).requires_grad_(False) + x = torch.arange(c1, dtype=torch.float) + self.conv.weight.data[:] = nn.Parameter(x.view(1, c1, 1, 1)) + self.c1 = c1 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply the DFL module to input tensor and return transformed output.""" + b, _, a = x.shape # batch, channels, anchors + return self.conv(x.view(b, 4, self.c1, a).transpose(2, 1).softmax(1)).view(b, 4, a) + # return self.conv(x.view(b, self.c1, 4, a).softmax(1)).view(b, 4, a) + + +class Proto(nn.Module): + """Ultralytics YOLO models mask Proto module for segmentation models.""" + + def __init__(self, c1: int, c_: int = 256, c2: int = 32): + """Initialize the Ultralytics YOLO models mask Proto module with specified number of protos and masks. + + Args: + c1 (int): Input channels. + c_ (int): Intermediate channels. + c2 (int): Output channels (number of protos). + """ + super().__init__() + self.cv1 = Conv(c1, c_, k=3) + self.upsample = nn.ConvTranspose2d(c_, c_, 2, 2, 0, bias=True) # nn.Upsample(scale_factor=2, mode='nearest') + self.cv2 = Conv(c_, c_, k=3) + self.cv3 = Conv(c_, c2) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Perform a forward pass through layers using an upsampled input image.""" + return self.cv3(self.cv2(self.upsample(self.cv1(x)))) + + +class HGStem(nn.Module): + """StemBlock of PPHGNetV2 with 5 convolutions and one maxpool2d. + + https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/backbones/hgnet_v2.py + """ + + def __init__(self, c1: int, cm: int, c2: int): + """Initialize the StemBlock of PPHGNetV2. + + Args: + c1 (int): Input channels. + cm (int): Middle channels. + c2 (int): Output channels. + """ + super().__init__() + self.stem1 = Conv(c1, cm, 3, 2, act=nn.ReLU()) + self.stem2a = Conv(cm, cm // 2, 2, 1, 0, act=nn.ReLU()) + self.stem2b = Conv(cm // 2, cm, 2, 1, 0, act=nn.ReLU()) + self.stem3 = Conv(cm * 2, cm, 3, 2, act=nn.ReLU()) + self.stem4 = Conv(cm, c2, 1, 1, act=nn.ReLU()) + self.pool = nn.MaxPool2d(kernel_size=2, stride=1, padding=0, ceil_mode=True) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass of a PPHGNetV2 backbone layer.""" + x = self.stem1(x) + x = F.pad(x, [0, 1, 0, 1]) + x2 = self.stem2a(x) + x2 = F.pad(x2, [0, 1, 0, 1]) + x2 = self.stem2b(x2) + x1 = self.pool(x) + x = torch.cat([x1, x2], dim=1) + x = self.stem3(x) + x = self.stem4(x) + return x + + +class HGBlock(nn.Module): + """HG_Block of PPHGNetV2 with 2 convolutions and LightConv. + + https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/backbones/hgnet_v2.py + """ + + def __init__( + self, + c1: int, + cm: int, + c2: int, + k: int = 3, + n: int = 6, + lightconv: bool = False, + shortcut: bool = False, + act: nn.Module | None = None, + ): + """Initialize HGBlock with specified parameters. + + Args: + c1 (int): Input channels. + cm (int): Middle channels. + c2 (int): Output channels. + k (int): Kernel size. + n (int): Number of LightConv or Conv blocks. + lightconv (bool): Whether to use LightConv. + shortcut (bool): Whether to use shortcut connection. + act (nn.Module): Activation function. + """ + super().__init__() + act = nn.ReLU() if act is None else act + block = LightConv if lightconv else Conv + self.m = nn.ModuleList(block(c1 if i == 0 else cm, cm, k=k, act=act) for i in range(n)) + self.sc = Conv(c1 + n * cm, c2 // 2, 1, 1, act=act) # squeeze conv + self.ec = Conv(c2 // 2, c2, 1, 1, act=act) # excitation conv + self.add = shortcut and c1 == c2 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass of a PPHGNetV2 backbone layer.""" + y = [x] + y.extend(m(y[-1]) for m in self.m) + y = self.ec(self.sc(torch.cat(y, 1))) + return y + x if self.add else y + + +class SPP(nn.Module): + """Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729.""" + + def __init__(self, c1: int, c2: int, k: tuple[int, ...] = (5, 9, 13)): + """Initialize the SPP layer with input/output channels and pooling kernel sizes. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + k (tuple): Kernel sizes for max pooling. + """ + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1) + self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k]) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass of the SPP layer, performing spatial pyramid pooling.""" + x = self.cv1(x) + return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) + + +class SPPF(nn.Module): + """Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher.""" + + def __init__(self, c1: int, c2: int, k: int = 5, n: int = 3, shortcut: bool = False): + """Initialize the SPPF layer with given input/output channels and kernel size. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + k (int): Kernel size. + n (int): Number of pooling iterations. + shortcut (bool): Whether to use shortcut connection. + + Notes: + This module is equivalent to SPP(k=(5, 9, 13)). + """ + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = Conv(c1, c_, 1, 1, act=False) + self.cv2 = Conv(c_ * (n + 1), c2, 1, 1) + self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2) + self.n = n + self.add = shortcut and c1 == c2 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply sequential pooling operations to input and return concatenated feature maps.""" + y = [self.cv1(x)] + y.extend(self.m(y[-1]) for _ in range(getattr(self, "n", 3))) + y = self.cv2(torch.cat(y, 1)) + return y + x if getattr(self, "add", False) else y + + +class C1(nn.Module): + """CSP Bottleneck with 1 convolution.""" + + def __init__(self, c1: int, c2: int, n: int = 1): + """Initialize the CSP Bottleneck with 1 convolution. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of convolutions. + """ + super().__init__() + self.cv1 = Conv(c1, c2, 1, 1) + self.m = nn.Sequential(*(Conv(c2, c2, 3) for _ in range(n))) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply convolution and residual connection to input tensor.""" + y = self.cv1(x) + return self.m(y) + y + + +class C2(nn.Module): + """CSP Bottleneck with 2 convolutions.""" + + def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5): + """Initialize a CSP Bottleneck with 2 convolutions. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of Bottleneck blocks. + shortcut (bool): Whether to use shortcut connections. + g (int): Groups for convolutions. + e (float): Expansion ratio. + """ + super().__init__() + self.c = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, 2 * self.c, 1, 1) + self.cv2 = Conv(2 * self.c, c2, 1) # optional act=FReLU(c2) + # self.attention = ChannelAttention(2 * self.c) # or SpatialAttention() + self.m = nn.Sequential(*(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass through the CSP bottleneck with 2 convolutions.""" + a, b = self.cv1(x).chunk(2, 1) + return self.cv2(torch.cat((self.m(a), b), 1)) + + +class C2f(nn.Module): + """Faster Implementation of CSP Bottleneck with 2 convolutions.""" + + def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = False, g: int = 1, e: float = 0.5): + """Initialize a CSP bottleneck with 2 convolutions. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of Bottleneck blocks. + shortcut (bool): Whether to use shortcut connections. + g (int): Groups for convolutions. + e (float): Expansion ratio. + """ + super().__init__() + self.c = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, 2 * self.c, 1, 1) + self.cv2 = Conv((2 + n) * self.c, c2, 1) # optional act=FReLU(c2) + self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass through C2f layer.""" + y = list(self.cv1(x).chunk(2, 1)) + y.extend(m(y[-1]) for m in self.m) + return self.cv2(torch.cat(y, 1)) + + def forward_split(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass using split() instead of chunk().""" + y = self.cv1(x).split((self.c, self.c), 1) + y = [y[0], y[1]] + y.extend(m(y[-1]) for m in self.m) + return self.cv2(torch.cat(y, 1)) + + +class C3(nn.Module): + """CSP Bottleneck with 3 convolutions.""" + + def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5): + """Initialize the CSP Bottleneck with 3 convolutions. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of Bottleneck blocks. + shortcut (bool): Whether to use shortcut connections. + g (int): Groups for convolutions. + e (float): Expansion ratio. + """ + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c1, c_, 1, 1) + self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2) + self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=((1, 1), (3, 3)), e=1.0) for _ in range(n))) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass through the CSP bottleneck with 3 convolutions.""" + return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1)) + + +class C3x(C3): + """C3 module with cross-convolutions.""" + + def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5): + """Initialize C3 module with cross-convolutions. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of Bottleneck blocks. + shortcut (bool): Whether to use shortcut connections. + g (int): Groups for convolutions. + e (float): Expansion ratio. + """ + super().__init__(c1, c2, n, shortcut, g, e) + self.c_ = int(c2 * e) + self.m = nn.Sequential(*(Bottleneck(self.c_, self.c_, shortcut, g, k=((1, 3), (3, 1)), e=1) for _ in range(n))) + + +class RepC3(nn.Module): + """Rep C3.""" + + def __init__(self, c1: int, c2: int, n: int = 3, e: float = 1.0): + """Initialize RepC3 module with RepConv blocks. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of RepConv blocks. + e (float): Expansion ratio. + """ + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c1, c_, 1, 1) + self.m = nn.Sequential(*[RepConv(c_, c_) for _ in range(n)]) + self.cv3 = Conv(c_, c2, 1, 1) if c_ != c2 else nn.Identity() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass of RepC3 module.""" + return self.cv3(self.m(self.cv1(x)) + self.cv2(x)) + + +class C3TR(C3): + """C3 module with TransformerBlock().""" + + def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5): + """Initialize C3 module with TransformerBlock. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of Transformer blocks. + shortcut (bool): Whether to use shortcut connections. + g (int): Groups for convolutions. + e (float): Expansion ratio. + """ + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = TransformerBlock(c_, c_, 4, n) + + +class C3Ghost(C3): + """C3 module with GhostBottleneck().""" + + def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5): + """Initialize C3 module with GhostBottleneck. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of Ghost bottleneck blocks. + shortcut (bool): Whether to use shortcut connections. + g (int): Groups for convolutions. + e (float): Expansion ratio. + """ + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) # hidden channels + self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n))) + + +class GhostBottleneck(nn.Module): + """Ghost Bottleneck https://github.com/huawei-noah/Efficient-AI-Backbones.""" + + def __init__(self, c1: int, c2: int, k: int = 3, s: int = 1): + """Initialize Ghost Bottleneck module. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + k (int): Kernel size. + s (int): Stride. + """ + super().__init__() + c_ = c2 // 2 + self.conv = nn.Sequential( + GhostConv(c1, c_, 1, 1), # pw + DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw + GhostConv(c_, c2, 1, 1, act=False), # pw-linear + ) + self.shortcut = ( + nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity() + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply skip connection and addition to input tensor.""" + return self.conv(x) + self.shortcut(x) + + +class Bottleneck(nn.Module): + """Standard bottleneck.""" + + def __init__( + self, c1: int, c2: int, shortcut: bool = True, g: int = 1, k: tuple[int, int] = (3, 3), e: float = 0.5 + ): + """Initialize a standard bottleneck module. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + shortcut (bool): Whether to use shortcut connection. + g (int): Groups for convolutions. + k (tuple): Kernel sizes for convolutions. + e (float): Expansion ratio. + """ + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, k[0], 1) + self.cv2 = Conv(c_, c2, k[1], 1, g=g) + self.add = shortcut and c1 == c2 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply bottleneck with optional shortcut connection.""" + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) + + +class BottleneckCSP(nn.Module): + """CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks.""" + + def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5): + """Initialize CSP Bottleneck. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of Bottleneck blocks. + shortcut (bool): Whether to use shortcut connections. + g (int): Groups for convolutions. + e (float): Expansion ratio. + """ + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False) + self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False) + self.cv4 = Conv(2 * c_, c2, 1, 1) + self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3) + self.act = nn.SiLU() + self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply CSP bottleneck with 4 convolutions.""" + y1 = self.cv3(self.m(self.cv1(x))) + y2 = self.cv2(x) + return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1)))) + + +class ResNetBlock(nn.Module): + """ResNet block with standard convolution layers.""" + + def __init__(self, c1: int, c2: int, s: int = 1, e: int = 4): + """Initialize ResNet block. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + s (int): Stride. + e (int): Expansion ratio. + """ + super().__init__() + c3 = e * c2 + self.cv1 = Conv(c1, c2, k=1, s=1, act=True) + self.cv2 = Conv(c2, c2, k=3, s=s, p=1, act=True) + self.cv3 = Conv(c2, c3, k=1, act=False) + self.shortcut = nn.Sequential(Conv(c1, c3, k=1, s=s, act=False)) if s != 1 or c1 != c3 else nn.Identity() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass through the ResNet block.""" + return F.relu(self.cv3(self.cv2(self.cv1(x))) + self.shortcut(x)) + + +class ResNetLayer(nn.Module): + """ResNet layer with multiple ResNet blocks.""" + + def __init__(self, c1: int, c2: int, s: int = 1, is_first: bool = False, n: int = 1, e: int = 4): + """Initialize ResNet layer. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + s (int): Stride. + is_first (bool): Whether this is the first layer. + n (int): Number of ResNet blocks. + e (int): Expansion ratio. + """ + super().__init__() + self.is_first = is_first + + if self.is_first: + self.layer = nn.Sequential( + Conv(c1, c2, k=7, s=2, p=3, act=True), nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + ) + else: + blocks = [ResNetBlock(c1, c2, s, e=e)] + blocks.extend([ResNetBlock(e * c2, c2, 1, e=e) for _ in range(n - 1)]) + self.layer = nn.Sequential(*blocks) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass through the ResNet layer.""" + return self.layer(x) + + +class MaxSigmoidAttnBlock(nn.Module): + """Max Sigmoid attention block.""" + + def __init__(self, c1: int, c2: int, nh: int = 1, ec: int = 128, gc: int = 512, scale: bool = False): + """Initialize MaxSigmoidAttnBlock. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + nh (int): Number of heads. + ec (int): Embedding channels. + gc (int): Guide channels. + scale (bool): Whether to use learnable scale parameter. + """ + super().__init__() + self.nh = nh + self.hc = c2 // nh + self.ec = Conv(c1, ec, k=1, act=False) if c1 != ec else None + self.gl = nn.Linear(gc, ec) + self.bias = nn.Parameter(torch.zeros(nh)) + self.proj_conv = Conv(c1, c2, k=3, s=1, act=False) + self.scale = nn.Parameter(torch.ones(1, nh, 1, 1)) if scale else 1.0 + + def forward(self, x: torch.Tensor, guide: torch.Tensor) -> torch.Tensor: + """Forward pass of MaxSigmoidAttnBlock. + + Args: + x (torch.Tensor): Input tensor. + guide (torch.Tensor): Guide tensor. + + Returns: + (torch.Tensor): Output tensor after attention. + """ + bs, _, h, w = x.shape + + guide = self.gl(guide) + guide = guide.view(bs, guide.shape[1], self.nh, self.hc) + embed = self.ec(x) if self.ec is not None else x + embed = embed.view(bs, self.nh, self.hc, h, w) + + aw = torch.einsum("bmchw,bnmc->bmhwn", embed, guide) + aw = aw.max(dim=-1)[0] + aw = aw / (self.hc**0.5) + aw = aw + self.bias[None, :, None, None] + aw = aw.sigmoid() * self.scale + + x = self.proj_conv(x) + x = x.view(bs, self.nh, -1, h, w) + x = x * aw.unsqueeze(2) + return x.view(bs, -1, h, w) + + +class C2fAttn(nn.Module): + """C2f module with an additional attn module.""" + + def __init__( + self, + c1: int, + c2: int, + n: int = 1, + ec: int = 128, + nh: int = 1, + gc: int = 512, + shortcut: bool = False, + g: int = 1, + e: float = 0.5, + ): + """Initialize C2f module with attention mechanism. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of Bottleneck blocks. + ec (int): Embedding channels for attention. + nh (int): Number of heads for attention. + gc (int): Guide channels for attention. + shortcut (bool): Whether to use shortcut connections. + g (int): Groups for convolutions. + e (float): Expansion ratio. + """ + super().__init__() + self.c = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, 2 * self.c, 1, 1) + self.cv2 = Conv((3 + n) * self.c, c2, 1) # optional act=FReLU(c2) + self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n)) + self.attn = MaxSigmoidAttnBlock(self.c, self.c, gc=gc, ec=ec, nh=nh) + + def forward(self, x: torch.Tensor, guide: torch.Tensor) -> torch.Tensor: + """Forward pass through C2f layer with attention. + + Args: + x (torch.Tensor): Input tensor. + guide (torch.Tensor): Guide tensor for attention. + + Returns: + (torch.Tensor): Output tensor after processing. + """ + y = list(self.cv1(x).chunk(2, 1)) + y.extend(m(y[-1]) for m in self.m) + y.append(self.attn(y[-1], guide)) + return self.cv2(torch.cat(y, 1)) + + def forward_split(self, x: torch.Tensor, guide: torch.Tensor) -> torch.Tensor: + """Forward pass using split() instead of chunk(). + + Args: + x (torch.Tensor): Input tensor. + guide (torch.Tensor): Guide tensor for attention. + + Returns: + (torch.Tensor): Output tensor after processing. + """ + y = list(self.cv1(x).split((self.c, self.c), 1)) + y.extend(m(y[-1]) for m in self.m) + y.append(self.attn(y[-1], guide)) + return self.cv2(torch.cat(y, 1)) + + +class ImagePoolingAttn(nn.Module): + """ImagePoolingAttn: Enhance the text embeddings with image-aware information.""" + + def __init__( + self, ec: int = 256, ch: tuple[int, ...] = (), ct: int = 512, nh: int = 8, k: int = 3, scale: bool = False + ): + """Initialize ImagePoolingAttn module. + + Args: + ec (int): Embedding channels. + ch (tuple): Channel dimensions for feature maps. + ct (int): Channel dimension for text embeddings. + nh (int): Number of attention heads. + k (int): Kernel size for pooling. + scale (bool): Whether to use learnable scale parameter. + """ + super().__init__() + + nf = len(ch) + self.query = nn.Sequential(nn.LayerNorm(ct), nn.Linear(ct, ec)) + self.key = nn.Sequential(nn.LayerNorm(ec), nn.Linear(ec, ec)) + self.value = nn.Sequential(nn.LayerNorm(ec), nn.Linear(ec, ec)) + self.proj = nn.Linear(ec, ct) + self.scale = nn.Parameter(torch.tensor([0.0]), requires_grad=True) if scale else 1.0 + self.projections = nn.ModuleList([nn.Conv2d(in_channels, ec, kernel_size=1) for in_channels in ch]) + self.im_pools = nn.ModuleList([nn.AdaptiveMaxPool2d((k, k)) for _ in range(nf)]) + self.ec = ec + self.nh = nh + self.nf = nf + self.hc = ec // nh + self.k = k + + def forward(self, x: list[torch.Tensor], text: torch.Tensor) -> torch.Tensor: + """Forward pass of ImagePoolingAttn. + + Args: + x (list[torch.Tensor]): List of input feature maps. + text (torch.Tensor): Text embeddings. + + Returns: + (torch.Tensor): Enhanced text embeddings. + """ + bs = x[0].shape[0] + assert len(x) == self.nf + num_patches = self.k**2 + x = [pool(proj(x)).view(bs, -1, num_patches) for (x, proj, pool) in zip(x, self.projections, self.im_pools)] + x = torch.cat(x, dim=-1).transpose(1, 2) + q = self.query(text) + k = self.key(x) + v = self.value(x) + + # q = q.reshape(1, text.shape[1], self.nh, self.hc).repeat(bs, 1, 1, 1) + q = q.reshape(bs, -1, self.nh, self.hc) + k = k.reshape(bs, -1, self.nh, self.hc) + v = v.reshape(bs, -1, self.nh, self.hc) + + aw = torch.einsum("bnmc,bkmc->bmnk", q, k) + aw = aw / (self.hc**0.5) + aw = F.softmax(aw, dim=-1) + + x = torch.einsum("bmnk,bkmc->bnmc", aw, v) + x = self.proj(x.reshape(bs, -1, self.ec)) + return x * self.scale + text + + +class ContrastiveHead(nn.Module): + """Implements contrastive learning head for region-text similarity in vision-language models.""" + + def __init__(self): + """Initialize ContrastiveHead with region-text similarity parameters.""" + super().__init__() + # NOTE: use -10.0 to keep the init cls loss consistency with other losses + self.bias = nn.Parameter(torch.tensor([-10.0])) + self.logit_scale = nn.Parameter(torch.ones([]) * torch.tensor(1 / 0.07).log()) + + def forward(self, x: torch.Tensor, w: torch.Tensor) -> torch.Tensor: + """Forward function of contrastive learning. + + Args: + x (torch.Tensor): Image features. + w (torch.Tensor): Text features. + + Returns: + (torch.Tensor): Similarity scores. + """ + x = F.normalize(x, dim=1, p=2) + w = F.normalize(w, dim=-1, p=2) + x = torch.einsum("bchw,bkc->bkhw", x, w) + return x * self.logit_scale.exp() + self.bias + + +class BNContrastiveHead(nn.Module): + """Batch Norm Contrastive Head using batch norm instead of l2-normalization. + + Args: + embed_dims (int): Embed dimensions of text and image features. + """ + + def __init__(self, embed_dims: int): + """Initialize BNContrastiveHead. + + Args: + embed_dims (int): Embedding dimensions for features. + """ + super().__init__() + self.norm = nn.BatchNorm2d(embed_dims) + # NOTE: use -10.0 to keep the init cls loss consistency with other losses + self.bias = nn.Parameter(torch.tensor([-10.0])) + # use -1.0 is more stable + self.logit_scale = nn.Parameter(-1.0 * torch.ones([])) + + def fuse(self): + """Fuse the batch normalization layer in the BNContrastiveHead module.""" + del self.norm + del self.bias + del self.logit_scale + self.forward = self.forward_fuse + + @staticmethod + def forward_fuse(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor: + """Passes image features through unchanged after fusing.""" + return x + + def forward(self, x: torch.Tensor, w: torch.Tensor) -> torch.Tensor: + """Forward function of contrastive learning with batch normalization. + + Args: + x (torch.Tensor): Image features. + w (torch.Tensor): Text features. + + Returns: + (torch.Tensor): Similarity scores. + """ + x = self.norm(x) + w = F.normalize(w, dim=-1, p=2) + + x = torch.einsum("bchw,bkc->bkhw", x, w) + return x * self.logit_scale.exp() + self.bias + + +class RepBottleneck(Bottleneck): + """Rep bottleneck.""" + + def __init__( + self, c1: int, c2: int, shortcut: bool = True, g: int = 1, k: tuple[int, int] = (3, 3), e: float = 0.5 + ): + """Initialize RepBottleneck. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + shortcut (bool): Whether to use shortcut connection. + g (int): Groups for convolutions. + k (tuple): Kernel sizes for convolutions. + e (float): Expansion ratio. + """ + super().__init__(c1, c2, shortcut, g, k, e) + c_ = int(c2 * e) # hidden channels + self.cv1 = RepConv(c1, c_, k[0], 1) + + +class RepCSP(C3): + """Repeatable Cross Stage Partial Network (RepCSP) module for efficient feature extraction.""" + + def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5): + """Initialize RepCSP layer. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of RepBottleneck blocks. + shortcut (bool): Whether to use shortcut connections. + g (int): Groups for convolutions. + e (float): Expansion ratio. + """ + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) # hidden channels + self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) + + +class RepNCSPELAN4(nn.Module): + """CSP-ELAN.""" + + def __init__(self, c1: int, c2: int, c3: int, c4: int, n: int = 1): + """Initialize CSP-ELAN layer. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + c3 (int): Intermediate channels. + c4 (int): Intermediate channels for RepCSP. + n (int): Number of RepCSP blocks. + """ + super().__init__() + self.c = c3 // 2 + self.cv1 = Conv(c1, c3, 1, 1) + self.cv2 = nn.Sequential(RepCSP(c3 // 2, c4, n), Conv(c4, c4, 3, 1)) + self.cv3 = nn.Sequential(RepCSP(c4, c4, n), Conv(c4, c4, 3, 1)) + self.cv4 = Conv(c3 + (2 * c4), c2, 1, 1) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass through RepNCSPELAN4 layer.""" + y = list(self.cv1(x).chunk(2, 1)) + y.extend((m(y[-1])) for m in [self.cv2, self.cv3]) + return self.cv4(torch.cat(y, 1)) + + def forward_split(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass using split() instead of chunk().""" + y = list(self.cv1(x).split((self.c, self.c), 1)) + y.extend(m(y[-1]) for m in [self.cv2, self.cv3]) + return self.cv4(torch.cat(y, 1)) + + +class ELAN1(RepNCSPELAN4): + """ELAN1 module with 4 convolutions.""" + + def __init__(self, c1: int, c2: int, c3: int, c4: int): + """Initialize ELAN1 layer. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + c3 (int): Intermediate channels. + c4 (int): Intermediate channels for convolutions. + """ + super().__init__(c1, c2, c3, c4) + self.c = c3 // 2 + self.cv1 = Conv(c1, c3, 1, 1) + self.cv2 = Conv(c3 // 2, c4, 3, 1) + self.cv3 = Conv(c4, c4, 3, 1) + self.cv4 = Conv(c3 + (2 * c4), c2, 1, 1) + + +class AConv(nn.Module): + """AConv.""" + + def __init__(self, c1: int, c2: int): + """Initialize AConv module. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + """ + super().__init__() + self.cv1 = Conv(c1, c2, 3, 2, 1) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass through AConv layer.""" + x = torch.nn.functional.avg_pool2d(x, 2, 1, 0, False, True) + return self.cv1(x) + + +class ADown(nn.Module): + """ADown.""" + + def __init__(self, c1: int, c2: int): + """Initialize ADown module. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + """ + super().__init__() + self.c = c2 // 2 + self.cv1 = Conv(c1 // 2, self.c, 3, 2, 1) + self.cv2 = Conv(c1 // 2, self.c, 1, 1, 0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass through ADown layer.""" + x = torch.nn.functional.avg_pool2d(x, 2, 1, 0, False, True) + x1, x2 = x.chunk(2, 1) + x1 = self.cv1(x1) + x2 = torch.nn.functional.max_pool2d(x2, 3, 2, 1) + x2 = self.cv2(x2) + return torch.cat((x1, x2), 1) + + +class SPPELAN(nn.Module): + """SPP-ELAN.""" + + def __init__(self, c1: int, c2: int, c3: int, k: int = 5): + """Initialize SPP-ELAN block. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + c3 (int): Intermediate channels. + k (int): Kernel size for max pooling. + """ + super().__init__() + self.c = c3 + self.cv1 = Conv(c1, c3, 1, 1) + self.cv2 = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2) + self.cv3 = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2) + self.cv4 = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2) + self.cv5 = Conv(4 * c3, c2, 1, 1) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass through SPPELAN layer.""" + y = [self.cv1(x)] + y.extend(m(y[-1]) for m in [self.cv2, self.cv3, self.cv4]) + return self.cv5(torch.cat(y, 1)) + + +class CBLinear(nn.Module): + """CBLinear.""" + + def __init__(self, c1: int, c2s: list[int], k: int = 1, s: int = 1, p: int | None = None, g: int = 1): + """Initialize CBLinear module. + + Args: + c1 (int): Input channels. + c2s (list[int]): List of output channel sizes. + k (int): Kernel size. + s (int): Stride. + p (int | None): Padding. + g (int): Groups. + """ + super().__init__() + self.c2s = c2s + self.conv = nn.Conv2d(c1, sum(c2s), k, s, autopad(k, p), groups=g, bias=True) + + def forward(self, x: torch.Tensor) -> list[torch.Tensor]: + """Forward pass through CBLinear layer.""" + return self.conv(x).split(self.c2s, dim=1) + + +class CBFuse(nn.Module): + """CBFuse.""" + + def __init__(self, idx: list[int]): + """Initialize CBFuse module. + + Args: + idx (list[int]): Indices for feature selection. + """ + super().__init__() + self.idx = idx + + def forward(self, xs: list[torch.Tensor]) -> torch.Tensor: + """Forward pass through CBFuse layer. + + Args: + xs (list[torch.Tensor]): List of input tensors. + + Returns: + (torch.Tensor): Fused output tensor. + """ + target_size = xs[-1].shape[2:] + res = [F.interpolate(x[self.idx[i]], size=target_size, mode="nearest") for i, x in enumerate(xs[:-1])] + return torch.sum(torch.stack(res + xs[-1:]), dim=0) + + +class C3f(nn.Module): + """Faster Implementation of CSP Bottleneck with 3 convolutions.""" + + def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = False, g: int = 1, e: float = 0.5): + """Initialize CSP bottleneck layer with three convolutions. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of Bottleneck blocks. + shortcut (bool): Whether to use shortcut connections. + g (int): Groups for convolutions. + e (float): Expansion ratio. + """ + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c1, c_, 1, 1) + self.cv3 = Conv((2 + n) * c_, c2, 1) # optional act=FReLU(c2) + self.m = nn.ModuleList(Bottleneck(c_, c_, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass through C3f layer.""" + y = [self.cv2(x), self.cv1(x)] + y.extend(m(y[-1]) for m in self.m) + return self.cv3(torch.cat(y, 1)) + + +class C3k2(C2f): + """Faster Implementation of CSP Bottleneck with 2 convolutions.""" + + def __init__( + self, + c1: int, + c2: int, + n: int = 1, + c3k: bool = False, + e: float = 0.5, + attn: bool = False, + g: int = 1, + shortcut: bool = True, + ): + """Initialize C3k2 module. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of blocks. + c3k (bool): Whether to use C3k blocks. + e (float): Expansion ratio. + attn (bool): Whether to use attention blocks. + g (int): Groups for convolutions. + shortcut (bool): Whether to use shortcut connections. + """ + super().__init__(c1, c2, n, shortcut, g, e) + self.m = nn.ModuleList( + nn.Sequential( + Bottleneck(self.c, self.c, shortcut, g), + PSABlock(self.c, attn_ratio=0.5, num_heads=max(self.c // 64, 1)), + ) + if attn + else C3k(self.c, self.c, 2, shortcut, g) + if c3k + else Bottleneck(self.c, self.c, shortcut, g) + for _ in range(n) + ) + + +class C3k(C3): + """C3k is a CSP bottleneck module with customizable kernel sizes for feature extraction in neural networks.""" + + def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5, k: int = 3): + """Initialize C3k module. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of Bottleneck blocks. + shortcut (bool): Whether to use shortcut connections. + g (int): Groups for convolutions. + e (float): Expansion ratio. + k (int): Kernel size. + """ + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) # hidden channels + # self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n))) + self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n))) + + +class RepVGGDW(torch.nn.Module): + """RepVGGDW is a class that represents a depth-wise convolutional block in RepVGG architecture.""" + + def __init__(self, ed: int) -> None: + """Initialize RepVGGDW module. + + Args: + ed (int): Input and output channels. + """ + super().__init__() + self.conv = Conv(ed, ed, 7, 1, 3, g=ed, act=False) + self.conv1 = Conv(ed, ed, 3, 1, 1, g=ed, act=False) + self.dim = ed + self.act = nn.SiLU() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Perform a forward pass of the RepVGGDW block. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor after applying the depth-wise convolution. + """ + return self.act(self.conv(x) + self.conv1(x)) + + def forward_fuse(self, x: torch.Tensor) -> torch.Tensor: + """Perform a forward pass of the fused RepVGGDW block. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor after applying the depth-wise convolution. + """ + return self.act(self.conv(x)) + + @torch.no_grad() + def fuse(self): + """Fuse the convolutional layers in the RepVGGDW block. + + This method fuses the convolutional layers and updates the weights and biases accordingly. + """ + if not hasattr(self, "conv1"): + return # already fused + conv = fuse_conv_and_bn(self.conv.conv, self.conv.bn) + conv1 = fuse_conv_and_bn(self.conv1.conv, self.conv1.bn) + + conv_w = conv.weight + conv_b = conv.bias + conv1_w = conv1.weight + conv1_b = conv1.bias + + conv1_w = torch.nn.functional.pad(conv1_w, [2, 2, 2, 2]) + + final_conv_w = conv_w + conv1_w + final_conv_b = conv_b + conv1_b + + conv.weight.data.copy_(final_conv_w) + conv.bias.data.copy_(final_conv_b) + + self.conv = conv + del self.conv1 + + +class CIB(nn.Module): + """Compact Inverted Block (CIB) module. + + Args: + c1 (int): Number of input channels. + c2 (int): Number of output channels. + shortcut (bool, optional): Whether to add a shortcut connection. Defaults to True. + e (float, optional): Scaling factor for the hidden channels. Defaults to 0.5. + lk (bool, optional): Whether to use RepVGGDW for the third convolutional layer. Defaults to False. + """ + + def __init__(self, c1: int, c2: int, shortcut: bool = True, e: float = 0.5, lk: bool = False): + """Initialize the CIB module. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + shortcut (bool): Whether to use shortcut connection. + e (float): Expansion ratio. + lk (bool): Whether to use RepVGGDW. + """ + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = nn.Sequential( + Conv(c1, c1, 3, g=c1), + Conv(c1, 2 * c_, 1), + RepVGGDW(2 * c_) if lk else Conv(2 * c_, 2 * c_, 3, g=2 * c_), + Conv(2 * c_, c2, 1), + Conv(c2, c2, 3, g=c2), + ) + + self.add = shortcut and c1 == c2 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass of the CIB module. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor. + """ + return x + self.cv1(x) if self.add else self.cv1(x) + + +class C2fCIB(C2f): + """C2fCIB class represents a convolutional block with C2f and CIB modules. + + Args: + c1 (int): Number of input channels. + c2 (int): Number of output channels. + n (int, optional): Number of CIB modules to stack. Defaults to 1. + shortcut (bool, optional): Whether to use shortcut connection. Defaults to False. + lk (bool, optional): Whether to use large kernel. Defaults to False. + g (int, optional): Number of groups for grouped convolution. Defaults to 1. + e (float, optional): Expansion ratio for CIB modules. Defaults to 0.5. + """ + + def __init__( + self, c1: int, c2: int, n: int = 1, shortcut: bool = False, lk: bool = False, g: int = 1, e: float = 0.5 + ): + """Initialize C2fCIB module. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of CIB modules. + shortcut (bool): Whether to use shortcut connection. + lk (bool): Whether to use large kernel. + g (int): Groups for convolutions. + e (float): Expansion ratio. + """ + super().__init__(c1, c2, n, shortcut, g, e) + self.m = nn.ModuleList(CIB(self.c, self.c, shortcut, e=1.0, lk=lk) for _ in range(n)) + + +class Attention(nn.Module): + """Attention module that performs self-attention on the input tensor. + + Args: + dim (int): The input tensor dimension. + num_heads (int): The number of attention heads. + attn_ratio (float): The ratio of the attention key dimension to the head dimension. + + Attributes: + num_heads (int): The number of attention heads. + head_dim (int): The dimension of each attention head. + key_dim (int): The dimension of the attention key. + scale (float): The scaling factor for the attention scores. + qkv (Conv): Convolutional layer for computing the query, key, and value. + proj (Conv): Convolutional layer for projecting the attended values. + pe (Conv): Convolutional layer for positional encoding. + """ + + format = None + + def __init__(self, dim: int, num_heads: int = 8, attn_ratio: float = 0.5): + """Initialize multi-head attention module. + + Args: + dim (int): Input dimension. + num_heads (int): Number of attention heads. + attn_ratio (float): Attention ratio for key dimension. + """ + super().__init__() + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.key_dim = int(self.head_dim * attn_ratio) + self.scale = self.key_dim**-0.5 + nh_kd = self.key_dim * num_heads + h = dim + nh_kd * 2 + self.qkv = Conv(dim, h, 1, act=False) + self.proj = Conv(dim, dim, 1, act=False) + self.pe = Conv(dim, dim, 3, 1, g=dim, act=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass of the Attention module. + + Args: + x (torch.Tensor): The input tensor. + + Returns: + (torch.Tensor): The output tensor after self-attention. + """ + B, C, H, W = x.shape + N = H * W + qkv = self.qkv(x) + q, k, v = qkv.view(B, self.num_heads, self.key_dim * 2 + self.head_dim, N).split( + [self.key_dim, self.key_dim, self.head_dim], dim=2 + ) + + if self.format == "coreml" and hasattr(F, "scaled_dot_product_attention"): + x = F.scaled_dot_product_attention(q.transpose(-2, -1), k.transpose(-2, -1), v.transpose(-2, -1)) + x = x.transpose(-2, -1).reshape(B, C, H, W) + self.pe(v.reshape(B, C, H, W)) + else: + attn = ((q * self.scale).transpose(-2, -1) @ k).softmax(dim=-1) + x = (v @ attn.transpose(-2, -1)).view(B, C, H, W) + self.pe(v.reshape(B, C, H, W)) + x = self.proj(x) + return x + + +class PSABlock(nn.Module): + """PSABlock class implementing a Position-Sensitive Attention block for neural networks. + + This class encapsulates the functionality for applying multi-head attention and feed-forward neural network layers + with optional shortcut connections. + + Attributes: + attn (Attention): Multi-head attention module. + ffn (nn.Sequential): Feed-forward neural network module. + add (bool): Flag indicating whether to add shortcut connections. + + Methods: + forward: Performs a forward pass through the PSABlock, applying attention and feed-forward layers. + + Examples: + Create a PSABlock and perform a forward pass + >>> psablock = PSABlock(c=128, attn_ratio=0.5, num_heads=4, shortcut=True) + >>> input_tensor = torch.randn(1, 128, 32, 32) + >>> output_tensor = psablock(input_tensor) + """ + + def __init__(self, c: int, attn_ratio: float = 0.5, num_heads: int = 4, shortcut: bool = True) -> None: + """Initialize the PSABlock. + + Args: + c (int): Input and output channels. + attn_ratio (float): Attention ratio for key dimension. + num_heads (int): Number of attention heads. + shortcut (bool): Whether to use shortcut connections. + """ + super().__init__() + + self.attn = Attention(c, attn_ratio=attn_ratio, num_heads=num_heads) + self.ffn = nn.Sequential(Conv(c, c * 2, 1), Conv(c * 2, c, 1, act=False)) + self.add = shortcut + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Execute a forward pass through PSABlock. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor after attention and feed-forward processing. + """ + x = x + self.attn(x) if self.add else self.attn(x) + x = x + self.ffn(x) if self.add else self.ffn(x) + return x + + +class PSA(nn.Module): + """PSA class for implementing Position-Sensitive Attention in neural networks. + + This class encapsulates the functionality for applying position-sensitive attention and feed-forward networks to + input tensors, enhancing feature extraction and processing capabilities. + + Attributes: + c (int): Number of hidden channels after applying the initial convolution. + cv1 (Conv): 1x1 convolution layer to reduce the number of input channels to 2*c. + cv2 (Conv): 1x1 convolution layer to reduce the number of output channels to c1. + attn (Attention): Attention module for position-sensitive attention. + ffn (nn.Sequential): Feed-forward network for further processing. + + Methods: + forward: Applies position-sensitive attention and feed-forward network to the input tensor. + + Examples: + Create a PSA module and apply it to an input tensor + >>> psa = PSA(c1=128, c2=128, e=0.5) + >>> input_tensor = torch.randn(1, 128, 64, 64) + >>> output_tensor = psa.forward(input_tensor) + """ + + def __init__(self, c1: int, c2: int, e: float = 0.5): + """Initialize PSA module. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + e (float): Expansion ratio. + """ + super().__init__() + assert c1 == c2 + self.c = int(c1 * e) + self.cv1 = Conv(c1, 2 * self.c, 1, 1) + self.cv2 = Conv(2 * self.c, c1, 1) + + self.attn = Attention(self.c, attn_ratio=0.5, num_heads=max(self.c // 64, 1)) + self.ffn = nn.Sequential(Conv(self.c, self.c * 2, 1), Conv(self.c * 2, self.c, 1, act=False)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Execute forward pass in PSA module. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor after attention and feed-forward processing. + """ + a, b = self.cv1(x).split((self.c, self.c), dim=1) + b = b + self.attn(b) + b = b + self.ffn(b) + return self.cv2(torch.cat((a, b), 1)) + + +class C2PSA(nn.Module): + """C2PSA module with attention mechanism for enhanced feature extraction and processing. + + This module implements a convolutional block with attention mechanisms to enhance feature extraction and processing + capabilities. It includes a series of PSABlock modules for self-attention and feed-forward operations. + + Attributes: + c (int): Number of hidden channels. + cv1 (Conv): 1x1 convolution layer to reduce the number of input channels to 2*c. + cv2 (Conv): 1x1 convolution layer to reduce the number of output channels to c1. + m (nn.Sequential): Sequential container of PSABlock modules for attention and feed-forward operations. + + Methods: + forward: Performs a forward pass through the C2PSA module, applying attention and feed-forward operations. + + Examples: + >>> c2psa = C2PSA(c1=256, c2=256, n=3, e=0.5) + >>> input_tensor = torch.randn(1, 256, 64, 64) + >>> output_tensor = c2psa(input_tensor) + + Notes: + This module essentially is the same as PSA module, but refactored to allow stacking more PSABlock modules. + """ + + def __init__(self, c1: int, c2: int, n: int = 1, e: float = 0.5): + """Initialize C2PSA module. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of PSABlock modules. + e (float): Expansion ratio. + """ + super().__init__() + assert c1 == c2 + self.c = int(c1 * e) + self.cv1 = Conv(c1, 2 * self.c, 1, 1) + self.cv2 = Conv(2 * self.c, c1, 1) + + self.m = nn.Sequential(*(PSABlock(self.c, attn_ratio=0.5, num_heads=max(self.c // 64, 1)) for _ in range(n))) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Process the input tensor through a series of PSA blocks. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor after processing. + """ + a, b = self.cv1(x).split((self.c, self.c), dim=1) + b = self.m(b) + return self.cv2(torch.cat((a, b), 1)) + + +class C2fPSA(C2f): + """C2fPSA module with enhanced feature extraction using PSA blocks. + + This class extends the C2f module by incorporating PSA blocks for improved attention mechanisms and feature + extraction. + + Attributes: + c (int): Number of hidden channels. + cv1 (Conv): 1x1 convolution layer to reduce the number of input channels to 2*c. + cv2 (Conv): 1x1 convolution layer to reduce the number of output channels to c2. + m (nn.ModuleList): List of PSABlock modules for feature extraction. + + Methods: + forward: Performs a forward pass through the C2fPSA module. + forward_split: Performs a forward pass using split() instead of chunk(). + + Examples: + >>> import torch + >>> from ultralytics.nn.modules.block import C2fPSA + >>> model = C2fPSA(c1=64, c2=64, n=3, e=0.5) + >>> x = torch.randn(1, 64, 128, 128) + >>> output = model(x) + >>> print(output.shape) + """ + + def __init__(self, c1: int, c2: int, n: int = 1, e: float = 0.5): + """Initialize C2fPSA module. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + n (int): Number of PSABlock modules. + e (float): Expansion ratio. + """ + assert c1 == c2 + super().__init__(c1, c2, n=n, e=e) + self.m = nn.ModuleList(PSABlock(self.c, attn_ratio=0.5, num_heads=max(self.c // 64, 1)) for _ in range(n)) + + +class SCDown(nn.Module): + """SCDown module for downsampling with separable convolutions. + + This module performs downsampling using a combination of pointwise and depthwise convolutions, which helps in + efficiently reducing the spatial dimensions of the input tensor while maintaining the channel information. + + Attributes: + cv1 (Conv): Pointwise convolution layer that reduces the number of channels. + cv2 (Conv): Depthwise convolution layer that performs spatial downsampling. + + Methods: + forward: Applies the SCDown module to the input tensor. + + Examples: + >>> import torch + >>> from ultralytics.nn.modules.block import SCDown + >>> model = SCDown(c1=64, c2=128, k=3, s=2) + >>> x = torch.randn(1, 64, 128, 128) + >>> y = model(x) + >>> print(y.shape) + torch.Size([1, 128, 64, 64]) + """ + + def __init__(self, c1: int, c2: int, k: int, s: int): + """Initialize SCDown module. + + Args: + c1 (int): Input channels. + c2 (int): Output channels. + k (int): Kernel size. + s (int): Stride. + """ + super().__init__() + self.cv1 = Conv(c1, c2, 1, 1) + self.cv2 = Conv(c2, c2, k=k, s=s, g=c2, act=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply convolution and downsampling to the input tensor. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Downsampled output tensor. + """ + return self.cv2(self.cv1(x)) + + +class TorchVision(nn.Module): + """TorchVision module to allow loading any torchvision model. + + This class provides a way to load a model from the torchvision library, optionally load pre-trained weights, and + customize the model by truncating or unwrapping layers. + + Args: + model (str): Name of the torchvision model to load. + weights (str, optional): Pre-trained weights to load. Default is "DEFAULT". + unwrap (bool, optional): Unwraps the model to a sequential containing all but the last `truncate` layers. + truncate (int, optional): Number of layers to truncate from the end if `unwrap` is True. Default is 2. + split (bool, optional): Returns output from intermediate child modules as list. Default is False. + + Attributes: + m (nn.Module): The loaded torchvision model, possibly truncated and unwrapped. + """ + + def __init__( + self, model: str, weights: str = "DEFAULT", unwrap: bool = True, truncate: int = 2, split: bool = False + ): + """Load the model and weights from torchvision. + + Args: + model (str): Name of the torchvision model to load. + weights (str): Pre-trained weights to load. + unwrap (bool): Whether to unwrap the model. + truncate (int): Number of layers to truncate. + split (bool): Whether to split the output. + """ + import torchvision # scope for faster 'import ultralytics' + + super().__init__() + if hasattr(torchvision.models, "get_model"): + self.m = torchvision.models.get_model(model, weights=weights) + else: + self.m = torchvision.models.__dict__[model](pretrained=bool(weights)) + if unwrap: + layers = list(self.m.children()) + if isinstance(layers[0], nn.Sequential): # Second-level for some models like EfficientNet, Swin + layers = [*list(layers[0].children()), *layers[1:]] + self.m = nn.Sequential(*(layers[:-truncate] if truncate else layers)) + self.split = split + else: + self.split = False + self.m.head = self.m.heads = nn.Identity() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass through the model. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor | list[torch.Tensor]): Output tensor or list of tensors. + """ + if self.split: + y = [x] + y.extend(m(y[-1]) for m in self.m) + else: + y = self.m(x) + return y + + +class AAttn(nn.Module): + """Area-attention module for YOLO models, providing efficient attention mechanisms. + + This module implements an area-based attention mechanism that processes input features in a spatially-aware manner, + making it particularly effective for object detection tasks. + + Attributes: + area (int): Number of areas the feature map is divided into. + num_heads (int): Number of heads into which the attention mechanism is divided. + head_dim (int): Dimension of each attention head. + qkv (Conv): Convolution layer for computing query, key and value tensors. + proj (Conv): Projection convolution layer. + pe (Conv): Position encoding convolution layer. + + Methods: + forward: Applies area-attention to input tensor. + + Examples: + >>> attn = AAttn(dim=256, num_heads=8, area=4) + >>> x = torch.randn(1, 256, 32, 32) + >>> output = attn(x) + >>> print(output.shape) + torch.Size([1, 256, 32, 32]) + """ + + def __init__(self, dim: int, num_heads: int, area: int = 1): + """Initialize an Area-attention module for YOLO models. + + Args: + dim (int): Number of hidden channels. + num_heads (int): Number of heads into which the attention mechanism is divided. + area (int): Number of areas the feature map is divided into. + """ + super().__init__() + self.area = area + + self.num_heads = num_heads + self.head_dim = head_dim = dim // num_heads + self.all_head_dim = all_head_dim = head_dim * self.num_heads + + self.qkv = Conv(dim, all_head_dim * 3, 1, act=False) + self.proj = Conv(all_head_dim, dim, 1, act=False) + self.pe = Conv(all_head_dim, all_head_dim, 7, 1, 3, g=all_head_dim, act=False) + + def __setstate__(self, state): + """Add missing all_head_dim attribute to old checkpoints.""" + super().__setstate__(state) + if not hasattr(self, "all_head_dim"): + self.all_head_dim = self.head_dim * self.num_heads + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Process the input tensor through the area-attention. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor after area-attention. + """ + B, _, H, W = x.shape + N = H * W + + qkv = self.qkv(x).flatten(2).transpose(1, 2) + if self.area > 1: + qkv = qkv.reshape(B * self.area, N // self.area, self.all_head_dim * 3) + B, N, _ = qkv.shape + q, k, v = ( + qkv.view(B, N, self.num_heads, self.head_dim * 3) + .permute(0, 2, 3, 1) + .split([self.head_dim, self.head_dim, self.head_dim], dim=2) + ) + attn = (q * (self.head_dim**-0.5)).transpose(-2, -1) @ k + attn = attn.softmax(dim=-1) + x = v @ attn.transpose(-2, -1) + x = x.permute(0, 3, 1, 2) + v = v.permute(0, 3, 1, 2) + + if self.area > 1: + x = x.reshape(B // self.area, N * self.area, self.all_head_dim) + v = v.reshape(B // self.area, N * self.area, self.all_head_dim) + B, N, _ = x.shape + + x = x.reshape(B, H, W, self.all_head_dim).permute(0, 3, 1, 2).contiguous() + v = v.reshape(B, H, W, self.all_head_dim).permute(0, 3, 1, 2).contiguous() + + x = x + self.pe(v) + return self.proj(x) + + +class ABlock(nn.Module): + """Area-attention block module for efficient feature extraction in YOLO models. + + This module implements an area-attention mechanism combined with a feed-forward network for processing feature maps. + It uses a novel area-based attention approach that is more efficient than traditional self-attention while + maintaining effectiveness. + + Attributes: + attn (AAttn): Area-attention module for processing spatial features. + mlp (nn.Sequential): Multi-layer perceptron for feature transformation. + + Methods: + _init_weights: Initializes module weights using truncated normal distribution. + forward: Applies area-attention and feed-forward processing to input tensor. + + Examples: + >>> block = ABlock(dim=256, num_heads=8, mlp_ratio=1.2, area=1) + >>> x = torch.randn(1, 256, 32, 32) + >>> output = block(x) + >>> print(output.shape) + torch.Size([1, 256, 32, 32]) + """ + + def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 1.2, area: int = 1): + """Initialize an Area-attention block module. + + Args: + dim (int): Number of input channels. + num_heads (int): Number of heads into which the attention mechanism is divided. + mlp_ratio (float): Expansion ratio for MLP hidden dimension. + area (int): Number of areas the feature map is divided into. + """ + super().__init__() + + self.attn = AAttn(dim, num_heads=num_heads, area=area) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = nn.Sequential(Conv(dim, mlp_hidden_dim, 1), Conv(mlp_hidden_dim, dim, 1, act=False)) + + self.apply(self._init_weights) + + @staticmethod + def _init_weights(m: nn.Module): + """Initialize weights using a truncated normal distribution. + + Args: + m (nn.Module): Module to initialize. + """ + if isinstance(m, nn.Conv2d): + nn.init.trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass through ABlock. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor after area-attention and feed-forward processing. + """ + x = x + self.attn(x) + return x + self.mlp(x) + + +class A2C2f(nn.Module): + """Area-Attention C2f module for enhanced feature extraction with area-based attention mechanisms. + + This module extends the C2f architecture by incorporating area-attention and ABlock layers for improved feature + processing. It supports both area-attention and standard convolution modes. + + Attributes: + cv1 (Conv): Initial 1x1 convolution layer that reduces input channels to hidden channels. + cv2 (Conv): Final 1x1 convolution layer that processes concatenated features. + gamma (nn.Parameter | None): Learnable parameter for residual scaling when using area attention. + m (nn.ModuleList): List of either ABlock or C3k modules for feature processing. + + Methods: + forward: Processes input through area-attention or standard convolution pathway. + + Examples: + >>> m = A2C2f(512, 512, n=1, a2=True, area=1) + >>> x = torch.randn(1, 512, 32, 32) + >>> output = m(x) + >>> print(output.shape) + torch.Size([1, 512, 32, 32]) + """ + + def __init__( + self, + c1: int, + c2: int, + n: int = 1, + a2: bool = True, + area: int = 1, + residual: bool = False, + mlp_ratio: float = 2.0, + e: float = 0.5, + g: int = 1, + shortcut: bool = True, + ): + """Initialize Area-Attention C2f module. + + Args: + c1 (int): Number of input channels. + c2 (int): Number of output channels. + n (int): Number of ABlock or C3k modules to stack. + a2 (bool): Whether to use area attention blocks. If False, uses C3k blocks instead. + area (int): Number of areas the feature map is divided into. + residual (bool): Whether to use residual connections with learnable gamma parameter. + mlp_ratio (float): Expansion ratio for MLP hidden dimension. + e (float): Channel expansion ratio for hidden channels. + g (int): Number of groups for grouped convolutions. + shortcut (bool): Whether to use shortcut connections in C3k blocks. + """ + super().__init__() + c_ = int(c2 * e) # hidden channels + assert c_ % 32 == 0, "Dimension of ABlock must be a multiple of 32." + + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv((1 + n) * c_, c2, 1) + + self.gamma = nn.Parameter(0.01 * torch.ones(c2), requires_grad=True) if a2 and residual else None + self.m = nn.ModuleList( + nn.Sequential(*(ABlock(c_, c_ // 32, mlp_ratio, area) for _ in range(2))) + if a2 + else C3k(c_, c_, 2, shortcut, g) + for _ in range(n) + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass through A2C2f layer. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor after processing. + """ + y = [self.cv1(x)] + y.extend(m(y[-1]) for m in self.m) + y = self.cv2(torch.cat(y, 1)) + if self.gamma is not None: + return x + self.gamma.view(-1, self.gamma.shape[0], 1, 1) * y + return y + + +class SwiGLUFFN(nn.Module): + """SwiGLU Feed-Forward Network for transformer-based architectures.""" + + def __init__(self, gc: int, ec: int, e: int = 4) -> None: + """Initialize SwiGLU FFN with input dimension, output dimension, and expansion factor. + + Args: + gc (int): Guide channels. + ec (int): Embedding channels. + e (int): Expansion factor. + """ + super().__init__() + self.w12 = nn.Linear(gc, e * ec) + self.w3 = nn.Linear(e * ec // 2, ec) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply SwiGLU transformation to input features.""" + x12 = self.w12(x) + x1, x2 = x12.chunk(2, dim=-1) + hidden = F.silu(x1) * x2 + return self.w3(hidden) + + +class Residual(nn.Module): + """Residual connection wrapper for neural network modules.""" + + def __init__(self, m: nn.Module) -> None: + """Initialize residual module with the wrapped module. + + Args: + m (nn.Module): Module to wrap with residual connection. + """ + super().__init__() + self.m = m + nn.init.zeros_(self.m.w3.bias) + # For models with l scale, please change the initialization to + # nn.init.constant_(self.m.w3.weight, 1e-6) + nn.init.zeros_(self.m.w3.weight) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply residual connection to input features.""" + return x + self.m(x) + + +class SAVPE(nn.Module): + """Spatial-Aware Visual Prompt Embedding module for feature enhancement.""" + + def __init__(self, ch: list[int], c3: int, embed: int): + """Initialize SAVPE module with channels, intermediate channels, and embedding dimension. + + Args: + ch (list[int]): List of input channel dimensions. + c3 (int): Intermediate channels. + embed (int): Embedding dimension. + """ + super().__init__() + self.cv1 = nn.ModuleList( + nn.Sequential( + Conv(x, c3, 3), Conv(c3, c3, 3), nn.Upsample(scale_factor=i * 2) if i in {1, 2} else nn.Identity() + ) + for i, x in enumerate(ch) + ) + + self.cv2 = nn.ModuleList( + nn.Sequential(Conv(x, c3, 1), nn.Upsample(scale_factor=i * 2) if i in {1, 2} else nn.Identity()) + for i, x in enumerate(ch) + ) + + self.c = 16 + self.cv3 = nn.Conv2d(3 * c3, embed, 1) + self.cv4 = nn.Conv2d(3 * c3, self.c, 3, padding=1) + self.cv5 = nn.Conv2d(1, self.c, 3, padding=1) + self.cv6 = nn.Sequential(Conv(2 * self.c, self.c, 3), nn.Conv2d(self.c, self.c, 3, padding=1)) + + def forward(self, x: list[torch.Tensor], vp: torch.Tensor) -> torch.Tensor: + """Process input features and visual prompts to generate enhanced embeddings.""" + y = [self.cv2[i](xi) for i, xi in enumerate(x)] + y = self.cv4(torch.cat(y, dim=1)) + + x = [self.cv1[i](xi) for i, xi in enumerate(x)] + x = self.cv3(torch.cat(x, dim=1)) + + B, C, H, W = x.shape + + Q = vp.shape[1] + + x = x.view(B, C, -1) + + y = y.reshape(B, 1, self.c, H, W).expand(-1, Q, -1, -1, -1).reshape(B * Q, self.c, H, W) + vp = vp.reshape(B, Q, 1, H, W).reshape(B * Q, 1, H, W) + + y = self.cv6(torch.cat((y, self.cv5(vp)), dim=1)) + + y = y.reshape(B, Q, self.c, -1) + vp = vp.reshape(B, Q, 1, -1) + + score = y * vp + torch.logical_not(vp) * torch.finfo(y.dtype).min + score = F.softmax(score, dim=-1).to(y.dtype) + aggregated = score.transpose(-2, -3) @ x.reshape(B, self.c, C // self.c, -1).transpose(-1, -2) + + return F.normalize(aggregated.transpose(-2, -3).reshape(B, Q, -1), dim=-1, p=2) + + +class Proto26(Proto): + """Ultralytics YOLO26 models mask Proto module for segmentation models.""" + + def __init__(self, ch: tuple = (), c_: int = 256, c2: int = 32, nc: int = 80): + """Initialize the Ultralytics YOLO models mask Proto module with specified number of protos and masks. + + Args: + ch (tuple): Tuple of channel sizes from backbone feature maps. + c_ (int): Intermediate channels. + c2 (int): Output channels (number of protos). + nc (int): Number of classes for semantic segmentation. + """ + super().__init__(c_, c_, c2) + self.feat_refine = nn.ModuleList(Conv(x, ch[0], k=1) for x in ch[1:]) + self.feat_fuse = Conv(ch[0], c_, k=3) + self.semseg = nn.Sequential(Conv(ch[0], c_, k=3), Conv(c_, c_, k=3), nn.Conv2d(c_, nc, 1)) + + def forward(self, x: torch.Tensor, return_semantic: bool = True) -> torch.Tensor: + """Perform a forward pass by fusing multi-scale feature maps and generating proto masks.""" + feat = x[0] + for i, f in enumerate(self.feat_refine): + up_feat = f(x[i + 1]) + # Constant scale (P4/P5 -> P3) keeps the upsample static for dynamic-shape CoreML export + up_feat = F.interpolate(up_feat, scale_factor=2 ** (i + 1), mode="nearest") + feat = feat + up_feat + p = super().forward(self.feat_fuse(feat)) + if self.training and return_semantic: + semantic = self.semseg(feat) + return (p, semantic) + return p + + def fuse(self): + """Fuse the model for inference by removing the semantic segmentation head.""" + self.semseg = None + + +class RealNVP(nn.Module): + """RealNVP: a flow-based generative model. + + References: + https://arxiv.org/abs/1605.08803 + https://github.com/open-mmlab/mmpose/blob/main/mmpose/models/utils/realnvp.py + """ + + @staticmethod + def nets(): + """Get the scale model in a single invertible mapping.""" + return nn.Sequential(nn.Linear(2, 64), nn.SiLU(), nn.Linear(64, 64), nn.SiLU(), nn.Linear(64, 2), nn.Tanh()) + + @staticmethod + def nett(): + """Get the translation model in a single invertible mapping.""" + return nn.Sequential(nn.Linear(2, 64), nn.SiLU(), nn.Linear(64, 64), nn.SiLU(), nn.Linear(64, 2)) + + def __init__(self): + super().__init__() + + # loc/cov are no longer read (the prior is the closed-form standard normal in log_prob) but stay registered so + # checkpoints saved before 8.4.126 still resume: the EMA state is loaded strictly. + self.register_buffer("loc", torch.zeros(2)) + self.register_buffer("cov", torch.eye(2)) + self.register_buffer("mask", torch.tensor([[0, 1], [1, 0]] * 3, dtype=torch.float32)) + + self.s = torch.nn.ModuleList([self.nets() for _ in range(len(self.mask))]) + self.t = torch.nn.ModuleList([self.nett() for _ in range(len(self.mask))]) + self.init_weights() + + def init_weights(self): + """Initialize model weights.""" + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.xavier_uniform_(m.weight, gain=0.01) + + def backward_p(self, x): + """Apply mapping from the data space to the latent space and calculate the log determinant of the Jacobian + matrix. + """ + log_det_jacob, z = x.new_zeros(x.shape[0]), x + for i in reversed(range(len(self.t))): + z_ = self.mask[i] * z + s = self.s[i](z_) * (1 - self.mask[i]) + t = self.t[i](z_) * (1 - self.mask[i]) + z = (1 - self.mask[i]) * (z - t) * torch.exp(-s) + z_ + log_det_jacob -= s.sum(dim=1) + return z, log_det_jacob + + def log_prob(self, x): + """Calculate the log probability of given sample in data space.""" + if x.dtype == torch.float32 and self.s[0][0].weight.dtype != torch.float32: + self.float() + z, log_det = self.backward_p(x) + # Closed-form log N(z; 0, I) in 2-D; fp32 keeps z**2 from overflowing under AMP. + return -0.5 * (z.float() ** 2).sum(-1) - math.log(2 * math.pi) + log_det diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/conv.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..252de9cd49fe34c2637511baf036cbe1db9360d4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/conv.py @@ -0,0 +1,670 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Convolution modules.""" + +from __future__ import annotations + +import math + +import numpy as np +import torch +from torch import nn + +__all__ = ( + "CBAM", + "ChannelAttention", + "Concat", + "Conv", + "Conv2", + "ConvTranspose", + "DWConv", + "DWConvTranspose2d", + "Focus", + "GhostConv", + "Index", + "LightConv", + "RepConv", + "SpatialAttention", +) + + +def autopad(k, p=None, d=1): # kernel, padding, dilation + """Pad to 'same' shape outputs.""" + if d > 1: + k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size + if p is None: + p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad + return p + + +class Conv(nn.Module): + """Standard convolution module with batch normalization and activation. + + Attributes: + conv (nn.Conv2d): Convolutional layer. + bn (nn.BatchNorm2d): Batch normalization layer. + act (nn.Module): Activation function layer. + default_act (nn.Module): Default activation function (SiLU). + """ + + default_act = nn.SiLU() # default activation + + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True): + """Initialize Conv layer with given parameters. + + Args: + c1 (int): Number of input channels. + c2 (int): Number of output channels. + k (int): Kernel size. + s (int): Stride. + p (int, optional): Padding. + g (int): Groups. + d (int): Dilation. + act (bool | nn.Module): Activation function. + """ + super().__init__() + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False) + self.bn = nn.BatchNorm2d(c2) + self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity() + + def forward(self, x): + """Apply convolution, batch normalization and activation to input tensor. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor. + """ + return self.act(self.bn(self.conv(x))) + + def forward_fuse(self, x): + """Apply convolution and activation without batch normalization. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor. + """ + return self.act(self.conv(x)) + + +class Conv2(Conv): + """Simplified RepConv module with Conv fusing. + + Attributes: + conv (nn.Conv2d): Main 3x3 convolutional layer. + cv2 (nn.Conv2d): Additional 1x1 convolutional layer. + bn (nn.BatchNorm2d): Batch normalization layer. + act (nn.Module): Activation function layer. + """ + + def __init__(self, c1, c2, k=3, s=1, p=None, g=1, d=1, act=True): + """Initialize Conv2 layer with given parameters. + + Args: + c1 (int): Number of input channels. + c2 (int): Number of output channels. + k (int): Kernel size. + s (int): Stride. + p (int, optional): Padding. + g (int): Groups. + d (int): Dilation. + act (bool | nn.Module): Activation function. + """ + super().__init__(c1, c2, k, s, p, g=g, d=d, act=act) + self.cv2 = nn.Conv2d(c1, c2, 1, s, autopad(1, p, d), groups=g, dilation=d, bias=False) # add 1x1 conv + + def forward(self, x): + """Apply convolution, batch normalization and activation to input tensor. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor. + """ + return self.act(self.bn(self.conv(x) + self.cv2(x))) + + def forward_fuse(self, x): + """Apply fused convolution, batch normalization and activation to input tensor. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor. + """ + return self.act(self.bn(self.conv(x))) + + def fuse_convs(self): + """Fuse parallel convolutions.""" + w = torch.zeros_like(self.conv.weight.data) + i = [x // 2 for x in w.shape[2:]] + w[:, :, i[0] : i[0] + 1, i[1] : i[1] + 1] = self.cv2.weight.data.clone() + self.conv.weight.data += w + self.__delattr__("cv2") + self.forward = self.forward_fuse + + +class LightConv(nn.Module): + """Light convolution module with 1x1 and depthwise convolutions. + + This implementation is based on the PaddleDetection HGNetV2 backbone. + + Attributes: + conv1 (Conv): 1x1 convolution layer. + conv2 (DWConv): Depthwise convolution layer. + """ + + def __init__(self, c1, c2, k=1, act=None): + """Initialize LightConv layer with given parameters. + + Args: + c1 (int): Number of input channels. + c2 (int): Number of output channels. + k (int): Kernel size for depthwise convolution. + act (nn.Module): Activation function. + """ + super().__init__() + act = nn.ReLU() if act is None else act + self.conv1 = Conv(c1, c2, 1, act=False) + self.conv2 = DWConv(c2, c2, k, act=act) + + def forward(self, x): + """Apply 2 convolutions to input tensor. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor. + """ + return self.conv2(self.conv1(x)) + + +class DWConv(Conv): + """Depth-wise convolution module.""" + + def __init__(self, c1, c2, k=1, s=1, d=1, act=True): + """Initialize depth-wise convolution with given parameters. + + Args: + c1 (int): Number of input channels. + c2 (int): Number of output channels. + k (int): Kernel size. + s (int): Stride. + d (int): Dilation. + act (bool | nn.Module): Activation function. + """ + super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act) + + +class DWConvTranspose2d(nn.ConvTranspose2d): + """Depth-wise transpose convolution module.""" + + def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): + """Initialize depth-wise transpose convolution with given parameters. + + Args: + c1 (int): Number of input channels. + c2 (int): Number of output channels. + k (int): Kernel size. + s (int): Stride. + p1 (int): Padding. + p2 (int): Output padding. + """ + super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2)) + + +class ConvTranspose(nn.Module): + """Convolution transpose module with optional batch normalization and activation. + + Attributes: + conv_transpose (nn.ConvTranspose2d): Transposed convolution layer. + bn (nn.BatchNorm2d | nn.Identity): Batch normalization layer. + act (nn.Module): Activation function layer. + default_act (nn.Module): Default activation function (SiLU). + """ + + default_act = nn.SiLU() # default activation + + def __init__(self, c1, c2, k=2, s=2, p=0, bn=True, act=True): + """Initialize ConvTranspose layer with given parameters. + + Args: + c1 (int): Number of input channels. + c2 (int): Number of output channels. + k (int): Kernel size. + s (int): Stride. + p (int): Padding. + bn (bool): Use batch normalization. + act (bool | nn.Module): Activation function. + """ + super().__init__() + self.conv_transpose = nn.ConvTranspose2d(c1, c2, k, s, p, bias=not bn) + self.bn = nn.BatchNorm2d(c2) if bn else nn.Identity() + self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity() + + def forward(self, x): + """Apply transposed convolution, batch normalization and activation to input. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor. + """ + return self.act(self.bn(self.conv_transpose(x))) + + def forward_fuse(self, x): + """Apply convolution transpose and activation to input. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor. + """ + return self.act(self.conv_transpose(x)) + + +class Focus(nn.Module): + """Focus module for concentrating feature information. + + Slices input tensor into 4 parts and concatenates them in the channel dimension. + + Attributes: + conv (Conv): Convolution layer. + """ + + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): + """Initialize Focus module with given parameters. + + Args: + c1 (int): Number of input channels. + c2 (int): Number of output channels. + k (int): Kernel size. + s (int): Stride. + p (int, optional): Padding. + g (int): Groups. + act (bool | nn.Module): Activation function. + """ + super().__init__() + self.conv = Conv(c1 * 4, c2, k, s, p, g, act=act) + # self.contract = Contract(gain=2) + + def forward(self, x): + """Apply Focus operation and convolution to input tensor. + + Input shape is (B, C, H, W) and output shape is (B, c2, H/2, W/2). + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor. + """ + return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1)) + # return self.conv(self.contract(x)) + + +class GhostConv(nn.Module): + """Ghost Convolution module. + + Generates more features with fewer parameters by using cheap operations. + + Attributes: + cv1 (Conv): Primary convolution. + cv2 (Conv): Cheap operation convolution. + + References: + https://github.com/huawei-noah/Efficient-AI-Backbones + """ + + def __init__(self, c1, c2, k=1, s=1, g=1, act=True): + """Initialize Ghost Convolution module with given parameters. + + Args: + c1 (int): Number of input channels. + c2 (int): Number of output channels. + k (int): Kernel size. + s (int): Stride. + g (int): Groups. + act (bool | nn.Module): Activation function. + """ + super().__init__() + c_ = c2 // 2 # hidden channels + self.cv1 = Conv(c1, c_, k, s, None, g, act=act) + self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act) + + def forward(self, x): + """Apply Ghost Convolution to input tensor. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor with concatenated features. + """ + y = self.cv1(x) + return torch.cat((y, self.cv2(y)), 1) + + +class RepConv(nn.Module): + """RepConv module with training and deploy modes. + + This module is used in RT-DETR and can fuse convolutions during inference for efficiency. + + Attributes: + conv1 (Conv): 3x3 convolution. + conv2 (Conv): 1x1 convolution. + bn (nn.BatchNorm2d, optional): Batch normalization for identity branch. + act (nn.Module): Activation function. + default_act (nn.Module): Default activation function (SiLU). + + References: + https://github.com/DingXiaoH/RepVGG/blob/main/repvgg.py + """ + + default_act = nn.SiLU() # default activation + + def __init__(self, c1, c2, k=3, s=1, p=1, g=1, d=1, act=True, bn=False, deploy=False): + """Initialize RepConv module with given parameters. + + Args: + c1 (int): Number of input channels. + c2 (int): Number of output channels. + k (int): Kernel size. + s (int): Stride. + p (int): Padding. + g (int): Groups. + d (int): Dilation. + act (bool | nn.Module): Activation function. + bn (bool): Use batch normalization for identity branch. + deploy (bool): Deploy mode for inference. + """ + super().__init__() + assert k == 3 and p == 1 + self.g = g + self.c1 = c1 + self.c2 = c2 + self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity() + + self.bn = nn.BatchNorm2d(num_features=c1) if bn and c2 == c1 and s == 1 else None + self.conv1 = Conv(c1, c2, k, s, p=p, g=g, act=False) + self.conv2 = Conv(c1, c2, 1, s, p=(p - k // 2), g=g, act=False) + + def forward_fuse(self, x): + """Forward pass for deploy mode. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor. + """ + return self.act(self.conv(x)) + + def forward(self, x): + """Forward pass for training mode. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor. + """ + id_out = 0 if self.bn is None else self.bn(x) + return self.act(self.conv1(x) + self.conv2(x) + id_out) + + def get_equivalent_kernel_bias(self): + """Calculate equivalent kernel and bias by fusing convolutions. + + Returns: + (torch.Tensor): Equivalent kernel + (torch.Tensor): Equivalent bias + """ + kernel3x3, bias3x3 = self._fuse_bn_tensor(self.conv1) + kernel1x1, bias1x1 = self._fuse_bn_tensor(self.conv2) + kernelid, biasid = self._fuse_bn_tensor(self.bn) + return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid + + @staticmethod + def _pad_1x1_to_3x3_tensor(kernel1x1): + """Pad a 1x1 kernel to 3x3 size. + + Args: + kernel1x1 (torch.Tensor): 1x1 convolution kernel. + + Returns: + (torch.Tensor): Padded 3x3 kernel. + """ + if kernel1x1 is None: + return 0 + else: + return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1]) + + def _fuse_bn_tensor(self, branch): + """Fuse batch normalization with convolution weights. + + Args: + branch (Conv | nn.BatchNorm2d | None): Branch to fuse. + + Returns: + kernel (torch.Tensor): Fused kernel. + bias (torch.Tensor): Fused bias. + """ + if branch is None: + return 0, 0 + if isinstance(branch, Conv): + kernel = branch.conv.weight + running_mean = branch.bn.running_mean + running_var = branch.bn.running_var + gamma = branch.bn.weight + beta = branch.bn.bias + eps = branch.bn.eps + elif isinstance(branch, nn.BatchNorm2d): + if not hasattr(self, "id_tensor"): + input_dim = self.c1 // self.g + kernel_value = np.zeros((self.c1, input_dim, 3, 3), dtype=np.float32) + for i in range(self.c1): + kernel_value[i, i % input_dim, 1, 1] = 1 + self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device) + kernel = self.id_tensor + running_mean = branch.running_mean + running_var = branch.running_var + gamma = branch.weight + beta = branch.bias + eps = branch.eps + std = (running_var + eps).sqrt() + t = (gamma / std).reshape(-1, 1, 1, 1) + return kernel * t, beta - running_mean * gamma / std + + def fuse_convs(self): + """Fuse convolutions for inference by creating a single equivalent convolution.""" + if hasattr(self, "conv"): + return + kernel, bias = self.get_equivalent_kernel_bias() + self.conv = nn.Conv2d( + in_channels=self.conv1.conv.in_channels, + out_channels=self.conv1.conv.out_channels, + kernel_size=self.conv1.conv.kernel_size, + stride=self.conv1.conv.stride, + padding=self.conv1.conv.padding, + dilation=self.conv1.conv.dilation, + groups=self.conv1.conv.groups, + bias=True, + ).requires_grad_(False) + self.conv.weight.data = kernel + self.conv.bias.data = bias + for para in self.parameters(): + para.detach_() + self.__delattr__("conv1") + self.__delattr__("conv2") + if hasattr(self, "nm"): + self.__delattr__("nm") + if hasattr(self, "bn"): + self.__delattr__("bn") + if hasattr(self, "id_tensor"): + self.__delattr__("id_tensor") + + +class ChannelAttention(nn.Module): + """Channel-attention module for feature recalibration. + + Applies attention weights to channels based on global average pooling. + + Attributes: + pool (nn.AdaptiveAvgPool2d): Global average pooling. + fc (nn.Conv2d): Fully connected layer implemented as 1x1 convolution. + act (nn.Sigmoid): Sigmoid activation for attention weights. + + References: + https://github.com/open-mmlab/mmdetection/tree/v3.0.0rc1/configs/rtmdet + """ + + def __init__(self, channels: int) -> None: + """Initialize Channel-attention module. + + Args: + channels (int): Number of input channels. + """ + super().__init__() + self.pool = nn.AdaptiveAvgPool2d(1) + self.fc = nn.Conv2d(channels, channels, 1, 1, 0, bias=True) + self.act = nn.Sigmoid() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply channel attention to input tensor. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Channel-attended output tensor. + """ + return x * self.act(self.fc(self.pool(x))) + + +class SpatialAttention(nn.Module): + """Spatial-attention module for feature recalibration. + + Applies attention weights to spatial dimensions based on channel statistics. + + Attributes: + cv1 (nn.Conv2d): Convolution layer for spatial attention. + act (nn.Sigmoid): Sigmoid activation for attention weights. + """ + + def __init__(self, kernel_size=7): + """Initialize Spatial-attention module. + + Args: + kernel_size (int): Size of the convolutional kernel (3 or 7). + """ + super().__init__() + assert kernel_size in {3, 7}, "kernel size must be 3 or 7" + padding = 3 if kernel_size == 7 else 1 + self.cv1 = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False) + self.act = nn.Sigmoid() + + def forward(self, x): + """Apply spatial attention to input tensor. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Spatial-attended output tensor. + """ + return x * self.act(self.cv1(torch.cat([torch.mean(x, 1, keepdim=True), torch.max(x, 1, keepdim=True)[0]], 1))) + + +class CBAM(nn.Module): + """Convolutional Block Attention Module. + + Combines channel and spatial attention mechanisms for comprehensive feature refinement. + + Attributes: + channel_attention (ChannelAttention): Channel attention module. + spatial_attention (SpatialAttention): Spatial attention module. + """ + + def __init__(self, c1, kernel_size=7): + """Initialize CBAM with given parameters. + + Args: + c1 (int): Number of input channels. + kernel_size (int): Size of the convolutional kernel for spatial attention. + """ + super().__init__() + self.channel_attention = ChannelAttention(c1) + self.spatial_attention = SpatialAttention(kernel_size) + + def forward(self, x): + """Apply channel and spatial attention sequentially to input tensor. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Attended output tensor. + """ + return self.spatial_attention(self.channel_attention(x)) + + +class Concat(nn.Module): + """Concatenate a list of tensors along specified dimension. + + Attributes: + d (int): Dimension along which to concatenate tensors. + """ + + def __init__(self, dimension=1): + """Initialize Concat module. + + Args: + dimension (int): Dimension along which to concatenate tensors. + """ + super().__init__() + self.d = dimension + + def forward(self, x: list[torch.Tensor]): + """Concatenate input tensors along specified dimension. + + Args: + x (list[torch.Tensor]): List of input tensors. + + Returns: + (torch.Tensor): Concatenated tensor. + """ + return torch.cat(x, self.d) + + +class Index(nn.Module): + """Returns a particular index of the input. + + Attributes: + index (int): Index to select from input. + """ + + def __init__(self, index=0): + """Initialize Index module. + + Args: + index (int): Index to select from input. + """ + super().__init__() + self.index = index + + def forward(self, x: list[torch.Tensor]): + """Select and return a particular index from input. + + Args: + x (list[torch.Tensor]): List of input tensors. + + Returns: + (torch.Tensor): Selected tensor. + """ + return x[self.index] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/head.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/head.py new file mode 100644 index 0000000000000000000000000000000000000000..e10471df4fc8751697f34c4d542748cdd6b7530b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/head.py @@ -0,0 +1,1877 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Model head modules.""" + +from __future__ import annotations + +import copy +import math + +import torch +import torch.nn.functional as F +from torch import nn +from torch.nn.init import constant_, xavier_uniform_ + +from ultralytics.utils import LOGGER +from ultralytics.utils.tal import dist2bbox, dist2rbox, make_anchors +from ultralytics.utils.torch_utils import TORCH_1_11, fuse_conv_and_bn, smart_inference_mode + +from .block import DFL, SAVPE, BNContrastiveHead, ContrastiveHead, Proto, Proto26, RealNVP, Residual, SwiGLUFFN +from .conv import Conv, DWConv +from .transformer import MLP, DeformableTransformerDecoder, DeformableTransformerDecoderLayer +from .utils import bias_init_with_prob + +__all__ = ( + "OBB", + "Classify", + "Depth", + "Detect", + "Pose", + "RTDETRDecoder", + "Segment", + "SemanticSegment", + "YOLOEDetect", + "YOLOESegment", + "v10Detect", +) + + +class Detect(nn.Module): + """YOLO Detect head for object detection models. + + This class implements the detection head used in YOLO models for predicting bounding boxes and class probabilities. + It supports both training and inference modes, with optional end-to-end detection capabilities. + + Attributes: + dynamic (bool): Force grid reconstruction. + export (bool): Export mode flag. + format (str): Export format. + end2end (bool): End-to-end detection mode. + max_det (int): Maximum detections per image. + shape (tuple): Input shape. + anchors (torch.Tensor): Anchor points. + strides (torch.Tensor): Feature map strides. + legacy (bool): Backward compatibility for v3/v5/v8/v9/v11 models. + xyxy (bool): Output format, xyxy or xywh. + nc (int): Number of classes. + nl (int): Number of detection layers. + reg_max (int): DFL channels. + no (int): Number of outputs per anchor. + stride (torch.Tensor): Strides computed during build. + cv2 (nn.ModuleList): Convolution layers for box regression. + cv3 (nn.ModuleList): Convolution layers for classification. + dfl (nn.Module): Distribution Focal Loss layer. + one2one_cv2 (nn.ModuleList): One-to-one convolution layers for box regression. + one2one_cv3 (nn.ModuleList): One-to-one convolution layers for classification. + + Methods: + forward: Perform forward pass and return predictions. + bias_init: Initialize detection head biases. + decode_bboxes: Decode bounding boxes from predictions. + postprocess: Post-process model predictions. + + Examples: + Create a detection head for 80 classes + >>> detect = Detect(nc=80, ch=(256, 512, 1024)) + >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)] + >>> outputs = detect(x) + """ + + dynamic = False # force grid reconstruction + export = False # export mode + format = None # export format + max_det = 300 # max_det + agnostic_nms = False + shape = None + anchors = torch.empty(0) # init + strides = torch.empty(0) # init + legacy = False # backward compatibility for v3/v5/v8/v9 models + xyxy = False # xyxy or xywh output + + @staticmethod + def _grouped_topk(x: torch.Tensor, k: int, groups: int = 8) -> tuple[torch.Tensor, torch.Tensor]: + """Select exact top-k values through smaller grouped selections.""" + n = x.shape[1] + while groups > 1 and (n % groups or n // groups < k): + groups //= 2 + if groups == 1: # nothing to gain, e.g. a short axis or one that does not divide evenly + return x.topk(k, dim=1) + size = n // groups + values, index = x.reshape(x.shape[0], groups, size).topk(k, dim=-1) + values, winners = values.flatten(1).topk(k, dim=1) + return values, winners // k * size + index.flatten(1).gather(1, winners) + + def _gather(self, x: torch.Tensor, index: torch.Tensor) -> torch.Tensor: + """Select index (batch, k) rows of x (batch, n, channels) along dim 1.""" + return x.gather(1, index if x.ndim == 2 else index[..., None].expand(-1, -1, x.shape[-1])) + + def __init__(self, nc: int = 80, reg_max=16, end2end=False, ch: tuple = ()): + """Initialize the YOLO detection layer with specified number of classes and channels. + + Args: + nc (int): Number of classes. + reg_max (int): Maximum number of DFL channels. + end2end (bool): Whether to use end-to-end NMS-free detection. + ch (tuple): Tuple of channel sizes from backbone feature maps. + """ + super().__init__() + self.nc = nc # number of classes + self.nl = len(ch) # number of detection layers + self.reg_max = reg_max # DFL channels + self.no = nc + self.reg_max * 4 # number of outputs per anchor + self.stride = torch.zeros(self.nl) # strides computed during build + c2, c3 = max((16, ch[0] // 4, self.reg_max * 4)), max(ch[0], min(self.nc, 100)) # channels + self.cv2 = nn.ModuleList( + nn.Sequential(Conv(x, c2, 3), Conv(c2, c2, 3), nn.Conv2d(c2, 4 * self.reg_max, 1)) for x in ch + ) + self.cv3 = ( + nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, self.nc, 1)) for x in ch) + if self.legacy + else nn.ModuleList( + nn.Sequential( + nn.Sequential(DWConv(x, x, 3), Conv(x, c3, 1)), + nn.Sequential(DWConv(c3, c3, 3), Conv(c3, c3, 1)), + nn.Conv2d(c3, self.nc, 1), + ) + for x in ch + ) + ) + self.dfl = DFL(self.reg_max) if self.reg_max > 1 else nn.Identity() + + if end2end: + self.one2one_cv2 = copy.deepcopy(self.cv2) + self.one2one_cv3 = copy.deepcopy(self.cv3) + + @property + def one2many(self): + """Returns the one-to-many head components, here for v3/v5/v8/v9/v11 backward compatibility.""" + return {"box_head": self.cv2, "cls_head": self.cv3} + + @property + def one2one(self): + """Returns the one-to-one head components.""" + return {"box_head": self.one2one_cv2, "cls_head": self.one2one_cv3} + + @property + def end2end(self): + """Select one-to-one inference when requested or when fusion has removed the one-to-many head.""" + return getattr(self, "one2one_cv2", None) is not None and (getattr(self, "_end2end", False) or self.cv2 is None) + + @end2end.setter + def end2end(self, value): + """Select the inference head without changing dual-head training.""" + if value and getattr(self, "one2one_cv2", None) is None: + LOGGER.warning("This model has no one-to-one head; using one-to-many outputs.") + elif not value and self.cv2 is None: + LOGGER.warning("The one-to-many head was removed by fusion; using the remaining one-to-one head.") + self._end2end = value + + def forward_head( + self, x: list[torch.Tensor], box_head: torch.nn.Module = None, cls_head: torch.nn.Module = None + ) -> dict[str, torch.Tensor]: + """Concatenates and returns predicted bounding boxes and class probabilities.""" + if box_head is None or cls_head is None: # for fused inference + return {} + bs = x[0].shape[0] # batch size + boxes = torch.cat([box_head[i](x[i]).view(bs, 4 * self.reg_max, -1) for i in range(self.nl)], dim=-1) + scores = torch.cat([cls_head[i](x[i]).view(bs, self.nc, -1) for i in range(self.nl)], dim=-1) + return {"boxes": boxes, "scores": scores, "feats": x} + + def forward( + self, x: list[torch.Tensor] + ) -> dict[str, torch.Tensor] | torch.Tensor | tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Concatenates and returns predicted bounding boxes and class probabilities.""" + preds = self.forward_head(x, **self.one2many) + if getattr(self, "one2one_cv2", None) is not None: + x_detach = [xi.detach() for xi in x] if self.training else x # detach keeps one2one out of the backbone + one2one = self.forward_head(x_detach, **self.one2one) + preds = {"one2many": preds, "one2one": one2one} + if self.training: + return preds + y = self._inference(preds["one2one" if self.end2end else "one2many"] if "one2one" in preds else preds) + if self.end2end: + y = self.postprocess(y.permute(0, 2, 1)) + return y if self.export else (y, preds) + + def _inference(self, x: dict[str, torch.Tensor]) -> torch.Tensor: + """Decode predicted bounding boxes and class probabilities based on multiple-level feature maps. + + Args: + x (dict[str, torch.Tensor]): Dictionary of predictions from detection layers. + + Returns: + (torch.Tensor): Concatenated tensor of decoded bounding boxes and class probabilities. + """ + # Inference path + dbox = self._get_decode_boxes(x) + return torch.cat((dbox, x["scores"].sigmoid()), 1) + + def _get_decode_boxes(self, x: dict[str, torch.Tensor]) -> torch.Tensor: + """Get decoded boxes based on anchors and strides.""" + shape = x["feats"][0].shape # BCHW + if self.dynamic or self.shape != shape: + self.anchors, self.strides = (a.transpose(0, 1) for a in make_anchors(x["feats"], self.stride, 0.5)) + self.shape = shape + + dbox = self.decode_bboxes(self.dfl(x["boxes"]), self.anchors.unsqueeze(0), x.get("angle")) * self.strides + return dbox + + def bias_init(self): + """Initialize Detect() biases, WARNING: requires stride availability.""" + for i, (a, b) in enumerate(zip(self.one2many["box_head"], self.one2many["cls_head"])): # from + a[-1].bias.data[:] = 2.0 # box + b[-1].bias.data[: self.nc] = math.log( + 5 / self.nc / (640 / self.stride[i]) ** 2 + ) # cls (.01 objects, 80 classes, 640 img) + if getattr(self, "one2one_cv2", None) is not None: + for i, (a, b) in enumerate(zip(self.one2one["box_head"], self.one2one["cls_head"])): # from + a[-1].bias.data[:] = 2.0 # box + b[-1].bias.data[: self.nc] = math.log( + 5 / self.nc / (640 / self.stride[i]) ** 2 + ) # cls (.01 objects, 80 classes, 640 img) + + def decode_bboxes( + self, bboxes: torch.Tensor, anchors: torch.Tensor, angle: torch.Tensor | None = None + ) -> torch.Tensor: + """Decode bounding boxes from predictions, angle is only used by the OBB head.""" + return dist2bbox(bboxes, anchors, xywh=not self.end2end and not self.xyxy, dim=1) + + def postprocess(self, preds: torch.Tensor) -> torch.Tensor: + """Post-processes YOLO model predictions. + + Args: + preds (torch.Tensor): Raw predictions with shape (batch_size, num_anchors, 4 + nc + extra) with last + dimension format [x1, y1, x2, y2, class_probs, extra], where extra holds the mask coefficients, + keypoints or angle of the Segment, Pose and OBB heads and is empty for Detect. + + Returns: + (torch.Tensor): Processed predictions with shape (batch_size, min(max_det, num_anchors), 6 + extra) and last + dimension format [x1, y1, x2, y2, max_class_prob, class_index, extra]. + """ + # Segment, Pose and OBB carry task channels after the class scores, Detect has none + boxes, scores, *extra = preds.split([s for s in (4, self.nc, preds.shape[-1] - 4 - self.nc) if s], dim=-1) + scores, conf, idx = self.get_topk_index(scores, self.max_det) + return torch.cat([self._gather(boxes, idx), scores, conf, *(self._gather(e, idx) for e in extra)], dim=-1) + + def get_topk_index(self, scores: torch.Tensor, max_det: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Get top-k indices from scores. + + Args: + scores (torch.Tensor): Scores tensor with shape (batch_size, num_anchors, num_classes). + max_det (int): Maximum detections per image. + + Returns: + (torch.Tensor, torch.Tensor, torch.Tensor): Top scores, class indices, and filtered indices. + """ + anchors, nc = scores.shape[1:] # i.e. shape(16,8400,80) + k = min(max_det, anchors) + if self.agnostic_nms: + scores, labels = scores.max(dim=-1) + scores, index = self._grouped_topk(scores, k, 1) + return scores[..., None], self._gather(labels[..., None].float(), index), index + groups = 8 if self.export and self.format == "engine" and not self.dynamic else 1 + ori_index = self._grouped_topk(scores.max(dim=-1)[0], k, groups)[1] + scores = self._gather(scores, ori_index) + scores, index = self._grouped_topk(scores.flatten(1), k, groups) + return scores[..., None], (index % nc)[..., None].float(), self._gather(ori_index, index // nc) + + def fuse(self) -> None: + """Remove the unused detection branch for inference.""" + end2end = self.end2end + for name in tuple(self._modules): + if name.startswith("one2one_"): + setattr(self, name[8:] if end2end else name, None) + + +class Segment(Detect): + """YOLO Segment head for segmentation models. + + This class extends the Detect head to include mask prediction capabilities for instance segmentation tasks. + + Attributes: + nm (int): Number of masks. + npr (int): Number of protos. + proto (Proto): Prototype generation module. + cv4 (nn.ModuleList): Convolution layers for mask coefficients. + + Methods: + forward: Return model outputs and mask coefficients. + + Examples: + Create a segmentation head + >>> segment = Segment(nc=80, nm=32, npr=256, ch=(256, 512, 1024)) + >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)] + >>> outputs = segment(x) + """ + + def __init__(self, nc: int = 80, nm: int = 32, npr: int = 256, reg_max=16, end2end=False, ch: tuple = ()): + """Initialize the YOLO model attributes such as the number of masks, prototypes, and the convolution layers. + + Args: + nc (int): Number of classes. + nm (int): Number of masks. + npr (int): Number of protos. + reg_max (int): Maximum number of DFL channels. + end2end (bool): Whether to use end-to-end NMS-free detection. + ch (tuple): Tuple of channel sizes from backbone feature maps. + """ + super().__init__(nc, reg_max, end2end, ch) + self.nm = nm # number of masks + self.npr = npr # number of protos + self.proto = Proto(ch[0], self.npr, self.nm) # protos + + c4 = max(ch[0] // 4, self.nm) + self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nm, 1)) for x in ch) + if end2end: + self.one2one_cv4 = copy.deepcopy(self.cv4) + + @property + def one2many(self): + """Returns the one-to-many head components, here for backward compatibility.""" + return {"box_head": self.cv2, "cls_head": self.cv3, "mask_head": self.cv4} + + @property + def one2one(self): + """Returns the one-to-one head components.""" + return {"box_head": self.one2one_cv2, "cls_head": self.one2one_cv3, "mask_head": self.one2one_cv4} + + def forward(self, x: list[torch.Tensor]) -> tuple | list[torch.Tensor] | dict[str, torch.Tensor]: + """Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients.""" + outputs = super().forward(x) + preds = outputs[1] if isinstance(outputs, tuple) else outputs + proto = self.proto(x[0]) # mask protos + if isinstance(preds, dict): # training and validating during training + if "one2one" in preds: + preds["one2many"]["proto"] = proto + preds["one2one"]["proto"] = proto.detach() + else: + preds["proto"] = proto + if self.training: + return preds + return (outputs, proto) if self.export else ((outputs[0], proto), preds) + + def _inference(self, x: dict[str, torch.Tensor]) -> torch.Tensor: + """Decode predicted bounding boxes and class probabilities, concatenated with mask coefficients.""" + preds = super()._inference(x) + return torch.cat([preds, x["mask_coefficient"]], dim=1) + + def forward_head( + self, x: list[torch.Tensor], box_head: torch.nn.Module, cls_head: torch.nn.Module, mask_head: torch.nn.Module + ) -> dict[str, torch.Tensor]: + """Concatenates and returns predicted bounding boxes, class probabilities, and mask coefficients.""" + preds = super().forward_head(x, box_head, cls_head) + if mask_head is not None: + bs = x[0].shape[0] # batch size + preds["mask_coefficient"] = torch.cat([mask_head[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) + return preds + + +class Segment26(Segment): + """YOLO26 Segment head for segmentation models. + + This class extends the Segment head with Proto26 for mask prediction in instance segmentation tasks. + + Attributes: + nm (int): Number of masks. + npr (int): Number of protos. + proto (Proto26): Prototype generation module. + cv4 (nn.ModuleList): Convolution layers for mask coefficients. + + Methods: + forward: Return model outputs and mask coefficients. + + Examples: + Create a segmentation head + >>> segment = Segment26(nc=80, nm=32, npr=256, ch=(256, 512, 1024)) + >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)] + >>> outputs = segment(x) + """ + + def __init__(self, nc: int = 80, nm: int = 32, npr: int = 256, reg_max=16, end2end=False, ch: tuple = ()): + """Initialize the YOLO model attributes such as the number of masks, prototypes, and the convolution layers. + + Args: + nc (int): Number of classes. + nm (int): Number of masks. + npr (int): Number of protos. + reg_max (int): Maximum number of DFL channels. + end2end (bool): Whether to use end-to-end NMS-free detection. + ch (tuple): Tuple of channel sizes from backbone feature maps. + """ + super().__init__(nc, nm, npr, reg_max, end2end, ch) + self.proto = Proto26(ch, self.npr, self.nm, nc) # protos + + def forward(self, x: list[torch.Tensor]) -> tuple | list[torch.Tensor] | dict[str, torch.Tensor]: + """Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients.""" + outputs = Detect.forward(self, x) + preds = outputs[1] if isinstance(outputs, tuple) else outputs + proto = self.proto(x) # mask protos + if isinstance(preds, dict): # training and validating during training + if "one2one" in preds: + preds["one2many"]["proto"] = proto + preds["one2one"]["proto"] = ( + tuple(p.detach() for p in proto) if isinstance(proto, tuple) else proto.detach() + ) + else: + preds["proto"] = proto + if self.training: + return preds + return (outputs, proto) if self.export else ((outputs[0], proto), preds) + + def fuse(self) -> None: + """Remove the unused detection branch and training-only prototype layers for inference.""" + super().fuse() + if hasattr(self.proto, "fuse"): + self.proto.fuse() + + +class OBB(Detect): + """YOLO OBB detection head for detection with rotation models. + + This class extends the Detect head to include oriented bounding box prediction with rotation angles. + + Attributes: + ne (int): Number of extra parameters. + cv4 (nn.ModuleList): Convolution layers for angle prediction. + + Methods: + forward: Concatenate and return predicted bounding boxes and class probabilities. + decode_bboxes: Decode rotated bounding boxes. + + Examples: + Create an OBB detection head + >>> obb = OBB(nc=80, ne=1, ch=(256, 512, 1024)) + >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)] + >>> outputs = obb(x) + """ + + def __init__(self, nc: int = 80, ne: int = 1, reg_max=16, end2end=False, ch: tuple = ()): + """Initialize OBB with number of classes `nc` and layer channels `ch`. + + Args: + nc (int): Number of classes. + ne (int): Number of extra parameters. + reg_max (int): Maximum number of DFL channels. + end2end (bool): Whether to use end-to-end NMS-free detection. + ch (tuple): Tuple of channel sizes from backbone feature maps. + """ + super().__init__(nc, reg_max, end2end, ch) + self.ne = ne # number of extra parameters + + c4 = max(ch[0] // 4, self.ne) + self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.ne, 1)) for x in ch) + if end2end: + self.one2one_cv4 = copy.deepcopy(self.cv4) + + @property + def one2many(self): + """Returns the one-to-many head components, here for backward compatibility.""" + return {"box_head": self.cv2, "cls_head": self.cv3, "angle_head": self.cv4} + + @property + def one2one(self): + """Returns the one-to-one head components.""" + return {"box_head": self.one2one_cv2, "cls_head": self.one2one_cv3, "angle_head": self.one2one_cv4} + + def _inference(self, x: dict[str, torch.Tensor]) -> torch.Tensor: + """Decode predicted bounding boxes and class probabilities, concatenated with rotation angles.""" + preds = super()._inference(x) + return torch.cat([preds, x["angle"]], dim=1) + + def forward_head( + self, x: list[torch.Tensor], box_head: torch.nn.Module, cls_head: torch.nn.Module, angle_head: torch.nn.Module + ) -> dict[str, torch.Tensor]: + """Concatenates and returns predicted bounding boxes, class probabilities, and angles.""" + preds = super().forward_head(x, box_head, cls_head) + if angle_head is not None: + bs = x[0].shape[0] # batch size + angle = torch.cat( + [angle_head[i](x[i]).view(bs, self.ne, -1) for i in range(self.nl)], 2 + ) # OBB theta logits + angle = (angle.sigmoid() - 0.25) * math.pi # [-pi/4, 3pi/4] + preds["angle"] = angle + return preds + + def decode_bboxes(self, bboxes: torch.Tensor, anchors: torch.Tensor, angle: torch.Tensor) -> torch.Tensor: + """Decode rotated bounding boxes.""" + return dist2rbox(bboxes, angle, anchors, dim=1) + + +class OBB26(OBB): + """YOLO26 OBB detection head for detection with rotation models. This class extends the OBB head with modified angle + processing that outputs raw angle predictions without sigmoid transformation, compared to the original + OBB class. + + Attributes: + ne (int): Number of extra parameters. + cv4 (nn.ModuleList): Convolution layers for angle prediction. + + Methods: + forward_head: Concatenate and return predicted bounding boxes, class probabilities, and raw angles. + + Examples: + Create an OBB26 detection head + >>> obb26 = OBB26(nc=80, ne=1, ch=(256, 512, 1024)) + >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)] + >>> outputs = obb26(x) + """ + + def forward_head( + self, x: list[torch.Tensor], box_head: torch.nn.Module, cls_head: torch.nn.Module, angle_head: torch.nn.Module + ) -> dict[str, torch.Tensor]: + """Concatenates and returns predicted bounding boxes, class probabilities, and raw angles.""" + preds = Detect.forward_head(self, x, box_head, cls_head) + if angle_head is not None: + bs = x[0].shape[0] # batch size + angle = torch.cat( + [angle_head[i](x[i]).view(bs, self.ne, -1) for i in range(self.nl)], 2 + ) # OBB theta logits (raw output without sigmoid transformation) + preds["angle"] = angle + return preds + + +class Pose(Detect): + """YOLO Pose head for keypoints models. + + This class extends the Detect head to include keypoint prediction capabilities for pose estimation tasks. + + Attributes: + kpt_shape (tuple): Number of keypoints and dimensions (2 for x,y or 3 for x,y,visible). + nk (int): Total number of keypoint values. + cv4 (nn.ModuleList): Convolution layers for keypoint prediction. + + Methods: + forward: Perform forward pass through YOLO model and return predictions. + kpts_decode: Decode keypoints from predictions. + + Examples: + Create a pose detection head + >>> pose = Pose(nc=80, kpt_shape=(17, 3), ch=(256, 512, 1024)) + >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)] + >>> outputs = pose(x) + """ + + def __init__(self, nc: int = 80, kpt_shape: tuple = (17, 3), reg_max=16, end2end=False, ch: tuple = ()): + """Initialize YOLO network with default parameters and Convolutional Layers. + + Args: + nc (int): Number of classes. + kpt_shape (tuple): Number of keypoints, number of dims (2 for x,y or 3 for x,y,visible). + reg_max (int): Maximum number of DFL channels. + end2end (bool): Whether to use end-to-end NMS-free detection. + ch (tuple): Tuple of channel sizes from backbone feature maps. + """ + super().__init__(nc, reg_max, end2end, ch) + self.kpt_shape = kpt_shape # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible) + self.nk = kpt_shape[0] * kpt_shape[1] # number of keypoints total + + c4 = max(ch[0] // 4, self.nk) + self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nk, 1)) for x in ch) + if end2end: + self.one2one_cv4 = copy.deepcopy(self.cv4) + + @property + def one2many(self): + """Returns the one-to-many head components, here for backward compatibility.""" + return {"box_head": self.cv2, "cls_head": self.cv3, "pose_head": self.cv4} + + @property + def one2one(self): + """Returns the one-to-one head components.""" + return {"box_head": self.one2one_cv2, "cls_head": self.one2one_cv3, "pose_head": self.one2one_cv4} + + def _inference(self, x: dict[str, torch.Tensor]) -> torch.Tensor: + """Decode predicted bounding boxes and class probabilities, concatenated with keypoints.""" + preds = super()._inference(x) + return torch.cat([preds, self.kpts_decode(x["kpts"])], dim=1) + + def forward_head( + self, x: list[torch.Tensor], box_head: torch.nn.Module, cls_head: torch.nn.Module, pose_head: torch.nn.Module + ) -> dict[str, torch.Tensor]: + """Concatenates and returns predicted bounding boxes, class probabilities, and keypoints.""" + preds = super().forward_head(x, box_head, cls_head) + if pose_head is not None: + bs = x[0].shape[0] # batch size + preds["kpts"] = torch.cat([pose_head[i](x[i]).view(bs, self.nk, -1) for i in range(self.nl)], 2) + return preds + + def kpts_decode(self, kpts: torch.Tensor) -> torch.Tensor: + """Decode keypoints from predictions.""" + ndim = self.kpt_shape[1] + bs = kpts.shape[0] + if self.export: + y = kpts.view(bs, *self.kpt_shape, -1) + a = (y[:, :, :2] * 2.0 + (self.anchors - 0.5)) * self.strides + if ndim == 3: + a = torch.cat((a, y[:, :, 2:3].sigmoid()), 2) + return a.view(bs, self.nk, -1) + else: + y = kpts.clone() + if ndim == 3: + y[:, 2::ndim] = y[:, 2::ndim].sigmoid() + y[:, 0::ndim] = (y[:, 0::ndim] * 2.0 + (self.anchors[0] - 0.5)) * self.strides + y[:, 1::ndim] = (y[:, 1::ndim] * 2.0 + (self.anchors[1] - 0.5)) * self.strides + return y + + +class Pose26(Pose): + """YOLO26 Pose head for keypoints models. + + This class extends the Pose head with normalizing flow for keypoint prediction in pose estimation tasks. + + Attributes: + kpt_shape (tuple): Number of keypoints and dimensions (2 for x,y or 3 for x,y,visible). + nk (int): Total number of keypoint values. + cv4 (nn.ModuleList): Convolution layers for keypoint prediction. + + Methods: + forward: Perform forward pass through YOLO model and return predictions. + kpts_decode: Decode keypoints from predictions. + + Examples: + Create a pose detection head + >>> pose = Pose26(nc=80, kpt_shape=(17, 3), ch=(256, 512, 1024)) + >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)] + >>> outputs = pose(x) + """ + + def __init__(self, nc: int = 80, kpt_shape: tuple = (17, 3), reg_max=16, end2end=False, ch: tuple = ()): + """Initialize YOLO network with default parameters and Convolutional Layers. + + Args: + nc (int): Number of classes. + kpt_shape (tuple): Number of keypoints, number of dims (2 for x,y or 3 for x,y,visible). + reg_max (int): Maximum number of DFL channels. + end2end (bool): Whether to use end-to-end NMS-free detection. + ch (tuple): Tuple of channel sizes from backbone feature maps. + """ + super().__init__(nc, kpt_shape, reg_max, end2end, ch) + self.flow_model = RealNVP() + + c4 = max(ch[0] // 4, kpt_shape[0] * (kpt_shape[1] + 2)) + self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3)) for x in ch) + + self.cv4_kpts = nn.ModuleList(nn.Conv2d(c4, self.nk, 1) for _ in ch) + self.nk_sigma = kpt_shape[0] * 2 # sigma_x, sigma_y for each keypoint + self.cv4_sigma = nn.ModuleList(nn.Conv2d(c4, self.nk_sigma, 1) for _ in ch) + + if end2end: + self.one2one_cv4 = copy.deepcopy(self.cv4) + self.one2one_cv4_kpts = copy.deepcopy(self.cv4_kpts) + self.one2one_cv4_sigma = copy.deepcopy(self.cv4_sigma) + + @property + def one2many(self): + """Returns the one-to-many head components, here for backward compatibility.""" + return { + "box_head": self.cv2, + "cls_head": self.cv3, + "pose_head": self.cv4, + "kpts_head": self.cv4_kpts, + "kpts_sigma_head": self.cv4_sigma, + } + + @property + def one2one(self): + """Returns the one-to-one head components.""" + return { + "box_head": self.one2one_cv2, + "cls_head": self.one2one_cv3, + "pose_head": self.one2one_cv4, + "kpts_head": self.one2one_cv4_kpts, + "kpts_sigma_head": self.one2one_cv4_sigma, + } + + def forward_head( + self, + x: list[torch.Tensor], + box_head: torch.nn.Module, + cls_head: torch.nn.Module, + pose_head: torch.nn.Module, + kpts_head: torch.nn.Module, + kpts_sigma_head: torch.nn.Module, + ) -> dict[str, torch.Tensor]: + """Concatenates and returns predicted bounding boxes, class probabilities, and keypoints.""" + preds = Detect.forward_head(self, x, box_head, cls_head) + if pose_head is not None: + bs = x[0].shape[0] # batch size + features = [pose_head[i](x[i]) for i in range(self.nl)] + preds["kpts"] = torch.cat([kpts_head[i](features[i]).view(bs, self.nk, -1) for i in range(self.nl)], 2) + if self.training: + preds["kpts_sigma"] = torch.cat( + [kpts_sigma_head[i](features[i]).view(bs, self.nk_sigma, -1) for i in range(self.nl)], 2 + ) + return preds + + def fuse(self) -> None: + """Remove the unused detection branch and training-only layers for inference.""" + super().fuse() + self.flow_model = None + setattr(self, "one2one_cv4_sigma" if self.end2end else "cv4_sigma", None) + + def kpts_decode(self, kpts: torch.Tensor) -> torch.Tensor: + """Decode keypoints from predictions.""" + ndim = self.kpt_shape[1] + bs = kpts.shape[0] + if self.export: + y = kpts.view(bs, *self.kpt_shape, -1) + # NCNN fix + a = (y[:, :, :2] + self.anchors) * self.strides + if ndim == 3: + a = torch.cat((a, y[:, :, 2:3].sigmoid()), 2) + return a.view(bs, self.nk, -1) + else: + y = kpts.clone() + if ndim == 3: + y[:, 2::ndim] = y[:, 2::ndim].sigmoid() + y[:, 0::ndim] = (y[:, 0::ndim] + self.anchors[0]) * self.strides + y[:, 1::ndim] = (y[:, 1::ndim] + self.anchors[1]) * self.strides + return y + + +class Depth(nn.Module): + """YOLO Depth head for monocular depth estimation. + + A dense prediction head that takes multi-scale backbone features and produces a single-channel depth map via + progressive upsampling and fusion. + + Attributes: + nl (int): Number of pyramid levels. + cal_a (torch.Tensor): Log-affine calibration scale buffer, identity 1.0 by default. + cal_b (torch.Tensor): Log-affine calibration offset buffer, identity 0.0 by default. + + Examples: + >>> depth = Depth(ch=(256, 512, 1024)) + >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)] + >>> out = depth(x) # training: {"depth": (1, 1, 160, 160)} at P2 resolution (input/4) + """ + + export = False # export mode + + def __init__(self, c_mid: int = 256, ch: tuple = ()): + """Initialize Depth head. + + Args: + c_mid (int): Number of intermediate channels for the fusion decoder. + ch (tuple): Input channel sizes from backbone feature maps (P3, P4, P5). + """ + super().__init__() + self.nl = len(ch) # number of detection layers (pyramid levels) + + # Project each pyramid level to c_mid channels + self.proj = nn.ModuleList(Conv(c, c_mid, k=1) for c in ch) + + # Refinement blocks after each of the nl-1 fusion steps (the coarsest level is not refined) + self.refine = nn.ModuleList(nn.Sequential(Conv(c_mid, c_mid, k=3), Conv(c_mid, c_mid, k=3)) for _ in ch[:-1]) + + self.head = nn.Sequential( + Conv(c_mid, c_mid // 2, k=3), + nn.ConvTranspose2d(c_mid // 2, c_mid // 2, kernel_size=2, stride=2, bias=True), + Conv(c_mid // 2, c_mid // 4, k=3), + nn.Conv2d(c_mid // 4, 1, kernel_size=1), + ) + # Initialize to ~1.2 m so early exp() outputs stay well-conditioned. + self.head[-1].bias.data.fill_(0.182) + + # Scale-only log-affine calibration d' = exp(a·log d + b); identity by default. + self.register_buffer("cal_a", torch.ones(1)) + self.register_buffer("cal_b", torch.zeros(1)) + + def forward(self, x: list[torch.Tensor]) -> dict[str, torch.Tensor] | torch.Tensor: + """Fuse multi-scale features and predict depth. + + Args: + x: List of feature tensors [P3, P4, P5] from the backbone/neck. + + Returns: + Training: dict {"depth": (B, 1, H/4, W/4)}, the raw head output the loss supervises. + Eval: (B, 1, H/4, W/4) with calibration applied; the predictor/validator resize to image/GT size. + Export (self.export=True): (B, 1, H, W), upsampled 4x to the input size. Output is unbounded. + """ + # Project all levels to same channel dim + feats = [self.proj[i](x[i]) for i in range(self.nl)] + + out = feats[-1] + for i in range(self.nl - 2, -1, -1): + # align_corners=True is baked into the released depth weights. Constant scale (consecutive pyramid + # levels) keeps the upsample static for dynamic-shape CoreML export; output size is identical. + out = F.interpolate(out, scale_factor=2, mode="bilinear", align_corners=True) + out = out + feats[i] + out = self.refine[i](out) + + out = self.head(out) # (B, 1, H/4, W/4) + depth = torch.exp(out.clamp(-4.0, 5.0)) + + if self.training: + return {"depth": depth} + + depth = depth.pow(self.cal_a) * self.cal_b.exp() + if self.export: + depth = F.interpolate(depth, scale_factor=4.0, mode="bilinear", align_corners=False) + return depth + + +class Classify(nn.Module): + """YOLO classification head, i.e. x(b,c1,20,20) to x(b,c2). + + This class implements a classification head that transforms feature maps into class predictions. + + Attributes: + export (bool): Export mode flag. + conv (Conv): Convolutional layer for feature transformation. + pool (nn.AdaptiveAvgPool2d): Global average pooling layer. + drop (nn.Dropout): Dropout layer for regularization. + linear (nn.Linear): Linear layer for final classification. + + Methods: + forward: Perform forward pass on input feature maps. + + Examples: + Create a classification head + >>> classify = Classify(c1=1024, c2=1000) + >>> x = torch.randn(1, 1024, 20, 20) + >>> output = classify(x) + """ + + export = False # export mode + + def __init__(self, c1: int, c2: int, k: int = 1, s: int = 1, p: int | None = None, g: int = 1): + """Initialize YOLO classification head to transform input tensor from (b,c1,20,20) to (b,c2) shape. + + Args: + c1 (int): Number of input channels. + c2 (int): Number of output classes. + k (int): Kernel size. + s (int): Stride. + p (int, optional): Padding. + g (int): Groups. + """ + super().__init__() + c_ = 1280 # efficientnet_b0 size + self.conv = Conv(c1, c_, k, s, p, g) + self.pool = nn.AdaptiveAvgPool2d(1) # to x(b,c_,1,1) + self.drop = nn.Dropout(p=0.0, inplace=True) + self.linear = nn.Linear(c_, c2) # to x(b,c2) + + def forward(self, x: list[torch.Tensor] | torch.Tensor) -> torch.Tensor | tuple: + """Perform forward pass on input feature maps.""" + if isinstance(x, list): + x = torch.cat(x, 1) + x = self.linear(self.drop(self.pool(self.conv(x)).flatten(1))) + if self.training: + return x + y = x.softmax(1) # get final output + return y if self.export else (y, x) + + +class WorldDetect(Detect): + """Head for integrating YOLO detection models with semantic understanding from text embeddings. + + This class extends the standard Detect head to incorporate text embeddings for enhanced semantic understanding in + object detection tasks. + + Attributes: + cv3 (nn.ModuleList): Convolution layers for embedding features. + cv4 (nn.ModuleList): Contrastive head layers for text-vision alignment. + + Methods: + forward: Concatenate and return predicted bounding boxes and class probabilities. + bias_init: Initialize detection head biases. + + Examples: + Create a WorldDetect head + >>> world_detect = WorldDetect(nc=80, embed=512, with_bn=False, ch=(256, 512, 1024)) + >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)] + >>> text = torch.randn(1, 80, 512) + >>> outputs = world_detect(x, text) + """ + + def __init__( + self, + nc: int = 80, + embed: int = 512, + with_bn: bool = False, + reg_max: int = 16, + end2end: bool = False, + ch: tuple = (), + ): + """Initialize YOLO detection layer with nc classes and layer channels ch. + + Args: + nc (int): Number of classes. + embed (int): Embedding dimension. + with_bn (bool): Whether to use batch normalization in contrastive head. + reg_max (int): Maximum number of DFL channels. + end2end (bool): Whether to use end-to-end NMS-free detection. + ch (tuple): Tuple of channel sizes from backbone feature maps. + """ + super().__init__(nc, reg_max=reg_max, end2end=end2end, ch=ch) + c3 = max(ch[0], min(self.nc, 100)) + self.cv3 = nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, embed, 1)) for x in ch) + self.cv4 = nn.ModuleList(BNContrastiveHead(embed) if with_bn else ContrastiveHead() for _ in ch) + + def forward(self, x: list[torch.Tensor], text: torch.Tensor) -> dict[str, torch.Tensor] | tuple: + """Concatenate and return predicted bounding boxes and class probabilities.""" + feats = list(x) # snapshot references for anchor generation; the loop below reassigns x[i], never mutates + for i in range(self.nl): + x[i] = torch.cat((self.cv2[i](x[i]), self.cv4[i](self.cv3[i](x[i]), text)), 1) + self.no = self.nc + self.reg_max * 4 # self.nc could be changed when inference with different texts + bs = x[0].shape[0] + x_cat = torch.cat([xi.view(bs, self.no, -1) for xi in x], 2) + boxes, scores = x_cat.split((self.reg_max * 4, self.nc), 1) + preds = {"boxes": boxes, "scores": scores, "feats": feats} + if self.training: + return preds + y = self._inference(preds) + return y if self.export else (y, preds) + + def bias_init(self): + """Initialize Detect() biases, WARNING: requires stride availability.""" + m = self # self.model[-1] # Detect() module + # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1 + # ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency + for a, b, s in zip(m.cv2, m.cv3, m.stride): # from + a[-1].bias.data[:] = 1.0 # box + # b[-1].bias.data[:] = math.log(5 / m.nc / (640 / s) ** 2) # cls (.01 objects, 80 classes, 640 img) + + +class LRPCHead(nn.Module): + """Lightweight Region Proposal and Classification Head for efficient object detection. + + This head combines region proposal filtering with classification to enable efficient detection with dynamic + vocabulary support. + + Attributes: + vocab (nn.Module): Vocabulary/classification layer. + pf (nn.Module): Proposal filter module. + loc (nn.Module): Localization module. + enabled (bool): Whether the head is enabled. + + Methods: + conv2linear: Convert a 1x1 convolutional layer to a linear layer. + forward: Process classification and localization features to generate detection proposals. + + Examples: + Create an LRPC head + >>> vocab = nn.Conv2d(256, 80, 1) + >>> pf = nn.Conv2d(256, 1, 1) + >>> loc = nn.Conv2d(256, 4, 1) + >>> head = LRPCHead(vocab, pf, loc, enabled=True) + """ + + def __init__(self, vocab: nn.Module, pf: nn.Module, loc: nn.Module, enabled: bool = True): + """Initialize LRPCHead with vocabulary, proposal filter, and localization components. + + Args: + vocab (nn.Module): Vocabulary/classification module. + pf (nn.Module): Proposal filter module. + loc (nn.Module): Localization module. + enabled (bool): Whether to enable the head functionality. + """ + super().__init__() + self.vocab = self.conv2linear(vocab) if enabled else vocab + self.pf = pf + self.loc = loc + self.enabled = enabled + + @staticmethod + def conv2linear(conv: nn.Conv2d) -> nn.Linear: + """Convert a 1x1 convolutional layer to a linear layer.""" + assert isinstance(conv, nn.Conv2d) and conv.kernel_size == (1, 1) + linear = nn.Linear(conv.in_channels, conv.out_channels).requires_grad_(conv.weight.requires_grad) + linear.weight.data = conv.weight.view(conv.out_channels, -1).data + linear.bias.data = conv.bias.data + return linear + + def forward(self, cls_feat: torch.Tensor, loc_feat: torch.Tensor, conf: float) -> tuple[tuple, torch.Tensor]: + """Process classification and localization features to generate detection proposals.""" + if self.enabled: + if not conf: # static export, every anchor passes the proposal filter + cls_feat = self.vocab(cls_feat.flatten(2).transpose(-1, -2)) + return self.loc(loc_feat), cls_feat.transpose(-1, -2), None + pf_score = self.pf(cls_feat)[0, 0].flatten(0) + mask = pf_score.sigmoid() > conf + cls_feat = cls_feat.flatten(2).transpose(-1, -2) + cls_feat = self.vocab(cls_feat[:, mask] if conf else cls_feat * mask.unsqueeze(-1).int()) + return self.loc(loc_feat), cls_feat.transpose(-1, -2), mask + else: + cls_feat = self.vocab(cls_feat) + loc_feat = self.loc(loc_feat) + return ( + loc_feat, + cls_feat.flatten(2), + cls_feat.new_ones(cls_feat.shape[2] * cls_feat.shape[3], dtype=torch.bool), + ) + + +class YOLOEDetect(Detect): + """Head for integrating YOLO detection models with semantic understanding from text embeddings. + + This class extends the standard Detect head to support text-guided detection with enhanced semantic understanding + through text embeddings and visual prompt embeddings. + + Attributes: + is_fused (bool): Whether the model is fused for inference. + cv3 (nn.ModuleList): Convolution layers for embedding features. + cv4 (nn.ModuleList): Contrastive head layers for text-vision alignment. + reprta (Residual): Residual block for text prompt embeddings. + savpe (SAVPE): Spatial-aware visual prompt embeddings module. + embed (int): Embedding dimension. + + Methods: + fuse: Fuse text features with model weights for efficient inference. + get_tpe: Get text prompt embeddings with normalization. + get_vpe: Get visual prompt embeddings with spatial awareness. + forward_lrpc: Process features with fused text embeddings for prompt-free model. + forward: Process features with class prompt embeddings to generate detections. + bias_init: Initialize biases for detection heads. + + Examples: + Create a YOLOEDetect head + >>> yoloe_detect = YOLOEDetect(nc=80, embed=512, with_bn=True, ch=(256, 512, 1024)) + >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)] + >>> cls_pe = torch.randn(1, 80, 512) + >>> outputs = yoloe_detect([*x, cls_pe]) + """ + + is_fused = False + + def __init__( + self, nc: int = 80, embed: int = 512, with_bn: bool = False, reg_max=16, end2end=False, ch: tuple = () + ): + """Initialize YOLO detection layer with nc classes and layer channels ch. + + Args: + nc (int): Number of classes. + embed (int): Embedding dimension. + with_bn (bool): Whether to use batch normalization in contrastive head. + reg_max (int): Maximum number of DFL channels. + end2end (bool): Whether to use end-to-end NMS-free detection. + ch (tuple): Tuple of channel sizes from backbone feature maps. + """ + super().__init__(nc, reg_max, end2end, ch) + c3 = max(ch[0], min(self.nc, 100)) + assert c3 <= embed + assert with_bn + self.cv3 = ( + nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, embed, 1)) for x in ch) + if self.legacy + else nn.ModuleList( + nn.Sequential( + nn.Sequential(DWConv(x, x, 3), Conv(x, c3, 1)), + nn.Sequential(DWConv(c3, c3, 3), Conv(c3, c3, 1)), + nn.Conv2d(c3, embed, 1), + ) + for x in ch + ) + ) + self.cv4 = nn.ModuleList(BNContrastiveHead(embed) if with_bn else ContrastiveHead() for _ in ch) + if end2end: + self.one2one_cv3 = copy.deepcopy(self.cv3) # overwrite with new cv3 + self.one2one_cv4 = copy.deepcopy(self.cv4) + + self.reprta = Residual(SwiGLUFFN(embed, embed)) + self.savpe = SAVPE(ch, c3, embed) + self.embed = embed + + @smart_inference_mode(False) # fused layers stay in the model, so they must not be inference tensors + def fuse(self, txt_feats: torch.Tensor = None): + """Fuse text features with model weights for efficient inference.""" + if txt_feats is None: # remove the unused detection branch + super().fuse() + return + if self.is_fused: + return + + assert not self.training + txt_feats = txt_feats.to(next(self.parameters()).dtype).squeeze(0) + if self.cv3 and self.cv4: + self._fuse_tp(txt_feats, self.cv3, self.cv4) + if getattr(self, "one2one_cv2", None) is not None: + self._fuse_tp(txt_feats, self.one2one_cv3, self.one2one_cv4) + del self.reprta + self.reprta = nn.Identity() + self.is_fused = True + + def _fuse_tp(self, txt_feats: torch.Tensor, cls_head: torch.nn.Module, bn_head: torch.nn.Module) -> None: + """Fuse text prompt embeddings with model weights for efficient inference.""" + for cls_h, bn_h in zip(cls_head, bn_head): + assert isinstance(cls_h, nn.Sequential) + assert isinstance(bn_h, BNContrastiveHead) + conv = cls_h[-1] + assert isinstance(conv, nn.Conv2d) + logit_scale = bn_h.logit_scale + bias = bn_h.bias + norm = bn_h.norm + + t = txt_feats * logit_scale.exp() + conv: nn.Conv2d = fuse_conv_and_bn(conv, norm) + + w = conv.weight.data.squeeze(-1).squeeze(-1) + b = conv.bias.data + + w = t @ w + b1 = (t @ b.reshape(-1).unsqueeze(-1)).squeeze(-1) + b2 = torch.ones_like(b1) * bias + + conv = ( + nn.Conv2d( + conv.in_channels, + w.shape[0], + kernel_size=1, + ) + .requires_grad_(False) + .to(conv.weight.device, conv.weight.dtype) + ) + + conv.weight.data.copy_(w.unsqueeze(-1).unsqueeze(-1)) + conv.bias.data.copy_(b1 + b2) + cls_h[-1] = conv + + bn_h.fuse() + + def get_tpe(self, tpe: torch.Tensor | None) -> torch.Tensor | None: + """Get text prompt embeddings with normalization.""" + return None if tpe is None else F.normalize(self.reprta(tpe), dim=-1, p=2) + + def get_vpe(self, x: list[torch.Tensor], vpe: torch.Tensor) -> torch.Tensor: + """Get visual prompt embeddings with spatial awareness.""" + if vpe.shape[1] == 0: # no visual prompt embeddings + return torch.zeros(x[0].shape[0], 0, self.embed, device=x[0].device) + if vpe.ndim == 4: # (B, N, H, W) + vpe = self.savpe(x, vpe) + assert vpe.ndim == 3 # (B, N, D) + return vpe + + def forward(self, x: list[torch.Tensor]) -> torch.Tensor | tuple: + """Process features with class prompt embeddings to generate detections.""" + if hasattr(self, "lrpc"): # for prompt-free inference + return self.forward_lrpc(x[:3]) + return super().forward(x) + + def forward_lrpc(self, x: list[torch.Tensor]) -> torch.Tensor | tuple: + """Process features with fused text embeddings to generate detections for prompt-free model.""" + boxes, scores, index = [], [], [] + bs = x[0].shape[0] + cv2 = self.one2one_cv2 if self.end2end else self.cv2 + cv3 = self.one2one_cv3 if self.end2end else self.cv3 + lrpc = self.one2one_lrpc if self.end2end and hasattr(self, "one2one_lrpc") else self.lrpc + conf = 0 if self.export and not self.dynamic else getattr(self, "conf", 0.001) + for i in range(self.nl): + cls_feat = cv3[i](x[i]) + loc_feat = cv2[i](x[i]) + assert isinstance(lrpc[i], LRPCHead) + box, score, idx = lrpc[i](cls_feat, loc_feat, conf) + boxes.append(box.view(bs, self.reg_max * 4, -1)) + scores.append(score) + index.append(idx) + index = torch.cat(index) if conf else None + preds = { + "boxes": torch.cat(boxes, 2), + "scores": torch.cat(scores, 2), + "feats": x, + "index": index, + **self.forward_mask(x, index), + } + y = self._inference(preds) + if self.end2end: + y = self.postprocess(y.permute(0, 2, 1)) + return y if self.export else (y, preds) + + def forward_mask(self, x: list[torch.Tensor], index: torch.Tensor | None) -> dict[str, torch.Tensor]: + """Return the prompt-free mask coefficients, which the detection head does not produce.""" + return {} + + def _get_decode_boxes(self, x): + """Decode predicted bounding boxes for inference.""" + dbox = super()._get_decode_boxes(x) + if hasattr(self, "lrpc"): + dbox = dbox if x["index"] is None else dbox[..., x["index"]] + return dbox + + @property + def one2many(self): + """Returns the one-to-many head components, here for v3/v5/v8/v9/v11 backward compatibility.""" + return {"box_head": self.cv2, "cls_head": self.cv3, "contrastive_head": self.cv4} + + @property + def one2one(self): + """Returns the one-to-one head components.""" + return {"box_head": self.one2one_cv2, "cls_head": self.one2one_cv3, "contrastive_head": self.one2one_cv4} + + def forward_head(self, x, box_head, cls_head, contrastive_head): + """Concatenates and returns predicted bounding boxes, class probabilities, and contrastive scores.""" + assert len(x) == 4, f"Expected 4 features including 3 feature maps and 1 text embeddings, but got {len(x)}." + if box_head is None or cls_head is None: # for fused inference + return {} + bs = x[0].shape[0] # batch size + boxes = torch.cat([box_head[i](x[i]).view(bs, 4 * self.reg_max, -1) for i in range(self.nl)], dim=-1) + self.nc = x[-1].shape[1] + scores = torch.cat( + [contrastive_head[i](cls_head[i](x[i]), x[-1]).reshape(bs, self.nc, -1) for i in range(self.nl)], dim=-1 + ) + self.no = self.nc + self.reg_max * 4 # self.nc could be changed when inference with different texts + return {"boxes": boxes, "scores": scores, "feats": x[:3]} + + def bias_init(self): + """Initialize Detect() biases, WARNING: requires stride availability.""" + for i, (a, b, c) in enumerate( + zip(self.one2many["box_head"], self.one2many["cls_head"], self.one2many["contrastive_head"]) + ): + a[-1].bias.data[:] = 2.0 # box + b[-1].bias.data[:] = 0.0 + c.bias.data[:] = math.log(5 / self.nc / (640 / self.stride[i]) ** 2) + if getattr(self, "one2one_cv2", None) is not None: + for i, (a, b, c) in enumerate( + zip(self.one2one["box_head"], self.one2one["cls_head"], self.one2one["contrastive_head"]) + ): + a[-1].bias.data[:] = 2.0 # box + b[-1].bias.data[:] = 0.0 + c.bias.data[:] = math.log(5 / self.nc / (640 / self.stride[i]) ** 2) + + +class YOLOESegment(YOLOEDetect): + """YOLO segmentation head with text embedding capabilities. + + This class extends YOLOEDetect to include mask prediction capabilities for instance segmentation tasks with + text-guided semantic understanding. + + Attributes: + nm (int): Number of masks. + npr (int): Number of protos. + proto (Proto): Prototype generation module. + cv5 (nn.ModuleList): Convolution layers for mask coefficients. + + Methods: + forward: Return model outputs and mask coefficients. + + Examples: + Create a YOLOESegment head + >>> yoloe_segment = YOLOESegment(nc=80, nm=32, npr=256, embed=512, with_bn=True, ch=(256, 512, 1024)) + >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)] + >>> text = torch.randn(1, 80, 512) + >>> outputs = yoloe_segment([*x, text]) + """ + + def __init__( + self, + nc: int = 80, + nm: int = 32, + npr: int = 256, + embed: int = 512, + with_bn: bool = False, + reg_max=16, + end2end=False, + ch: tuple = (), + ): + """Initialize YOLOESegment with class count, mask parameters, and embedding dimensions. + + Args: + nc (int): Number of classes. + nm (int): Number of masks. + npr (int): Number of protos. + embed (int): Embedding dimension. + with_bn (bool): Whether to use batch normalization in contrastive head. + reg_max (int): Maximum number of DFL channels. + end2end (bool): Whether to use end-to-end NMS-free detection. + ch (tuple): Tuple of channel sizes from backbone feature maps. + """ + super().__init__(nc, embed, with_bn, reg_max, end2end, ch) + self.nm = nm + self.npr = npr + self.proto = Proto(ch[0], self.npr, self.nm) + + c5 = max(ch[0] // 4, self.nm) + self.cv5 = nn.ModuleList(nn.Sequential(Conv(x, c5, 3), Conv(c5, c5, 3), nn.Conv2d(c5, self.nm, 1)) for x in ch) + if end2end: + self.one2one_cv5 = copy.deepcopy(self.cv5) + + @property + def one2many(self): + """Returns the one-to-many head components, here for v3/v5/v8/v9/v11 backward compatibility.""" + return {"box_head": self.cv2, "cls_head": self.cv3, "mask_head": self.cv5, "contrastive_head": self.cv4} + + @property + def one2one(self): + """Returns the one-to-one head components.""" + return { + "box_head": self.one2one_cv2, + "cls_head": self.one2one_cv3, + "mask_head": self.one2one_cv5, + "contrastive_head": self.one2one_cv4, + } + + def forward_mask(self, x: list[torch.Tensor], index: torch.Tensor | None) -> dict[str, torch.Tensor]: + """Return the prompt-free mask coefficients of the anchors the proposal filter kept.""" + cv5 = self.one2one_cv5 if self.end2end else self.cv5 + mc = torch.cat([cv5[i](x[i]).view(x[0].shape[0], self.nm, -1) for i in range(self.nl)], 2) + return {"mask_coefficient": mc if index is None else mc[..., index]} + + def forward(self, x: list[torch.Tensor]) -> tuple | list[torch.Tensor] | dict[str, torch.Tensor]: + """Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients.""" + outputs = super().forward(x) + preds = outputs[1] if isinstance(outputs, tuple) else outputs + proto = self.proto(x[0]) # mask protos + if isinstance(preds, dict): # training and validating during training + if "one2one" in preds: + preds["one2many"]["proto"] = proto + preds["one2one"]["proto"] = proto.detach() + else: + preds["proto"] = proto + if self.training: + return preds + return (outputs, proto) if self.export else ((outputs[0], proto), preds) + + def _inference(self, x: dict[str, torch.Tensor]) -> torch.Tensor: + """Decode predicted bounding boxes and class probabilities, concatenated with mask coefficients.""" + preds = super()._inference(x) + return torch.cat([preds, x["mask_coefficient"]], dim=1) + + def forward_head( + self, + x: list[torch.Tensor], + box_head: torch.nn.Module, + cls_head: torch.nn.Module, + mask_head: torch.nn.Module, + contrastive_head: torch.nn.Module, + ) -> dict[str, torch.Tensor]: + """Concatenates and returns predicted bounding boxes, class probabilities, and mask coefficients.""" + preds = super().forward_head(x, box_head, cls_head, contrastive_head) + if mask_head is not None: + bs = x[0].shape[0] # batch size + preds["mask_coefficient"] = torch.cat([mask_head[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) + return preds + + def fuse(self, txt_feats: torch.Tensor = None): + """Fuse text features with model weights for efficient inference.""" + super().fuse(txt_feats) + if txt_feats is None: # remove training-only prototype layers + if hasattr(self.proto, "fuse"): + self.proto.fuse() + return + + +class YOLOESegment26(YOLOESegment): + """YOLOE-style segmentation head module using Proto26 for mask generation. + + This class extends the YOLOESegment functionality to include segmentation capabilities by integrating a Proto26 + generation module and convolutional layers to predict mask coefficients. + + Args: + nc (int): Number of classes. Defaults to 80. + nm (int): Number of masks. Defaults to 32. + npr (int): Number of prototype channels. Defaults to 256. + embed (int): Embedding dimensionality. Defaults to 512. + with_bn (bool): Whether to use Batch Normalization. Defaults to False. + reg_max (int): Maximum number of DFL channels. Defaults to 16. + end2end (bool): Whether to use end-to-end detection mode. Defaults to False. + ch (tuple[int, ...]): Input channels for each scale. + + Attributes: + nm (int): Number of segmentation masks. + npr (int): Number of prototype channels. + proto (Proto26): Prototype generation module for segmentation. + cv5 (nn.ModuleList): Convolutional layers for generating mask coefficients from features. + one2one_cv5 (nn.ModuleList, optional): Deep copy of cv5 for end-to-end detection branches. + """ + + def __init__( + self, + nc: int = 80, + nm: int = 32, + npr: int = 256, + embed: int = 512, + with_bn: bool = False, + reg_max=16, + end2end=False, + ch: tuple = (), + ): + """Initialize YOLOESegment26 with class count, mask parameters, and embedding dimensions.""" + YOLOEDetect.__init__(self, nc, embed, with_bn, reg_max, end2end, ch) + self.nm = nm + self.npr = npr + self.proto = Proto26(ch, self.npr, self.nm, nc) # protos + + c5 = max(ch[0] // 4, self.nm) + self.cv5 = nn.ModuleList(nn.Sequential(Conv(x, c5, 3), Conv(c5, c5, 3), nn.Conv2d(c5, self.nm, 1)) for x in ch) + if end2end: + self.one2one_cv5 = copy.deepcopy(self.cv5) + + def forward(self, x: list[torch.Tensor]) -> tuple | list[torch.Tensor] | dict[str, torch.Tensor]: + """Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients.""" + outputs = YOLOEDetect.forward(self, x) + preds = outputs[1] if isinstance(outputs, tuple) else outputs + proto = self.proto([xi.detach() for xi in x], return_semantic=False) # mask protos + + if isinstance(preds, dict): # training and validating during training + if "one2one" in preds: # dual-head outputs, not prompt-free + preds["one2many"]["proto"] = proto + preds["one2one"]["proto"] = proto.detach() + else: + preds["proto"] = proto + if self.training: + return preds + return (outputs, proto) if self.export else ((outputs[0], proto), preds) + + +class RTDETRDecoder(nn.Module): + """Real-Time Deformable Transformer Decoder (RTDETRDecoder) module for object detection. + + This decoder module utilizes Transformer architecture along with deformable convolutions to predict bounding boxes + and class labels for objects in an image. It integrates features from multiple layers and runs through a series of + Transformer decoder layers to output the final predictions. + + Attributes: + export (bool): Export mode flag. + hidden_dim (int): Dimension of hidden layers. + nhead (int): Number of heads in multi-head attention. + nl (int): Number of feature levels. + nc (int): Number of classes. + num_queries (int): Number of query points. + num_decoder_layers (int): Number of decoder layers. + input_proj (nn.ModuleList): Input projection layers for backbone features. + decoder (DeformableTransformerDecoder): Transformer decoder module. + denoising_class_embed (nn.Embedding): Class embeddings for denoising. + num_denoising (int): Number of denoising queries. + label_noise_ratio (float): Label noise ratio for training. + box_noise_scale (float): Box noise scale for training. + learnt_init_query (bool): Whether to learn initial query embeddings. + tgt_embed (nn.Embedding): Target embeddings for queries. + query_pos_head (MLP): Query position head. + enc_output (nn.Sequential): Encoder output layers. + enc_score_head (nn.Linear): Encoder score prediction head. + enc_bbox_head (MLP): Encoder bbox prediction head. + dec_score_head (nn.ModuleList): Decoder score prediction heads. + dec_bbox_head (nn.ModuleList): Decoder bbox prediction heads. + + Methods: + forward: Run forward pass and return bounding box and classification scores. + + Examples: + Create an RTDETRDecoder + >>> decoder = RTDETRDecoder(nc=80, ch=(512, 1024, 2048), hd=256, nq=300) + >>> x = [torch.randn(1, 512, 64, 64), torch.randn(1, 1024, 32, 32), torch.randn(1, 2048, 16, 16)] + >>> outputs = decoder(x) + """ + + export = False # export mode + max_det = 300 # max detections per image + shapes = [] + anchors = torch.empty(0) + valid_mask = torch.empty(0) + dynamic = False + + def __init__( + self, + nc: int = 80, + ch: tuple = (512, 1024, 2048), + hd: int = 256, # hidden dim + nq: int = 300, # num queries + ndp: int = 4, # num decoder points + nh: int = 8, # num head + ndl: int = 6, # num decoder layers + d_ffn: int = 1024, # dim of feedforward + dropout: float = 0.0, + act: nn.Module | None = None, + eval_idx: int = -1, + # Training args + nd: int = 100, # num denoising + label_noise_ratio: float = 0.5, + box_noise_scale: float = 1.0, + learnt_init_query: bool = False, + ): + """Initialize the RTDETRDecoder module with the given parameters. + + Args: + nc (int): Number of classes. + ch (tuple): Channels in the backbone feature maps. + hd (int): Dimension of hidden layers. + nq (int): Number of query points. + ndp (int): Number of decoder points. + nh (int): Number of heads in multi-head attention. + ndl (int): Number of decoder layers. + d_ffn (int): Dimension of the feed-forward networks. + dropout (float): Dropout rate. + act (nn.Module): Activation function. + eval_idx (int): Evaluation index. + nd (int): Number of denoising. + label_noise_ratio (float): Label noise ratio. + box_noise_scale (float): Box noise scale. + learnt_init_query (bool): Whether to learn initial query embeddings. + """ + super().__init__() + act = nn.ReLU() if act is None else act + self.hidden_dim = hd + self.nhead = nh + self.nl = len(ch) # num level + self.nc = nc + self.num_queries = nq + self.num_decoder_layers = ndl + + # Backbone feature projection + self.input_proj = nn.ModuleList(nn.Sequential(nn.Conv2d(x, hd, 1, bias=False), nn.BatchNorm2d(hd)) for x in ch) + # NOTE: simplified version but it's not consistent with .pt weights. + # self.input_proj = nn.ModuleList(Conv(x, hd, act=False) for x in ch) + + # Transformer module + decoder_layer = DeformableTransformerDecoderLayer(hd, nh, d_ffn, dropout, act, self.nl, ndp) + self.decoder = DeformableTransformerDecoder(hd, decoder_layer, ndl, eval_idx) + + # Denoising part + self.denoising_class_embed = nn.Embedding(nc, hd) + self.num_denoising = nd + self.label_noise_ratio = label_noise_ratio + self.box_noise_scale = box_noise_scale + + # Decoder embedding + self.learnt_init_query = learnt_init_query + if learnt_init_query: + self.tgt_embed = nn.Embedding(nq, hd) + self.query_pos_head = MLP(4, 2 * hd, hd, num_layers=2) + + # Encoder head + self.enc_output = nn.Sequential(nn.Linear(hd, hd), nn.LayerNorm(hd)) + self.enc_score_head = nn.Linear(hd, nc) + self.enc_bbox_head = MLP(hd, hd, 4, num_layers=3) + + # Decoder head + self.dec_score_head = nn.ModuleList([nn.Linear(hd, nc) for _ in range(ndl)]) + self.dec_bbox_head = nn.ModuleList([MLP(hd, hd, 4, num_layers=3) for _ in range(ndl)]) + + self._reset_parameters() + + def forward(self, x: list[torch.Tensor], batch: dict | None = None) -> tuple | torch.Tensor: + """Run the forward pass of the module, returning bounding box and classification scores for the input. + + Args: + x (list[torch.Tensor]): List of feature maps from the backbone. + batch (dict, optional): Batch information for training. + + Returns: + outputs (tuple | torch.Tensor): During training, returns a tuple of bounding boxes, scores, and other + metadata. During inference, returns a tensor of shape (bs, num_queries, 6) containing bounding boxes, + confidence scores, and class labels. + """ + from ultralytics.models.utils.ops import get_cdn_group + + # Input projection and embedding + feats, shapes = self._get_encoder_input(x) + + # Prepare denoising training + dn_embed, dn_bbox, attn_mask, dn_meta = get_cdn_group( + batch, + self.nc, + min(self.num_queries, feats.shape[1]), + self.denoising_class_embed.weight, + self.num_denoising, + self.label_noise_ratio, + self.box_noise_scale, + self.training, + ) + + embed, refer_bbox, enc_bboxes, enc_scores = self._get_decoder_input(feats, shapes, dn_embed, dn_bbox) + + # Decoder + dec_bboxes, dec_scores = self.decoder( + embed, + refer_bbox, + feats, + shapes, + self.dec_bbox_head, + self.dec_score_head, + self.query_pos_head, + attn_mask=attn_mask, + ) + if self.training and dn_meta is None: + # Touch denoising_class_embed so DDP sees it as used when batch has zero GTs. + dec_bboxes = dec_bboxes + 0 * self.denoising_class_embed.weight.sum() + x = dec_bboxes, dec_scores, enc_bboxes, enc_scores, dn_meta + if self.training: + return x + # (bs, num_queries, 4), (bs, num_queries, nc) + y = self.postprocess(dec_bboxes.squeeze(0), dec_scores.squeeze(0).sigmoid()) + return y if self.export else (y, x) + + def postprocess(self, boxes: torch.Tensor, scores: torch.Tensor) -> torch.Tensor: + """Post-process predictions to select top-k detections. + + Args: + boxes (torch.Tensor): Predicted bounding boxes with shape (batch_size, num_queries, 4) in xywh format. + scores (torch.Tensor): Class scores with shape (batch_size, num_queries, nc). + + Returns: + (torch.Tensor): Processed predictions with shape (batch_size, num_queries, 6), limited to max_det during + export, and last dimension format [cx, cy, w, h, max_class_prob, class_index]. + """ + k = min(self.num_queries, self.max_det) if self.export else self.num_queries + k = ( + (torch._shape_as_tensor(scores)[1] * self.nc).clamp(max=k) + if self.dynamic + else min(k, scores.shape[1] * self.nc) + ) + groups = 8 if self.export and self.format == "engine" and not self.dynamic else 1 + scores, index = Detect._grouped_topk(scores.flatten(1), k, groups) + # CoreML MIL lacks integer floor-div and mod lowering: use torch.div(rounding_mode="floor") and (index - q*nc). + query_idx = torch.div(index, self.nc, rounding_mode="floor") + boxes = boxes.gather(dim=1, index=query_idx.unsqueeze(-1).expand(-1, -1, 4).long()) + return torch.cat([boxes, scores[..., None], (index - query_idx * self.nc)[..., None].float()], dim=-1) + + @staticmethod + def _generate_anchors( + shapes: list[list[int]], + feats: torch.Tensor, + grid_size: float = 0.05, + eps: float = 1e-2, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Generate anchor bounding boxes for given shapes with specific grid size and validate them. + + Args: + shapes (list): List of feature map shapes. + feats (torch.Tensor): Tensor whose dtype and device the anchors inherit. + grid_size (float, optional): Base size of grid cells. + eps (float, optional): Small value for numerical stability. + + Returns: + anchors (torch.Tensor): Generated anchor boxes. + valid_mask (torch.Tensor): Valid mask for anchors. + """ + anchors = [] + for i, (h, w) in enumerate(shapes): + sy = torch.arange(h).type_as(feats) # type_as inherits the runtime device in traces, unlike device= + sx = torch.arange(w).type_as(feats) + grid_y, grid_x = torch.meshgrid(sy, sx, indexing="ij") if TORCH_1_11 else torch.meshgrid(sy, sx) + grid_xy = torch.stack([(grid_x + 0.5) / w, (grid_y + 0.5) / h], -1)[None] # (1, h, w, 2) + wh = torch.full_like(grid_xy, grid_size * (2.0**i)) + anchors.append(torch.cat([grid_xy, wh], -1).view(-1, h * w, 4)) # (1, h*w, 4) + + anchors = torch.cat(anchors, 1) # (1, h*w*nl, 4) + valid_mask = ((anchors > eps) & (anchors < 1 - eps)).all(-1, keepdim=True) # 1, h*w*nl, 1 + anchors = torch.log(anchors / (1 - anchors)) + anchors = anchors.masked_fill(~valid_mask, float("inf")) + return anchors, valid_mask + + def _get_encoder_input(self, x: list[torch.Tensor]) -> tuple[torch.Tensor, list[list[int]]]: + """Process and return encoder inputs by getting projection features from input and concatenating them. + + Args: + x (list[torch.Tensor]): List of feature maps from the backbone. + + Returns: + feats (torch.Tensor): Processed features. + shapes (list): List of feature map shapes. + """ + # Get projection features + x = [self.input_proj[i](feat) for i, feat in enumerate(x)] + # Get encoder inputs + feats = [] + shapes = [] + for feat in x: + h, w = feat.shape[2:] + # [b, c, h, w] -> [b, h*w, c] + feats.append(feat.flatten(2).permute(0, 2, 1)) + # [nl, 2] + shapes.append([h, w]) + + # [b, h*w, c] + feats = torch.cat(feats, 1) + return feats, shapes + + def _get_decoder_input( + self, + feats: torch.Tensor, + shapes: list[list[int]], + dn_embed: torch.Tensor | None = None, + dn_bbox: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Generate and prepare the input required for the decoder from the provided features and shapes. + + Args: + feats (torch.Tensor): Processed features from encoder. + shapes (list): List of feature map shapes. + dn_embed (torch.Tensor, optional): Denoising embeddings. + dn_bbox (torch.Tensor, optional): Denoising bounding boxes. + + Returns: + embeddings (torch.Tensor): Query embeddings for decoder. + refer_bbox (torch.Tensor): Reference bounding boxes. + enc_bboxes (torch.Tensor): Encoded bounding boxes. + enc_scores (torch.Tensor): Encoded scores. + """ + bs = feats.shape[0] + if self.dynamic or self.shapes != shapes: + self.anchors, self.valid_mask = self._generate_anchors(shapes, feats) + self.shapes = shapes + + # Prepare input for decoder + features = self.enc_output(self.valid_mask * feats) # bs, h*w, 256 + enc_outputs_scores = self.enc_score_head(features) # (bs, h*w, nc) + + # Query selection + # (bs*num_queries,) + groups = 8 if self.export and self.format == "engine" and not self.dynamic else 1 + k = ( + torch._shape_as_tensor(enc_outputs_scores)[1].clamp(max=self.num_queries) + if self.dynamic + else min(self.num_queries, enc_outputs_scores.shape[1]) + ) + topk_ind = Detect._grouped_topk(enc_outputs_scores.max(-1).values, k, groups)[1].view(-1) + # (bs*num_queries,) + batch_ind = torch.arange(end=bs, dtype=topk_ind.dtype).unsqueeze(-1).repeat(1, k).view(-1) + + # (bs, num_queries, 256) + top_k_features = features[batch_ind, topk_ind].view(bs, k, -1) + # (bs, num_queries, 4) + top_k_anchors = self.anchors[:, topk_ind].view(bs, k, -1) + + # Dynamic anchors + static content + refer_bbox = self.enc_bbox_head(top_k_features) + top_k_anchors + + enc_bboxes = refer_bbox.sigmoid() + if dn_bbox is not None: + refer_bbox = torch.cat([dn_bbox, refer_bbox], 1) + enc_scores = enc_outputs_scores[batch_ind, topk_ind].view(bs, k, -1) + + embeddings = ( + self.tgt_embed.weight[:k].unsqueeze(0).repeat(bs, 1, 1) if self.learnt_init_query else top_k_features + ) + if self.training: + refer_bbox = refer_bbox.detach() + if not self.learnt_init_query: + embeddings = embeddings.detach() + if dn_embed is not None: + embeddings = torch.cat([dn_embed, embeddings], 1) + + return embeddings, refer_bbox, enc_bboxes, enc_scores + + def _reset_parameters(self): + """Initialize or reset the parameters of the model's various components with predefined weights and biases.""" + # Class and bbox head init + bias_cls = bias_init_with_prob(0.01) / 80 * self.nc + constant_(self.enc_score_head.bias, bias_cls) + constant_(self.enc_bbox_head.layers[-1].weight, 0.0) + constant_(self.enc_bbox_head.layers[-1].bias, 0.0) + for cls_, reg_ in zip(self.dec_score_head, self.dec_bbox_head): + constant_(cls_.bias, bias_cls) + constant_(reg_.layers[-1].weight, 0.0) + constant_(reg_.layers[-1].bias, 0.0) + + xavier_uniform_(self.enc_output[0].weight) + if self.learnt_init_query: + xavier_uniform_(self.tgt_embed.weight) + xavier_uniform_(self.query_pos_head.layers[0].weight) + xavier_uniform_(self.query_pos_head.layers[1].weight) + for layer in self.input_proj: + xavier_uniform_(layer[0].weight) + + +class v10Detect(Detect): + """v10 Detection head from https://arxiv.org/pdf/2405.14458. + + This class implements the YOLOv10 detection head with dual-assignment training and consistent dual predictions for + improved efficiency and performance. + + Attributes: + end2end (bool): End-to-end detection mode. + max_det (int): Maximum number of detections. + cv3 (nn.ModuleList): Light classification head layers. + one2one_cv3 (nn.ModuleList): One-to-one classification head layers. + + Methods: + __init__: Initialize the v10Detect object with specified number of classes and input channels. + forward: Perform forward pass of the v10Detect module. + bias_init: Initialize biases of the Detect module. + fuse: Remove the unused detection branch for inference. + + Examples: + Create a v10Detect head + >>> v10_detect = v10Detect(nc=80, ch=(256, 512, 1024)) + >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)] + >>> outputs = v10_detect(x) + """ + + def __init__(self, nc: int = 80, ch: tuple = ()): + """Initialize the v10Detect object with the specified number of classes and input channels. + + Args: + nc (int): Number of classes. + ch (tuple): Tuple of channel sizes from backbone feature maps. + """ + super().__init__(nc, end2end=True, ch=ch) + c3 = max(ch[0], min(self.nc, 100)) # channels + # Light cls head + self.cv3 = nn.ModuleList( + nn.Sequential( + nn.Sequential(Conv(x, x, 3, g=x), Conv(x, c3, 1)), + nn.Sequential(Conv(c3, c3, 3, g=c3), Conv(c3, c3, 1)), + nn.Conv2d(c3, self.nc, 1), + ) + for x in ch + ) + self.one2one_cv3 = copy.deepcopy(self.cv3) + + +class SemanticSegment(nn.Module): + """YOLO semantic segmentation head for per-pixel classification. + + This head produces dense per-pixel class predictions. Unlike instance segmentation, no bounding boxes or instance + masks are produced. + + Attributes: + nc (int): Number of semantic classes. + nl (int): Number of input feature levels. + stride (torch.Tensor): Feature map strides. + export (bool): Export mode flag. + format (str): Export format. + classifier (nn.Sequential): Final convolutional classifier head. + aux_head (nn.Sequential | None): Auxiliary classifier on P4 for deep supervision. + """ + + export = False # export mode + format = None # export format + bake_argmax = False # export: emit [B, H, W] class map (TensorRT>=10 and multi-class Hailo-10/15) + + def __init__(self, nc=19, ch=()): + """Initialize the semantic segmentation head. + + Args: + nc (int): Number of semantic classes. + ch (tuple): Tuple of channel sizes from neck feature maps (P3, P4). + """ + super().__init__() + self.nc = nc + self.nl = len(ch) + self.stride = torch.zeros(self.nl) + + c_mid = ch[0] # use P3 channel width as intermediate dimension + # Final classifier + self.classifier = nn.Sequential(Conv(c_mid, c_mid, 3), nn.Conv2d(c_mid, nc, 1)) + # Auxiliary head on P4 (index 1) for training + self.aux_head = nn.Sequential(Conv(ch[1], c_mid, 3), nn.Conv2d(c_mid, nc, 1)) if len(ch) > 1 else None + + def forward(self, x): + """Forward pass: fuse multi-scale features and predict per-pixel classes. + + Args: + x (list[torch.Tensor]): List of feature maps [P3, P4]. + + Returns: + (torch.Tensor | tuple): Logits of shape [B, nc, H/8, W/8] during training (or a (main, aux) tuple when + aux_head is present) and inference. ONNX, MNN, OpenVINO, TensorRT>=10, and multi-class Hailo-10/15 + export bake in the class reduction and return a compact map of shape [B, H, W] (uint8 when nc <= 256, + else int32). Other export formats return upsampled logits of shape [B, nc, H, W]. + """ + # Classify + logits = self.classifier(x[0]) # [B, nc, H/8, W/8] + if self.training: + if self.aux_head is not None: + return logits, self.aux_head(x[1]) # main + aux (P4) + return logits + if self.export: + y = F.interpolate(logits, scale_factor=8, mode="bilinear", align_corners=False) # [B, nc, H, W] + # Bake class reduction: emit [B, H, W] map, shrinking the D2H copy ~80x. ONNX/MNN/OpenVINO and + # multi-class Hailo-10/15 preserve the integer output; TensorRT supports uint8 graph outputs only on + # TRT>=10, so engine and Hailo baking are gated by the exporter. + if self.format in {"onnx", "mnn", "openvino"} or (self.format in {"engine", "hailo"} and self.bake_argmax): + cls = y.argmax(1) if self.nc > 1 else y.squeeze(1) > 0 + return cls.to(torch.uint8 if self.nc <= 256 else torch.int32) + return y + return logits diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/transformer.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..7e28635100793f1be4069491d2bee25d5ddd85c8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/transformer.py @@ -0,0 +1,800 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Transformer modules.""" + +from __future__ import annotations + +import math + +import torch +import torch.nn.functional as F +from torch import nn +from torch.nn.init import constant_, xavier_uniform_ + +from ultralytics.utils.torch_utils import TORCH_1_11 + +from .conv import Conv +from .utils import _get_clones, inverse_sigmoid, multi_scale_deformable_attn_pytorch + +__all__ = ( + "AIFI", + "MLP", + "DeformableTransformerDecoder", + "DeformableTransformerDecoderLayer", + "LayerNorm2d", + "MLPBlock", + "MSDeformAttn", + "TransformerBlock", + "TransformerEncoderLayer", + "TransformerLayer", +) + + +class TransformerEncoderLayer(nn.Module): + """A single layer of the transformer encoder. + + This class implements a standard transformer encoder layer with multi-head attention and feedforward network, + supporting both pre-normalization and post-normalization configurations. + + Attributes: + ma (nn.MultiheadAttention): Multi-head attention module. + fc1 (nn.Linear): First linear layer in the feedforward network. + fc2 (nn.Linear): Second linear layer in the feedforward network. + norm1 (nn.LayerNorm): Layer normalization after attention. + norm2 (nn.LayerNorm): Layer normalization after feedforward network. + dropout (nn.Dropout): Dropout layer for the feedforward network. + dropout1 (nn.Dropout): Dropout layer after attention. + dropout2 (nn.Dropout): Dropout layer after feedforward network. + act (nn.Module): Activation function. + normalize_before (bool): Whether to apply normalization before attention and feedforward. + """ + + def __init__( + self, + c1: int, + cm: int = 2048, + num_heads: int = 8, + dropout: float = 0.0, + act: nn.Module | None = None, + normalize_before: bool = False, + ): + """Initialize the TransformerEncoderLayer with specified parameters. + + Args: + c1 (int): Input dimension. + cm (int): Hidden dimension in the feedforward network. + num_heads (int): Number of attention heads. + dropout (float): Dropout probability. + act (nn.Module): Activation function. + normalize_before (bool): Whether to apply normalization before attention and feedforward. + """ + super().__init__() + from ...utils.torch_utils import TORCH_1_9 + + if not TORCH_1_9: + raise ModuleNotFoundError( + "TransformerEncoderLayer() requires torch>=1.9 to use nn.MultiheadAttention(batch_first=True)." + ) + self.ma = nn.MultiheadAttention(c1, num_heads, dropout=dropout, batch_first=True) + # Implementation of Feedforward model + self.fc1 = nn.Linear(c1, cm) + self.fc2 = nn.Linear(cm, c1) + + self.norm1 = nn.LayerNorm(c1) + self.norm2 = nn.LayerNorm(c1) + self.dropout = nn.Dropout(dropout) + self.dropout1 = nn.Dropout(dropout) + self.dropout2 = nn.Dropout(dropout) + + self.act = nn.GELU() if act is None else act + self.normalize_before = normalize_before + + @staticmethod + def with_pos_embed(tensor: torch.Tensor, pos: torch.Tensor | None = None) -> torch.Tensor: + """Add position embeddings to the tensor if provided.""" + return tensor if pos is None else tensor + pos + + def forward_post( + self, + src: torch.Tensor, + src_mask: torch.Tensor | None = None, + src_key_padding_mask: torch.Tensor | None = None, + pos: torch.Tensor | None = None, + ) -> torch.Tensor: + """Perform forward pass with post-normalization. + + Args: + src (torch.Tensor): Input tensor. + src_mask (torch.Tensor, optional): Mask for the src sequence. + src_key_padding_mask (torch.Tensor, optional): Mask for the src keys per batch. + pos (torch.Tensor, optional): Positional encoding. + + Returns: + (torch.Tensor): Output tensor after attention and feedforward. + """ + q = k = self.with_pos_embed(src, pos) + src2 = self.ma(q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0] + src = src + self.dropout1(src2) + src = self.norm1(src) + src2 = self.fc2(self.dropout(self.act(self.fc1(src)))) + src = src + self.dropout2(src2) + return self.norm2(src) + + def forward_pre( + self, + src: torch.Tensor, + src_mask: torch.Tensor | None = None, + src_key_padding_mask: torch.Tensor | None = None, + pos: torch.Tensor | None = None, + ) -> torch.Tensor: + """Perform forward pass with pre-normalization. + + Args: + src (torch.Tensor): Input tensor. + src_mask (torch.Tensor, optional): Mask for the src sequence. + src_key_padding_mask (torch.Tensor, optional): Mask for the src keys per batch. + pos (torch.Tensor, optional): Positional encoding. + + Returns: + (torch.Tensor): Output tensor after attention and feedforward. + """ + src2 = self.norm1(src) + q = k = self.with_pos_embed(src2, pos) + src2 = self.ma(q, k, value=src2, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0] + src = src + self.dropout1(src2) + src2 = self.norm2(src) + src2 = self.fc2(self.dropout(self.act(self.fc1(src2)))) + return src + self.dropout2(src2) + + def forward( + self, + src: torch.Tensor, + src_mask: torch.Tensor | None = None, + src_key_padding_mask: torch.Tensor | None = None, + pos: torch.Tensor | None = None, + ) -> torch.Tensor: + """Forward propagate the input through the encoder module. + + Args: + src (torch.Tensor): Input tensor. + src_mask (torch.Tensor, optional): Mask for the src sequence. + src_key_padding_mask (torch.Tensor, optional): Mask for the src keys per batch. + pos (torch.Tensor, optional): Positional encoding. + + Returns: + (torch.Tensor): Output tensor after transformer encoder layer. + """ + if self.normalize_before: + return self.forward_pre(src, src_mask, src_key_padding_mask, pos) + return self.forward_post(src, src_mask, src_key_padding_mask, pos) + + +class AIFI(TransformerEncoderLayer): + """AIFI transformer layer for 2D data with positional embeddings. + + This class extends TransformerEncoderLayer to work with 2D feature maps by adding 2D sine-cosine positional + embeddings and handling the spatial dimensions appropriately. + """ + + def __init__( + self, + c1: int, + cm: int = 2048, + num_heads: int = 8, + dropout: float = 0, + act: nn.Module | None = None, + normalize_before: bool = False, + ): + """Initialize the AIFI instance with specified parameters. + + Args: + c1 (int): Input dimension. + cm (int): Hidden dimension in the feedforward network. + num_heads (int): Number of attention heads. + dropout (float): Dropout probability. + act (nn.Module): Activation function. + normalize_before (bool): Whether to apply normalization before attention and feedforward. + """ + super().__init__(c1, cm, num_heads, dropout, act, normalize_before) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass for the AIFI transformer layer. + + Args: + x (torch.Tensor): Input tensor with shape [B, C, H, W]. + + Returns: + (torch.Tensor): Output tensor with shape [B, C, H, W]. + """ + c, h, w = x.shape[1:] + pos_embed = self.build_2d_sincos_position_embedding(w, h, c, like=x) + # Flatten [B, C, H, W] to [B, HxW, C] + x = super().forward(x.flatten(2).permute(0, 2, 1), pos=pos_embed.to(x.dtype)) + return x.permute(0, 2, 1).view([-1, c, h, w]).contiguous() + + @staticmethod + def build_2d_sincos_position_embedding( + w: int, h: int, embed_dim: int = 256, temperature: float = 10000.0, *, like: torch.Tensor + ) -> torch.Tensor: + """Build 2D sine-cosine position embedding. + + Args: + w (int): Width of the feature map. + h (int): Height of the feature map. + embed_dim (int): Embedding dimension. + temperature (float): Temperature for the sine/cosine functions. + like (torch.Tensor): Tensor whose device the embedding grids are built on. + + Returns: + (torch.Tensor): Position embedding with shape [1, h*w, embed_dim]. + """ + assert embed_dim % 4 == 0, "Embed dimension must be divisible by 4 for 2D sin-cos position embedding" + # type_as inherits the runtime device in traces, unlike a device= literal; fp32 seed keeps sin/cos exact + like = like.new_zeros(1, dtype=torch.float32) + grid_w = torch.arange(w).type_as(like) + grid_h = torch.arange(h).type_as(like) + grid_w, grid_h = torch.meshgrid(grid_w, grid_h, indexing="ij") if TORCH_1_11 else torch.meshgrid(grid_w, grid_h) + pos_dim = embed_dim // 4 + omega = torch.arange(pos_dim).type_as(like) / pos_dim + omega = 1.0 / (temperature**omega) + + # Pin matmul to fp32 for CoreML export: fp16 sin/cos on integer-derived positions accumulates visible error. + out_w = grid_w.flatten()[..., None].float() @ omega[None] + out_h = grid_h.flatten()[..., None].float() @ omega[None] + + return torch.cat([torch.sin(out_w), torch.cos(out_w), torch.sin(out_h), torch.cos(out_h)], 1)[None] + + +class TransformerLayer(nn.Module): + """Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance).""" + + def __init__(self, c: int, num_heads: int): + """Initialize a self-attention mechanism using linear transformations and multi-head attention. + + Args: + c (int): Input and output channel dimension. + num_heads (int): Number of attention heads. + """ + super().__init__() + self.q = nn.Linear(c, c, bias=False) + self.k = nn.Linear(c, c, bias=False) + self.v = nn.Linear(c, c, bias=False) + self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads) + self.fc1 = nn.Linear(c, c, bias=False) + self.fc2 = nn.Linear(c, c, bias=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply a transformer block to the input x and return the output. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor after transformer layer. + """ + x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x + return self.fc2(self.fc1(x)) + x + + +class TransformerBlock(nn.Module): + """Vision Transformer block based on https://arxiv.org/abs/2010.11929. + + This class implements a complete transformer block with optional convolution layer for channel adjustment, learnable + position embedding, and multiple transformer layers. + + Attributes: + conv (Conv, optional): Convolution layer if input and output channels differ. + linear (nn.Linear): Learnable position embedding. + tr (nn.Sequential): Sequential container of transformer layers. + c2 (int): Output channel dimension. + """ + + def __init__(self, c1: int, c2: int, num_heads: int, num_layers: int): + """Initialize a Transformer module with position embedding and specified number of heads and layers. + + Args: + c1 (int): Input channel dimension. + c2 (int): Output channel dimension. + num_heads (int): Number of attention heads. + num_layers (int): Number of transformer layers. + """ + super().__init__() + self.conv = None + if c1 != c2: + self.conv = Conv(c1, c2) + self.linear = nn.Linear(c2, c2) # learnable position embedding + self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers))) + self.c2 = c2 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward propagate the input through the transformer block. + + Args: + x (torch.Tensor): Input tensor with shape [b, c1, h, w]. + + Returns: + (torch.Tensor): Output tensor with shape [b, c2, h, w]. + """ + if self.conv is not None: + x = self.conv(x) + b, _, h, w = x.shape + p = x.flatten(2).permute(2, 0, 1) + return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, h, w) + + +class MLPBlock(nn.Module): + """A single block of a multi-layer perceptron.""" + + def __init__(self, embedding_dim: int, mlp_dim: int, act=nn.GELU): + """Initialize the MLPBlock with specified embedding dimension, MLP dimension, and activation function. + + Args: + embedding_dim (int): Input and output dimension. + mlp_dim (int): Hidden dimension. + act (type): Activation function class. + """ + super().__init__() + self.lin1 = nn.Linear(embedding_dim, mlp_dim) + self.lin2 = nn.Linear(mlp_dim, embedding_dim) + self.act = act() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass for the MLPBlock. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor after MLP block. + """ + return self.lin2(self.act(self.lin1(x))) + + +class MLP(nn.Module): + """A simple multi-layer perceptron (also called FFN). + + This class implements a configurable MLP with multiple linear layers, activation functions, and optional sigmoid + output activation. + + Attributes: + num_layers (int): Number of layers in the MLP. + layers (nn.ModuleList): List of linear layers. + sigmoid (bool): Whether to apply sigmoid to the output. + act (nn.Module): Activation function. + """ + + def __init__( + self, + input_dim: int, + hidden_dim: int, + output_dim: int, + num_layers: int, + act=nn.ReLU, + sigmoid: bool = False, + residual: bool = False, + out_norm: nn.Module = None, + ): + """Initialize the MLP with specified input, hidden, output dimensions and number of layers. + + Args: + input_dim (int): Input dimension. + hidden_dim (int): Hidden dimension. + output_dim (int): Output dimension. + num_layers (int): Number of layers. + act (type): Activation function class. + sigmoid (bool): Whether to apply sigmoid to the output. + residual (bool): Whether to use residual connections. + out_norm (nn.Module, optional): Normalization layer for the output. + """ + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim, *h], [*h, output_dim])) + self.sigmoid = sigmoid + self.act = act() + if residual and input_dim != output_dim: + raise ValueError("residual is only supported if input_dim == output_dim") + self.residual = residual + # whether to apply a normalization layer to the output + assert isinstance(out_norm, nn.Module) or out_norm is None + self.out_norm = out_norm or nn.Identity() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Forward pass for the entire MLP. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor after MLP. + """ + orig_x = x + for i, layer in enumerate(self.layers): + x = getattr(self, "act", nn.ReLU())(layer(x)) if i < self.num_layers - 1 else layer(x) + if getattr(self, "residual", False): + x = x + orig_x + x = getattr(self, "out_norm", nn.Identity())(x) + return x.sigmoid() if getattr(self, "sigmoid", False) else x + + +class LayerNorm2d(nn.Module): + """2D Layer Normalization module inspired by Detectron2 and ConvNeXt implementations. + + This class implements layer normalization for 2D feature maps, normalizing across the channel dimension while + preserving spatial dimensions. + + Attributes: + weight (nn.Parameter): Learnable scale parameter. + bias (nn.Parameter): Learnable bias parameter. + eps (float): Small constant for numerical stability. + + References: + https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py + https://github.com/facebookresearch/ConvNeXt/blob/main/models/convnext.py + """ + + def __init__(self, num_channels: int, eps: float = 1e-6): + """Initialize LayerNorm2d with the given parameters. + + Args: + num_channels (int): Number of channels in the input. + eps (float): Small constant for numerical stability. + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Perform forward pass for 2D layer normalization. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Normalized output tensor. + """ + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + return self.weight[:, None, None] * x + self.bias[:, None, None] + + +class MSDeformAttn(nn.Module): + """Multiscale Deformable Attention Module based on Deformable-DETR and PaddleDetection implementations. + + This module implements multiscale deformable attention that can attend to features at multiple scales with learnable + sampling locations and attention weights. + + Attributes: + im2col_step (int): Step size for im2col operations. + d_model (int): Model dimension. + n_levels (int): Number of feature levels. + n_heads (int): Number of attention heads. + n_points (int): Number of sampling points per attention head per feature level. + sampling_offsets (nn.Linear): Linear layer for generating sampling offsets. + attention_weights (nn.Linear): Linear layer for generating attention weights. + value_proj (nn.Linear): Linear layer for projecting values. + output_proj (nn.Linear): Linear layer for projecting output. + + References: + https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/modules/ms_deform_attn.py + """ + + def __init__(self, d_model: int = 256, n_levels: int = 4, n_heads: int = 8, n_points: int = 4): + """Initialize MSDeformAttn with the given parameters. + + Args: + d_model (int): Model dimension. + n_levels (int): Number of feature levels. + n_heads (int): Number of attention heads. + n_points (int): Number of sampling points per attention head per feature level. + """ + super().__init__() + if d_model % n_heads != 0: + raise ValueError(f"d_model must be divisible by n_heads, but got {d_model} and {n_heads}") + _d_per_head = d_model // n_heads + # Better to set _d_per_head to a power of 2 which is more efficient in a CUDA implementation + assert _d_per_head * n_heads == d_model, "`d_model` must be divisible by `n_heads`" + + self.im2col_step = 64 + + self.d_model = d_model + self.n_levels = n_levels + self.n_heads = n_heads + self.n_points = n_points + + self.sampling_offsets = nn.Linear(d_model, n_heads * n_levels * n_points * 2) + self.attention_weights = nn.Linear(d_model, n_heads * n_levels * n_points) + self.value_proj = nn.Linear(d_model, d_model) + self.output_proj = nn.Linear(d_model, d_model) + + self._reset_parameters() + + def _reset_parameters(self): + """Reset module parameters.""" + constant_(self.sampling_offsets.weight.data, 0.0) + thetas = torch.arange(self.n_heads, dtype=torch.float32) * (2.0 * math.pi / self.n_heads) + grid_init = torch.stack([thetas.cos(), thetas.sin()], -1) + grid_init = ( + (grid_init / grid_init.abs().max(-1, keepdim=True)[0]) + .view(self.n_heads, 1, 1, 2) + .repeat(1, self.n_levels, self.n_points, 1) + ) + for i in range(self.n_points): + grid_init[:, :, i, :] *= i + 1 + with torch.no_grad(): + self.sampling_offsets.bias = nn.Parameter(grid_init.view(-1)) + constant_(self.attention_weights.weight.data, 0.0) + constant_(self.attention_weights.bias.data, 0.0) + xavier_uniform_(self.value_proj.weight.data) + constant_(self.value_proj.bias.data, 0.0) + xavier_uniform_(self.output_proj.weight.data) + constant_(self.output_proj.bias.data, 0.0) + + def forward( + self, + query: torch.Tensor, + refer_bbox: torch.Tensor, + value: torch.Tensor, + value_shapes: list, + value_mask: torch.Tensor | None = None, + ) -> torch.Tensor: + """Perform forward pass for multiscale deformable attention. + + Args: + query (torch.Tensor): Query tensor with shape [bs, query_length, C]. + refer_bbox (torch.Tensor): Reference bounding boxes with shape [bs, query_length, 1, 2 or 4], range in [0, + 1], top-left (0,0), bottom-right (1, 1). The size-1 axis broadcasts across n_levels. + value (torch.Tensor): Value tensor with shape [bs, value_length, C]. + value_shapes (list): List with shape [n_levels, 2], [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]. + value_mask (torch.Tensor, optional): Mask tensor with shape [bs, value_length], True for padding elements, + False for non-padding elements. + + Returns: + (torch.Tensor): Output tensor with shape [bs, Length_{query}, C]. + + References: + https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py + """ + bs, len_q = query.shape[:2] + len_v = value.shape[1] + assert sum(s[0] * s[1] for s in value_shapes) == len_v + + value = self.value_proj(value) + if value_mask is not None: + value = value.masked_fill(value_mask[..., None], float(0)) + value = value.view(bs, len_v, self.n_heads, self.d_model // self.n_heads) + # Fold (n_levels, n_points) into one axis so every traced tensor stays at rank <= 5 (required for CoreML + # export); refer_bbox arrives as (bs, len_q, 1, 2 or 4) and its size-1 axis broadcasts implicitly. + n_total_points = self.n_levels * self.n_points + sampling_offsets = self.sampling_offsets(query).view(bs, len_q, self.n_heads, n_total_points, 2) + attention_weights = self.attention_weights(query).view(bs, len_q, self.n_heads, n_total_points) + attention_weights = F.softmax(attention_weights, -1) + num_points = refer_bbox.shape[-1] + if num_points == 2: + offset_normalizer = torch.as_tensor(value_shapes, dtype=query.dtype, device=query.device).flip(-1) + offset_normalizer = offset_normalizer[:, None, :].expand(-1, self.n_points, -1).reshape(n_total_points, 2) + sampling_locations = refer_bbox[:, :, None, :, :] + sampling_offsets / offset_normalizer + elif num_points == 4: + sampling_locations = ( + refer_bbox[:, :, None, :, :2] + sampling_offsets / self.n_points * refer_bbox[:, :, None, :, 2:] * 0.5 + ) + else: + raise ValueError(f"Last dim of reference_points must be 2 or 4, but got {num_points}.") + output = multi_scale_deformable_attn_pytorch(value, value_shapes, sampling_locations, attention_weights) + return self.output_proj(output) + + +class DeformableTransformerDecoderLayer(nn.Module): + """Deformable Transformer Decoder Layer inspired by PaddleDetection and Deformable-DETR implementations. + + This class implements a single decoder layer with self-attention, cross-attention using multiscale deformable + attention, and a feedforward network. + + Attributes: + self_attn (nn.MultiheadAttention): Self-attention module. + dropout1 (nn.Dropout): Dropout after self-attention. + norm1 (nn.LayerNorm): Layer normalization after self-attention. + cross_attn (MSDeformAttn): Cross-attention module. + dropout2 (nn.Dropout): Dropout after cross-attention. + norm2 (nn.LayerNorm): Layer normalization after cross-attention. + linear1 (nn.Linear): First linear layer in the feedforward network. + act (nn.Module): Activation function. + dropout3 (nn.Dropout): Dropout in the feedforward network. + linear2 (nn.Linear): Second linear layer in the feedforward network. + dropout4 (nn.Dropout): Dropout after the feedforward network. + norm3 (nn.LayerNorm): Layer normalization after the feedforward network. + + References: + https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py + https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/deformable_transformer.py + """ + + def __init__( + self, + d_model: int = 256, + n_heads: int = 8, + d_ffn: int = 1024, + dropout: float = 0.0, + act: nn.Module | None = None, + n_levels: int = 4, + n_points: int = 4, + ): + """Initialize the DeformableTransformerDecoderLayer with the given parameters. + + Args: + d_model (int): Model dimension. + n_heads (int): Number of attention heads. + d_ffn (int): Dimension of the feedforward network. + dropout (float): Dropout probability. + act (nn.Module): Activation function. + n_levels (int): Number of feature levels. + n_points (int): Number of sampling points. + """ + super().__init__() + + # Self attention + self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout) + self.dropout1 = nn.Dropout(dropout) + self.norm1 = nn.LayerNorm(d_model) + + # Cross attention + self.cross_attn = MSDeformAttn(d_model, n_levels, n_heads, n_points) + self.dropout2 = nn.Dropout(dropout) + self.norm2 = nn.LayerNorm(d_model) + + # FFN + self.linear1 = nn.Linear(d_model, d_ffn) + self.act = nn.ReLU() if act is None else act + self.dropout3 = nn.Dropout(dropout) + self.linear2 = nn.Linear(d_ffn, d_model) + self.dropout4 = nn.Dropout(dropout) + self.norm3 = nn.LayerNorm(d_model) + + @staticmethod + def with_pos_embed(tensor: torch.Tensor, pos: torch.Tensor | None) -> torch.Tensor: + """Add positional embeddings to the input tensor, if provided.""" + return tensor if pos is None else tensor + pos + + def forward_ffn(self, tgt: torch.Tensor) -> torch.Tensor: + """Perform forward pass through the Feed-Forward Network part of the layer. + + Args: + tgt (torch.Tensor): Input tensor. + + Returns: + (torch.Tensor): Output tensor after FFN. + """ + tgt2 = self.linear2(self.dropout3(self.act(self.linear1(tgt)))) + tgt = tgt + self.dropout4(tgt2) + return self.norm3(tgt) + + def forward( + self, + embed: torch.Tensor, + refer_bbox: torch.Tensor, + feats: torch.Tensor, + shapes: list, + padding_mask: torch.Tensor | None = None, + attn_mask: torch.Tensor | None = None, + query_pos: torch.Tensor | None = None, + ) -> torch.Tensor: + """Perform the forward pass through the entire decoder layer. + + Args: + embed (torch.Tensor): Input embeddings. + refer_bbox (torch.Tensor): Reference bounding boxes. + feats (torch.Tensor): Feature maps. + shapes (list): Feature shapes. + padding_mask (torch.Tensor, optional): Padding mask. + attn_mask (torch.Tensor, optional): Attention mask. + query_pos (torch.Tensor, optional): Query position embeddings. + + Returns: + (torch.Tensor): Output tensor after decoder layer. + """ + # Self attention + q = k = self.with_pos_embed(embed, query_pos) + tgt = self.self_attn(q.transpose(0, 1), k.transpose(0, 1), embed.transpose(0, 1), attn_mask=attn_mask)[ + 0 + ].transpose(0, 1) + embed = embed + self.dropout1(tgt) + embed = self.norm1(embed) + + # Cross attention + tgt = self.cross_attn( + self.with_pos_embed(embed, query_pos), refer_bbox.unsqueeze(2), feats, shapes, padding_mask + ) + embed = embed + self.dropout2(tgt) + embed = self.norm2(embed) + + # FFN + return self.forward_ffn(embed) + + +class DeformableTransformerDecoder(nn.Module): + """Deformable Transformer Decoder based on PaddleDetection implementation. + + This class implements a complete deformable transformer decoder with multiple decoder layers and prediction heads + for bounding box regression and classification. + + Attributes: + layers (nn.ModuleList): List of decoder layers. + num_layers (int): Number of decoder layers. + hidden_dim (int): Hidden dimension. + eval_idx (int): Index of the layer to use during evaluation. + + References: + https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py + """ + + def __init__(self, hidden_dim: int, decoder_layer: nn.Module, num_layers: int, eval_idx: int = -1): + """Initialize the DeformableTransformerDecoder with the given parameters. + + Args: + hidden_dim (int): Hidden dimension. + decoder_layer (nn.Module): Decoder layer module. + num_layers (int): Number of decoder layers. + eval_idx (int): Index of the layer to use during evaluation. + """ + super().__init__() + self.layers = _get_clones(decoder_layer, num_layers) + self.num_layers = num_layers + self.hidden_dim = hidden_dim + self.eval_idx = eval_idx if eval_idx >= 0 else num_layers + eval_idx + + def forward( + self, + embed: torch.Tensor, # decoder embeddings + refer_bbox: torch.Tensor, # anchor + feats: torch.Tensor, # image features + shapes: list, # feature shapes + bbox_head: nn.Module, + score_head: nn.Module, + pos_mlp: nn.Module, + attn_mask: torch.Tensor | None = None, + padding_mask: torch.Tensor | None = None, + ): + """Perform the forward pass through the entire decoder. + + Args: + embed (torch.Tensor): Decoder embeddings. + refer_bbox (torch.Tensor): Reference bounding boxes. + feats (torch.Tensor): Image features. + shapes (list): Feature shapes. + bbox_head (nn.Module): Bounding box prediction head. + score_head (nn.Module): Score prediction head. + pos_mlp (nn.Module): Position MLP. + attn_mask (torch.Tensor, optional): Attention mask. + padding_mask (torch.Tensor, optional): Padding mask. + + Returns: + dec_bboxes (torch.Tensor): Decoded bounding boxes. + dec_cls (torch.Tensor): Decoded classification scores. + """ + output = embed + dec_bboxes = [] + dec_cls = [] + last_refined_bbox = None + refer_bbox = refer_bbox.sigmoid() + for i, layer in enumerate(self.layers): + output = layer(output, refer_bbox, feats, shapes, padding_mask, attn_mask, pos_mlp(refer_bbox)) + + bbox = bbox_head[i](output) + refined_bbox = torch.sigmoid(bbox + inverse_sigmoid(refer_bbox)) + + if self.training: + dec_cls.append(score_head[i](output)) + if i == 0: + dec_bboxes.append(refined_bbox) + else: + dec_bboxes.append(torch.sigmoid(bbox + inverse_sigmoid(last_refined_bbox))) + elif i == self.eval_idx: + dec_cls.append(score_head[i](output)) + dec_bboxes.append(refined_bbox) + break + + last_refined_bbox = refined_bbox + refer_bbox = refined_bbox.detach() if self.training else refined_bbox + + return torch.stack(dec_bboxes), torch.stack(dec_cls) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/utils.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..791420a802b9b6006f67e5b8fefb4c8e2cfa3d7c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/modules/utils.py @@ -0,0 +1,126 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import copy + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + +__all__ = "inverse_sigmoid", "multi_scale_deformable_attn_pytorch" + + +def _get_clones(module, n): + """Create a list of cloned modules from the given module. + + Args: + module (nn.Module): The module to be cloned. + n (int): Number of clones to create. + + Returns: + (nn.ModuleList): A ModuleList containing n clones of the input module. + + Examples: + >>> import torch.nn as nn + >>> layer = nn.Linear(10, 10) + >>> clones = _get_clones(layer, 3) + >>> len(clones) + 3 + """ + return nn.ModuleList([copy.deepcopy(module) for _ in range(n)]) + + +def bias_init_with_prob(prior_prob=0.01): + """Initialize conv/fc bias value according to a given probability value. + + This function calculates the bias initialization value based on a prior probability using the inverse sigmoid + (logit) + function. It's commonly used in object detection models to initialize classification layers with a specific positive + prediction probability. + + Args: + prior_prob (float, optional): Prior probability for bias initialization. + + Returns: + (float): Bias initialization value calculated from the prior probability. + + Examples: + >>> bias = bias_init_with_prob(0.01) + >>> print(f"Bias initialization value: {bias:.4f}") + Bias initialization value: -4.5951 + """ + return float(-np.log((1 - prior_prob) / prior_prob)) # return bias_init + + +def inverse_sigmoid(x, eps=1e-5): + """Calculate the inverse sigmoid function for a tensor. + + This function applies the inverse of the sigmoid function to a tensor, which is useful in various neural network + operations, particularly in attention mechanisms and coordinate transformations. + + Args: + x (torch.Tensor): Input tensor with values in range [0, 1]. + eps (float, optional): Small epsilon value to prevent numerical instability. + + Returns: + (torch.Tensor): Tensor after applying the inverse sigmoid function. + + Examples: + >>> x = torch.tensor([0.2, 0.5, 0.8]) + >>> inverse_sigmoid(x) + tensor([-1.3863, 0.0000, 1.3863]) + """ + x = x.clamp(min=0, max=1) + x1 = x.clamp(min=eps) + x2 = (1 - x).clamp(min=eps) + return torch.log(x1 / x2) + + +def multi_scale_deformable_attn_pytorch( + value: torch.Tensor, + value_spatial_shapes: list, + sampling_locations: torch.Tensor, + attention_weights: torch.Tensor, +) -> torch.Tensor: + """Implement multi-scale deformable attention in PyTorch. + + Folds the (num_levels, num_points) axes into a single num_total_points axis so every traced tensor stays at rank <= + 5, the maximum rank supported by CoreML's MIL converter. Numerically equivalent to the rank-6 reference + implementation on CUDA and CPU. + + Args: + value (torch.Tensor): Value tensor with shape (bs, num_keys, num_heads, embed_dims). + value_spatial_shapes (list): Per-level spatial shapes as [(H_0, W_0), ..., (H_{L-1}, W_{L-1})]. + sampling_locations (torch.Tensor): Sampling locations with shape (bs, num_queries, num_heads, num_levels * + num_points, 2). + attention_weights (torch.Tensor): Attention weights with shape (bs, num_queries, num_heads, num_levels * + num_points). + + Returns: + (torch.Tensor): Output tensor with shape (bs, num_queries, num_heads * embed_dims). + + References: + https://github.com/IDEA-Research/detrex/blob/main/detrex/layers/multi_scale_deform_attn.py + """ + bs, _, num_heads, embed_dims = value.shape + _, num_queries, _, num_total_points, _ = sampling_locations.shape + num_points = num_total_points // len(value_spatial_shapes) + + # (bs, num_keys, num_heads, embed_dims) -> tuple of (bs*num_heads, embed_dims, H*W) per level + value_list = value.permute(0, 2, 3, 1).flatten(0, 1).split([h * w for h, w in value_spatial_shapes], dim=-1) + # Map to grid_sample coords in [-1, 1] and split per level: tuple of (bs*num_heads, num_queries, num_points, 2) + sampling_grids = (2 * sampling_locations - 1).permute(0, 2, 1, 3, 4).flatten(0, 1).split(num_points, dim=-2) + + sampling_value_list = [] + for level, (h, w) in enumerate(value_spatial_shapes): + value_l = value_list[level].reshape(bs * num_heads, embed_dims, h, w) + sampling_value_list.append( + F.grid_sample(value_l, sampling_grids[level], mode="bilinear", padding_mode="zeros", align_corners=False) + ) + attention_weights = attention_weights.permute(0, 2, 1, 3).reshape(bs * num_heads, 1, num_queries, num_total_points) + output = ( + (torch.cat(sampling_value_list, dim=-1) * attention_weights) + .sum(-1) + .view(bs, num_heads * embed_dims, num_queries) + ) + return output.transpose(1, 2).contiguous() diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/tasks.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..46b1b50e957045c066f4ed951563015783803536 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/tasks.py @@ -0,0 +1,2344 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import contextlib +import importlib +import pickle +import re +import threading +from copy import deepcopy +from pathlib import Path + +import numpy as np +import torch +from torch import nn + +from ultralytics.nn.autobackend import check_class_names +from ultralytics.nn.modules import ( + AIFI, + C1, + C2, + C2PSA, + C3, + C3TR, + ELAN1, + OBB, + OBB26, + PSA, + SPP, + SPPELAN, + SPPF, + A2C2f, + AConv, + ADown, + Bottleneck, + BottleneckCSP, + C2f, + C2fAttn, + C2fCIB, + C2fPSA, + C3Ghost, + C3k2, + C3x, + CBFuse, + CBLinear, + Classify, + Concat, + Conv, + Conv2, + ConvTranspose, + Depth, + Detect, + DWConv, + DWConvTranspose2d, + Focus, + GhostBottleneck, + GhostConv, + HGBlock, + HGStem, + ImagePoolingAttn, + Index, + LRPCHead, + Pose, + Pose26, + RepC3, + RepConv, + RepNCSPELAN4, + RepVGGDW, + ResNetLayer, + RTDETRDecoder, + SCDown, + Segment, + Segment26, + SemanticSegment, + TorchVision, + WorldDetect, + YOLOEDetect, + YOLOESegment, + YOLOESegment26, + v10Detect, +) +from ultralytics.utils import ( + DEFAULT_CFG_DICT, + LOGGER, + SAFE_LOAD, + SETTINGS, + WINDOWS, + YAML, + IterableSimpleNamespace, + colorstr, + emojis, +) +from ultralytics.utils.checks import REMOTE_FILE_PREFIXES, check_file, check_requirements, check_suffix, check_yaml +from ultralytics.utils.loss import ( + DepthLoss26, + E2ELoss, + PoseLoss26, + SemanticSegmentationLoss, + v8ClassificationLoss, + v8DetectionLoss, + v8OBBLoss, + v8PoseLoss, + v8SegmentationLoss, +) +from ultralytics.utils.ops import make_divisible +from ultralytics.utils.patches import torch_load +from ultralytics.utils.torch_utils import ( + fuse_conv_and_bn, + fuse_deconv_and_bn, + initialize_weights, + intersect_dicts, + is_qat, + model_info, + restore_qat, + scale_img, + smart_inference_mode, + time_sync, +) + + +class BaseModel(torch.nn.Module): + """Base class for all YOLO models in the Ultralytics family. + + This class provides common functionality for YOLO models including forward pass handling, model fusion, information + display, and weight loading capabilities. + + Attributes: + model (torch.nn.Sequential): The neural network model. + save (list): List of layer indices to save outputs from. + stride (torch.Tensor): Model stride values. + + Methods: + forward: Perform forward pass for training or inference. + predict: Perform inference on input tensor. + fuse: Fuse Conv/BatchNorm layers and reparameterize for optimization. + info: Print model information. + load: Load weights into the model. + loss: Compute loss for training. + + Examples: + Create a BaseModel instance + >>> model = BaseModel() + >>> model.info() # Display model information + """ + + def forward(self, x, *args, **kwargs): + """Perform forward pass of the model for either training or inference. + + If x is a dict, calculates and returns the loss for training. Otherwise, returns predictions for inference. + + Args: + x (torch.Tensor | dict): Input tensor for inference, or dict with image tensor and labels for training. + *args (Any): Variable length argument list. + **kwargs (Any): Arbitrary keyword arguments. + + Returns: + (torch.Tensor): Loss if x is a dict (training), or network predictions (inference). + """ + if isinstance(x, dict): # for cases of training and validating while training. + return self.loss(x, *args, **kwargs) + return self.predict(x, *args, **kwargs) + + def predict(self, x, profile=False, augment=False, embed=None): + """Perform a forward pass through the network. + + Args: + x (torch.Tensor): The input tensor to the model. + profile (bool): Print the computation time of each layer if True. + augment (bool): Augment image during prediction. + embed (list, optional): A list of layer indices to return embeddings from. + + Returns: + (torch.Tensor): The last output of the model. + """ + if augment: + return self._predict_augment(x) + return self._predict_once(x, profile, embed) + + def _predict_once(self, x, profile=False, embed=None): + """Perform a forward pass through the network. + + Args: + x (torch.Tensor): The input tensor to the model. + profile (bool): Print the computation time of each layer if True. + embed (list, optional): A list of layer indices to return embeddings from. + + Returns: + (torch.Tensor): The last output of the model. + """ + y, dt, embeddings = [], [], [] # outputs + embed = frozenset(embed) if embed else {-1} + max_idx = max(embed) + for m in self.model: + if m.f != -1: # if not from previous layer + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers + if profile: + self._profile_one_layer(m, x, dt) + x = m(x) # run + y.append(x if m.i in self.save else None) # save output + if m.i in embed: + embeddings.append(torch.nn.functional.adaptive_avg_pool2d(x, (1, 1)).squeeze(-1).squeeze(-1)) # flatten + if m.i == max_idx: + return torch.unbind(torch.cat(embeddings, 1), dim=0) + return x + + def _predict_augment(self, x): + """Perform augmentations on input image x and return augmented inference.""" + LOGGER.warning( + f"{self.__class__.__name__} does not support 'augment=True' prediction. " + f"Reverting to single-scale prediction." + ) + return self._predict_once(x) + + def _profile_one_layer(self, m, x, dt): + """Profile the computation time and FLOPs of a single layer of the model on a given input. + + Args: + m (torch.nn.Module): The layer to be profiled. + x (torch.Tensor): The input data to the layer. + dt (list): A list to store the computation time of the layer. + """ + try: + import thop + except ImportError: + thop = None # conda support without 'ultralytics-thop' installed + + c = m == self.model[-1] and isinstance(x, list) # is final layer list, copy input as inplace fix + flops = thop.profile(m, inputs=[x.copy() if c else x], verbose=False)[0] / 1e9 * 2 if thop else 0 + device = next(self.parameters()).device + t = time_sync(device) + for _ in range(10): + m(x.copy() if c else x) + dt.append((time_sync(device) - t) * 100) + if m == self.model[0]: + LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module") + LOGGER.info(f"{dt[-1]:10.2f} {flops:10.2f} {m.np:10.0f} {m.type}") + if c: + LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total") + + def fuse(self, verbose=True, imgsz=640): + """Fuse Conv/ConvTranspose and BatchNorm layers, and reparameterize RepConv/RepVGGDW for improved efficiency. + + Args: + verbose (bool): Whether to print model information after fusion. + imgsz (int | list): Input image size used for FLOPs calculation. + + Returns: + (torch.nn.Module): The fused model is returned. + """ + # BN folds into a QAT conv exactly, its per-channel weight range scales along; merged branches and transposed + # convs have no such rescale for their ranges, so they stay as trained + skip = (Conv2, ConvTranspose, RepConv, RepVGGDW) if is_qat(self) else () + if not self.is_fused(): + for m in self.model.modules(): + if isinstance(m, skip): + continue + if isinstance(m, (Conv, Conv2, DWConv)) and hasattr(m, "bn"): + if isinstance(m, Conv2): + m.fuse_convs() + m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv + delattr(m, "bn") # remove batchnorm + m.forward = m.forward_fuse # update forward + if isinstance(m, ConvTranspose) and hasattr(m, "bn"): + m.conv_transpose = fuse_deconv_and_bn(m.conv_transpose, m.bn) + delattr(m, "bn") # remove batchnorm + m.forward = m.forward_fuse # update forward + if isinstance(m, RepConv): + m.fuse_convs() + m.forward = m.forward_fuse # update forward + if isinstance(m, RepVGGDW): + m.fuse() + m.forward = m.forward_fuse + if isinstance(m, Detect): + m.fuse() # remove the unused detection branch + self.info(verbose=verbose, imgsz=imgsz) + + return self + + def is_fused(self): + """Return True once fuse() has nothing left to do.""" + return not any( + (isinstance(m, (Conv, ConvTranspose)) and hasattr(m, "bn")) + or (isinstance(m, (RepConv, RepVGGDW)) and hasattr(m, "conv1")) + or (isinstance(m, Detect) and m.cv2 is not None and getattr(m, "one2one_cv2", None) is not None) + for m in self.modules() + ) + + def info(self, detailed=False, verbose=True, imgsz=640): + """Print model information. + + Args: + detailed (bool): If True, prints out detailed information about the model. + verbose (bool): If True, prints out the model information. + imgsz (int): The size of the image used for computing model information. + """ + return model_info(self, detailed=detailed, verbose=verbose, imgsz=imgsz) + + def _apply(self, fn): + """Apply a function to all tensors in the model, including Detect head attributes like stride and anchors. + + Args: + fn (function): The function to apply to the model. + + Returns: + (BaseModel): An updated BaseModel object. + """ + super()._apply(fn) + m = self.model[-1] # Detect() + if isinstance( + m, Detect + ): # includes all Detect subclasses like Segment, Pose, OBB, WorldDetect, YOLOEDetect, YOLOESegment + m.stride = fn(m.stride) + m.anchors = fn(m.anchors) + m.strides = fn(m.strides) + return self + + def load(self, weights, verbose=True): + """Load weights into the model. + + Args: + weights (dict | torch.nn.Module): The pre-trained weights to be loaded. + verbose (bool, optional): Whether to log the transfer progress. + """ + model = (weights.get("ema") or weights["model"]) if isinstance(weights, dict) else weights # ema first + csd = model.float().state_dict() # checkpoint state_dict as FP32 + + # Remap classification head rows by class-name when nc differs (e.g. Obj365 -> COCO fine-tune) + cls_remapped = self._remap_cls_by_names(csd, model, verbose=verbose) + + updated_csd = intersect_dicts(csd, self.state_dict()) # intersect + self.load_state_dict(updated_csd, strict=False) # load + len_updated_csd = len(updated_csd) + cls_remapped + first_conv = "model.0.conv.weight" # hard-coded to yolo models for now + # mostly used to boost multi-channel training + state_dict = self.state_dict() + if first_conv not in updated_csd and first_conv in state_dict: + c1, c2, h, w = state_dict[first_conv].shape + cc1, cc2, ch, cw = csd[first_conv].shape + if ch == h and cw == w: + c1, c2 = min(c1, cc1), min(c2, cc2) + state_dict[first_conv][:c1, :c2] = csd[first_conv][:c1, :c2] + len_updated_csd += 1 + self.pt_path = getattr(model, "pt_path", None) # provenance follows the weights selected above + if verbose: + LOGGER.info(f"Transferred {len_updated_csd}/{len(self.model.state_dict())} items from pretrained weights") + if getattr(model, "is_fused", lambda: False)() and not self.is_fused(): + LOGGER.warning("Pretrained weights are fused for inference; train from the unfused checkpoint instead.") + + def _remap_cls_by_names(self, csd: dict[str, torch.Tensor], src_model: torch.nn.Module, verbose: bool = True): + """Remap pretrained classification head rows to current class order by name. + + Copies rows from pretrained cls layers into the current model's state_dict where the destination class name + matches a source class name (case-insensitive, whitespace-stripped). Useful when fine-tuning across datasets + with overlapping classes, whether the class counts differ (e.g. Objects365 -> COCO) or match but the class + order differs. Mutates the destination tensors in-place via state_dict references; matched cls tensors are + removed from `csd` so the subsequent intersect_dicts skips them. + + Args: + csd (dict): Pretrained checkpoint state_dict (will be mutated). + src_model (torch.nn.Module): Pretrained module, used to read `.names` and `.nc`. + verbose (bool): Log mapping summary. + + Returns: + (int): Number of cls tensors remapped (counted toward "Transferred" log line). + """ + src_names = getattr(src_model, "names", None) + tgt_names = getattr(self, "names", None) + if not (isinstance(src_names, dict) and isinstance(tgt_names, dict)): + return 0 + src_nc, tgt_nc = len(src_names), len(tgt_names) + + def _norm(s): + return str(s).strip().lower() + + # Skip default placeholder names {0:"0", 1:"1", ...} (also catches empty dicts) — nothing to match on + if any(all(str(k) == str(v) for k, v in n.items()) for n in (src_names, tgt_names)): + return 0 + + src_lookup = {_norm(v): k for k, v in src_names.items()} + idx = torch.tensor([src_lookup.get(_norm(tgt_names.get(k)), -1) for k in range(tgt_nc)], dtype=torch.long) + n_match = int((idx >= 0).sum()) + # Skip if nothing matches, or class names already share order and count (intersect_dicts copies directly) + if n_match == 0 or (src_nc == tgt_nc and torch.equal(idx, torch.arange(tgt_nc))): + return 0 + + valid = idx >= 0 + state_dict = self.state_dict() + # Exact class-logit conv weight/bias keys from the detection head(s) — restricting to these avoids + # class-ordering tensors that merely share the nc dimension (backbone blocks, box/mask/pose branches). + cls_keys = { + f"{name}.{attr}.{i}.{len(seq) - 1}.{p}" + for name, m in self.named_modules() + if isinstance(m, Detect) + for attr in ("cv3", "one2one_cv3") + for i, seq in enumerate(getattr(m, attr, ())) + if getattr(seq[-1], "out_channels", None) == tgt_nc + for p in ("weight", "bias") + } + remapped = 0 + for k in cls_keys & csd.keys(): + v_src, v_tgt = csd[k], state_dict[k] + if v_src.shape[1:] != v_tgt.shape[1:]: # cls-conv weight input width (c3) differs across nc; copy bias only + continue + v_tgt[valid] = v_src[idx[valid]].to(v_tgt.dtype) + csd.pop(k) # prevent intersect_dicts from copying these rows in the wrong (source) order + remapped += 1 + if verbose and remapped: + LOGGER.info(f"Remapped {n_match}/{tgt_nc} cls head rows from pretrained weights by class name") + return remapped + + def loss(self, batch, preds=None): + """Compute loss. + + Args: + batch (dict): Batch to compute loss on. + preds (torch.Tensor | list[torch.Tensor], optional): Predictions. + """ + if getattr(self, "criterion", None) is None: + self.criterion = self.init_criterion() + + if preds is None: + preds = self.forward(batch["img"]) + return self.criterion(preds, batch) + + def init_criterion(self): + """Initialize the loss criterion for the BaseModel.""" + raise NotImplementedError("compute_loss() needs to be implemented by task heads") + + +def _initialize_yolo_model(model, cfg, ch, nc, verbose): + """Initialize common YOLO model attributes from a YAML config.""" + model.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg) # cfg dict + if model.yaml["backbone"][0][2] == "Silence": + LOGGER.warning( + "YOLOv9 `Silence` module is deprecated in favor of torch.nn.Identity. " + "Please delete local *.pt file and re-download the latest model checkpoint." + ) + model.yaml["backbone"][0][2] = "nn.Identity" + + model.yaml["channels"] = ch # save channels + if nc and nc != model.yaml["nc"]: + LOGGER.info(f"Overriding model.yaml nc={model.yaml['nc']} with nc={nc}") + model.yaml["nc"] = nc # override YAML value + model.model, model.save = parse_model(deepcopy(model.yaml), ch=ch, verbose=verbose) # model, savelist + model.names = {i: f"{i}" for i in range(model.yaml["nc"])} # default names dict + model.inplace = model.yaml.get("inplace", True) + + +class DetectionModel(BaseModel): + """YOLO detection model. + + This class implements the YOLO detection architecture, handling model initialization, forward pass, augmented + inference, and loss computation for object detection tasks. + + Attributes: + yaml (dict): Model configuration dictionary. + model (torch.nn.Sequential): The neural network model. + save (list): List of layer indices to save outputs from. + names (dict): Class names dictionary. + inplace (bool): Whether to use inplace operations. + end2end (bool): Whether the model uses end-to-end detection. + stride (torch.Tensor): Model stride values. + + Methods: + __init__: Initialize the YOLO detection model. + _predict_augment: Perform augmented inference. + _descale_pred: De-scale predictions following augmented inference. + _clip_augmented: Clip YOLO augmented inference tails. + init_criterion: Initialize the loss criterion. + + Examples: + Initialize a detection model + >>> model = DetectionModel("yolo26n.yaml", ch=3, nc=80) + >>> results = model.predict(image_tensor) + """ + + def __init__(self, cfg="yolo26n.yaml", ch=3, nc=None, verbose=True): + """Initialize the YOLO detection model with the given config and parameters. + + Args: + cfg (str | dict): Model configuration file path or dictionary. + ch (int): Number of input channels. + nc (int, optional): Number of classes. + verbose (bool): Whether to display model information. + """ + super().__init__() + _initialize_yolo_model(self, cfg, ch, nc, verbose) + + # Build strides + m = self.model[-1] # Detect() + if isinstance(m, Detect): # includes all Detect subclasses like Segment, Pose, OBB, YOLOEDetect, YOLOESegment + s = 256 # 2x min stride + m.inplace = self.inplace + + def _forward(x): + """Perform a forward pass through the model, handling different Detect subclass types accordingly.""" + output = self.forward(x) + if "one2many" in output: + output = output["one2many"] + return output["feats"] + + self.model.eval() # Avoid changing batch statistics until training begins + m.training = True # Setting it to True to properly return strides + m.stride = torch.tensor([s / x.shape[-2] for x in _forward(torch.zeros(1, ch, s, s))]) # forward + self.stride = m.stride + self.model.train() # Set model back to training(default) mode + m.bias_init() # only run once + else: + self.stride = torch.Tensor([32]) # default stride, e.g., RTDETR + + # Init weights, biases + initialize_weights(self) + if verbose: + self.info() + LOGGER.info("") + + @property + def end2end(self): + """Return whether the model uses end-to-end NMS-free detection.""" + return getattr(self.model[-1], "end2end", False) + + @end2end.setter + def end2end(self, value): + """Select the inference head while retaining both branches for training.""" + if isinstance(self.model[-1], Detect): + self.model[-1].end2end = value + + def set_head_attr(self, **kwargs): + """Set attributes of the model head (last layer). + + Args: + **kwargs (Any): Arbitrary keyword arguments representing attributes to set. + """ + head = self.model[-1] + for k, v in kwargs.items(): + if not hasattr(head, k): + LOGGER.warning(f"Head has no attribute '{k}'.") + continue + setattr(head, k, v) + + def _predict_augment(self, x): + """Perform augmentations on input image x and return augmented inference and train outputs. + + Args: + x (torch.Tensor): Input image tensor. + + Returns: + (tuple[torch.Tensor, None]): Augmented inference output and None for train output. + """ + if getattr(self, "end2end", False) or type(self.model[-1]) is not Detect: + LOGGER.warning("Model does not support 'augment=True', reverting to single-scale prediction.") + return self._predict_once(x) + img_size = x.shape[-2:] # height, width + s = [1, 0.83, 0.67] # scales + f = [None, 3, None] # flips (2-ud, 3-lr) + y = [] # outputs + for si, fi in zip(s, f): + xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) + yi = super().predict(xi)[0] # forward + yi = self._descale_pred(yi, fi, si, img_size) + y.append(yi) + y = self._clip_augmented(y) # clip augmented tails + return torch.cat(y, -1), None # augmented inference, train + + @staticmethod + def _descale_pred(p, flips, scale, img_size, dim=1): + """De-scale predictions following augmented inference (inverse operation). + + Args: + p (torch.Tensor): Predictions tensor. + flips (int | None): Flip type (None=none, 2=ud, 3=lr). + scale (float): Scale factor. + img_size (tuple): Original image size (height, width). + dim (int): Dimension to split at. + + Returns: + (torch.Tensor): De-scaled predictions. + """ + p[:, :4] /= scale # de-scale + x, y, wh, cls = p.split((1, 1, 2, p.shape[dim] - 4), dim) + if flips == 2: + y = img_size[0] - y # de-flip ud + elif flips == 3: + x = img_size[1] - x # de-flip lr + return torch.cat((x, y, wh, cls), dim) + + def _clip_augmented(self, y): + """Clip YOLO augmented inference tails. + + Args: + y (list[torch.Tensor]): List of detection tensors. + + Returns: + (list[torch.Tensor]): Clipped detection tensors. + """ + nl = self.model[-1].nl # number of detection layers (P3-P5) + g = sum(4**x for x in range(nl)) # grid points + e = 1 # exclude layer count + i = (y[0].shape[-1] // g) * sum(4**x for x in range(e)) # indices + y[0] = y[0][..., :-i] # large + i = (y[-1].shape[-1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices + y[-1] = y[-1][..., i:] # small + return y + + def init_criterion(self): + """Initialize the loss criterion for the DetectionModel.""" + return E2ELoss(self) if getattr(self.model[-1], "one2one_cv2", None) is not None else v8DetectionLoss(self) + + +class OBBModel(DetectionModel): + """YOLO Oriented Bounding Box (OBB) model. + + This class extends DetectionModel to handle oriented bounding box detection tasks, providing specialized loss + computation for rotated object detection. + + Methods: + __init__: Initialize YOLO OBB model. + init_criterion: Initialize the loss criterion for OBB detection. + + Examples: + Initialize an OBB model + >>> model = OBBModel("yolo26n-obb.yaml", ch=3, nc=80) + >>> results = model.predict(image_tensor) + """ + + def __init__(self, cfg="yolo26n-obb.yaml", ch=3, nc=None, verbose=True): + """Initialize YOLO OBB model with given config and parameters. + + Args: + cfg (str | dict): Model configuration file path or dictionary. + ch (int): Number of input channels. + nc (int, optional): Number of classes. + verbose (bool): Whether to display model information. + """ + super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose) + + def init_criterion(self): + """Initialize the loss criterion for the model.""" + return E2ELoss(self, v8OBBLoss) if getattr(self.model[-1], "one2one_cv2", None) is not None else v8OBBLoss(self) + + +class SegmentationModel(DetectionModel): + """YOLO segmentation model. + + This class extends DetectionModel to handle instance segmentation tasks, providing specialized loss computation for + pixel-level object detection and segmentation. + + Methods: + __init__: Initialize YOLO segmentation model. + init_criterion: Initialize the loss criterion for segmentation. + + Examples: + Initialize a segmentation model + >>> model = SegmentationModel("yolo26n-seg.yaml", ch=3, nc=80) + >>> results = model.predict(image_tensor) + """ + + def __init__(self, cfg="yolo26n-seg.yaml", ch=3, nc=None, verbose=True): + """Initialize Ultralytics YOLO segmentation model with given config and parameters. + + Args: + cfg (str | dict): Model configuration file path or dictionary. + ch (int): Number of input channels. + nc (int, optional): Number of classes. + verbose (bool): Whether to display model information. + """ + super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose) + + def init_criterion(self): + """Initialize the loss criterion for the SegmentationModel.""" + return ( + E2ELoss(self, v8SegmentationLoss) + if getattr(self.model[-1], "one2one_cv2", None) is not None + else v8SegmentationLoss(self) + ) + + +class SemanticSegmentationModel(BaseModel): + """YOLO semantic segmentation model. + + This class implements a semantic segmentation model that produces per-pixel class predictions. Unlike + SegmentationModel (instance segmentation), this does not produce bounding boxes. + + Methods: + __init__: Initialize the semantic segmentation model. + init_criterion: Initialize the loss criterion for semantic segmentation. + + Examples: + Initialize a semantic segmentation model + >>> model = SemanticSegmentationModel("yolo26n-sem.yaml", ch=3, nc=19) + """ + + def __init__(self, cfg="yolo26n-sem.yaml", ch=3, nc=None, verbose=True): + """Initialize the YOLO semantic segmentation model. + + Args: + cfg (str | dict): Model configuration file path or dictionary. + ch (int): Number of input channels. + nc (int, optional): Number of classes. + verbose (bool): Whether to display model information. + """ + super().__init__() + _initialize_yolo_model(self, cfg, ch, nc, verbose) + + # Build strides: track smallest spatial size across all layers to find the deepest + # backbone stride (e.g. P5/32). Head input alone is insufficient: the FPN upsamples + # P5 away before the head, but the encoder still requires inputs aligned to that + # deepest stride or FPN concats fail on rounding mismatches. + m = self.model[-1] + if isinstance(m, SemanticSegment): + s = 256 + self.model.eval() + m.training = True # get training output (stride-4) + min_h = [s] + + def _record(_m, _inp, out, _h=min_h): + if isinstance(out, torch.Tensor) and out.ndim == 4: + _h[0] = min(_h[0], out.shape[-2]) + + hooks = [layer.register_forward_hook(_record) for layer in self.model] + try: + self.forward(torch.zeros(1, ch, s, s)) + finally: + for h in hooks: + h.remove() + m.stride = torch.tensor([s / min_h[0]], dtype=torch.float32) # e.g., 256/8 = 32 + self.stride = m.stride + self.model.train() + else: + self.stride = torch.Tensor([32]) + + initialize_weights(self) + if verbose: + self.info() + LOGGER.info("") + + def init_criterion(self): + """Initialize the loss criterion for semantic segmentation.""" + return SemanticSegmentationLoss(self) + + def _apply(self, fn): + """Apply a function to all tensors in the model.""" + super()._apply(fn) + m = self.model[-1] + if isinstance(m, SemanticSegment): + m.stride = fn(m.stride) + return self + + +class PoseModel(DetectionModel): + """YOLO pose model. + + This class extends DetectionModel to handle human pose estimation tasks, providing specialized loss computation for + keypoint detection and pose estimation. + + Attributes: + kpt_shape (tuple): Shape of keypoints data (num_keypoints, num_dimensions). + + Methods: + __init__: Initialize YOLO pose model. + init_criterion: Initialize the loss criterion for pose estimation. + + Examples: + Initialize a pose model + >>> model = PoseModel("yolo26n-pose.yaml", ch=3, nc=1, data_kpt_shape=(17, 3)) + >>> results = model.predict(image_tensor) + """ + + def __init__(self, cfg="yolo26n-pose.yaml", ch=3, nc=None, data_kpt_shape=(None, None), verbose=True): + """Initialize Ultralytics YOLO Pose model. + + Args: + cfg (str | dict): Model configuration file path or dictionary. + ch (int): Number of input channels. + nc (int, optional): Number of classes. + data_kpt_shape (tuple): Shape of keypoints data. + verbose (bool): Whether to display model information. + """ + if not isinstance(cfg, dict): + cfg = yaml_model_load(cfg) # load model YAML + if any(data_kpt_shape) and list(data_kpt_shape) != list(cfg["kpt_shape"]): + LOGGER.info(f"Overriding model.yaml kpt_shape={cfg['kpt_shape']} with kpt_shape={data_kpt_shape}") + cfg["kpt_shape"] = data_kpt_shape + super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose) + + def init_criterion(self): + """Initialize the loss criterion for the PoseModel.""" + loss = PoseLoss26 if isinstance(self.model[-1], Pose26) else v8PoseLoss + return E2ELoss(self, loss) if getattr(self.model[-1], "one2one_cv2", None) is not None else loss(self) + + +class DepthModel(DetectionModel): + """YOLO depth estimation model. + + This class extends DetectionModel for monocular depth estimation, using YOLO backbone + FPN with a DPT-style dense + depth decoder head. Follows the Depth Anything approach adapted to YOLO architecture. + + Examples: + >>> model = DepthModel("yolo26n-depth.yaml", ch=3) + >>> results = model(image_tensor) + """ + + def __init__(self, cfg="yolo26n-depth.yaml", ch=3, nc=None, verbose=True): + """Initialize YOLO Depth model.""" + super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose) + + def init_criterion(self): + """Initialize the depth loss criterion.""" + return DepthLoss26(self) + + +class ClassificationModel(BaseModel): + """YOLO classification model. + + This class implements the YOLO classification architecture for image classification tasks, providing model + initialization, configuration, and output reshaping capabilities. + + Attributes: + yaml (dict): Model configuration dictionary. + model (torch.nn.Sequential): The neural network model. + stride (torch.Tensor): Model stride values. + names (dict): Class names dictionary. + + Methods: + __init__: Initialize ClassificationModel. + _from_yaml: Set model configurations and define architecture. + reshape_outputs: Update model to specified class count. + init_criterion: Initialize the loss criterion. + + Examples: + Initialize a classification model + >>> model = ClassificationModel("yolo26n-cls.yaml", ch=3, nc=1000) + >>> results = model.predict(image_tensor) + """ + + def __init__(self, cfg="yolo26n-cls.yaml", ch=3, nc=None, verbose=True): + """Initialize ClassificationModel with YAML, channels, number of classes, verbose flag. + + Args: + cfg (str | dict): Model configuration file path or dictionary. + ch (int): Number of input channels. + nc (int, optional): Number of classes. + verbose (bool): Whether to display model information. + """ + super().__init__() + self._from_yaml(cfg, ch, nc, verbose) + + def _from_yaml(self, cfg, ch, nc, verbose): + """Set Ultralytics YOLO model configurations and define the model architecture. + + Args: + cfg (str | dict): Model configuration file path or dictionary. + ch (int): Number of input channels. + nc (int, optional): Number of classes. + verbose (bool): Whether to display model information. + """ + self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg) # cfg dict + + # Define model + ch = self.yaml["channels"] = self.yaml.get("channels", ch) # input channels + if nc and nc != self.yaml["nc"]: + LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") + self.yaml["nc"] = nc # override YAML value + elif not nc and not self.yaml.get("nc", None): + raise ValueError("nc not specified. Must specify nc in model.yaml or function arguments.") + self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose) # model, savelist + self.stride = torch.Tensor([1]) # no stride constraints + self.names = {i: f"{i}" for i in range(self.yaml["nc"])} # default names dict + self.info() + + @staticmethod + def reshape_outputs(model, nc): + """Update a TorchVision classification model to class count 'nc' if required. + + Args: + model (torch.nn.Module): Model to update. + nc (int): New number of classes. + """ + name, m = list((model.model if hasattr(model, "model") else model).named_children())[-1] # last module + if isinstance(m, Classify): # YOLO Classify() head + if m.linear.out_features != nc: + m.linear = torch.nn.Linear(m.linear.in_features, nc) + elif isinstance(m, torch.nn.Linear): # ResNet, EfficientNet + if m.out_features != nc: + setattr(model, name, torch.nn.Linear(m.in_features, nc)) + elif isinstance(m, torch.nn.Sequential): + types = [type(x) for x in m] + if torch.nn.Linear in types: + i = len(types) - 1 - types[::-1].index(torch.nn.Linear) # last torch.nn.Linear index + if m[i].out_features != nc: + m[i] = torch.nn.Linear(m[i].in_features, nc) + elif torch.nn.Conv2d in types: + i = len(types) - 1 - types[::-1].index(torch.nn.Conv2d) # last torch.nn.Conv2d index + if m[i].out_channels != nc: + m[i] = torch.nn.Conv2d( + m[i].in_channels, nc, m[i].kernel_size, m[i].stride, bias=m[i].bias is not None + ) + + def init_criterion(self): + """Initialize the loss criterion for the ClassificationModel.""" + return v8ClassificationLoss() + + +class RTDETRDetectionModel(DetectionModel): + """RTDETR (Real-time DEtection and Tracking using Transformers) Detection Model class. + + This class is responsible for constructing the RTDETR architecture, defining loss functions, and facilitating both + the training and inference processes. RTDETR is an object detection and tracking model that extends from the + DetectionModel base class. + + Attributes: + nc (int): Number of classes for detection. + criterion (RTDETRDetectionLoss): Loss function for training. + + Methods: + __init__: Initialize the RTDETRDetectionModel. + init_criterion: Initialize the loss criterion. + loss: Compute loss for training. + predict: Perform forward pass through the model. + + Examples: + Initialize an RTDETR model + >>> model = RTDETRDetectionModel("rtdetr-l.yaml", ch=3, nc=80) + >>> results = model.predict(image_tensor) + """ + + def __init__(self, cfg="rtdetr-l.yaml", ch=3, nc=None, verbose=True): + """Initialize the RTDETRDetectionModel. + + Args: + cfg (str | dict): Configuration file name or path. + ch (int): Number of input channels. + nc (int, optional): Number of classes. + verbose (bool): Print additional information during initialization. + """ + super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose) + + def _remap_cls_by_names(self, csd: dict[str, torch.Tensor], src_model: torch.nn.Module, verbose: bool = True): + """Remap RT-DETR decoder cls-head rows by class name. + + Overrides BaseModel's YOLO-specific implementation: RT-DETR's classification tensors live under + `score_head` and `class_embed` inside `RTDETRDecoder` rather than `Detect.cv3`. All of them are + row-per-class, including the training-only `denoising_class_embed` embedding, so matched class rows + transfer even when source and target `nc` differ; any residual shape mismatch is dropped by + `intersect_dicts`. + + Args: + csd (dict): Pretrained checkpoint state_dict (will be mutated). + src_model (torch.nn.Module): Pretrained module, used to read `.names`. + verbose (bool): Log mapping summary. + + Returns: + (int): Number of cls tensors remapped (counted toward "Transferred" log line). + """ + src_names = getattr(src_model, "names", None) + tgt_names = getattr(self, "names", None) + if not (isinstance(src_names, dict) and isinstance(tgt_names, dict)): + return 0 + # Skip default placeholder names {0:"0", 1:"1", ...} (also catches empty dicts) + if any(all(str(k) == str(v) for k, v in n.items()) for n in (src_names, tgt_names)): + return 0 + + src_lookup = {str(v).strip().lower(): k for k, v in src_names.items()} + tgt_nc = len(tgt_names) + idx = torch.tensor( + [src_lookup.get(str(tgt_names[k]).strip().lower(), -1) for k in range(tgt_nc)], dtype=torch.long + ) + n_match = int((idx >= 0).sum()) + # Skip if nothing matches, or class names already share order and count (intersect_dicts handles it directly) + if n_match == 0 or (len(src_names) == tgt_nc and torch.equal(idx, torch.arange(tgt_nc))): + return 0 + + valid = idx >= 0 + state_dict = self.state_dict() + cls_keys = {k for k in csd if ("score_head" in k or "class_embed" in k) and k in state_dict} + remapped = 0 + for k in cls_keys: + v_src, v_tgt = csd[k], state_dict[k] + if v_src.ndim != v_tgt.ndim or v_src.shape[1:] != v_tgt.shape[1:]: + continue + v_tgt[valid] = v_src[idx[valid]].to(v_tgt.dtype) + csd.pop(k) # prevent intersect_dicts from copying these rows in the wrong (source) order + remapped += 1 + if verbose and remapped: + LOGGER.info(f"Remapped {n_match}/{tgt_nc} decoder cls head rows from pretrained weights by class name") + return remapped + + def _apply(self, fn): + """Apply a function to all tensors in the model, including decoder anchors and valid mask. + + Args: + fn (function): The function to apply to the model. + + Returns: + (RTDETRDetectionModel): An updated RTDETRDetectionModel object. + """ + super()._apply(fn) + m = self.model[-1] + m.anchors = fn(m.anchors) + m.valid_mask = fn(m.valid_mask) + return self + + def init_criterion(self): + """Initialize the loss criterion for the RTDETRDetectionModel.""" + from ultralytics.models.utils.loss import RTDETRDetectionLoss + + return RTDETRDetectionLoss(nc=self.nc, use_vfl=True) + + def loss(self, batch, preds=None): + """Compute the loss for the given batch of data. + + Args: + batch (dict): Dictionary containing image and label data. + preds (tuple, optional): Precomputed model predictions. + + Returns: + (torch.Tensor): Total loss value. + (dict): Main three losses in a dict. + """ + if not hasattr(self, "criterion"): + self.criterion = self.init_criterion() + + img = batch["img"] + # NOTE: preprocess gt_bbox and gt_labels to list. + bs = img.shape[0] + batch_idx = batch["batch_idx"] + gt_groups = [(batch_idx == i).sum().item() for i in range(bs)] + targets = { + "cls": batch["cls"].to(img.device, dtype=torch.long).view(-1), + "bboxes": batch["bboxes"].to(device=img.device), + "batch_idx": batch_idx.to(img.device, dtype=torch.long).view(-1), + "gt_groups": gt_groups, + } + + if preds is None: + preds = self.predict(img, batch=targets) + dec_bboxes, dec_scores, enc_bboxes, enc_scores, dn_meta = preds if self.training else preds[1] + if dn_meta is None: + dn_bboxes, dn_scores = None, None + else: + dn_bboxes, dec_bboxes = torch.split(dec_bboxes, dn_meta["dn_num_split"], dim=2) + dn_scores, dec_scores = torch.split(dec_scores, dn_meta["dn_num_split"], dim=2) + + dec_bboxes = torch.cat([enc_bboxes.unsqueeze(0), dec_bboxes]) # (7, bs, 300, 4) + dec_scores = torch.cat([enc_scores.unsqueeze(0), dec_scores]) + + loss = self.criterion( + (dec_bboxes, dec_scores), targets, dn_bboxes=dn_bboxes, dn_scores=dn_scores, dn_meta=dn_meta + ) + # NOTE: There are like 12 losses in RTDETR, backward with all losses but only show the main three losses. + return sum(loss.values()), { + "giou_loss": loss["loss_giou"].detach(), + "cls_loss": loss["loss_class"].detach(), + "l1_loss": loss["loss_bbox"].detach(), + } + + def predict(self, x, profile=False, batch=None, augment=False, embed=None): + """Perform a forward pass through the model. + + Args: + x (torch.Tensor): The input tensor. + profile (bool): If True, profile the computation time for each layer. + batch (dict, optional): Ground truth data for evaluation. + augment (bool): If True, perform data augmentation during inference. + embed (list, optional): A list of layer indices to return embeddings from. + + Returns: + (torch.Tensor): Model's output tensor. + """ + y, dt, embeddings = [], [], [] # outputs + embed = frozenset(embed) if embed else {-1} + max_idx = max(embed) + for m in self.model[:-1]: # except the head part + if m.f != -1: # if not from previous layer + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers + if profile: + self._profile_one_layer(m, x, dt) + x = m(x) # run + y.append(x if m.i in self.save else None) # save output + if m.i in embed: + embeddings.append(torch.nn.functional.adaptive_avg_pool2d(x, (1, 1)).squeeze(-1).squeeze(-1)) # flatten + if m.i == max_idx: + return torch.unbind(torch.cat(embeddings, 1), dim=0) + head = self.model[-1] + x = head([y[j] for j in head.f], batch) # head inference + return x + + +class WorldModel(DetectionModel): + """YOLOv8 World Model. + + This class implements the YOLOv8 World model for open-vocabulary object detection, supporting text-based class + specification and CLIP model integration for zero-shot detection capabilities. + + Attributes: + txt_feats (torch.Tensor): Text feature embeddings for classes. + clip_model (torch.nn.Module): CLIP model for text encoding. + + Methods: + __init__: Initialize YOLOv8 world model. + set_classes: Set classes for offline inference. + get_text_pe: Get text positional embeddings. + predict: Perform forward pass with text features. + loss: Compute loss with text features. + + Examples: + Initialize a world model + >>> model = WorldModel("yolov8s-world.yaml", ch=3, nc=80) + >>> model.set_classes(["person", "car", "bicycle"]) + >>> results = model.predict(image_tensor) + """ + + def __init__(self, cfg="yolov8s-world.yaml", ch=3, nc=None, verbose=True): + """Initialize YOLOv8 world model with given config and parameters. + + Args: + cfg (str | dict): Model configuration file path or dictionary. + ch (int): Number of input channels. + nc (int, optional): Number of classes. + verbose (bool): Whether to display model information. + """ + self.txt_feats = torch.randn(1, nc or 80, 512) # features placeholder + self.clip_model = None # CLIP model placeholder + super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose) + + def set_classes(self, text, batch=80, cache_clip_model=True): + """Set classes in advance so that model could do offline-inference without clip model. + + Args: + text (list[str]): List of class names. + batch (int): Batch size for processing text tokens. + cache_clip_model (bool): Whether to cache the CLIP model. + """ + self.txt_feats = self.get_text_pe(text, batch=batch, cache_clip_model=cache_clip_model) + self.model[-1].nc = len(text) + + def get_text_pe(self, text, batch=80, cache_clip_model=True): + """Get text positional embeddings using the CLIP model. + + Args: + text (list[str]): List of class names. + batch (int): Batch size for processing text tokens. + cache_clip_model (bool): Whether to cache the CLIP model. + + Returns: + (torch.Tensor): Text positional embeddings. + """ + from ultralytics.nn.text_model import build_text_model + + device = next(self.model.parameters()).device + if not getattr(self, "clip_model", None) and cache_clip_model: + # For backwards compatibility of models lacking clip_model attribute + self.clip_model = build_text_model("clip:ViT-B/32", device=device) + model = self.clip_model if cache_clip_model else build_text_model("clip:ViT-B/32", device=device) + text_token = model.tokenize(text) + txt_feats = [model.encode_text(token).detach() for token in text_token.split(batch)] + txt_feats = txt_feats[0] if len(txt_feats) == 1 else torch.cat(txt_feats, dim=0) + return txt_feats.reshape(-1, len(text), txt_feats.shape[-1]) + + def predict(self, x, profile=False, txt_feats=None, augment=False, embed=None): + """Perform a forward pass through the model. + + Args: + x (torch.Tensor): The input tensor. + profile (bool): If True, profile the computation time for each layer. + txt_feats (torch.Tensor, optional): The text features, use it if it's given. + augment (bool): If True, perform data augmentation during inference. + embed (list, optional): A list of layer indices to return embeddings from. + + Returns: + (torch.Tensor): Model's output tensor. + """ + txt_feats = (self.txt_feats if txt_feats is None else txt_feats).type_as(x) + if txt_feats.shape[0] != x.shape[0] or self.model[-1].export: + txt_feats = txt_feats.expand(x.shape[0], -1, -1) + ori_txt_feats = txt_feats.clone() + y, dt, embeddings = [], [], [] # outputs + embed = frozenset(embed) if embed else {-1} + max_idx = max(embed) + for m in self.model: # except the head part + if m.f != -1: # if not from previous layer + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers + if profile: + self._profile_one_layer(m, x, dt) + if isinstance(m, C2fAttn): + x = m(x, txt_feats) + elif isinstance(m, WorldDetect): + x = m(x, ori_txt_feats) + elif isinstance(m, ImagePoolingAttn): + txt_feats = m(x, txt_feats) + else: + x = m(x) # run + + y.append(x if m.i in self.save else None) # save output + if m.i in embed: + embeddings.append(torch.nn.functional.adaptive_avg_pool2d(x, (1, 1)).squeeze(-1).squeeze(-1)) # flatten + if m.i == max_idx: + return torch.unbind(torch.cat(embeddings, 1), dim=0) + return x + + def loss(self, batch, preds=None): + """Compute loss. + + Args: + batch (dict): Batch to compute loss on. + preds (torch.Tensor | list[torch.Tensor], optional): Predictions. + """ + if not hasattr(self, "criterion"): + self.criterion = self.init_criterion() + + if preds is None: + preds = self.forward(batch["img"], txt_feats=batch["txt_feats"]) + return self.criterion(preds, batch) + + +class YOLOEModel(DetectionModel): + """YOLOE detection model. + + This class implements the YOLOE architecture for efficient object detection with text and visual prompts, supporting + both prompt-based and prompt-free inference modes. + + Attributes: + pe (torch.Tensor): Prompt embeddings for classes. + clip_model (torch.nn.Module): CLIP model for text encoding. + + Methods: + __init__: Initialize YOLOE model. + get_text_pe: Get text positional embeddings. + get_visual_pe: Get visual embeddings. + set_vocab: Set vocabulary for prompt-free model. + get_vocab: Get fused vocabulary layer. + set_classes: Set classes for offline inference. + get_cls_pe: Get class positional embeddings. + predict: Perform forward pass with prompts. + loss: Compute loss with prompts. + + Examples: + Initialize a YOLOE model + >>> model = YOLOEModel("yoloe-v8s.yaml", ch=3, nc=80) + >>> results = model.predict(image_tensor, tpe=text_embeddings) + """ + + def __init__(self, cfg="yoloe-v8s.yaml", ch=3, nc=None, verbose=True): + """Initialize YOLOE model with given config and parameters. + + Args: + cfg (str | dict): Model configuration file path or dictionary. + ch (int): Number of input channels. + nc (int, optional): Number of classes. + verbose (bool): Whether to display model information. + """ + super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose) + self.text_model = self.yaml.get("text_model", "mobileclip:blt") + + @smart_inference_mode() + def get_text_pe(self, text, batch=80, cache_clip_model=False, without_reprta=False): + """Get text positional embeddings using the CLIP model. + + Args: + text (list[str]): List of class names. + batch (int): Batch size for processing text tokens. + cache_clip_model (bool): Whether to cache the CLIP model. + without_reprta (bool): Whether to return text embeddings without reprta module processing. + + Returns: + (torch.Tensor): Text positional embeddings in the model's parameter dtype. + """ + from ultralytics.nn.text_model import build_text_model + + assert len(text), f"Expected at least one class name, but got {text}" + param = next(self.model.parameters()) + device = param.device + if not getattr(self, "clip_model", None) and cache_clip_model: + # For backwards compatibility of models lacking clip_model attribute + self.clip_model = build_text_model(getattr(self, "text_model", "mobileclip:blt"), device=device) + + model = ( + self.clip_model + if cache_clip_model + else build_text_model(getattr(self, "text_model", "mobileclip:blt"), device=device) + ) + text_token = model.tokenize(text) + txt_feats = [model.encode_text(token).detach() for token in text_token.split(batch)] + txt_feats = txt_feats[0] if len(txt_feats) == 1 else torch.cat(txt_feats, dim=0) + txt_feats = txt_feats.reshape(-1, len(text), txt_feats.shape[-1]).to(param.dtype) # CLIP always emits float32 + if without_reprta: + return txt_feats + + head = self.model[-1] + assert isinstance(head, YOLOEDetect) + return head.get_tpe(txt_feats) # run auxiliary text head + + @smart_inference_mode() + def get_visual_pe(self, img, visual): + """Get visual positional embeddings. + + Args: + img (torch.Tensor): Input image tensor. + visual (torch.Tensor): Visual features. + + Returns: + (torch.Tensor): Visual positional embeddings. + """ + return self(img, vpe=visual, return_vpe=True) + + def set_vocab(self, vocab, names, one2one_vocab=None): + """Set vocabulary for the prompt-free model. + + Args: + vocab (nn.ModuleList): One-to-many vocabulary items returned by ``get_vocab`` for ``names``. + names (list[str]): List of class names. + one2one_vocab (nn.ModuleList | None): One-to-one vocabulary items. When provided, both the one-to-many and + one-to-one prompt-free heads are built, so the ``nms`` argument keeps selecting between them at + inference. When omitted, only the branch selected by ``end2end`` is built, as before. + """ + assert not self.training + head = self.model[-1] + assert isinstance(head, YOLOEDetect) + names = check_class_names(names) # validate before the re-parameterization below, which cannot be undone + # Cache anchors for head + with torch.no_grad(): # a tracked warmup would build a graph through the backbone + self(next(self.parameters()).new_empty(1, 3, self.args["imgsz"], self.args["imgsz"])) # warmup + + # re-parameterization for prompt-free model, one LRPC head per (vocabulary, loc branch, cls branch) + if one2one_vocab is None: # single vocabulary for the branch end2end selects + e2e = "one2one_" if head.end2end else "" + branches = {"lrpc": (vocab, getattr(head, f"{e2e}cv2"), getattr(head, f"{e2e}cv3"))} + else: + branches = { + "lrpc": (vocab, head.cv2, head.cv3), + "one2one_lrpc": (one2one_vocab, head.one2one_cv2, head.one2one_cv3), + } + assert all(len(v) == head.nl for v, _, _ in branches.values()), f"Each vocabulary needs {head.nl} items." + for name, (v, cv2, cv3) in branches.items(): + lrpc = (LRPCHead(cls, pf[-1], loc[-1], enabled=i != 2) for i, (cls, pf, loc) in enumerate(zip(v, cv3, cv2))) + setattr(head, name, nn.ModuleList(lrpc)) + for loc_head, cls_head in zip(cv2, cv3): + assert isinstance(loc_head, nn.Sequential) + assert isinstance(cls_head, nn.Sequential) + del loc_head[-1] + del cls_head[-1] + if one2one_vocab is None: + head.fuse() # LRPC is built for one branch; discard the other before inference can select it. + self.model[-1].nc = len(names) + self.names = names + + def get_vocab(self, names): + """Get fused vocabulary layer from the model. + + Args: + names (list[str]): List of class names. + + Returns: + (nn.ModuleList): List of vocabulary modules. + """ + assert not self.training + head = self.model[-1] + assert isinstance(head, YOLOEDetect) + assert not head.is_fused + names = list(check_class_names(names).values()) # validate before fusing the head, which cannot be undone + + tpe = self.get_text_pe(names) + self.set_classes(names, tpe) + device = next(self.model.parameters()).device + head.fuse(self.pe.to(device)) # fuse prompt embeddings to classify head + + cv3 = head.one2one_cv3 if head.end2end else head.cv3 + vocab = nn.ModuleList() + for cls_head in cv3: + assert isinstance(cls_head, nn.Sequential) + vocab.append(cls_head[-1]) + return vocab + + def set_classes(self, names, embeddings): + """Set classes in advance so that model could do offline-inference without clip model. + + Args: + names (list[str]): List of class names. + embeddings (torch.Tensor): Embeddings tensor. + """ + assert not hasattr(self.model[-1], "lrpc"), ( + "Prompt-free model does not support setting classes. Please try with Text/Visual prompt models." + ) + assert embeddings.ndim == 3 + self.names = check_class_names(names) # validate before any state is written + self.pe = embeddings + self.model[-1].nc = len(names) + + def get_cls_pe(self, tpe, vpe): + """Get class positional embeddings. + + Args: + tpe (torch.Tensor | None): Text positional embeddings. + vpe (torch.Tensor | None): Visual positional embeddings. + + Returns: + (torch.Tensor): Class positional embeddings. + """ + all_pe = [] + if tpe is not None: + assert tpe.ndim == 3 + all_pe.append(tpe) + if vpe is not None: + assert vpe.ndim == 3 + all_pe.append(vpe) + if not all_pe: + all_pe.append(getattr(self, "pe", torch.zeros(1, 80, 512))) + return torch.cat(all_pe, dim=1) + + def predict(self, x, profile=False, tpe=None, augment=False, embed=None, vpe=None, return_vpe=False): + """Perform a forward pass through the model. + + Args: + x (torch.Tensor): The input tensor. + profile (bool): If True, profile the computation time for each layer. + tpe (torch.Tensor, optional): Text positional embeddings. + augment (bool): If True, perform data augmentation during inference. + embed (list, optional): A list of layer indices to return embeddings from. + vpe (torch.Tensor, optional): Visual positional embeddings. + return_vpe (bool): If True, return visual positional embeddings. + + Returns: + (torch.Tensor): Model's output tensor. + """ + y, dt, embeddings = [], [], [] # outputs + b = x.shape[0] + embed = frozenset(embed) if embed else {-1} + max_idx = max(embed) + for m in self.model: # except the head part + if m.f != -1: # if not from previous layer + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers + if profile: + self._profile_one_layer(m, x, dt) + if isinstance(m, YOLOEDetect): + vpe = m.get_vpe(x, vpe) if vpe is not None else None + if return_vpe: + assert vpe is not None + assert not self.training + return vpe + cls_pe = self.get_cls_pe(m.get_tpe(tpe), vpe).type_as(x[0]) + if cls_pe.shape[0] != b or m.export: + cls_pe = cls_pe.expand(b, -1, -1) + x.append(cls_pe) # adding cls embedding + x = m(x) # run + + y.append(x if m.i in self.save else None) # save output + if m.i in embed: + embeddings.append(torch.nn.functional.adaptive_avg_pool2d(x, (1, 1)).squeeze(-1).squeeze(-1)) # flatten + if m.i == max_idx: + return torch.unbind(torch.cat(embeddings, 1), dim=0) + return x + + def loss(self, batch, preds=None): + """Compute loss. + + Args: + batch (dict): Batch to compute loss on. + preds (torch.Tensor | list[torch.Tensor], optional): Predictions. + """ + if not hasattr(self, "criterion"): + from ultralytics.utils.loss import TVPDetectLoss + + visual_prompt = batch.get("visuals", None) is not None # TODO + self.criterion = ( + ( + E2ELoss(self, TVPDetectLoss) + if getattr(self.model[-1], "one2one_cv2", None) is not None + else TVPDetectLoss(self) + ) + if visual_prompt + else self.init_criterion() + ) + if preds is None: + preds = self.forward( + batch["img"], + tpe=None if "visuals" in batch else batch.get("txt_feats", None), + vpe=batch.get("visuals", None), + ) + return self.criterion(preds, batch) + + +class YOLOESegModel(YOLOEModel, SegmentationModel): + """YOLOE segmentation model. + + This class extends YOLOEModel to handle instance segmentation tasks with text and visual prompts, providing + specialized loss computation for pixel-level object detection and segmentation. + + Methods: + __init__: Initialize YOLOE segmentation model. + loss: Compute loss with prompts for segmentation. + + Examples: + Initialize a YOLOE segmentation model + >>> model = YOLOESegModel("yoloe-v8s-seg.yaml", ch=3, nc=80) + >>> results = model.predict(image_tensor, tpe=text_embeddings) + """ + + def __init__(self, cfg="yoloe-v8s-seg.yaml", ch=3, nc=None, verbose=True): + """Initialize YOLOE segmentation model with given config and parameters. + + Args: + cfg (str | dict): Model configuration file path or dictionary. + ch (int): Number of input channels. + nc (int, optional): Number of classes. + verbose (bool): Whether to display model information. + """ + super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose) + + def loss(self, batch, preds=None): + """Compute loss. + + Args: + batch (dict): Batch to compute loss on. + preds (torch.Tensor | list[torch.Tensor], optional): Predictions. + """ + if not hasattr(self, "criterion"): + from ultralytics.utils.loss import TVPSegmentLoss + + visual_prompt = batch.get("visuals", None) is not None # TODO + self.criterion = ( + ( + E2ELoss(self, TVPSegmentLoss) + if getattr(self.model[-1], "one2one_cv2", None) is not None + else TVPSegmentLoss(self) + ) + if visual_prompt + else self.init_criterion() + ) + + return super().loss(batch, preds) + + +class Ensemble(torch.nn.ModuleList): + """Ensemble of models. + + This class allows combining multiple YOLO models into an ensemble for improved performance through model averaging + or other ensemble techniques. + + Methods: + __init__: Initialize an ensemble of models. + forward: Generate predictions from all models in the ensemble. + + Examples: + Create an ensemble of models + >>> ensemble = Ensemble() + >>> ensemble.append(model1) + >>> ensemble.append(model2) + >>> results = ensemble(image_tensor) + """ + + def __init__(self): + """Initialize an ensemble of models.""" + super().__init__() + + def forward(self, x, augment=False, profile=False): + """Run ensemble forward pass and concatenate predictions from all models. + + Args: + x (torch.Tensor): Input tensor. + augment (bool): Whether to augment the input. + profile (bool): Whether to profile the model. + + Returns: + (torch.Tensor): Concatenated predictions from all models. + (None): Always None for ensemble inference. + """ + y = [module(x, augment, profile)[0] for module in self] + # y = torch.stack(y).max(0)[0] # max ensemble + # y = torch.stack(y).mean(0) # mean ensemble + y = torch.cat(y, 2) # nms ensemble, y shape(B, HW, C*num_models) + return y, None # inference, train output + + +# Functions ------------------------------------------------------------------------------------------------------------ + + +_temporary_modules_lock = threading.RLock() + + +@contextlib.contextmanager +def temporary_modules(modules=None, attributes=None): + """Context manager for temporarily adding or modifying modules in Python's module cache (`sys.modules`). + + This function can be used to change the module paths during runtime. It's useful when refactoring code, where you've + moved a module from one location to another, but you still want to support the old import paths for backwards + compatibility. + + Args: + modules (dict, optional): A dictionary mapping old module paths to new module paths. + attributes (dict, optional): A dictionary mapping old module attributes to new module attributes. + + Examples: + >>> with temporary_modules({"old.module": "new.module"}, {"old.module.attribute": "new.module.attribute"}): + >>> import old.module # this will now import new.module + >>> from old.module import attribute # this will now import new.module.attribute + + Notes: + The changes are only in effect inside the context manager and are undone once the context manager exits. + Be aware that directly manipulating `sys.modules` can lead to unpredictable results, especially in larger + applications or libraries. Use this function with caution. + """ + if modules is None: + modules = {} + if attributes is None: + attributes = {} + import sys + from importlib import import_module + + missing = object() + previous = [] # (module, attribute, prior value) so exiting restores e.g. pathlib.WindowsPath + with _temporary_modules_lock: + try: + # Set attributes in sys.modules under their old name + for old, new in attributes.items(): + old_module, old_attr = old.rsplit(".", 1) + new_module, new_attr = new.rsplit(".", 1) + module = import_module(old_module) + previous.append((module, old_attr, module.__dict__.get(old_attr, missing))) + setattr(module, old_attr, getattr(import_module(new_module), new_attr)) + + # Set modules in sys.modules under their old name + for old, new in modules.items(): + sys.modules[old] = import_module(new) + + yield + finally: + # Remove the temporary module paths and attributes + for old in modules: + if old in sys.modules: + del sys.modules[old] + for module, attr, value in previous: + if value is missing: + delattr(module, attr) + else: + setattr(module, attr, value) + + +class _SafeLoad: + """Opt-in restricted checkpoint loading: reconstruct only known model classes (`weights_only=True` plus an + allow-list) and build models without `eval()`. + + Enabled per-process by the `ULTRALYTICS_SAFE_LOAD` env flag, or per-call by `torch_safe_load(..., safe_only=True)`. + Default loading (flag off) is unchanged. The globals a restricted load registers stay registered for the process, so + they also apply to any other `torch.load(weights_only=True)` call made afterwards. + """ + + # Restricted loading needs torch 2.6+: the checkpoint global scan and `(obj, "module.Name")` allow-list aliases. + # On older torch restricted loading degrades to a standard load. + SUPPORTED = hasattr(torch.serialization, "get_unsafe_globals_in_checkpoint") + _registry = None # {"module.Name": allow-list entry}, built once per process + _lock = ( + threading.Lock() + ) # add_safe_globals rebinds a process-global set; held across _build(), so no load may run at import + _local = threading.local() # per-thread flag set while a weights_only load is in progress + + @classmethod + def restricted(cls): + """Whether model construction should use the no-eval, known-layer path (env flag or an in-progress load).""" + return cls.SUPPORTED and (SAFE_LOAD or getattr(cls._local, "active", False)) + + @classmethod + @contextlib.contextmanager + def loading(cls, weight): + """Load with `weights_only=True`: register the globals this checkpoint needs and mark the thread restricted, so + a checkpoint that reaches model construction (parse_model) also uses the no-eval, known-layer path. + + Globals are registered with `add_safe_globals` for the life of the process, never scoped per load: the + `safe_globals()` context manager removes its entries from a process-global set on exit, so with concurrent + loads one thread's exit strips the allow-list out of another thread's in-flight unpickle. Registering only + the globals a checkpoint references also keeps the restricted unpickler fast — torch rebuilds its lookup from + the whole registered set on every GLOBAL/NEWOBJ/REDUCE/BUILD opcode, so a 660-entry allow-list nearly doubled + the load time of a checkpoint that references 20 of them. + """ + try: + needed = torch.serialization.get_unsafe_globals_in_checkpoint(weight) + except ValueError: # Not a torch.save() zip archive; torch.load reports the format error, nothing to register + needed = [] + with cls._lock: + if cls._registry is None: + cls._registry = cls._build() + for name in needed: + module, _, attr = name.rpartition(".") + if name not in cls._registry and ( + module in {"torch.nn.modules", "ultralytics.nn.modules", "ultralytics.nn.tasks"} + or module.rpartition(".")[0] in {"torch.nn.modules", "ultralytics.nn.modules"} + or module in {"ultralytics.utils.loss", "ultralytics.utils.tal"} + ): + obj = getattr(importlib.import_module(module), attr, None) + if isinstance(obj, type) and ( + obj.__module__ == module + if module in {"ultralytics.utils.loss", "ultralytics.utils.tal"} + else issubclass(obj, nn.Module) + ): + cls._registry[name] = obj + if any(name.startswith("torchvision.transforms.") for name in needed): + # Classification preprocessing transforms; imported only for checkpoints that serialize them. + import torchvision.transforms.transforms as tvt + from torchvision.transforms.functional import InterpolationMode + + for obj in (tvt.Compose, tvt.Normalize, tvt.Resize, tvt.CenterCrop, tvt.ToTensor, InterpolationMode): + cls._registry[f"{obj.__module__}.{obj.__qualname__}"] = obj + if "ultralytics.nn.text_model.CLIP" in needed: + import clip + + from ultralytics.nn.text_model import CLIP + + for obj in ( + CLIP, + clip.model.CLIP, + clip.model.LayerNorm, + clip.model.QuickGELU, + clip.model.ResidualAttentionBlock, + clip.model.Transformer, + clip.model.VisionTransformer, + clip.clip._convert_image_to_rgb, + ): + cls._registry[f"{obj.__module__}.{obj.__qualname__}"] = obj + entries = [(cls._registry[name], name) for name in needed if name in cls._registry] + if "numpy.dtype" in needed: + entries.append(type(np.dtype(np.float64))) # Built dynamically, absent from the checkpoint global scan. + if entries: + torch.serialization.add_safe_globals(entries) + cls._local.active = True + try: + yield + finally: + cls._local.active = False + + @staticmethod + def activation(act): + """Resolve a model-yaml `activation` spec to a `torch.nn` module instance without `eval()`. + + Accepts only the documented `[torch.]nn.(literal args)` shape (e.g. `nn.SiLU()`, + `torch.nn.LeakyReLU(0.1)`) with literal arguments, and rejects anything else. + """ + import ast + + try: + call = ast.parse(act.strip(), mode="eval").body + assert isinstance(call, ast.Call) + attrs = [] + node = call.func + while isinstance(node, ast.Attribute): # unwind e.g. torch.nn.SiLU -> ["SiLU","nn","torch"] + attrs.append(node.attr) + node = node.value + assert isinstance(node, ast.Name) + attrs.append(node.id) # e.g. ["SiLU", "nn"] or ["SiLU", "nn", "torch"] + assert attrs[1:] in (["nn"], ["nn", "torch"]), "activation must be a torch.nn class" + klass = getattr(nn, attrs[0]) + assert isinstance(klass, type) and issubclass(klass, nn.Module) + args = [ast.literal_eval(a) for a in call.args] + kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in call.keywords} + return klass(*args, **kwargs) + except Exception as e: + raise TypeError( + emojis(f"ERROR ❌️ unsupported activation '{act}' blocked during restricted model load.") + ) from e + + @classmethod + def _build(cls): + """Build the known data globals and legacy aliases; model classes are resolved only when referenced.""" + import enum + import pathlib + + import ultralytics.utils.loss as ul_loss + + allow = [] + + # Non-nn.Module data globals in official checkpoints, incl. the pre-8.0.44 `ultralytics.yolo.utils` path. + scalar = np.float64(0).__reduce__()[0] + allow += [np.dtype, (scalar, "numpy.core.multiarray.scalar"), (scalar, "numpy._core.multiarray.scalar")] + allow.append(IterableSimpleNamespace) + allow.append((IterableSimpleNamespace, "ultralytics.yolo.utils.IterableSimpleNamespace")) + + # Legacy/cross-platform aliases (pickled paths with no current class namespace), mirroring temporary_modules(). + def _getattr(obj, name): # ckpts pickle `Detect.forward` and `InterpolationMode.BILINEAR` via getattr + if isinstance(obj, type) and not name.startswith("__") and issubclass(obj, (nn.Module, enum.Enum)): + return getattr(obj, name) + if isinstance(obj, nn.Module) and name in {"forward", "forward_fuse"}: + return getattr(type(obj), name).__get__(obj) + raise pickle.UnpicklingError( + f"unsafe getattr({type(obj).__name__}, {name!r}) blocked during restricted model load" + ) + + allow += [ + (nn.Identity, "ultralytics.nn.modules.block.Silence"), # YOLOv9e + (DetectionModel, "ultralytics.nn.tasks.YOLOv10DetectionModel"), # YOLOv10 + (ul_loss.E2EDetectLoss, "ultralytics.utils.loss.v10DetectLoss"), # YOLOv10 + (_getattr, "builtins.getattr"), # non-det YOLOv8, YOLO11 ckpts (restrict to nn.Module attrs) + ] + if WINDOWS: + allow += [ + pathlib.WindowsPath, + (pathlib.WindowsPath, "pathlib.WindowsPath"), + (pathlib.WindowsPath, "pathlib.PosixPath"), + (pathlib.WindowsPath, f"{pathlib.PosixPath.__module__}.{pathlib.PosixPath.__qualname__}"), + ] + else: + allow += [ + pathlib.PosixPath, + (pathlib.PosixPath, "pathlib.PosixPath"), + (pathlib.PosixPath, "pathlib.WindowsPath"), + (pathlib.PosixPath, f"{pathlib.WindowsPath.__module__}.{pathlib.WindowsPath.__qualname__}"), + ] + return { + (e[1] if isinstance(e, tuple) else f"{e.__module__}.{e.__qualname__}"): ( + e[0] if isinstance(e, tuple) else e + ) + for e in allow + } + + +def torch_safe_load(weight, safe_only=None): + """Attempt to load a PyTorch model with the torch.load() function. If a ModuleNotFoundError is raised, it catches + the error, logs a warning message, and attempts to install the missing module via the check_requirements() + function. After installation, the function again attempts to load the model using torch.load(). + + Args: + weight (str | Path): The file path of the PyTorch model. + safe_only (bool, optional): Load with `torch.load(weights_only=True)`, reconstructing only the known + Ultralytics/torch model classes on the allow-list. Defaults to the `ULTRALYTICS_SAFE_LOAD` environment + variable (off), so standard usage is unchanged; set the env to opt in. + + Returns: + (dict): The loaded model checkpoint. + (str): The loaded filename. + + Examples: + >>> from ultralytics.nn.tasks import torch_safe_load + >>> ckpt, file = torch_safe_load("path/to/best.pt", safe_only=True) + """ + from ultralytics.utils.downloads import GITHUB_ASSETS_NAMES, attempt_download_asset + + if safe_only is None: + safe_only = SAFE_LOAD + if safe_only and not _SafeLoad.SUPPORTED: + safe_only = False + check_suffix(file=weight, suffix=".pt") + file = attempt_download_asset(weight) # search online if missing locally + + def _load(): + with temporary_modules( + modules={ + "ultralytics.yolo.utils": "ultralytics.utils", + "ultralytics.yolo.v8": "ultralytics.models.yolo", + "ultralytics.yolo.data": "ultralytics.data", + }, + attributes={ + "ultralytics.nn.modules.block.Silence": "torch.nn.Identity", # YOLOv9e + "ultralytics.nn.tasks.YOLOv10DetectionModel": "ultralytics.nn.tasks.DetectionModel", # YOLOv10 + "ultralytics.utils.loss.v10DetectLoss": "ultralytics.utils.loss.E2EDetectLoss", # YOLOv10 + # resolve cross-platform pathlib pickle incompatibility + **( + {"pathlib.PosixPath": "pathlib.WindowsPath"} + if WINDOWS + else {"pathlib.WindowsPath": "pathlib.PosixPath"} + ), + }, + ): + if safe_only: + with _SafeLoad.loading(file): # weights_only load against the known-class allow-list + return torch_load(file, map_location="cpu", weights_only=True) + return torch_load(file, map_location="cpu") + + # weights_only=True raises on a TorchScript archive; the default path returns a ScriptModule instead. + torchscript_error = emojis( + f"ERROR ❌️ {weight} is a TorchScript archive, not an Ultralytics PyTorch checkpoint.\n" + f"Load the original .pt weights, or export again with format='torchscript' and load that file directly." + ) + + try: + ckpt = _load() + + except (RuntimeError, EOFError, pickle.UnpicklingError) as e: + # An unreadable file reaches the loader as one of three internal errors depending on how it is damaged: + # RuntimeError for a truncated zip, EOFError for an empty one, UnpicklingError for bytes that are not a + # pickle at all (an image or archive renamed .pt). They are one user-facing condition, so they share one + # handler and one message. + if isinstance(e, RuntimeError) and "TorchScript archive" in str(e): + raise TypeError(torchscript_error) from e + if isinstance(e, RuntimeError) and "PytorchStreamReader" not in str(e): + raise # an unrelated RuntimeError is a real failure, not a damaged file + if safe_only and isinstance(e, pickle.UnpicklingError): + # weights_only=True refused a global outside the allow-list: a format problem, not a damaged file + raise TypeError( + emojis( + f"ERROR ❌️ {weight} references types outside the supported Ultralytics checkpoint format. " + f"Use an official Ultralytics model, i.e. 'yolo predict model=yolo26n.pt'" + ) + ) from e + # Recover only a corrupt cached official asset requested by bare name; never touch user-supplied paths. + name = Path(str(weight)).name + if str(weight) != name or name not in GITHUB_ASSETS_NAMES: + raise TypeError( + emojis( + f"ERROR ❌️ {weight} is not a loadable checkpoint — the file is empty, truncated or corrupted " + f"({type(e).__name__}: {e}).\nRecommend fixes are to re-download or re-export the file, or to " + f"run a command with an official Ultralytics model, i.e. 'yolo predict model=yolo26n.pt'" + ) + ) from e + LOGGER.warning(f"Corrupt cache {file}, re-downloading {weight}...") + Path(file).unlink(missing_ok=True) + file = attempt_download_asset(weight) + ckpt = _load() + + except ModuleNotFoundError as e: # e.name is missing module name + if e.name in {"models", "models.yolo", "models.common", "models.experimental"}: + raise TypeError( + emojis( + f"ERROR ❌️ {weight} appears to be an Ultralytics YOLOv5 model originally trained " + f"with https://github.com/ultralytics/yolov5. This model is NOT forwards compatible with " + f"YOLOv8 at https://github.com/ultralytics/ultralytics." + f"\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to " + f"run a command with an official Ultralytics model, i.e. 'yolo predict model=yolo26n.pt'" + ) + ) from e + elif e.name == "numpy._core": + raise ModuleNotFoundError( + emojis( + f"ERROR ❌️ {weight} requires numpy>=1.26.1, however numpy=={__import__('numpy').__version__} is installed." + ) + ) from e + elif e.name and e.name.startswith("ultralytics."): + raise ModuleNotFoundError( + emojis( + f"ERROR ❌️ {weight} requires missing Ultralytics module '{e.name}'. " + "Train a new model using the latest 'ultralytics' package or run a command with an official " + "Ultralytics model, i.e. 'yolo predict model=yolo26n.pt'" + ) + ) from e + if safe_only: + # Under weights_only loading, do not auto-install a module named by the checkpoint or fall back to a + # weights_only=False reload. + raise + LOGGER.warning( + f"{weight} appears to require '{e.name}', which is not in Ultralytics requirements." + f"\nAutoInstall will run now for '{e.name}' but this feature will be removed in the future." + f"\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to " + f"run a command with an official Ultralytics model, i.e. 'yolo predict model=yolo26n.pt'" + ) + check_requirements(e.name) # install missing module + ckpt = torch_load(file, map_location="cpu") + + if isinstance(ckpt, torch.jit.ScriptModule): + raise TypeError(torchscript_error) # default path: torch.load dispatched to torch.jit.load and succeeded + + if not isinstance(ckpt, dict): + # File is likely a YOLO instance saved with i.e. torch.save(model, "saved_model.pt") + LOGGER.warning( + f"The file '{weight}' appears to be improperly saved or formatted. " + f"For optimal results, use model.save('filename.pt') to correctly save YOLO models." + ) + ckpt = {"model": ckpt.model} + + return ckpt, file + + +def load_checkpoint(weight, device=None, inplace=True, fuse=False): + """Load single model weights. + + Args: + weight (str | Path): Model weight path. + device (torch.device, optional): Device to load model to. + inplace (bool): Whether to do inplace operations. + fuse (bool): Whether to fuse model. + + Returns: + (torch.nn.Module): Loaded model. + (dict): Model checkpoint dictionary. + """ + if str(weight).lower().startswith(REMOTE_FILE_PREFIXES): + weight = check_file(weight, download_dir=SETTINGS["weights_dir"]) + ckpt, weight = torch_safe_load(weight) # load ckpt + args = {**DEFAULT_CFG_DICT, **(ckpt.get("train_args", {}))} # combine model and default args, preferring model args + candidate = ckpt.get("ema") or ckpt.get("model") + if not isinstance(candidate, torch.nn.Module): + raise TypeError( + emojis( + f"ERROR ❌️ {weight} references types outside the supported Ultralytics checkpoint format. " + f"Use an official Ultralytics model, i.e. 'yolo predict model=yolo26n.pt'" + ) + ) + model = candidate.float() # FP32 model + if ckpt.get("modelopt"): # QAT checkpoint: re-apply the fake-quantization it learned + restore_qat(model, ckpt["modelopt"]) + + # Model compatibility updates + model.args = args # attach args to model + model.pt_path = str(weight) # attach *.pt file path to model as string (avoids WindowsPath pickle issues) + model.task = getattr(model, "task", guess_model_task(model)) + if not hasattr(model, "stride"): + model.stride = torch.tensor([32.0]) + + model = (model.fuse() if fuse and hasattr(model, "fuse") else model).eval().to(device) # model in eval mode + + # Module updates + for m in model.modules(): + if hasattr(m, "inplace"): + m.inplace = inplace + elif isinstance(m, torch.nn.Upsample) and not hasattr(m, "recompute_scale_factor"): + m.recompute_scale_factor = None # torch 1.11.0 compatibility + + # Return model and ckpt + return model, ckpt + + +def parse_model(d, ch, verbose=True): + """Parse a YOLO model.yaml dictionary into a PyTorch model. + + Args: + d (dict): Model dictionary. + ch (int): Input channels. + verbose (bool): Whether to print model details. + + Returns: + (torch.nn.Sequential): PyTorch model. + (list): Sorted list of layer indices whose outputs need to be saved. + """ + import ast + + # Args + legacy = True # backward compatibility for v3/v5/v8/v9 models + max_channels = float("inf") + nc, act, scales, end2end = (d.get(x) for x in ("nc", "activation", "scales", "end2end")) + reg_max = d.get("reg_max", 16) + depth, width, kpt_shape = (d.get(x, 1.0) for x in ("depth_multiple", "width_multiple", "kpt_shape")) + scale = d.get("scale") + if scales: + if not scale: + scale = next(iter(scales.keys())) + LOGGER.warning(f"no model scale passed. Assuming scale='{scale}'.") + depth, width, max_channels = scales[scale] + + restricted = _SafeLoad.restricted() + if act: + # redefine default activation, i.e. Conv.default_act = torch.nn.SiLU(). Under restricted loading, resolve the + # spec without eval() (see _SafeLoad.activation). + Conv.default_act = _SafeLoad.activation(act) if restricted else eval(act) + if verbose: + LOGGER.info(f"{colorstr('activation:')} {act}") # print + + if verbose: + LOGGER.info(f"\n{'':>3}{'from':>20}{'n':>3}{'params':>10} {'module':<45}{'arguments':<30}") + ch = [ch] + layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out + base_modules = frozenset( + { + Classify, + Conv, + ConvTranspose, + GhostConv, + Bottleneck, + GhostBottleneck, + SPP, + SPPF, + C2fPSA, + C2PSA, + DWConv, + Focus, + BottleneckCSP, + C1, + C2, + C2f, + C3k2, + RepNCSPELAN4, + ELAN1, + ADown, + AConv, + SPPELAN, + C2fAttn, + C3, + C3TR, + C3Ghost, + torch.nn.ConvTranspose2d, + DWConvTranspose2d, + C3x, + RepC3, + PSA, + SCDown, + C2fCIB, + A2C2f, + } + ) + repeat_modules = frozenset( # modules with 'repeat' arguments + { + BottleneckCSP, + C1, + C2, + C2f, + C3k2, + C2fAttn, + C3, + C3TR, + C3Ghost, + C3x, + RepC3, + C2fPSA, + C2fCIB, + C2PSA, + A2C2f, + } + ) + for i, (f, n, m, args) in enumerate(d["backbone"] + d["head"]): # from, number, module, args + m = ( + getattr(torch.nn, m[3:]) + if m.startswith("nn.") + else getattr(__import__("torchvision").ops, m[16:]) + if m.startswith("torchvision.ops.") + else globals()[m] + ) # get module + if restricted and not (isinstance(m, type) and issubclass(m, torch.nn.Module)): + # Under restricted loading, only known model layers may be named here. + raise TypeError(emojis(f"ERROR ❌️ module '{m}' is not a permitted model layer under restricted loading.")) + for j, a in enumerate(args): + if isinstance(a, str): + with contextlib.suppress(ValueError): + args[j] = locals()[a] if a in locals() else ast.literal_eval(a) + n = n_ = max(round(n * depth), 1) if n > 1 else n # depth gain + if m in base_modules: + c1, c2 = ch[f], args[0] + if m is not Classify: # Classify() output must stay at nc; every other layer scales by width + c2 = make_divisible(min(c2, max_channels) * width, 8) + if m is C2fAttn: # set 1) embed channels and 2) num heads + args[2] = int(max(round(min(args[2], max_channels // 2 // 32)) * width, 1) if args[2] > 1 else args[2]) + hidden_channels = int(c2 * (args[6] if len(args) > 6 else 0.5)) + if hidden_channels % args[2]: + raise ValueError( + f"C2fAttn hidden channels {hidden_channels} (from c2={c2}) must be divisible by nh={args[2]}; " + "adjust width_multiple, nh, or C2fAttn expansion" + ) + args[1] = hidden_channels + + args = [c1, c2, *args[1:]] + if m in repeat_modules: + args.insert(2, n) # number of repeats + n = 1 + if m is C3k2: # for M/L/X sizes + legacy = False + if scale in {"m", "l", "x"}: + args[3:4] = [True] # slice assignment also supplies c3k when the YAML omits it + if m is A2C2f: + legacy = False + if scale in {"l", "x"}: # for L/X sizes + args.extend((True, 1.2)) + if m is C2fCIB: + legacy = False + elif m is AIFI: + args = [ch[f], *args] + elif m in frozenset({HGStem, HGBlock}): + c1, cm, c2 = ch[f], args[0], args[1] + args = [c1, cm, c2, *args[2:]] + if m is HGBlock: + args.insert(4, n) # number of repeats + n = 1 + elif m is ResNetLayer: + c2 = args[1] if args[3] else args[1] * 4 + elif m is torch.nn.BatchNorm2d: + args = [ch[f]] + elif m is Concat: + c2 = sum(ch[x] for x in f) + elif m in frozenset( + { + Detect, + WorldDetect, + YOLOEDetect, + Segment, + Segment26, + YOLOESegment, + YOLOESegment26, + Pose, + Pose26, + OBB, + OBB26, + } + ): + args.extend([reg_max, end2end, [ch[x] for x in f]]) + if m is Segment or m is YOLOESegment or m is Segment26 or m is YOLOESegment26: + args[2] = make_divisible(min(args[2], max_channels) * width, 8) + if m in {Detect, YOLOEDetect, Segment, Segment26, YOLOESegment, YOLOESegment26, Pose, Pose26, OBB, OBB26}: + m.legacy = legacy + elif m is Depth: + args = [*args[:1], [ch[x] for x in f]] # c_mid, ch tuple; drops the legacy mode arg old checkpoints store + elif m is SemanticSegment: + args.append([ch[x] for x in f]) # nc, ch tuple + elif m is v10Detect: + args.append([ch[x] for x in f]) + elif m is ImagePoolingAttn: + args.insert(1, [ch[x] for x in f]) # channels as second arg + elif m is RTDETRDecoder: # special case, channels arg must be passed in index 1 + args.insert(1, [ch[x] for x in f]) + elif m is CBLinear: + c2 = args[0] + c1 = ch[f] + args = [c1, c2, *args[1:]] + elif m is CBFuse: + c2 = ch[f[-1]] + elif m in frozenset({TorchVision, Index}): + c2 = args[0] + c1 = ch[f] + args = [*args[1:]] + else: + c2 = ch[f] + + m_ = torch.nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module + if m is SPPF and len(args) <= 3: # Legacy YAML rows predate the unactivated YOLO26 SPPF. + for block in m_ if n > 1 else [m_]: + block.cv1.act = Conv.default_act + t = str(m)[8:-2].replace("__main__.", "") # module type + m_.np = sum(x.numel() for x in m_.parameters()) # number params + m_.i, m_.f, m_.type = i, f, t # attach index, 'from' index, type + if verbose: + LOGGER.info(f"{i:>3}{f!s:>20}{n_:>3}{m_.np:10.0f} {t:<45}{args!s:<30}") # print + save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist + layers.append(m_) + if i == 0: + ch = [] + ch.append(c2) + return torch.nn.Sequential(*layers), sorted(save) + + +def yaml_model_load(path): + """Load a YOLO model from a YAML file. + + Args: + path (str | Path): Path to the YAML file. + + Returns: + (dict): Model dictionary. + """ + path = Path(path) + if path.stem in (f"yolov{d}{x}6" for x in "nsmlx" for d in (5, 8)): + new_stem = re.sub(r"(\d+)([nslmx])6(.+)?$", r"\1\2-p6\3", path.stem) + LOGGER.warning(f"Ultralytics YOLO P6 models now use -p6 suffix. Renaming {path.stem} to {new_stem}.") + path = path.with_name(new_stem + path.suffix) + + unified_path = re.sub(r"(\d+)([nslmx])(.+)?$", r"\1\3", str(path)) # i.e. yolov8x.yaml -> yolov8.yaml + yaml_file = check_yaml(path, hard=False) or check_yaml(unified_path) + d = YAML.load(yaml_file) # model dict + d["scale"] = guess_model_scale(path) + d["yaml_file"] = str(path) + return d + + +def guess_model_scale(model_path): + """Extract the size character n, s, m, l, or x of the model's scale from the model path. + + Args: + model_path (str | Path): The path to the YOLO model's YAML file. + + Returns: + (str): The size character of the model's scale (n, s, m, l, or x), or empty string if not found. + """ + try: + return re.search(r"yolo(e-)?[v]?\d+([nslmx])", Path(model_path).stem).group(2) + except AttributeError: + return "" + + +def guess_model_task(model): + """Guess the task of a PyTorch model from its architecture or configuration. + + Args: + model (torch.nn.Module | dict | str | Path): PyTorch model, model configuration dict, or model file path. + + Returns: + (str): Task of the model ('detect', 'segment', 'semantic', 'depth', 'classify', 'pose', 'obb'). + """ + + def cfg2task(cfg): + """Guess from YAML dictionary.""" + m = cfg["head"][-1][-2].lower() # output module name + if m in {"classify", "classifier", "cls", "fc"}: + return "classify" + if "detect" in m: + return "detect" + if "semanticsegment" in m: + return "semantic" + if "segment" in m: + return "segment" + if "pose" in m: + return "pose" + if "obb" in m: + return "obb" + if "depth" in m: + return "depth" + + # Guess from model cfg + if isinstance(model, dict): + with contextlib.suppress(Exception): + return cfg2task(model) + # Guess from PyTorch model + if isinstance(model, torch.nn.Module): # PyTorch model + for x in "model.args", "model.model.args", "model.model.model.args": + with contextlib.suppress(Exception): + return eval(x)["task"] # nosec B307: safe eval of known attribute paths + for x in "model.yaml", "model.model.yaml", "model.model.model.yaml": + with contextlib.suppress(Exception): + return cfg2task(eval(x)) # nosec B307: safe eval of known attribute paths + for m in model.modules(): + if isinstance(m, SemanticSegment): + return "semantic" + elif isinstance(m, (Segment, YOLOESegment)): + return "segment" + elif isinstance(m, Classify): + return "classify" + elif isinstance(m, Pose): + return "pose" + elif isinstance(m, OBB): + return "obb" + elif isinstance(m, Depth): + return "depth" + elif isinstance(m, (Detect, WorldDetect, YOLOEDetect, v10Detect)): + return "detect" + + if isinstance(model, (str, Path)): + from ultralytics.nn.backends.base import BaseBackend + + if task := BaseBackend.read_metadata(model).get("task"): # exports embed their task, i.e. a renamed best.onnx + return task + + # Guess from model filename + model = Path(model) + if "-sem" in model.stem or "semantic" in model.parts: + return "semantic" + elif "-seg" in model.stem or "segment" in model.parts: + return "segment" + elif "-cls" in model.stem or "classify" in model.parts: + return "classify" + elif "-pose" in model.stem or "pose" in model.parts: + return "pose" + elif "-obb" in model.stem or "obb" in model.parts: + return "obb" + elif "-depth" in model.stem or "depth" in model.parts: + return "depth" + elif "detect" in model.parts: + return "detect" + + # Unable to determine task from model + LOGGER.warning( + "Unable to automatically guess model task, assuming 'task=detect'. " + "Explicitly define task for your model, i.e. 'task=detect', 'segment', 'semantic', 'depth', 'classify', 'pose' " + "or 'obb'." + ) + return "detect" # assume detect diff --git a/.venv/lib/python3.12/site-packages/ultralytics/nn/text_model.py b/.venv/lib/python3.12/site-packages/ultralytics/nn/text_model.py new file mode 100644 index 0000000000000000000000000000000000000000..24e2786c62c0fd311b581ec686ba7e1ba3a2b481 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/nn/text_model.py @@ -0,0 +1,358 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from abc import abstractmethod +from pathlib import Path + +import torch +from PIL import Image +from torch import nn + +from ultralytics.utils import WEIGHTS_DIR, checks +from ultralytics.utils.torch_utils import smart_inference_mode + +try: + import clip +except ImportError: + checks.check_requirements("git+https://github.com/ultralytics/CLIP.git") + import clip + + +class TextModel(nn.Module): + """Abstract base class for text encoding models. + + This class defines the interface for text encoding models used in vision-language tasks. Subclasses must implement + the tokenize and encode_text methods to provide text tokenization and encoding functionality. + + Methods: + tokenize: Convert input texts to tokens for model processing. + encode_text: Encode tokenized texts into normalized feature vectors. + """ + + def __init__(self): + """Initialize the TextModel base class.""" + super().__init__() + + @abstractmethod + def tokenize(self, texts): + """Convert input texts to tokens for model processing.""" + + @abstractmethod + def encode_text(self, texts, dtype): + """Encode tokenized texts into normalized feature vectors.""" + + +class CLIP(TextModel): + """Implements OpenAI's CLIP (Contrastive Language-Image Pre-training) text encoder. + + This class provides a text encoder based on OpenAI's CLIP model, which can convert text into feature vectors that + are aligned with corresponding image features in a shared embedding space. + + Attributes: + model (clip.model.CLIP): The loaded CLIP model. + image_preprocess (callable): Preprocessing transform for images. + device (torch.device): Device where the model is loaded. + + Methods: + tokenize: Convert input texts to CLIP tokens. + encode_text: Encode tokenized texts into normalized feature vectors. + + Examples: + >>> import torch + >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + >>> clip_model = CLIP(size="ViT-B/32", device=device) + >>> tokens = clip_model.tokenize(["a photo of a cat", "a photo of a dog"]) + >>> text_features = clip_model.encode_text(tokens) + >>> print(text_features.shape) + """ + + def __init__(self, size: str, device: torch.device) -> None: + """Initialize the CLIP text encoder. + + This class implements the TextModel interface using OpenAI's CLIP model for text encoding. It loads a + pre-trained CLIP model of the specified size and prepares it for text encoding tasks. + + Args: + size (str): Model size identifier (e.g., 'ViT-B/32'). + device (torch.device): Device to load the model on. + """ + super().__init__() + self.model, self.image_preprocess = clip.load(size, device=device, download_root=str(WEIGHTS_DIR / "clip")) + self.to(device) + self.device = device + self.eval() + + def tokenize(self, texts: str | list[str], truncate: bool = True) -> torch.Tensor: + """Convert input texts to CLIP tokens. + + Args: + texts (str | list[str]): Input text or list of texts to tokenize. + truncate (bool, optional): Whether to trim texts that exceed CLIP's context length. Defaults to True to + avoid RuntimeError from overly long inputs while still allowing explicit opt-out. + + Returns: + (torch.Tensor): Tokenized text tensor with shape (batch_size, context_length) ready for model processing. + + Examples: + >>> model = CLIP("ViT-B/32", device="cpu") + >>> tokens = model.tokenize("a photo of a cat") + >>> print(tokens.shape) # torch.Size([1, 77]) + >>> strict_tokens = model.tokenize("a photo of a cat", truncate=False) # Enforce strict length checks + >>> print(strict_tokens.shape) # Same shape/content as tokens since prompt less than 77 tokens + """ + return clip.tokenize(texts, truncate=truncate).to(self.device) + + @smart_inference_mode() + def encode_text(self, texts: torch.Tensor, dtype: torch.dtype = torch.float32) -> torch.Tensor: + """Encode tokenized texts into normalized feature vectors. + + This method processes tokenized text inputs through the CLIP model to generate feature vectors, which are then + normalized to unit length. These normalized vectors can be used for text-image similarity comparisons. + + Args: + texts (torch.Tensor): Tokenized text inputs, typically created using the tokenize() method. + dtype (torch.dtype, optional): Data type for output features. + + Returns: + (torch.Tensor): Normalized text feature vectors with unit length (L2 norm = 1). + + Examples: + >>> clip_model = CLIP("ViT-B/32", device="cuda") + >>> tokens = clip_model.tokenize(["a photo of a cat", "a photo of a dog"]) + >>> features = clip_model.encode_text(tokens) + >>> features.shape + torch.Size([2, 512]) + """ + txt_feats = self.model.encode_text(texts).to(dtype) + txt_feats = txt_feats / txt_feats.norm(p=2, dim=-1, keepdim=True) + return txt_feats + + @smart_inference_mode() + def encode_image(self, image: Image.Image | torch.Tensor, dtype: torch.dtype = torch.float32) -> torch.Tensor: + """Encode images into normalized feature vectors. + + This method processes image inputs through the CLIP model to generate feature vectors, which are then + normalized to unit length. These normalized vectors can be used for text-image similarity comparisons. + + Args: + image (PIL.Image | torch.Tensor): Image input as a PIL Image or preprocessed tensor. If a PIL Image is + provided, it will be converted to a tensor using the model's image preprocessing function. + dtype (torch.dtype, optional): Data type for output features. + + Returns: + (torch.Tensor): Normalized image feature vectors with unit length (L2 norm = 1). + + Examples: + >>> from ultralytics.nn.text_model import CLIP + >>> from PIL import Image + >>> clip_model = CLIP("ViT-B/32", device="cuda") + >>> image = Image.open("path/to/image.jpg") + >>> image_tensor = clip_model.image_preprocess(image).unsqueeze(0).to("cuda") + >>> features = clip_model.encode_image(image_tensor) + >>> features.shape + torch.Size([1, 512]) + """ + if isinstance(image, Image.Image): + image = self.image_preprocess(image).unsqueeze(0).to(self.device) + img_feats = self.model.encode_image(image).to(dtype) + img_feats = img_feats / img_feats.norm(p=2, dim=-1, keepdim=True) + return img_feats + + +class MobileCLIP(TextModel): + """Implement Apple's MobileCLIP text encoder for efficient text encoding. + + This class implements the TextModel interface using Apple's MobileCLIP model, providing efficient text encoding + capabilities for vision-language tasks with reduced computational requirements compared to standard CLIP models. + + Attributes: + model (mobileclip.model.MobileCLIP): The loaded MobileCLIP model. + tokenizer (callable): Tokenizer function for processing text inputs. + device (torch.device): Device where the model is loaded. + config_size_map (dict): Mapping from size identifiers to model configuration names. + + Methods: + tokenize: Convert input texts to MobileCLIP tokens. + encode_text: Encode tokenized texts into normalized feature vectors. + + Examples: + >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + >>> text_encoder = MobileCLIP(size="s0", device=device) + >>> tokens = text_encoder.tokenize(["a photo of a cat", "a photo of a dog"]) + >>> features = text_encoder.encode_text(tokens) + """ + + config_size_map = {"s0": "s0", "s1": "s1", "s2": "s2", "b": "b", "blt": "b"} + + def __init__(self, size: str, device: torch.device) -> None: + """Initialize the MobileCLIP text encoder. + + This class implements the TextModel interface using Apple's MobileCLIP model for efficient text encoding. + + Args: + size (str): Model size identifier (e.g., 's0', 's1', 's2', 'b', 'blt'). + device (torch.device): Device to load the model on. + """ + try: + import mobileclip + except ImportError: + # Ultralytics fork preferred since Apple MobileCLIP repo has incorrect version of torchvision + checks.check_requirements("git+https://github.com/ultralytics/mobileclip.git") + import mobileclip + + super().__init__() + config = self.config_size_map[size] + file = f"mobileclip_{size}.pt" + if not Path(file).is_file(): + from ultralytics import download + + download(f"https://docs-assets.developer.apple.com/ml-research/datasets/mobileclip/{file}") + self.model = mobileclip.create_model_and_transforms(f"mobileclip_{config}", pretrained=file, device=device)[0] + self.tokenizer = mobileclip.get_tokenizer(f"mobileclip_{config}") + self.to(device) + self.device = device + self.eval() + + def tokenize(self, texts: list[str]) -> torch.Tensor: + """Convert input texts to MobileCLIP tokens. + + Args: + texts (list[str]): List of text strings to tokenize. + + Returns: + (torch.Tensor): Tokenized text inputs with shape (batch_size, sequence_length). + + Examples: + >>> model = MobileCLIP("s0", "cpu") + >>> tokens = model.tokenize(["a photo of a cat", "a photo of a dog"]) + """ + return self.tokenizer(texts).to(self.device) + + @smart_inference_mode() + def encode_text(self, texts: torch.Tensor, dtype: torch.dtype = torch.float32) -> torch.Tensor: + """Encode tokenized texts into normalized feature vectors. + + Args: + texts (torch.Tensor): Tokenized text inputs. + dtype (torch.dtype, optional): Data type for output features. + + Returns: + (torch.Tensor): Normalized text feature vectors with L2 normalization applied. + + Examples: + >>> model = MobileCLIP("s0", device="cpu") + >>> tokens = model.tokenize(["a photo of a cat", "a photo of a dog"]) + >>> features = model.encode_text(tokens) + >>> features.shape + torch.Size([2, 512]) # Actual dimension depends on model size + """ + text_features = self.model.encode_text(texts).to(dtype) + text_features /= text_features.norm(p=2, dim=-1, keepdim=True) + return text_features + + +class MobileCLIPTS(TextModel): + """Load a TorchScript traced version of MobileCLIP. + + This class implements the TextModel interface using Apple's MobileCLIP model in TorchScript format, providing + efficient text encoding capabilities for vision-language tasks with optimized inference performance. + + Attributes: + encoder (torch.jit.ScriptModule): The loaded TorchScript MobileCLIP text encoder. + tokenizer (callable): Tokenizer function for processing text inputs. + device (torch.device): Device where the model is loaded. + + Methods: + tokenize: Convert input texts to MobileCLIP tokens. + encode_text: Encode tokenized texts into normalized feature vectors. + + Examples: + >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + >>> text_encoder = MobileCLIPTS(device=device) + >>> tokens = text_encoder.tokenize(["a photo of a cat", "a photo of a dog"]) + >>> features = text_encoder.encode_text(tokens) + """ + + def __init__(self, device: torch.device, weight: str = "mobileclip_blt.ts"): + """Initialize the MobileCLIP TorchScript text encoder. + + This class implements the TextModel interface using Apple's MobileCLIP model in TorchScript format for efficient + text encoding with optimized inference performance. + + Args: + device (torch.device): Device to load the model on. + weight (str): Path to the TorchScript model weights. + """ + super().__init__() + from ultralytics.utils.downloads import attempt_download_asset + + self.encoder = torch.jit.load(attempt_download_asset(weight), map_location=device) + self.tokenizer = clip.clip.tokenize + self.device = device + + def tokenize(self, texts: list[str], truncate: bool = True) -> torch.Tensor: + """Convert input texts to MobileCLIP tokens. + + Args: + texts (list[str]): List of text strings to tokenize. + truncate (bool, optional): Whether to trim texts that exceed the tokenizer context length. Defaults to True, + matching CLIP's behavior to prevent runtime failures on long captions. + + Returns: + (torch.Tensor): Tokenized text inputs with shape (batch_size, sequence_length). + + Examples: + >>> model = MobileCLIPTS(device=torch.device("cpu")) + >>> tokens = model.tokenize(["a photo of a cat", "a photo of a dog"]) + >>> strict_tokens = model.tokenize( + ... ["a very long caption"], truncate=False + ... ) # RuntimeError if exceeds 77-token + """ + return self.tokenizer(texts, truncate=truncate).to(self.device) + + @smart_inference_mode() + def encode_text(self, texts: torch.Tensor, dtype: torch.dtype = torch.float32) -> torch.Tensor: + """Encode tokenized texts into normalized feature vectors. + + Args: + texts (torch.Tensor): Tokenized text inputs. + dtype (torch.dtype, optional): Data type for output features. + + Returns: + (torch.Tensor): Normalized text feature vectors with L2 normalization applied. + + Examples: + >>> model = MobileCLIPTS(device="cpu") + >>> tokens = model.tokenize(["a photo of a cat", "a photo of a dog"]) + >>> features = model.encode_text(tokens) + >>> features.shape + torch.Size([2, 512]) # Actual dimension depends on model size + """ + # NOTE: no need to do normalization here as it's embedded in the torchscript model + return self.encoder(texts).to(dtype) + + +def build_text_model(variant: str, device: torch.device = None) -> TextModel: + """Build a text encoding model based on the specified variant. + + Args: + variant (str): Model variant in format "base:size" (e.g., "clip:ViT-B/32" or "mobileclip:s0"). + device (torch.device, optional): Device to load the model on. + + Returns: + (TextModel): Instantiated text encoding model. + + Examples: + >>> model = build_text_model("clip:ViT-B/32", device=torch.device("cuda")) + >>> model = build_text_model("mobileclip:s0", device=torch.device("cpu")) + """ + base, size = variant.split(":") + if base == "clip": + return CLIP(size, device) + elif base == "mobileclip": + return MobileCLIPTS(device) + elif base == "mobileclip2": + return MobileCLIPTS(device, weight="mobileclip2_b.ts") + else: + raise ValueError(f"Unrecognized base model '{base}'. Supported models are 'clip', 'mobileclip', 'mobileclip2'.") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/optim/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/optim/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d1bee8feefc03ac8b562cba61db08c08ee45fd80 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/optim/__init__.py @@ -0,0 +1,5 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .muon import MuSGD + +__all__ = ["MuSGD"] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/optim/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/optim/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9f153cabf560a080711bef309a6f6e93f53d4cc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/optim/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/optim/__pycache__/muon.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/optim/__pycache__/muon.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..641ca6fb6841b239b8628e8059788f126cdc9cc7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/optim/__pycache__/muon.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/optim/muon.py b/.venv/lib/python3.12/site-packages/ultralytics/optim/muon.py new file mode 100644 index 0000000000000000000000000000000000000000..3fe5aa390ee3eca3259481ff7c76553be9924bb5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/optim/muon.py @@ -0,0 +1,264 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import torch +from torch import optim + + +def zeropower_via_newtonschulz5(G: torch.Tensor, eps: float = 1e-7) -> torch.Tensor: + """Compute the zeroth power / orthogonalization of matrix G using Newton-Schulz iteration. + + This function implements a quintic Newton-Schulz iteration to compute an approximate orthogonalization of the input + matrix G. The iteration coefficients are optimized to maximize convergence slope at zero, producing a result similar + to UV^T from SVD, where USV^T = G, but with relaxed convergence guarantees that empirically work well for + optimization purposes. + + Args: + G (torch.Tensor): Input 2D matrix or 3D batch of matrices to orthogonalize. + eps (float, optional): Small epsilon value added to norm for numerical stability. Default: 1e-7. + + Returns: + (torch.Tensor): Orthogonalized matrix/matrices with same shape as input G. + + Examples: + >>> G = torch.randn(128, 64) + >>> G_ortho = zeropower_via_newtonschulz5(G) + >>> print(G_ortho.shape) + torch.Size([128, 64]) + + Notes: + - Uses bfloat16 precision for computation. + - Performs exactly 5 Newton-Schulz iteration steps with fixed coefficients. + - Automatically transposes for efficiency when rows > columns. + - Output approximates US'V^T where S' has diagonal entries ~ Uniform(0.5, 1.5). + - Does not produce exact UV^T but works well empirically for neural network optimization. + """ + assert G.ndim in {2, 3} + X = G.reshape(-1, G.size(-2), G.size(-1)).bfloat16() + X /= X.norm(dim=(-2, -1), keepdim=True) + eps # ensure top singular value <= 1 + if G.size(-2) > G.size(-1): + X = X.transpose(-2, -1) + a, b, c = 3.4445, -4.7750, 2.0315 + for _ in range(5): + A = X @ X.transpose(-2, -1) + B = torch.baddbmm(A, A, A, beta=b, alpha=c) # b * A + c * A @ A + X = torch.baddbmm(X, B, X, beta=a) # a * X + B @ X + if G.size(-2) > G.size(-1): + X = X.transpose(-2, -1) + return X.reshape(G.shape) + + +def muon_update( + grad: torch.Tensor | list[torch.Tensor], + momentum: torch.Tensor | list[torch.Tensor], + beta: float = 0.95, + nesterov: bool = True, +) -> torch.Tensor | list[torch.Tensor]: + """Compute Muon optimizer updates with momentum and orthogonalization. + + This function applies momentum to the gradients, optionally uses Nesterov acceleration, and then orthogonalizes the + updates using Newton-Schulz iterations. Matrices with the same column count are zero-padded and orthogonalized in a + single batched call, and momentum math uses fused foreach ops, avoiding per-parameter kernel launch overhead. + Higher-rank tensors are reshaped before orthogonalization, and each update is scaled based on parameter dimensions. + + Args: + grad (torch.Tensor | list[torch.Tensor]): Gradient tensor(s) to update. Each must have at least two dimensions. + momentum (torch.Tensor | list[torch.Tensor]): Momentum buffer tensor(s), modified in-place. + beta (float, optional): Momentum coefficient for exponential moving average. Default: 0.95. + nesterov (bool, optional): Whether to use Nesterov momentum acceleration. Default: True. + + Returns: + (torch.Tensor | list[torch.Tensor]): Orthogonalized update tensor(s), each with the gradient's shape and dtype. + + Examples: + >>> grad = torch.randn(64, 128) + >>> momentum = torch.zeros_like(grad) + >>> update = muon_update(grad, momentum, beta=0.95, nesterov=True) + >>> print(update.shape) + torch.Size([64, 128]) + + Notes: + - Momentum buffers are updated in-place: momentum = beta * momentum + (1-beta) * grad. + - With Nesterov: update = beta * momentum + (1-beta) * grad. + - Without Nesterov: update = momentum. + - Tensors with more than 2 dimensions are reshaped to 2D with the first dimension preserved. + - Final updates are scaled by sqrt(max(1, dim[-2] / dim[-1])) to account for parameter dimensions. + """ + single = isinstance(grad, torch.Tensor) + grads, momentums = ([grad], [momentum]) if single else (grad, momentum) + torch._foreach_mul_(momentums, beta) + torch._foreach_add_(momentums, grads, alpha=1 - beta) + if nesterov: + updates = list(torch._foreach_mul(momentums, beta)) + torch._foreach_add_(updates, grads, alpha=1 - beta) + else: + updates = list(momentums) + buckets = {} # group matrices by (columns, scale) for batched orthogonalization + for i, u in enumerate(updates): + # flatten in the update's own memory order, a view for NCHW and NHWC alike: permuting columns permutes + # the orthogonalized columns identically, and the write-back below restores the update's layout. Any + # other layout is materialized row-major and written back row-major. + dense = u.is_contiguous() + nhwc = not dense and u.ndim == 4 and u.is_contiguous(memory_format=torch.channels_last) + m = u.permute(0, 2, 3, 1).flatten(1) if nhwc else (u.flatten(1) if u.ndim > 2 else u.contiguous()) + scale = max(1, grads[i].size(-2) / grads[i].size(-1)) ** 0.5 + buckets.setdefault((m.size(1), scale, m.device, m.dtype), []).append( + (i, m, u.stride() if dense or nhwc else None) + ) + groups = [] # split each bucket until its row counts span at most 16x, bounding the padding below + for key, items in buckets.items(): + items.sort(key=lambda t: -t[1].size(0)) + start = 0 + for j in range(1, len(items) + 1): + if j == len(items) or items[start][1].size(0) > 16 * items[j][1].size(0): + groups.append((key, items[start:j])) + start = j + for (cols, scale, device, dtype), items in groups: + # zero-pad rows, not columns, so that different shapes share one batched call (zeros stay zero through + # Newton-Schulz) while the fill below and every write-back below stay contiguous + X = torch.zeros(len(items), items[0][1].size(0), cols, device=device, dtype=dtype) + torch._foreach_add_([X[j, : m.size(0)] for j, (_, m, _) in enumerate(items)], [m for _, m, _ in items]) + X = zeropower_via_newtonschulz5(X).contiguous().to(grads[items[0][0]].dtype).mul_(scale) + for j, (i, m, stride) in enumerate(items): + x = X[j, : m.size(0)] + updates[i] = x.as_strided(grads[i].shape, stride) if stride else x.reshape(grads[i].shape) + return updates[0] if single else updates + + +class MuSGD(optim.Optimizer): + """Hybrid optimizer combining Muon and SGD updates for neural network training. + + This optimizer implements a combination of Muon (a momentum-based optimizer with orthogonalization via Newton-Schulz + iterations) and standard SGD with momentum. It allows different parameter groups to use either the hybrid Muon+SGD + approach or pure SGD. + + Args: + params (Iterable): Parameters to optimize or dicts defining parameter groups. + muon (float, optional): Weight factor for Muon updates in hybrid mode. Default: 0.5. + sgd (float, optional): Weight factor for SGD updates in hybrid mode. Default: 0.5. + + Attributes: + muon (float): Scaling factor applied to Muon learning rate. + sgd (float): Scaling factor applied to SGD learning rate in hybrid mode. + + Examples: + >>> param_groups = [ + ... { + ... "params": model.conv_params, + ... "lr": 0.02, + ... "use_muon": True, + ... "momentum": 0.95, + ... "nesterov": True, + ... "weight_decay": 0.01, + ... }, + ... { + ... "params": model.other_params, + ... "lr": 0.01, + ... "use_muon": False, + ... "momentum": 0.9, + ... "nesterov": False, + ... "weight_decay": 0, + ... }, + ... ] + >>> optimizer = MuSGD(param_groups, muon=0.5, sgd=0.5) + >>> loss = model(data) + >>> loss.backward() + >>> optimizer.step() + + Notes: + - Parameter groups with 'use_muon': True will receive both Muon and SGD updates. + - Parameter groups with 'use_muon': False will receive only SGD updates. + - The Muon update uses orthogonalization which works best for 2D+ parameter tensors. + """ + + def __init__( + self, + params, + lr: float = 1e-3, + momentum: float = 0.0, + weight_decay: float = 0.0, + nesterov: bool = False, + use_muon: bool = False, + muon: float = 0.5, + sgd: float = 0.5, + ): + """Initialize MuSGD optimizer with hybrid Muon and SGD capabilities. + + Args: + params (Iterable): Iterable of parameters to optimize or dicts defining parameter groups. + lr (float): Learning rate. + momentum (float): Momentum factor for SGD. + weight_decay (float): Weight decay (L2 penalty). + nesterov (bool): Whether to use Nesterov momentum. + use_muon (bool): Whether to enable Muon updates. + muon (float): Scaling factor for Muon component. + sgd (float): Scaling factor for SGD component. + """ + defaults = { + "lr": lr, + "momentum": momentum, + "weight_decay": weight_decay, + "nesterov": nesterov, + "use_muon": use_muon, + } + super().__init__(params, defaults) + self.muon = muon + self.sgd = sgd + + @torch.no_grad() + def step(self, closure=None): + """Perform a single optimization step. + + Applies either hybrid Muon+SGD updates or pure SGD updates depending on the + 'use_muon' flag in each parameter group. For Muon-enabled groups, parameters + receive both an orthogonalized Muon update and a standard SGD momentum update. + + Args: + closure (Callable, optional): A closure that reevaluates the model + and returns the loss. Default: None. + + Returns: + (torch.Tensor | None): The loss value if closure is provided, otherwise None. + + Notes: + - Parameters with None gradients are skipped. + - Muon updates use Newton-Schulz orthogonalization and work best on 2D+ tensors. + - Weight decay is applied only to the SGD component in hybrid mode. + """ + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + params = [p for p in group["params"] if p.grad is not None] + if not params: + continue + lr, momentum, nesterov = group["lr"], group["momentum"], group["nesterov"] + for p in params: + if len(self.state[p]) == 0: + self.state[p]["momentum_buffer"] = torch.zeros_like(p) + if group["use_muon"]: + self.state[p]["momentum_buffer_SGD"] = torch.zeros_like(p) + if group["use_muon"]: + updates = muon_update( + [p.grad for p in params], + [self.state[p]["momentum_buffer"] for p in params], + beta=momentum, + nesterov=nesterov, + ) + torch._foreach_add_(params, updates, alpha=-(lr * self.muon)) + buffers = [self.state[p]["momentum_buffer_SGD"] for p in params] + lr *= self.sgd + else: + buffers = [self.state[p]["momentum_buffer"] for p in params] + # SGD update + grads = [p.grad for p in params] + if group["weight_decay"] != 0: + grads = torch._foreach_add(grads, params, alpha=group["weight_decay"]) + torch._foreach_mul_(buffers, momentum) + torch._foreach_add_(buffers, grads) + updates = torch._foreach_add(grads, buffers, alpha=momentum) if nesterov else buffers + torch._foreach_add_(params, updates, alpha=-lr) + return loss diff --git a/.venv/lib/python3.12/site-packages/ultralytics/py.typed b/.venv/lib/python3.12/site-packages/ultralytics/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..b648ac92333301658c4f49b315f21130c689c819 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/py.typed @@ -0,0 +1 @@ +partial diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a072a3f586ed51abad12ddd47e4cb4042f77212e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__init__.py @@ -0,0 +1,41 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .ai_gym import AIGym +from .analytics import Analytics +from .distance_calculation import DistanceCalculation +from .heatmap import Heatmap +from .instance_segmentation import InstanceSegmentation +from .object_blurrer import ObjectBlurrer +from .object_counter import ObjectCounter +from .object_cropper import ObjectCropper +from .parking_management import ParkingManagement, ParkingPtsSelection +from .queue_management import QueueManager +from .region_counter import RegionCounter +from .security_alarm import SecurityAlarm +from .similarity_search import SearchApp, VisualAISearch +from .speed_estimation import SpeedEstimator +from .streamlit_inference import Inference +from .trackzone import TrackZone +from .vision_eye import VisionEye + +__all__ = ( + "AIGym", + "Analytics", + "DistanceCalculation", + "Heatmap", + "Inference", + "InstanceSegmentation", + "ObjectBlurrer", + "ObjectCounter", + "ObjectCropper", + "ParkingManagement", + "ParkingPtsSelection", + "QueueManager", + "RegionCounter", + "SearchApp", + "SecurityAlarm", + "SpeedEstimator", + "TrackZone", + "VisionEye", + "VisualAISearch", +) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9339edf970832b2bf591b9779df281dd8be2cc6d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/ai_gym.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/ai_gym.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75e73b6da170aa8801c87a05e28449dd6fe6f5f0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/ai_gym.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/analytics.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/analytics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a240fc86d47cee6b751b907c140d5a6683dd868 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/analytics.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7b27fa9bada3d6eca76891535571240ea439850 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/distance_calculation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/distance_calculation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..310130526dcca4a7b853c60ce26f01261007fd89 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/distance_calculation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/heatmap.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/heatmap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eba2d995a2856c937c36c3b5a9d7aa7670883c1d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/heatmap.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/instance_segmentation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/instance_segmentation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d87aa2a5da414a9b550d1bf746bbf1d6b0202710 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/instance_segmentation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/object_blurrer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/object_blurrer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e01cd603b82733c7a9f8469e41ff97ce510dcf55 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/object_blurrer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/object_counter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/object_counter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31dbfd1872cdd196b090ba6c9906592c2874eb10 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/object_counter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/object_cropper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/object_cropper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..837ba9a2ef2645e319fc5130df355ecc5305523d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/object_cropper.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/parking_management.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/parking_management.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c6014518afd02d7e145cb70ab98cb0059c62040 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/parking_management.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/queue_management.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/queue_management.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6384b3e2f99e161f5ee0bf0471f018e2fa89de24 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/queue_management.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/region_counter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/region_counter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cdef47f9edb51a3025177c8fc2e937eb0e0acda Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/region_counter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/security_alarm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/security_alarm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93b2fb90e4f2273f0a0ad7d2b7bf180d930510c5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/security_alarm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/similarity_search.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/similarity_search.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..556e5d3a96b8dcea63237cc0c060bb6383886522 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/similarity_search.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/solutions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/solutions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20d9a8a0ed7ddf0c4ed01590b4624044ee6621af Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/solutions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/speed_estimation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/speed_estimation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..660857e21d37f971d8b5785a9fb76c19792b6c37 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/speed_estimation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/streamlit_inference.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/streamlit_inference.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4be09e184453e302406a59693b0741092d3705c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/streamlit_inference.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/trackzone.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/trackzone.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05450bbb89e8829c01555f291cf887c1d091efb0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/trackzone.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/vision_eye.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/vision_eye.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd3a96355f62d4ca8cb356257da6064b9b74535b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/solutions/__pycache__/vision_eye.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/ai_gym.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/ai_gym.py new file mode 100644 index 0000000000000000000000000000000000000000..e055d38a551db1725eb95507aca0c1f0f483be83 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/ai_gym.py @@ -0,0 +1,119 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from collections import defaultdict +from typing import Any + +from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults + + +class AIGym(BaseSolution): + """A class to manage gym steps of people in a real-time video stream based on their poses. + + This class extends BaseSolution to monitor workouts using YOLO pose estimation models. It tracks and counts + repetitions of exercises based on predefined angle thresholds for up and down positions. + + Attributes: + states (dict[int, dict[str, float | int | str]]): Per-track angle, rep count, and stage for workout monitoring. + up_angle (float): Angle threshold for considering the 'up' position of an exercise. + down_angle (float): Angle threshold for considering the 'down' position of an exercise. + kpts (list[int]): Indices of keypoints used for angle calculation. + + Methods: + process: Process a frame to detect poses, calculate angles, and count repetitions. + + Examples: + >>> gym = AIGym(model="yolo26n-pose.pt") + >>> image = cv2.imread("gym_scene.jpg") + >>> results = gym.process(image) + >>> processed_image = results.plot_im + >>> cv2.imshow("Processed Image", processed_image) + >>> cv2.waitKey(0) + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize AIGym for workout monitoring using pose estimation and predefined angles. + + Args: + **kwargs (Any): Keyword arguments passed to the parent class constructor including: + - model (str): Model name or path, defaults to "yolo26n-pose.pt". + """ + kwargs["model"] = kwargs.get("model", "yolo26n-pose.pt") + super().__init__(**kwargs) + self.states = defaultdict(lambda: {"angle": 0, "count": 0, "stage": "-"}) # Dict for count, angle and stage + + # Extract details from CFG single time for usage later + self.up_angle = float(self.CFG["up_angle"]) # Pose up predefined angle to consider up pose + self.down_angle = float(self.CFG["down_angle"]) # Pose down predefined angle to consider down pose + self.kpts = self.CFG["kpts"] # User selected kpts of workouts storage for further usage + + def forget_tracks(self, track_ids): + """Drop retired IDs from workout state so it doesn't grow across a 24/7 stream (see BaseSolution).""" + super().forget_tracks(track_ids) + for track_id in track_ids: + self.states.pop(track_id, None) + + def process(self, im0) -> SolutionResults: + """Monitor workouts using Ultralytics YOLO Pose Model. + + This function processes an input image to track and analyze human poses for workout monitoring. It uses the YOLO + Pose model to detect keypoints, estimate angles, and count repetitions based on predefined angle thresholds. + + Args: + im0 (np.ndarray): Input image for processing. + + Returns: + (SolutionResults): Contains processed image `plot_im`, 'workout_count' (list[int] of completed reps, one + entry per currently tracked individual), 'workout_stage' (list[str] of current stages), 'workout_angle' + (list[float] of current angles), and 'total_tracks' (int, total number of tracked individuals). All + per-track lists are aligned with the currently visible tracks so that ``len(results.workout_count) + == results.total_tracks``. + + Examples: + >>> gym = AIGym() + >>> image = cv2.imread("workout.jpg") + >>> results = gym.process(image) + >>> processed_image = results.plot_im + """ + annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator + + self.extract_tracks(im0) # Extract tracks (bounding boxes, classes, and masks) + + if len(self.boxes): + kpt_data = self.tracks.keypoints.data.cpu().numpy() # one host transfer, avoids per-keypoint GPU sync + + for i, k in enumerate(kpt_data): + state = self.states[self.track_ids[i]] # get state details + # Get keypoints and estimate the angle + state["angle"] = annotator.estimate_pose_angle(*[k[int(idx)] for idx in self.kpts]) + annotator.draw_specific_kpts(k, self.kpts, radius=self.line_width * 3) + + # Determine stage and count logic based on angle thresholds + if state["angle"] < self.down_angle: + if state["stage"] == "up": + state["count"] += 1 + state["stage"] = "down" + elif state["angle"] > self.up_angle: + state["stage"] = "up" + + # Display angle, count, and stage text + if self.show_labels: + annotator.plot_angle_and_count_and_stage( + angle_text=state["angle"], # angle text for display + count_text=state["count"], # count text for workouts + stage_text=state["stage"], # stage position text + center_kpt=k[int(self.kpts[1])], # center keypoint for display + ) + plot_im = annotator.result() + self.display_output(plot_im) # Display output image, if environment support display + + # Return SolutionResults aligned with currently tracked individuals only. + # self.states is keyed by track_id and may contain entries for people who have + # already left the frame; iterating self.track_ids keeps the per-track lists in + # sync with total_tracks so len(workout_count) == total_tracks at all times. + return SolutionResults( + plot_im=plot_im, + workout_count=[self.states[tid]["count"] for tid in self.track_ids], + workout_stage=[self.states[tid]["stage"] for tid in self.track_ids], + workout_angle=[self.states[tid]["angle"] for tid in self.track_ids], + total_tracks=len(self.track_ids), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/analytics.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/analytics.py new file mode 100644 index 0000000000000000000000000000000000000000..68ce30adee9e6d6c8ec6b799efd8537a2ad9234a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/analytics.py @@ -0,0 +1,264 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from itertools import cycle +from typing import Any + +import cv2 +import numpy as np + +from ultralytics.solutions.solutions import BaseSolution, SolutionResults # Import a parent class +from ultralytics.utils import plt_settings + + +class Analytics(BaseSolution): + """A class for creating and updating various types of charts for visual analytics. + + This class extends BaseSolution to provide functionality for generating line, bar, pie, and area charts based on + object detection and tracking data. + + Attributes: + type (str): The type of analytics chart to generate ('line', 'bar', 'pie', or 'area'). + x_label (str): Label for the x-axis. + y_label (str): Label for the y-axis. + bg_color (str): Background color of the chart frame. + fg_color (str): Foreground color of the chart frame. + title (str): Title of the chart window. + max_points (int): Maximum number of data points to display on the chart. + fontsize (int): Font size for text display. + color_cycle (cycle): Cyclic iterator for chart colors. + total_counts (int): Total count of detected objects (used for line charts). + clswise_count (dict[str, int]): Dictionary for class-wise object counts. + fig (Figure): Matplotlib figure object for the chart. + ax (Axes): Matplotlib axes object for the chart. + canvas (FigureCanvasAgg): Canvas for rendering the chart. + lines (dict): Dictionary to store line objects for area charts. + color_mapping (dict[str, str]): Dictionary mapping class labels to colors for consistent visualization. + + Methods: + process: Process image data and update the chart. + update_graph: Update the chart with new data points. + + Examples: + >>> analytics = Analytics(analytics_type="line") + >>> frame = cv2.imread("image.jpg") + >>> results = analytics.process(frame, frame_number=1) + >>> cv2.imshow("Analytics", results.plot_im) + """ + + @plt_settings() + def __init__(self, **kwargs: Any) -> None: + """Initialize Analytics class with various chart types for visual data representation.""" + super().__init__(**kwargs) + + import matplotlib.pyplot as plt # scope for faster 'import ultralytics' + from matplotlib.backends.backend_agg import FigureCanvasAgg + from matplotlib.figure import Figure + + self.type = self.CFG["analytics_type"] # Chart type: "line", "pie", "bar", or "area". + self.x_label = "Classes" if self.type in {"bar", "pie"} else "Frame#" + self.y_label = "Total Counts" + + # Predefined data + self.bg_color = "#F3F3F3" # background color of frame + self.fg_color = "#111E68" # foreground color of frame + self.title = "Ultralytics Solutions" # window name + self.max_points = 45 # maximum points to be drawn on window + self.fontsize = 25 # text font size for display + figsize = self.CFG["figsize"] # Output size, e.g. (12.8, 7.2) -> 1280x720. + self.color_cycle = cycle(["#DD00BA", "#042AFF", "#FF4447", "#7D24FF", "#BD00FF"]) + + self.total_counts = 0 # Stores total counts for line charts. + self.clswise_count = {} # dictionary for class-wise counts + self.update_every = kwargs.get("update_every", 30) # Only update graph every 30 frames by default + self.last_plot_im = None # Cache of the last rendered chart + + # Ensure line and area chart + if self.type in {"line", "area"}: + self.lines = {} + self.fig = Figure(facecolor=self.bg_color, figsize=figsize) + self.canvas = FigureCanvasAgg(self.fig) # Set common axis properties + self.ax = self.fig.add_subplot(111, facecolor=self.bg_color) + if self.type == "line": + (self.line,) = self.ax.plot([], [], color="cyan", linewidth=self.line_width) + elif self.type in {"bar", "pie"}: + # Initialize bar or pie plot + self.fig, self.ax = plt.subplots(figsize=figsize, facecolor=self.bg_color) + self.canvas = FigureCanvasAgg(self.fig) # Set common axis properties + self.ax.set_facecolor(self.bg_color) + self.color_mapping = {} + + if self.type == "pie": # Ensure pie chart is circular + self.ax.axis("equal") + + def process(self, im0: np.ndarray, frame_number: int) -> SolutionResults: + """Process image data and run object tracking to update analytics charts. + + Args: + im0 (np.ndarray): Input image for processing. + frame_number (int): Video frame number for plotting the data. + + Returns: + (SolutionResults): Contains processed image `plot_im`, 'total_tracks' (int, total number of tracked objects) + and 'classwise_count' (dict, per-class object count). + + Raises: + ValueError: If an unsupported chart type is specified. + + Examples: + >>> analytics = Analytics(analytics_type="line") + >>> frame = np.zeros((480, 640, 3), dtype=np.uint8) + >>> results = analytics.process(frame, frame_number=1) + """ + self.extract_tracks(im0) # Extract tracks + if self.type == "line": + self.total_counts += len(self.boxes) + update_required = frame_number % self.update_every == 0 or self.last_plot_im is None + if update_required: + self.last_plot_im = self.update_graph(frame_number=frame_number) + self.total_counts = 0 + plot_im = self.last_plot_im + elif self.type in {"pie", "bar", "area"}: + from collections import Counter + + self.clswise_count = Counter(self.names[int(cls)] for cls in self.clss) + update_required = frame_number % self.update_every == 0 or self.last_plot_im is None + if update_required: + self.last_plot_im = self.update_graph( + frame_number=frame_number, count_dict=self.clswise_count, plot=self.type + ) + plot_im = self.last_plot_im + else: + raise ValueError(f"Unsupported analytics_type='{self.type}'. Supported types: line, bar, pie, area.") + + # Return results for downstream use. + return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids), classwise_count=self.clswise_count) + + def update_graph( + self, frame_number: int, count_dict: dict[str, int] | None = None, plot: str = "line" + ) -> np.ndarray: + """Update the graph with new data for single or multiple classes. + + Args: + frame_number (int): The current frame number. + count_dict (dict[str, int], optional): Dictionary with class names as keys and counts as values for multiple + classes. If None, updates a single line graph. + plot (str): Type of the plot. Options are 'line', 'bar', 'pie', or 'area'. + + Returns: + (np.ndarray): Updated image containing the graph. + + Examples: + >>> analytics = Analytics(analytics_type="bar") + >>> frame_num = 10 + >>> results_dict = {"person": 5, "car": 3} + >>> updated_image = analytics.update_graph(frame_num, results_dict, plot="bar") + """ + if count_dict is None: + # Single line update + x_data = np.append(self.line.get_xdata(), float(frame_number)) + y_data = np.append(self.line.get_ydata(), float(self.total_counts)) + + if len(x_data) > self.max_points: + x_data, y_data = x_data[-self.max_points :], y_data[-self.max_points :] + + self.line.set_data(x_data, y_data) + self.line.set_label("Counts") + self.line.set_color("#7b0068") # Pink color + self.line.set_marker("*") + self.line.set_markersize(self.line_width * 5) + else: + labels = list(count_dict.keys()) + counts = list(count_dict.values()) + if plot == "area": + color_cycle = cycle(["#DD00BA", "#042AFF", "#FF4447", "#7D24FF", "#BD00FF"]) + # Multiple lines or area update + x_data = self.ax.lines[0].get_xdata() if self.ax.lines else np.array([]) + y_data_dict = {key: np.array([]) for key in count_dict} + if self.ax.lines: + for line, key in zip(self.ax.lines, count_dict.keys()): + y_data_dict[key] = line.get_ydata() + + x_data = np.append(x_data, float(frame_number)) + max_length = len(x_data) + for key in count_dict: + y_data_dict[key] = np.append(y_data_dict[key], float(count_dict[key])) + if len(y_data_dict[key]) < max_length: + y_data_dict[key] = np.pad(y_data_dict[key], (0, max_length - len(y_data_dict[key]))) + if len(x_data) > self.max_points: + x_data = x_data[1:] + for key in count_dict: + y_data_dict[key] = y_data_dict[key][1:] + + self.ax.clear() + for key, y_data in y_data_dict.items(): + color = next(color_cycle) + self.ax.fill_between(x_data, y_data, color=color, alpha=0.55) + self.ax.plot( + x_data, + y_data, + color=color, + linewidth=self.line_width, + marker="o", + markersize=self.line_width * 5, + label=f"{key} Data Points", + ) + elif plot == "bar": + self.ax.clear() # clear bar data + for label in labels: # Map labels to colors + if label not in self.color_mapping: + self.color_mapping[label] = next(self.color_cycle) + colors = [self.color_mapping[label] for label in labels] + bars = self.ax.bar(labels, counts, color=colors) + for bar, count in zip(bars, counts): + self.ax.text( + bar.get_x() + bar.get_width() / 2, + bar.get_height(), + str(count), + ha="center", + va="bottom", + color=self.fg_color, + ) + # Create the legend using labels from the bars + for bar, label in zip(bars, labels): + bar.set_label(label) # Assign label to each bar + elif plot == "pie": + total = sum(counts) + percentages = [size / total * 100 for size in counts] + self.ax.clear() + + start_angle = 90 + # Create pie chart and create legend labels with percentages + wedges, _ = self.ax.pie( + counts, labels=labels, startangle=start_angle, textprops={"color": self.fg_color}, autopct=None + ) + legend_labels = [f"{label} ({percentage:.1f}%)" for label, percentage in zip(labels, percentages)] + + # Assign the legend using the wedges and manually created labels + self.ax.legend(wedges, legend_labels, title="Classes", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1)) + self.fig.subplots_adjust(left=0.1, right=0.75) # Adjust layout to fit the legend + + # Common plot settings + self.ax.set_facecolor("#f0f0f0") # Set to light gray or any other color you like + self.ax.grid(True, linestyle="--", linewidth=0.5, alpha=0.5) # Display grid for more data insights + self.ax.set_title(self.title, color=self.fg_color, fontsize=self.fontsize) + self.ax.set_xlabel(self.x_label, color=self.fg_color, fontsize=self.fontsize - 3) + self.ax.set_ylabel(self.y_label, color=self.fg_color, fontsize=self.fontsize - 3) + + # Add and format legend + legend = self.ax.get_legend() or self.ax.legend( + loc="upper left", fontsize=13, facecolor=self.bg_color, edgecolor=self.bg_color + ) + for text in legend.get_texts(): + text.set_color(self.fg_color) + + # Redraw graph, update view, capture, and display the updated plot + self.ax.relim() + self.ax.autoscale_view() + self.canvas.draw() + im0 = np.array(self.canvas.renderer.buffer_rgba()) + im0 = cv2.cvtColor(im0[:, :, :3], cv2.COLOR_RGBA2BGR) + self.display_output(im0) + + return im0 # Return the image diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/config.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/config.py new file mode 100644 index 0000000000000000000000000000000000000000..1c6ea7b8902029a302615a460c09818ed2a3b681 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/config.py @@ -0,0 +1,118 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +import cv2 + + +@dataclass +class SolutionConfig: + """Manages configuration parameters for Ultralytics Vision AI solutions. + + The SolutionConfig class serves as a centralized configuration container for all the Ultralytics solution modules: + https://docs.ultralytics.com/solutions#solutions. It leverages Python `dataclass` for clear, type-safe, and + maintainable parameter definitions. + + Attributes: + source (str, optional): Path to the input source (video, RTSP, etc.). Only usable with Solutions CLI. + model (str, optional): Path to the Ultralytics YOLO model to be used for inference. + classes (list[int], optional): List of class indices to filter detections. + show_conf (bool): Whether to show confidence scores on the visual output. + show_labels (bool): Whether to display class labels on visual output. + show_boxes (bool): Whether to display bounding boxes on the visual output. + region (list[tuple[int, int]], optional): Polygonal region or line for object counting. + colormap (int, optional): OpenCV colormap constant for visual overlays (e.g., cv2.COLORMAP_DEEPGREEN). + show_in (bool): Whether to display count number for objects entering the region. + show_out (bool): Whether to display count number for objects leaving the region. + up_angle (float): Upper angle threshold used in pose-based workouts monitoring. + down_angle (int): Lower angle threshold used in pose-based workouts monitoring. + kpts (list[int]): Keypoint indices to monitor, e.g., for pose analytics. + analytics_type (str): Type of analytics to perform ("line", "area", "bar", "pie", etc.). + figsize (tuple[float, float], optional): Size of the matplotlib figure used for analytical plots (width, + height). + blur_ratio (float): Ratio used to blur objects in the video frames (0.0 to 1.0). + vision_point (tuple[int, int]): Reference point for directional tracking or perspective drawing. + crop_dir (str): Directory path to save cropped detection images. + json_file (str, optional): Path to a JSON file containing data for parking areas. + line_width (int): Width for visual display, e.g. bounding boxes, keypoints, and counts. + records (int): Number of detection records to send email alerts. + fps (float): Frame rate (Frames Per Second) for speed estimation calculation. + max_hist (int): Maximum number of historical points or states stored per tracked object for speed estimation. + meter_per_pixel (float): Scale for real-world measurement, used in speed or distance calculations. + max_speed (int): Maximum speed limit (e.g., km/h or mph) used in visual alerts or constraints. + show (bool): Whether to display the visual output on screen. + iou (float): Intersection-over-Union threshold for detection filtering. + conf (float): Confidence threshold for keeping predictions. + device (str, optional): Device to run inference on (e.g., 'cpu', '0' for CUDA GPU). + max_det (int): Maximum number of detections allowed per video frame. + quantize (int | str | None): Inference precision, e.g. 16 (FP16). Only PyTorch and TorchScript models compute in + it; elsewhere the artifact and runtime decide, though 16 rounds OpenVINO inputs. Replaces the deprecated + half flag. + tracker (str): Path to tracking configuration YAML file (e.g., 'botsort.yaml'). + verbose (bool): Enable verbose logging output for debugging or diagnostics. + data (str): Path to image directory used for similarity search. + + Methods: + update: Update the configuration with user-defined keyword arguments and raise error on invalid keys. + + Examples: + >>> from ultralytics.solutions.config import SolutionConfig + >>> cfg = SolutionConfig(model="yolo26n.pt", region=[(0, 0), (100, 0), (100, 100), (0, 100)]) + >>> cfg.update(show=False, conf=0.3) + >>> print(cfg.model) + """ + + source: str | None = None + model: str | None = None + classes: list[int] | None = None + show_conf: bool = True + show_labels: bool = True + show_boxes: bool = True + region: list[tuple[int, int]] | None = None + colormap: int | None = cv2.COLORMAP_DEEPGREEN + show_in: bool = True + show_out: bool = True + up_angle: float = 145.0 + down_angle: int = 90 + kpts: list[int] = field(default_factory=lambda: [6, 8, 10]) + analytics_type: str = "line" + figsize: tuple[float, float] | None = (12.8, 7.2) + blur_ratio: float = 0.5 + vision_point: tuple[int, int] = (20, 20) + crop_dir: str = "cropped-detections" + json_file: str | None = None + line_width: int = 2 + records: int = 5 + fps: float = 30.0 + max_hist: int = 5 + meter_per_pixel: float = 0.05 + max_speed: int = 120 + show: bool = False + iou: float = 0.7 + conf: float = 0.25 + device: str | None = None + max_det: int = 300 + quantize: int | str | None = None + imgsz: int = 640 + tracker: str = "botsort.yaml" + verbose: bool = True + data: str = "images" + + def update(self, **kwargs: Any): + """Update configuration parameters with new values provided as keyword arguments.""" + if "half" in kwargs: # deprecated alias, forwarded to quantize + from ultralytics.utils import deprecation_warn + + deprecation_warn("half", "quantize") + kwargs["quantize"] = 16 if kwargs.pop("half") else None + for key, value in kwargs.items(): + if hasattr(self, key): + setattr(self, key, value) + else: + url = "https://docs.ultralytics.com/solutions#solutions-arguments" + raise ValueError(f"{key} is not a valid solution argument, see {url}") + + return self diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/distance_calculation.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/distance_calculation.py new file mode 100644 index 0000000000000000000000000000000000000000..1e3aa570afb989c9339c14867981a1cccf45f280 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/distance_calculation.py @@ -0,0 +1,127 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import math +from typing import Any + +import cv2 + +from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults +from ultralytics.utils.plotting import colors + + +class DistanceCalculation(BaseSolution): + """A class to calculate distance between two objects in a real-time video stream based on their tracks. + + This class extends BaseSolution to provide functionality for selecting objects and calculating the distance between + them in a video stream using YOLO object detection and tracking. + + Attributes: + left_mouse_count (int): Counter for left mouse button clicks. + selected_boxes (dict[int, Any]): Dictionary to store selected bounding boxes keyed by track ID. + centroids (list[list[int]]): List to store centroids of selected bounding boxes. + + Methods: + mouse_event_for_distance: Handle mouse events for selecting objects in the video stream. + process: Process video frames and calculate the distance between selected objects. + + Examples: + >>> distance_calc = DistanceCalculation() + >>> frame = cv2.imread("frame.jpg") + >>> results = distance_calc.process(frame) + >>> cv2.imshow("Distance Calculation", results.plot_im) + >>> cv2.waitKey(0) + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the DistanceCalculation class for measuring object distances in video streams.""" + super().__init__(**kwargs) + + # Mouse event information + self.left_mouse_count = 0 + self.selected_boxes: dict[int, list[float]] = {} + self.centroids: list[list[int]] = [] # Store centroids of selected objects + + def mouse_event_for_distance(self, event: int, x: int, y: int, flags: int, param: Any) -> None: + """Handle mouse events to select regions in a real-time video stream for distance calculation. + + Args: + event (int): Type of mouse event (e.g., cv2.EVENT_MOUSEMOVE, cv2.EVENT_LBUTTONDOWN). + x (int): X-coordinate of the mouse pointer. + y (int): Y-coordinate of the mouse pointer. + flags (int): Flags associated with the event (e.g., cv2.EVENT_FLAG_CTRLKEY, cv2.EVENT_FLAG_SHIFTKEY). + param (Any): Additional parameters passed to the function. + + Examples: + >>> # Assuming 'dc' is an instance of DistanceCalculation + >>> cv2.setMouseCallback("window_name", dc.mouse_event_for_distance) + """ + if event == cv2.EVENT_LBUTTONDOWN: + self.left_mouse_count += 1 + if self.left_mouse_count <= 2: + for box, track_id in zip(self.boxes, self.track_ids): + x0, y0, x1, y1 = self.get_enclosing_box(box) + if x0 < x < x1 and y0 < y < y1 and track_id not in self.selected_boxes: + self.selected_boxes[track_id] = box + + elif event == cv2.EVENT_RBUTTONDOWN: + self.selected_boxes = {} + self.left_mouse_count = 0 + + def process(self, im0) -> SolutionResults: + """Process a video frame and calculate the distance between two selected bounding boxes. + + This method extracts tracks from the input frame, annotates bounding boxes, and calculates the distance between + two user-selected objects if they have been chosen. + + Args: + im0 (np.ndarray): The input image frame to process. + + Returns: + (SolutionResults): Contains processed image `plot_im`, `total_tracks` (int) representing the total number of + tracked objects, and `pixels_distance` (float) representing the distance between selected objects + in pixels. + + Examples: + >>> import numpy as np + >>> from ultralytics.solutions import DistanceCalculation + >>> dc = DistanceCalculation() + >>> frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) + >>> results = dc.process(frame) + >>> print(f"Distance: {results.pixels_distance:.2f} pixels") + """ + self.extract_tracks(im0) # Extract tracks + annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator + + pixels_distance = 0 + # Iterate over bounding boxes, track ids and classes index + for box, track_id, cls, conf in zip(self.boxes, self.track_ids, self.clss, self.confs): + annotator.box_label(box, color=colors(int(cls), True), label=self.adjust_box_label(cls, conf, track_id)) + + # Update selected boxes if they're being tracked + if len(self.selected_boxes) == 2: + for trk_id in self.selected_boxes: + if trk_id == track_id: + self.selected_boxes[track_id] = box + + if len(self.selected_boxes) == 2: + # Calculate centroids of selected boxes + self.centroids.extend( + [ + [int((box[0] + box[2]) // 2), int((box[1] + box[3]) // 2)] + for box in map(self.get_enclosing_box, self.selected_boxes.values()) + ] + ) + # Calculate Euclidean distance between centroids + pixels_distance = math.sqrt( + (self.centroids[0][0] - self.centroids[1][0]) ** 2 + (self.centroids[0][1] - self.centroids[1][1]) ** 2 + ) + annotator.plot_distance_and_line(pixels_distance, self.centroids) + + self.centroids = [] # Reset centroids for next frame + plot_im = annotator.result() + self.display_output(plot_im) # Display output with base class function + if self.CFG.get("show") and self.env_check: + cv2.setMouseCallback("Ultralytics Solutions", self.mouse_event_for_distance) + + # Return SolutionResults with processed image and calculated metrics + return SolutionResults(plot_im=plot_im, pixels_distance=pixels_distance, total_tracks=len(self.track_ids)) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/heatmap.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/heatmap.py new file mode 100644 index 0000000000000000000000000000000000000000..47d251de0294d8bb847de0e6e72265b3bc9df8c3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/heatmap.py @@ -0,0 +1,130 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any + +import cv2 +import numpy as np +import torch + +from ultralytics.solutions.object_counter import ObjectCounter +from ultralytics.solutions.solutions import SolutionAnnotator, SolutionResults + + +class Heatmap(ObjectCounter): + """A class to draw heatmaps in real-time video streams based on object tracks. + + This class extends the ObjectCounter class to generate and visualize heatmaps of object movements in video + streams. It uses tracked object positions to create a cumulative heatmap effect over time. + + Attributes: + initialized (bool): Flag indicating whether the heatmap has been initialized. + colormap (int): OpenCV colormap used for heatmap visualization. + heatmap (np.ndarray): Array storing the cumulative heatmap data. + annotator (SolutionAnnotator): Object for drawing annotations on the image. + + Methods: + heatmap_effect: Calculate and update the heatmap effect for a given bounding box. + process: Generate and apply the heatmap effect to each frame. + + Examples: + >>> from ultralytics.solutions import Heatmap + >>> heatmap = Heatmap(model="yolo26n.pt", colormap=cv2.COLORMAP_JET) + >>> frame = cv2.imread("frame.jpg") + >>> processed_frame = heatmap.process(frame) + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the Heatmap class for real-time video stream heatmap generation based on object tracks. + + Args: + **kwargs (Any): Keyword arguments passed to the parent ObjectCounter class. + """ + super().__init__(**kwargs) + + self.initialized = False # Flag for heatmap initialization + if self.region is not None: # Check if user provided the region coordinates + self.initialize_region() + + # Store colormap + self.colormap = self.CFG["colormap"] + self.heatmap = None + + def heatmap_effect(self, box: torch.Tensor) -> None: + """Efficiently calculate heatmap area and effect location for applying colormap. + + Args: + box (torch.Tensor): Bounding box coordinates [x0, y0, x1, y1] or (4, 2) OBB corner points. + """ + x0, y0, x1, y1 = map(int, self.get_enclosing_box(box)) + h, w = self.heatmap.shape[:2] + x0, y0, x1, y1 = max(x0, 0), max(y0, 0), min(x1, w), min(y1, h) # clip OBB corners to image bounds + radius_squared = (min(x1 - x0, y1 - y0) // 2) ** 2 + + # Create a meshgrid with region of interest (ROI) for vectorized distance calculations + xv, yv = np.meshgrid(np.arange(x0, x1), np.arange(y0, y1)) + + # Calculate squared distances from the center + dist_squared = (xv - ((x0 + x1) // 2)) ** 2 + (yv - ((y0 + y1) // 2)) ** 2 + + # Create a mask of points within the radius + within_radius = dist_squared <= radius_squared + + # Update only the values within the bounding box in a single vectorized operation + self.heatmap[y0:y1, x0:x1][within_radius] += 2 + + def process(self, im0: np.ndarray) -> SolutionResults: + """Generate heatmap for each frame using Ultralytics tracking. + + Args: + im0 (np.ndarray): Input image array for processing. + + Returns: + (SolutionResults): Contains processed image `plot_im`, 'in_count' (int, count of objects entering the + region), 'out_count' (int, count of objects exiting the region), 'classwise_count' (dict, per-class + object count), and 'total_tracks' (int, total number of tracked objects). + """ + if not self.initialized: + self.heatmap = np.zeros(im0.shape[:2], dtype=np.float32) + self.initialized = True # Initialize heatmap only once + + self.extract_tracks(im0) # Extract tracks + self.annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator + + if self.region is not None: + self.annotator.draw_region(reg_pts=self.region, color=(104, 0, 123), thickness=self.line_width * 2) + + # Iterate over bounding boxes, track ids and classes index + for box, track_id, cls in zip(self.boxes, self.track_ids, self.clss): + # Apply heatmap effect for the bounding box + self.heatmap_effect(box) + + if self.region is not None: + self.store_tracking_history(track_id, box) # Store track history + # Get previous position if available + prev_position = None + if len(self.track_history[track_id]) > 1: + prev_position = self.track_history[track_id][-2] + self.count_objects(self.track_history[track_id][-1], track_id, prev_position, cls) # object counting + + plot_im = self.annotator.result() + if self.region is not None: + self.display_counts(plot_im) # Display the counts on the frame + + # Normalize, apply colormap to heatmap and combine with original image + if self.heatmap.any(): + normalized_heatmap = cv2.normalize(self.heatmap, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8) + colored_heatmap = cv2.applyColorMap(normalized_heatmap, self.colormap) + plot_im = cv2.addWeighted(plot_im, 0.5, colored_heatmap, 0.5, 0) + + self.display_output(plot_im) # Display output with base class function + + # Return SolutionResults + return SolutionResults( + plot_im=plot_im, + in_count=self.in_count, + out_count=self.out_count, + classwise_count=dict(self.classwise_count), + total_tracks=len(self.track_ids), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/instance_segmentation.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/instance_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..2457321f752b14ddfde78c106de01d550a46807a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/instance_segmentation.py @@ -0,0 +1,86 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from typing import Any + +from ultralytics.engine.results import Results +from ultralytics.solutions.solutions import BaseSolution, SolutionResults + + +class InstanceSegmentation(BaseSolution): + """A class to manage instance segmentation in images or video streams. + + This class extends the BaseSolution class and provides functionality for performing instance segmentation, including + drawing segmented masks with bounding boxes and labels. + + Attributes: + model (YOLO): The segmentation model instance used for inference. + line_width (int): Width of the bounding box and text lines. + names (dict[int, str]): Dictionary mapping class indices to class names. + clss (list[int]): List of detected class indices. + track_ids (list[int]): List of track IDs for detected instances. + masks (list[np.ndarray]): List of segmentation masks for detected instances. + show_conf (bool): Whether to display confidence scores. + show_labels (bool): Whether to display class labels. + show_boxes (bool): Whether to display bounding boxes. + + Methods: + process: Process the input image to perform instance segmentation and annotate results. + extract_tracks: Extract tracks including bounding boxes, classes, and masks from model predictions. + + Examples: + >>> segmenter = InstanceSegmentation() + >>> frame = cv2.imread("frame.jpg") + >>> results = segmenter.process(frame) + >>> print(f"Total segmented instances: {results.total_tracks}") + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the InstanceSegmentation class for detecting and annotating segmented instances. + + Args: + **kwargs (Any): Keyword arguments passed to the BaseSolution parent class including: + - model (str): Model name or path, defaults to "yolo26n-seg.pt". + """ + kwargs["model"] = kwargs.get("model", "yolo26n-seg.pt") + super().__init__(**kwargs) + + self.show_conf = self.CFG.get("show_conf", True) + self.show_labels = self.CFG.get("show_labels", True) + self.show_boxes = self.CFG.get("show_boxes", True) + + def process(self, im0) -> SolutionResults: + """Perform instance segmentation on the input image and annotate the results. + + Args: + im0 (np.ndarray): The input image for segmentation. + + Returns: + (SolutionResults): Object containing the annotated image and total number of tracked instances. + + Examples: + >>> segmenter = InstanceSegmentation() + >>> frame = cv2.imread("image.jpg") + >>> summary = segmenter.process(frame) + >>> print(summary) + """ + self.extract_tracks(im0) # Extract tracks (bounding boxes, classes, and masks) + self.masks = getattr(self.tracks, "masks", None) + + # Iterate over detected classes, track IDs, and segmentation masks + if self.masks is None: + self.LOGGER.warning("No masks detected! Ensure you're using a supported Ultralytics segmentation model.") + plot_im = im0 + else: + results = Results(im0, path=None, names=self.names, boxes=self.track_data.data, masks=self.masks.data) + plot_im = results.plot( + line_width=self.line_width, + boxes=self.show_boxes, + conf=self.show_conf, + labels=self.show_labels, + color_mode="instance", + ) + + self.display_output(plot_im) # Display the annotated output using the base class function + + # Return SolutionResults + return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids)) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/object_blurrer.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/object_blurrer.py new file mode 100644 index 0000000000000000000000000000000000000000..9c497f5f8f0a0263feae3bcdfe0c921c8914b858 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/object_blurrer.py @@ -0,0 +1,91 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from typing import Any + +import cv2 + +from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults +from ultralytics.utils import LOGGER +from ultralytics.utils.plotting import colors + + +class ObjectBlurrer(BaseSolution): + """A class to manage the blurring of detected objects in a real-time video stream. + + This class extends the BaseSolution class and provides functionality for blurring objects based on detected bounding + boxes. The blurred areas are updated directly in the input image, allowing for privacy preservation or other effects. + + Attributes: + blur_ratio (int): The intensity of the blur effect applied to detected objects (higher values create more blur). + iou (float): Intersection over Union threshold for object detection. + conf (float): Confidence threshold for object detection. + + Methods: + process: Apply a blurring effect to detected objects in the input image. + extract_tracks: Extract tracking information from detected objects. + display_output: Display the processed output image. + + Examples: + >>> blurrer = ObjectBlurrer() + >>> frame = cv2.imread("frame.jpg") + >>> processed_results = blurrer.process(frame) + >>> print(f"Total blurred objects: {processed_results.total_tracks}") + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the ObjectBlurrer class for applying a blur effect to objects detected in video streams or images. + + Args: + **kwargs (Any): Keyword arguments passed to the parent class and for configuration including: + - blur_ratio (float): Intensity of the blur effect (0.1-1.0, default=0.5). + """ + super().__init__(**kwargs) + blur_ratio = self.CFG["blur_ratio"] + if blur_ratio < 0.1: + LOGGER.warning("blur ratio cannot be less than 0.1, updating it to default value 0.5") + blur_ratio = 0.5 + self.blur_ratio = int(blur_ratio * 100) + + def process(self, im0) -> SolutionResults: + """Apply a blurring effect to detected objects in the input image. + + This method extracts tracking information, applies blur to regions corresponding to detected objects, and + annotates the image with bounding boxes. + + Args: + im0 (np.ndarray): The input image containing detected objects. + + Returns: + (SolutionResults): Object containing the processed image and number of tracked objects. + - plot_im (np.ndarray): The annotated output image with blurred objects. + - total_tracks (int): The total number of tracked objects in the frame. + + Examples: + >>> blurrer = ObjectBlurrer() + >>> frame = cv2.imread("image.jpg") + >>> results = blurrer.process(frame) + >>> print(f"Blurred {results.total_tracks} objects") + """ + self.extract_tracks(im0) # Extract tracks + annotator = SolutionAnnotator(im0, self.line_width) + + # Iterate over bounding boxes and classes + h, w = im0.shape[:2] + for box, cls, conf in zip(self.boxes, self.clss, self.confs): + x0, y0, x1, y1 = map(int, self.get_enclosing_box(box)) + x0, y0, x1, y1 = max(x0, 0), max(y0, 0), min(x1, w), min(y1, h) # clip OBB corners to image bounds + if x0 >= x1 or y0 >= y1: # box fully outside the frame clips to an empty ROI, cv2.blur would assert + continue + # Crop and blur the detected object + blur_obj = cv2.blur(im0[y0:y1, x0:x1], (self.blur_ratio, self.blur_ratio)) + # Update the blurred area in the original image + im0[y0:y1, x0:x1] = blur_obj + annotator.box_label( + box, label=self.adjust_box_label(cls, conf), color=colors(cls, True) + ) # Annotate bounding box + + plot_im = annotator.result() + self.display_output(plot_im) # Display the output using the base class function + + # Return a SolutionResults + return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids)) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/object_counter.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/object_counter.py new file mode 100644 index 0000000000000000000000000000000000000000..818f77e45ebbc25669a6a101c701a0ccdbfd626f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/object_counter.py @@ -0,0 +1,205 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from collections import defaultdict +from typing import Any + +from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults +from ultralytics.utils.plotting import colors + + +class ObjectCounter(BaseSolution): + """A class to manage the counting of objects in a real-time video stream based on their tracks. + + This class extends the BaseSolution class and provides functionality for counting objects moving in and out of a + specified region in a video stream. It supports both polygonal and linear regions for counting. + + Attributes: + in_count (int): Counter for objects moving inward. + out_count (int): Counter for objects moving outward. + counted_ids (set[int]): IDs of objects that have been counted. + classwise_count (dict[str, dict[str, int]]): Dictionary for counts, categorized by object class. + region_initialized (bool): Flag indicating whether the counting region has been initialized. + show_in (bool): Flag to control display of inward count. + show_out (bool): Flag to control display of outward count. + margin (int): Margin for background rectangle size to display counts properly. + + Methods: + count_objects: Count objects within a polygonal or linear region based on their tracks. + display_counts: Display object counts on the frame. + process: Process input data and update counts. + + Examples: + >>> counter = ObjectCounter() + >>> frame = cv2.imread("frame.jpg") + >>> results = counter.process(frame) + >>> print(f"Inward count: {results.in_count}, Outward count: {results.out_count}") + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the ObjectCounter class for real-time object counting in video streams.""" + super().__init__(**kwargs) + + self.in_count = 0 # Counter for objects moving inward + self.out_count = 0 # Counter for objects moving outward + self.counted_ids = set() # IDs of objects that have been counted + self.classwise_count = defaultdict(lambda: {"IN": 0, "OUT": 0}) # Dictionary for counts, categorized by class + self.region_initialized = False # Flag indicating whether the region has been initialized + + self.show_in = self.CFG["show_in"] + self.show_out = self.CFG["show_out"] + self.margin = self.line_width * 2 # Scales the background rectangle size to display counts properly + + def count_objects( + self, + current_centroid: tuple[float, float], + track_id: int, + prev_position: tuple[float, float] | None, + cls: int, + ) -> None: + """Count objects within a polygonal or linear region based on their tracks. + + Args: + current_centroid (tuple[float, float]): Current centroid coordinates (x, y) in the current frame. + track_id (int): Unique identifier for the tracked object. + prev_position (tuple[float, float], optional): Last frame position coordinates (x, y) of the track. + cls (int): Class index for classwise count updates. + + Examples: + >>> counter = ObjectCounter() + >>> track_line = {1: [100, 200], 2: [110, 210], 3: [120, 220]} + >>> box = [130, 230, 150, 250] + >>> track_id_num = 1 + >>> previous_position = (120, 220) + >>> class_to_count = 0 # In COCO model, class 0 = person + >>> counter.count_objects((140, 240), track_id_num, previous_position, class_to_count) + """ + if prev_position is None or track_id in self.counted_ids: + return + + if len(self.region) == 2: # Linear region (defined as a line segment) + if self.r_s.intersects(self.LineString([prev_position, current_centroid])): + # Determine orientation of the region (vertical or horizontal) + if abs(self.region[0][0] - self.region[1][0]) < abs(self.region[0][1] - self.region[1][1]): + # Vertical region: Compare x-coordinates to determine direction + if current_centroid[0] > prev_position[0]: # Moving right + self.in_count += 1 + self.classwise_count[self.names[cls]]["IN"] += 1 + else: # Moving left + self.out_count += 1 + self.classwise_count[self.names[cls]]["OUT"] += 1 + # Horizontal region: Compare y-coordinates to determine direction + elif current_centroid[1] > prev_position[1]: # Moving downward + self.in_count += 1 + self.classwise_count[self.names[cls]]["IN"] += 1 + else: # Moving upward + self.out_count += 1 + self.classwise_count[self.names[cls]]["OUT"] += 1 + self.counted_ids.add(track_id) + + # An object fast enough to straddle the region leaves no centroid inside it, so count a crossing segment + # too, but only from outside: a track already inside has had the containment check since it entered. + elif len(self.region) > 2 and ( + self.r_s.contains(self.Point(current_centroid)) + or ( + not self.r_s.contains(self.Point(prev_position)) + and self.r_s.crosses(self.LineString([prev_position, current_centroid])) + ) + ): + # Judge direction by the object's dominant motion axis over its recent track, not by the + # region's shape; a ~5-frame baseline is robust to tracker jitter where a 1-frame delta is not. + # The baseline is the oldest recent point OUTSIDE the region, so the entry vector is not + # polluted by an uncounted first frame that spawned inside (quick exit and re-entry). + window = self.track_history[track_id][-5:] or [prev_position] + baseline = next((p for p in window if not self.r_s.contains(self.Point(p))), window[0]) + dx = current_centroid[0] - baseline[0] + dy = current_centroid[1] - baseline[1] + moving_in = dx > 0 if abs(dx) > abs(dy) else dy > 0 # moving right or downward + if moving_in: + self.in_count += 1 + self.classwise_count[self.names[cls]]["IN"] += 1 + else: # Moving left or upward + self.out_count += 1 + self.classwise_count[self.names[cls]]["OUT"] += 1 + self.counted_ids.add(track_id) + + def forget_tracks(self, track_ids: list[int]) -> None: + """Drop retired IDs from `counted_ids` so it doesn't grow across a 24/7 stream (see BaseSolution).""" + super().forget_tracks(track_ids) + self.counted_ids.difference_update(track_ids) + + def display_counts(self, plot_im) -> None: + """Display object counts on the input image or frame. + + Args: + plot_im (np.ndarray): The image or frame to display counts on. + + Examples: + >>> counter = ObjectCounter() + >>> frame = cv2.imread("image.jpg") + >>> counter.display_counts(frame) + """ + labels_dict = { + str.capitalize(key): f"{'IN ' + str(value['IN']) if self.show_in else ''} " + f"{'OUT ' + str(value['OUT']) if self.show_out else ''}".strip() + for key, value in self.classwise_count.items() + if (value["IN"] != 0 and self.show_in) or (value["OUT"] != 0 and self.show_out) + } + if labels_dict: + self.annotator.display_analytics(plot_im, labels_dict, (104, 31, 17), (255, 255, 255), self.margin) + + def process(self, im0) -> SolutionResults: + """Process input data (frames or object tracks) and update object counts. + + This method initializes the counting region, extracts tracks, draws bounding boxes and regions, updates object + counts, and displays the results on the input image. + + Args: + im0 (np.ndarray): The input image or frame to be processed. + + Returns: + (SolutionResults): Contains processed image `plot_im`, 'in_count' (int, count of objects entering the + region), 'out_count' (int, count of objects exiting the region), 'classwise_count' (dict, per-class + object count), and 'total_tracks' (int, total number of tracked objects). + + Examples: + >>> counter = ObjectCounter() + >>> frame = cv2.imread("path/to/image.jpg") + >>> results = counter.process(frame) + """ + if not self.region_initialized: + self.initialize_region() + self.region_initialized = True + + self.extract_tracks(im0) # Extract tracks + self.annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator + + self.annotator.draw_region( + reg_pts=self.region, color=(104, 0, 123), thickness=self.line_width * 2 + ) # Draw region + + # Iterate over bounding boxes, track ids and classes index + for box, track_id, cls, conf in zip(self.boxes, self.track_ids, self.clss, self.confs): + # Draw bounding box and counting region + self.annotator.box_label(box, label=self.adjust_box_label(cls, conf, track_id), color=colors(cls, True)) + self.store_tracking_history(track_id, box) # Store track history + + # Store previous position of track for object counting + prev_position = None + if len(self.track_history[track_id]) > 1: + prev_position = self.track_history[track_id][-2] + self.count_objects(self.track_history[track_id][-1], track_id, prev_position, cls) # object counting + + plot_im = self.annotator.result() + self.display_counts(plot_im) # Display the counts on the frame + self.display_output(plot_im) # Display output with base class function + + # Return SolutionResults + return SolutionResults( + plot_im=plot_im, + in_count=self.in_count, + out_count=self.out_count, + classwise_count=dict(self.classwise_count), + total_tracks=len(self.track_ids), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/object_cropper.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/object_cropper.py new file mode 100644 index 0000000000000000000000000000000000000000..59759fd6ca5306ecd4e5f731318270219ec4ce61 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/object_cropper.py @@ -0,0 +1,88 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from pathlib import Path +from typing import Any + +from ultralytics.solutions.solutions import BaseSolution, SolutionResults +from ultralytics.utils.plotting import save_one_box + + +class ObjectCropper(BaseSolution): + """A class to manage the cropping of detected objects in a real-time video stream or images. + + This class extends the BaseSolution class and provides functionality for cropping objects based on detected bounding + boxes. The cropped images are saved to a specified directory for further analysis or usage. + + Attributes: + crop_dir (str): Directory where cropped object images are stored. + crop_idx (int): Counter for the total number of cropped objects. + iou (float): IoU (Intersection over Union) threshold for non-maximum suppression. + conf (float): Confidence threshold for filtering detections. + + Methods: + process: Crop detected objects from the input image and save them to the output directory. + + Examples: + >>> cropper = ObjectCropper() + >>> frame = cv2.imread("frame.jpg") + >>> processed_results = cropper.process(frame) + >>> print(f"Total cropped objects: {cropper.crop_idx}") + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the ObjectCropper class for cropping objects from detected bounding boxes. + + Args: + **kwargs (Any): Keyword arguments passed to the parent class and used for configuration including: + - crop_dir (str): Path to the directory for saving cropped object images. + """ + super().__init__(**kwargs) + + self.crop_dir = self.CFG["crop_dir"] # Directory for storing cropped detections + Path(self.crop_dir).mkdir(parents=True, exist_ok=True) + if self.CFG["show"]: + self.LOGGER.warning(f"show=True is not supported for ObjectCropper; saving crops to '{self.crop_dir}'.") + self.CFG["show"] = False + self.crop_idx = 0 # Initialize counter for total cropped objects + self.iou = self.CFG["iou"] + self.conf = self.CFG["conf"] + + def process(self, im0) -> SolutionResults: + """Crop detected objects from the input image and save them as separate images. + + Args: + im0 (np.ndarray): The input image containing detected objects. + + Returns: + (SolutionResults): A SolutionResults object containing the total number of cropped objects and processed + image. + + Examples: + >>> cropper = ObjectCropper() + >>> frame = cv2.imread("image.jpg") + >>> results = cropper.process(frame) + >>> print(f"Total cropped objects: {results.total_crop_objects}") + """ + with self.profilers[0]: + results = self.model.predict( + im0, + classes=self.classes, + conf=self.conf, + iou=self.iou, + device=self.CFG["device"], + imgsz=self.CFG["imgsz"], + verbose=False, + )[0] + self.clss = results.boxes.cls.tolist() # required for logging only. + + for box in results.boxes: + self.crop_idx += 1 + save_one_box( + box.xyxy, + im0, + file=Path(self.crop_dir) / f"crop_{self.crop_idx}.jpg", + BGR=True, + ) + + # Return SolutionResults + return SolutionResults(plot_im=im0, total_crop_objects=self.crop_idx) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/parking_management.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/parking_management.py new file mode 100644 index 0000000000000000000000000000000000000000..f825b3eeaaa95314953e194a2d8a253bae251f27 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/parking_management.py @@ -0,0 +1,281 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import json +from typing import Any + +import cv2 +import numpy as np + +from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults +from ultralytics.utils import LOGGER +from ultralytics.utils.checks import check_imshow + + +class ParkingPtsSelection: + """A class for selecting and managing parking zone points on images using a Tkinter-based UI. + + This class provides functionality to upload an image, select points to define parking zones, and save the selected + points to a JSON file. It uses Tkinter for the graphical user interface. + + Attributes: + tk (module): The Tkinter module for GUI operations. + filedialog (module): Tkinter's filedialog module for file selection operations. + messagebox (module): Tkinter's messagebox module for displaying message boxes. + master (tk.Tk): The main Tkinter window. + canvas (tk.Canvas): The canvas widget for displaying the image and drawing bounding boxes. + image (PIL.Image.Image): The uploaded image. + canvas_image (ImageTk.PhotoImage): The image displayed on the canvas. + rg_data (list[list[tuple[int, int]]]): List of bounding boxes, each defined by 4 points. + current_box (list[tuple[int, int]]): Temporary storage for the points of the current bounding box. + imgw (int): Original width of the uploaded image. + imgh (int): Original height of the uploaded image. + canvas_max_width (int): Maximum width of the canvas. + canvas_max_height (int): Maximum height of the canvas. + + Methods: + initialize_properties: Initialize properties for image, canvas, bounding boxes, and dimensions. + upload_image: Upload and display an image on the canvas, resizing it to fit within specified dimensions. + on_canvas_click: Handle mouse clicks to add points for bounding boxes on the canvas. + draw_box: Draw a bounding box on the canvas using the provided coordinates. + remove_last_bounding_box: Remove the last bounding box from the list and redraw the canvas. + redraw_canvas: Redraw the canvas with the image and all bounding boxes. + save_to_json: Save the selected parking zone points to a JSON file with scaled coordinates. + + Examples: + >>> parking_selector = ParkingPtsSelection() + >>> # Use the GUI to upload an image, select parking zones, and save the data + """ + + def __init__(self) -> None: + """Initialize the ParkingPtsSelection class, setting up UI and properties for parking zone point selection.""" + try: # Check if tkinter is installed + import tkinter as tk + from tkinter import filedialog, messagebox + except ImportError: # Display error with recommendations + import platform + + install_cmd = { + "Linux": "sudo apt install python3-tk (Debian/Ubuntu) | sudo dnf install python3-tkinter (Fedora) | " + "sudo pacman -S tk (Arch)", + "Windows": "reinstall Python and enable the checkbox `tcl/tk and IDLE` on **Optional Features** during installation", + "Darwin": "reinstall Python from https://www.python.org/downloads/macos/ or `brew install python-tk`", + }.get(platform.system(), "Unknown OS. Check your Python installation.") + + LOGGER.warning(f" Tkinter is not configured or supported. Potential fix: {install_cmd}") + return + + if not check_imshow(warn=True): + return + + self.tk, self.filedialog, self.messagebox = tk, filedialog, messagebox + self.master = self.tk.Tk() # Reference to the main application window + self.master.title("Ultralytics Parking Zones Points Selector") + self.master.resizable(False, False) + + self.canvas = self.tk.Canvas(self.master, bg="white") # Canvas widget for displaying images + self.canvas.pack(side=self.tk.BOTTOM) + + self.image = None # Variable to store the loaded image + self.canvas_image = None # Reference to the image displayed on the canvas + self.canvas_max_width = None # Maximum allowed width for the canvas + self.canvas_max_height = None # Maximum allowed height for the canvas + self.rg_data = None # Data for region annotation management + self.current_box = None # Stores the currently selected bounding box + self.imgh = None # Height of the current image + self.imgw = None # Width of the current image + + # Button frame with buttons + button_frame = self.tk.Frame(self.master) + button_frame.pack(side=self.tk.TOP) + + for text, cmd in [ + ("Upload Image", self.upload_image), + ("Remove Last Bounding Box", self.remove_last_bounding_box), + ("Save", self.save_to_json), + ]: + self.tk.Button(button_frame, text=text, command=cmd).pack(side=self.tk.LEFT) + + self.initialize_properties() + self.master.mainloop() + + def initialize_properties(self) -> None: + """Initialize properties for image, canvas, bounding boxes, and dimensions.""" + self.image = self.canvas_image = None + self.rg_data, self.current_box = [], [] + self.imgw = self.imgh = 0 + self.canvas_max_width, self.canvas_max_height = 1280, 720 + + def upload_image(self) -> None: + """Upload and display an image on the canvas, resizing it to fit within specified dimensions.""" + from PIL import Image, ImageTk # Scoped import because ImageTk requires tkinter package + + file = self.filedialog.askopenfilename(filetypes=[("Image Files", "*.png *.jpg *.jpeg")]) + if not file: + LOGGER.info("No image selected.") + return + + self.image = Image.open(file) + self.imgw, self.imgh = self.image.size + aspect_ratio = self.imgw / self.imgh + canvas_width = ( + min(self.canvas_max_width, self.imgw) if aspect_ratio > 1 else int(self.canvas_max_height * aspect_ratio) + ) + canvas_height = ( + min(self.canvas_max_height, self.imgh) if aspect_ratio <= 1 else int(canvas_width / aspect_ratio) + ) + + self.canvas.config(width=canvas_width, height=canvas_height) + self.canvas_image = ImageTk.PhotoImage(self.image.resize((canvas_width, canvas_height))) + self.canvas.create_image(0, 0, anchor=self.tk.NW, image=self.canvas_image) + self.canvas.bind("", self.on_canvas_click) + + self.rg_data.clear(), self.current_box.clear() + + def on_canvas_click(self, event) -> None: + """Handle mouse clicks to add points for bounding boxes on the canvas.""" + self.current_box.append((event.x, event.y)) + self.canvas.create_oval(event.x - 3, event.y - 3, event.x + 3, event.y + 3, fill="red") + if len(self.current_box) == 4: + self.rg_data.append(self.current_box.copy()) + self.draw_box(self.current_box) + self.current_box.clear() + + def draw_box(self, box: list[tuple[int, int]]) -> None: + """Draw a bounding box on the canvas using the provided coordinates.""" + for i in range(4): + self.canvas.create_line(box[i], box[(i + 1) % 4], fill="blue", width=2) + + def remove_last_bounding_box(self) -> None: + """Remove the last bounding box from the list and redraw the canvas.""" + if not self.rg_data: + self.messagebox.showwarning("Warning", "No bounding boxes to remove.") + return + self.rg_data.pop() + self.redraw_canvas() + + def redraw_canvas(self) -> None: + """Redraw the canvas with the image and all bounding boxes.""" + self.canvas.delete("all") + self.canvas.create_image(0, 0, anchor=self.tk.NW, image=self.canvas_image) + for box in self.rg_data: + self.draw_box(box) + + def save_to_json(self) -> None: + """Save the selected parking zone points to a JSON file with scaled coordinates.""" + scale_w, scale_h = self.imgw / self.canvas.winfo_width(), self.imgh / self.canvas.winfo_height() + data = [{"points": [(int(x * scale_w), int(y * scale_h)) for x, y in box]} for box in self.rg_data] + + from io import StringIO # Function level import, as it's only required to store coordinates + + write_buffer = StringIO() + json.dump(data, write_buffer, indent=4) + with open("bounding_boxes.json", "w", encoding="utf-8") as f: + f.write(write_buffer.getvalue()) + self.messagebox.showinfo("Success", "Bounding boxes saved to bounding_boxes.json") + + +class ParkingManagement(BaseSolution): + """Manages parking occupancy and availability using YOLO model for real-time monitoring and visualization. + + This class extends BaseSolution to provide functionality for parking lot management, including detection of occupied + spaces, visualization of parking regions, and display of occupancy statistics. + + Attributes: + json_file (str): Path to the JSON file containing parking region details. + json (list[dict]): Loaded JSON data containing parking region information. + pr_info (dict[str, int]): Dictionary storing parking information (Occupancy and Available spaces). + arc (tuple[int, int, int]): BGR color tuple for available region visualization. + occ (tuple[int, int, int]): BGR color tuple for occupied region visualization. + dc (tuple[int, int, int]): BGR color tuple for centroid visualization of detected objects. + + Methods: + process: Process the input image for parking lot management and visualization. + + Examples: + >>> from ultralytics.solutions import ParkingManagement + >>> parking_manager = ParkingManagement(model="yolo26n.pt", json_file="parking_regions.json") + >>> print(f"Occupied spaces: {parking_manager.pr_info['Occupancy']}") + >>> print(f"Available spaces: {parking_manager.pr_info['Available']}") + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the parking management system with a YOLO model and visualization settings.""" + super().__init__(**kwargs) + + self.json_file = self.CFG["json_file"] # Load parking regions JSON data + if not self.json_file: + LOGGER.warning("ParkingManagement requires `json_file` with parking region coordinates.") + raise ValueError("❌ JSON file path cannot be empty.") + + with open(self.json_file, encoding="utf-8") as f: + self.json = json.load(f) + + self.pr_info = {"Occupancy": 0, "Available": 0} # Dictionary for parking information + + self.arc = (0, 0, 255) # Available region color + self.occ = (0, 255, 0) # Occupied region color + self.dc = (255, 0, 189) # Centroid color for each box + + def process(self, im0: np.ndarray) -> SolutionResults: + """Process the input image for parking lot management and visualization. + + This function analyzes the input image, extracts tracks, and determines the occupancy status of parking regions + defined in the JSON file. It annotates the image with occupied and available parking spots, and updates the + parking information. + + Args: + im0 (np.ndarray): The input inference image. + + Returns: + (SolutionResults): Contains processed image `plot_im`, 'filled_slots' (number of occupied parking slots), + 'available_slots' (number of available parking slots), and 'total_tracks' (total number of + tracked objects). + + Examples: + >>> parking_manager = ParkingManagement(json_file="parking_regions.json") + >>> image = cv2.imread("parking_lot.jpg") + >>> results = parking_manager.process(image) + """ + self.extract_tracks(im0) # Extract tracks from im0 + available_slots, occupied_slots = len(self.json), 0 + annotator = SolutionAnnotator(im0, self.line_width) # Initialize annotator + + for region in self.json: + # Convert points to a NumPy array with the correct dtype and reshape properly + region_polygon = np.array(region["points"], dtype=np.int32).reshape((-1, 1, 2)) + region_occupied = False + for box, cls in zip(self.boxes, self.clss): + x0, y0, x1, y1 = self.get_enclosing_box(box) + xc, yc = int((x0 + x1) / 2), int((y0 + y1) / 2) + inside_distance = cv2.pointPolygonTest(region_polygon, (xc, yc), False) + if inside_distance >= 0: + # cv2.circle(im0, (xc, yc), radius=self.line_width * 4, color=self.dc, thickness=-1) + annotator.display_objects_labels( + im0, self.model.names[int(cls)], (104, 31, 17), (255, 255, 255), xc, yc, 10 + ) + region_occupied = True + break + if region_occupied: + occupied_slots += 1 + available_slots -= 1 + # Plot regions + cv2.polylines( + im0, [region_polygon], isClosed=True, color=self.occ if region_occupied else self.arc, thickness=2 + ) + + self.pr_info["Occupancy"], self.pr_info["Available"] = occupied_slots, available_slots + + annotator.display_analytics(im0, self.pr_info, (104, 31, 17), (255, 255, 255), 10) + + plot_im = annotator.result() + self.display_output(plot_im) # Display output with base class function + + # Return SolutionResults + return SolutionResults( + plot_im=plot_im, + filled_slots=self.pr_info["Occupancy"], + available_slots=self.pr_info["Available"], + total_tracks=len(self.track_ids), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/queue_management.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/queue_management.py new file mode 100644 index 0000000000000000000000000000000000000000..c418f778bb8141e51e61005e2f0cd3c5d3c23af2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/queue_management.py @@ -0,0 +1,93 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from typing import Any + +from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults +from ultralytics.utils.plotting import colors + + +class QueueManager(BaseSolution): + """Manages queue counting in real-time video streams based on object tracks. + + This class extends BaseSolution to provide functionality for tracking and counting objects within a specified region + in video frames. + + Attributes: + counts (int): The current count of objects in the queue. + rect_color (tuple[int, int, int]): BGR color tuple for drawing the queue region rectangle. + region_length (int): The number of points defining the queue region. + track_line (list[tuple[int, int]]): List of track line coordinates. + track_history (dict[int, list[tuple[int, int]]]): Dictionary storing tracking history for each object. + + Methods: + initialize_region: Initialize the queue region. + process: Process a single frame for queue management. + extract_tracks: Extract object tracks from the current frame. + store_tracking_history: Store the tracking history for an object. + display_output: Display the processed output. + + Examples: + >>> cap = cv2.VideoCapture("path/to/video.mp4") + >>> queue_manager = QueueManager(region=[(20, 400), (1080, 400), (1080, 360), (20, 360)]) + >>> while cap.isOpened(): + ... success, im0 = cap.read() + ... if not success: + ... break + ... results = queue_manager.process(im0) + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the QueueManager with parameters for tracking and counting objects in a video stream.""" + super().__init__(**kwargs) + self.initialize_region() + self.counts = 0 # Queue counts information + self.rect_color = (255, 255, 255) # Rectangle color for visualization + self.region_length = len(self.region) # Store region length for further usage + + def process(self, im0) -> SolutionResults: + """Process queue management for a single frame of video. + + Args: + im0 (np.ndarray): Input image for processing, typically a frame from a video stream. + + Returns: + (SolutionResults): Contains processed image `plot_im`, 'queue_count' (int, number of objects in the queue) + and 'total_tracks' (int, total number of tracked objects). + + Examples: + >>> queue_manager = QueueManager() + >>> frame = cv2.imread("frame.jpg") + >>> results = queue_manager.process(frame) + """ + self.counts = 0 # Reset counts every frame + self.extract_tracks(im0) # Extract tracks from the current frame + annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator + annotator.draw_region(reg_pts=self.region, color=self.rect_color, thickness=self.line_width * 2) # Draw region + + for box, track_id, cls, conf in zip(self.boxes, self.track_ids, self.clss, self.confs): + # Draw bounding box and counting region + annotator.box_label(box, label=self.adjust_box_label(cls, conf, track_id), color=colors(track_id, True)) + self.store_tracking_history(track_id, box) # Store track history + + # Cache frequently accessed attributes + track_history = self.track_history.get(track_id, []) + + # Store previous position of track and check if the object is inside the counting region + prev_position = None + if len(track_history) > 1: + prev_position = track_history[-2] + if self.region_length >= 3 and prev_position and self.r_s.contains(self.Point(self.track_line[-1])): + self.counts += 1 + + # Display queue counts + annotator.queue_counts_display( + f"Queue Counts : {self.counts}", + points=self.region, + region_color=self.rect_color, + txt_color=(104, 31, 17), + ) + plot_im = annotator.result() + self.display_output(plot_im) # Display output with base class function + + # Return a SolutionResults object with processed data + return SolutionResults(plot_im=plot_im, queue_count=self.counts, total_tracks=len(self.track_ids)) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/region_counter.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/region_counter.py new file mode 100644 index 0000000000000000000000000000000000000000..f72592243aa1270c797b91c765bced7fae76af3e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/region_counter.py @@ -0,0 +1,142 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any + +import numpy as np + +from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults +from ultralytics.utils.plotting import colors + + +class RegionCounter(BaseSolution): + """A class for real-time counting of objects within user-defined regions in a video stream. + + This class inherits from `BaseSolution` and provides functionality to define polygonal regions in a video frame, + track objects, and count those objects that pass through each defined region. Useful for applications requiring + counting in specified areas, such as monitoring zones or segmented sections. + + Attributes: + region_template (dict): Template for creating new counting regions with default attributes including name, + polygon coordinates, and display colors. + counting_regions (list): List storing all defined regions, where each entry is based on `region_template` and + includes specific region settings like name, coordinates, and color. + region_counts (dict): Dictionary storing the count of objects for each named region. + + Methods: + add_region: Add a new counting region with specified attributes. + process: Process video frames to count objects in each region. + initialize_regions: Initialize zones to count the objects in each one. Zones could be multiple as well. + + Examples: + Initialize a RegionCounter and add a counting region + >>> counter = RegionCounter() + >>> counter.add_region("Zone1", [(100, 100), (200, 100), (200, 200), (100, 200)], (255, 0, 0), (255, 255, 255)) + >>> results = counter.process(frame) + >>> print(f"Total tracks: {results.total_tracks}") + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the RegionCounter for real-time object counting in user-defined regions.""" + super().__init__(**kwargs) + self.region_template = { + "name": "Default Region", + "polygon": None, + "prepared_polygon": None, + "counts": 0, + "region_color": (255, 255, 255), + "text_color": (0, 0, 0), + } + self.region_counts = {} + self.counting_regions = [] + self.initialize_regions() + + def add_region( + self, + name: str, + polygon_points: list[tuple], + region_color: tuple[int, int, int], + text_color: tuple[int, int, int], + ) -> dict[str, Any]: + """Add a new region to the counting list based on the provided template with specific attributes. + + Args: + name (str): Name assigned to the new region. + polygon_points (list[tuple]): List of (x, y) coordinates defining the region's polygon. + region_color (tuple[int, int, int]): BGR color for region visualization. + text_color (tuple[int, int, int]): BGR color for the text within the region. + + Returns: + (dict[str, Any]): Region information including name, polygon, and display colors. + """ + if len(polygon_points) < 3: + raise ValueError( + f"RegionCounter requires regions with at least 3 points to form a polygon, " + f"but got {len(polygon_points)} for '{name}'." + ) + polygon = self.Polygon(polygon_points) + region = self.region_template.copy() + region.update( + { + "name": name, + "polygon": polygon, + "prepared_polygon": self.prep(polygon), + "region_color": region_color, + "text_color": text_color, + } + ) + self.counting_regions.append(region) + return region + + def initialize_regions(self): + """Initialize regions from `self.region` only once.""" + if self.region is None: + self.initialize_region() + if not isinstance(self.region, dict): # Ensure self.region is initialized and structured as a dictionary + self.region = {"Region#01": self.region} + for i, (name, pts) in enumerate(self.region.items()): + self.add_region(name, pts, colors(i, True), (255, 255, 255)) + + def process(self, im0: np.ndarray) -> SolutionResults: + """Process the input frame to detect and count objects within each defined region. + + Args: + im0 (np.ndarray): Input image frame where objects and regions are annotated. + + Returns: + (SolutionResults): Contains processed image `plot_im`, 'total_tracks' (int, total number of tracked + objects), and 'region_counts' (dict, counts of objects per region). + """ + self.extract_tracks(im0) + annotator = SolutionAnnotator(im0, line_width=self.line_width) + self.region_counts = {region["name"]: 0 for region in self.counting_regions} + + for box, cls, track_id, conf in zip(self.boxes, self.clss, self.track_ids, self.confs): + annotator.box_label(box, label=self.adjust_box_label(cls, conf, track_id), color=colors(track_id, True)) + x0, y0, x1, y1 = self.get_enclosing_box(box) + center = self.Point(((x0 + x1) / 2, (y0 + y1) / 2)) + for region in self.counting_regions: + if region["prepared_polygon"].contains(center): + region["counts"] += 1 + self.region_counts[region["name"]] = region["counts"] + + # Display region counts + for region in self.counting_regions: + poly = region["polygon"] + pts = list(map(tuple, np.array(poly.exterior.coords, dtype=np.int32))) + (x1, y1), (x2, y2) = [(int(poly.centroid.x), int(poly.centroid.y))] * 2 + annotator.draw_region(pts, region["region_color"], self.line_width * 2) + annotator.adaptive_label( + [x1, y1, x2, y2], + label=str(region["counts"]), + color=region["region_color"], + txt_color=region["text_color"], + margin=self.line_width * 4, + shape="rect", + ) + region["counts"] = 0 # Reset for next frame + plot_im = annotator.result() + self.display_output(plot_im) + + return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids), region_counts=self.region_counts) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/security_alarm.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/security_alarm.py new file mode 100644 index 0000000000000000000000000000000000000000..a0a949f761a1ec431f410cb6a903cf9f35d9d0ed --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/security_alarm.py @@ -0,0 +1,151 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from typing import Any + +from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults +from ultralytics.utils import LOGGER +from ultralytics.utils.plotting import colors + + +class SecurityAlarm(BaseSolution): + """A class to manage security alarm functionalities for real-time monitoring. + + This class extends the BaseSolution class and provides features to monitor objects in a frame, send email + notifications when specific thresholds are exceeded for total detections, and annotate the output frame for + visualization. + + Attributes: + email_sent (bool): Flag to track if an email has already been sent for the current event. + records (int): Threshold for the number of detected objects to trigger an alert. + server (smtplib.SMTP): SMTP server connection for sending email alerts. + to_email (str): Recipient's email address for alerts. + from_email (str): Sender's email address for alerts. + + Methods: + authenticate: Set up email server authentication for sending alerts. + send_email: Send an email notification with details and an image attachment. + process: Monitor the frame, process detections, and trigger alerts if thresholds are crossed. + + Examples: + >>> security = SecurityAlarm() + >>> security.authenticate("abc@gmail.com", "1111222233334444", "xyz@gmail.com") + >>> frame = cv2.imread("frame.jpg") + >>> results = security.process(frame) + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the SecurityAlarm class with parameters for real-time object monitoring. + + Args: + **kwargs (Any): Additional keyword arguments passed to the parent class. + """ + super().__init__(**kwargs) + self.email_sent = False + self.records = self.CFG["records"] + self.server = None + self.to_email = "" + self.from_email = "" + + def authenticate(self, from_email: str, password: str, to_email: str) -> None: + """Authenticate the email server for sending alert notifications. + + This method initializes a secure connection with the SMTP server and logs in using the provided credentials. + + Args: + from_email (str): Sender's email address. + password (str): Password for the sender's email account. + to_email (str): Recipient's email address. + + Examples: + >>> alarm = SecurityAlarm() + >>> alarm.authenticate("sender@example.com", "password123", "recipient@example.com") + """ + import smtplib + + self.server = smtplib.SMTP("smtp.gmail.com", 587) + self.server.starttls() + self.server.login(from_email, password) + self.to_email = to_email + self.from_email = from_email + + def send_email(self, im0, records: int = 5) -> None: + """Send an email notification with an image attachment indicating the number of objects detected. + + This method encodes the input image, composes the email message with details about the detection, and sends it + to the specified recipient. + + Args: + im0 (np.ndarray): The input image or frame to be attached to the email. + records (int, optional): The number of detected objects to be included in the email message. + + Examples: + >>> alarm = SecurityAlarm() + >>> frame = cv2.imread("path/to/image.jpg") + >>> alarm.send_email(frame, records=10) + """ + from email.mime.image import MIMEImage + from email.mime.multipart import MIMEMultipart + from email.mime.text import MIMEText + + import cv2 + + img_bytes = cv2.imencode(".jpg", im0)[1].tobytes() # Encode the image as JPEG + + # Create the email + message = MIMEMultipart() + message["From"] = self.from_email + message["To"] = self.to_email + message["Subject"] = "Security Alert" + + # Add the text message body + message_body = f"Ultralytics alert: {records} object(s) detected." + message.attach(MIMEText(message_body)) + + # Attach the image + image_attachment = MIMEImage(img_bytes, name="ultralytics.jpg") + message.attach(image_attachment) + + # Send the email + try: + self.server.send_message(message) + LOGGER.info("Email sent successfully!") + except Exception as e: + LOGGER.error(f"Failed to send email: {e}") + + def process(self, im0) -> SolutionResults: + """Monitor the frame, process object detections, and trigger alerts if thresholds are met. + + This method processes the input frame, extracts detections, annotates the frame with bounding boxes, and sends + an email notification if the number of detected objects meets or exceeds the specified threshold and an alert + has not already been sent. + + Args: + im0 (np.ndarray): The input image or frame to be processed and annotated. + + Returns: + (SolutionResults): Contains processed image `plot_im`, 'total_tracks' (total number of tracked objects) and + 'email_sent' (whether an email alert was triggered). + + Examples: + >>> alarm = SecurityAlarm() + >>> frame = cv2.imread("path/to/image.jpg") + >>> results = alarm.process(frame) + """ + self.extract_tracks(im0) # Extract tracks + annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator + + # Iterate over bounding boxes and classes index + for box, cls in zip(self.boxes, self.clss): + # Draw bounding box + annotator.box_label(box, label=self.names[cls], color=colors(cls, True)) + + total_det = len(self.clss) + if total_det >= self.records and not self.email_sent and self.server: + self.send_email(im0, total_det) + self.email_sent = True + + plot_im = annotator.result() + self.display_output(plot_im) # Display output with base class function + + # Return a SolutionResults + return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids), email_sent=self.email_sent) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/similarity_search.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/similarity_search.py new file mode 100644 index 0000000000000000000000000000000000000000..1a33e2a53e53f9f9d803836dba8779e07146293d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/similarity_search.py @@ -0,0 +1,222 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import os +from pathlib import Path +from typing import Any + +import numpy as np +from PIL import Image + +from ultralytics.data.utils import IMG_FORMATS +from ultralytics.utils import LOGGER, TORCH_VERSION +from ultralytics.utils.checks import check_requirements +from ultralytics.utils.torch_utils import TORCH_2_4, select_device + +os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" # Avoid OpenMP conflict on some systems + + +class VisualAISearch: + """A semantic image search system that leverages OpenAI's CLIP for generating high-quality image and text embeddings + and NumPy cosine similarity for fast similarity-based retrieval. + + This class aligns image and text embeddings in a shared semantic space, enabling users to search large collections + of images using natural language queries with high accuracy and speed. + + Attributes: + data (str): Directory containing images. + device (str): Computation device, e.g., 'cpu' or 'cuda'. + index_path (str): Path to the numpy file storing image embeddings. + data_path_npy (str): Path to the numpy file storing image paths. + data_dir (Path): Path object for the data directory. + model: Loaded CLIP model. + index (np.ndarray): L2-normalized image embeddings used for cosine similarity search. + image_paths (list[str]): List of image file paths. + + Methods: + extract_image_feature: Extract CLIP embedding from an image. + extract_text_feature: Extract CLIP embedding from text. + load_or_build_index: Load existing embeddings or build them from images. + search: Perform semantic search for similar images. + + Examples: + Initialize and search for images + >>> searcher = VisualAISearch(data="path/to/images", device="cuda") + >>> results = searcher.search("a cat sitting on a chair", k=10) + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the VisualAISearch class with the embedding index and CLIP model.""" + assert TORCH_2_4, f"VisualAISearch requires torch>=2.4 (found torch=={TORCH_VERSION})" + from ultralytics.nn.text_model import build_text_model + + self.index_path = "embeddings.npy" + self.data_path_npy = "paths.npy" + self.data_dir = Path(kwargs.get("data", "images")) + self.device = select_device(kwargs.get("device", "cpu")) + + if not self.data_dir.exists(): + from ultralytics.utils import ASSETS_URL + + LOGGER.warning(f"{self.data_dir} not found. Downloading images.zip from {ASSETS_URL}/images.zip") + from ultralytics.utils.downloads import safe_download + + safe_download(url=f"{ASSETS_URL}/images.zip", unzip=True, retry=3) + self.data_dir = Path("images") + + self.model = build_text_model("clip:ViT-B/32", device=self.device) + + self.index = None + self.image_paths = [] + + self.load_or_build_index() + + def extract_image_feature(self, path: Path) -> np.ndarray: + """Extract CLIP image embedding from the given image path.""" + return self.model.encode_image(Image.open(path)).detach().cpu().numpy() + + def extract_text_feature(self, text: str) -> np.ndarray: + """Extract CLIP text embedding from the given text query.""" + return self.model.encode_text(self.model.tokenize([text])).detach().cpu().numpy() + + @staticmethod + def _normalize(x: np.ndarray) -> np.ndarray: + """L2-normalize each row of `x` so inner products equal cosine similarity. + + Args: + x (np.ndarray): Feature array of shape (N, D). + + Returns: + (np.ndarray): Row-wise L2-normalized array with the same shape as the input. + """ + return x / np.maximum(np.linalg.norm(x, axis=1, keepdims=True), 1e-12) + + def load_or_build_index(self) -> None: + """Load existing image embeddings or build them from the image directory. + + Checks if the embeddings and image paths exist on disk. If found, loads them directly. Otherwise, builds the + index by extracting features from all images in the data directory, L2-normalizes them, and saves both the + embeddings and image paths for future use. + """ + # Check if the embeddings and corresponding image paths already exist + if Path(self.index_path).exists() and Path(self.data_path_npy).exists(): + LOGGER.info("Loading existing embeddings...") + self.index = np.load(self.index_path) # Load the L2-normalized embeddings from disk + self.image_paths = np.load(self.data_path_npy) # Load the saved image path list + return # Exit the function as the index is successfully loaded + + # If the embeddings don't exist, start building them from scratch + LOGGER.info("Building embeddings from images...") + vectors = [] # List to store feature vectors of images + + # Iterate over all image files in the data directory + for file in self.data_dir.iterdir(): + # Skip files that are not valid image formats + if file.suffix.lower().lstrip(".") not in IMG_FORMATS: + continue + try: + # Extract feature vector for the image and add to the list + vectors.append(self.extract_image_feature(file)) + self.image_paths.append(file.name) # Store the corresponding image name + except Exception as e: + LOGGER.warning(f"Skipping {file.name}: {e}") + + # If no vectors were successfully created, raise an error + if not vectors: + raise RuntimeError("No image embeddings could be generated.") + + vectors = np.vstack(vectors).astype("float32") # Stack all vectors into a NumPy array and convert to float32 + self.index = self._normalize(vectors) # L2-normalize so inner product equals cosine similarity + np.save(self.index_path, self.index) # Save the embeddings to disk + np.save(self.data_path_npy, np.array(self.image_paths)) # Save the list of image paths to disk + + LOGGER.info(f"Indexed {len(self.image_paths)} images.") + + def search(self, query: str, k: int = 30, similarity_thresh: float = 0.1) -> list[str]: + """Return top-k semantically similar images to the given query. + + Args: + query (str): Natural language text query to search for. + k (int, optional): Maximum number of results to return. + similarity_thresh (float, optional): Minimum similarity threshold for filtering results. + + Returns: + (list[str]): List of image filenames ranked by similarity score. + + Examples: + Search for images matching a query + >>> searcher = VisualAISearch(data="images") + >>> results = searcher.search("red car", k=5, similarity_thresh=0.2) + """ + text_feat = self._normalize(self.extract_text_feature(query).astype("float32")) + scores = self.index @ text_feat[0] # cosine similarity (embeddings are L2-normalized) + top_k = np.argsort(scores)[::-1][: max(k, 0)] + results = [(self.image_paths[i], float(scores[i])) for i in top_k if scores[i] >= similarity_thresh] + results.sort(key=lambda x: x[1], reverse=True) + + LOGGER.info("\nRanked Results:") + for name, score in results: + LOGGER.info(f" - {name} | Similarity: {score:.4f}") + + return [r[0] for r in results] + + def __call__(self, query: str) -> list[str]: + """Direct call interface for the search function.""" + return self.search(query) + + +class SearchApp: + """A Flask-based web interface for semantic image search with natural language queries. + + This class provides a clean, responsive frontend that enables users to input natural language queries and instantly + view the most relevant images retrieved from the indexed database. + + Attributes: + render_template: Flask template rendering function. + request: Flask request object. + searcher (VisualAISearch): Instance of the VisualAISearch class. + app (Flask): Flask application instance. + + Methods: + index: Process user queries and display search results. + run: Start the Flask web application. + + Examples: + Start a search application + >>> app = SearchApp(data="path/to/images", device="cuda") + >>> app.run(debug=True) + """ + + def __init__(self, data: str = "images", device: str | None = None) -> None: + """Initialize the SearchApp with VisualAISearch backend. + + Args: + data (str, optional): Path to directory containing images to index and search. + device (str, optional): Device to run inference on (e.g. 'cpu', 'cuda'). + """ + check_requirements("flask>=3.0.1") + from flask import Flask, render_template, request + + self.render_template = render_template + self.request = request + self.searcher = VisualAISearch(data=data, device=device) + self.app = Flask( + __name__, + template_folder="templates", + static_folder=Path(data).resolve(), # Absolute path to serve images + static_url_path="/images", # URL prefix for images + ) + self.app.add_url_rule("/", view_func=self.index, methods=["GET", "POST"]) + + def index(self) -> str: + """Process user query and display search results in the web interface.""" + results = [] + if self.request.method == "POST": + query = self.request.form.get("query", "").strip() + results = self.searcher(query) + return self.render_template("similarity-search.html", results=results) + + def run(self, debug: bool = False) -> None: + """Start the Flask web application server.""" + self.app.run(debug=debug) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/solutions.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/solutions.py new file mode 100644 index 0000000000000000000000000000000000000000..5a1da55864efcfff269af9602b38e645e097bc3f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/solutions.py @@ -0,0 +1,867 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import math +from collections import Counter, defaultdict +from functools import lru_cache +from typing import Any + +import cv2 +import numpy as np +import torch + +from ultralytics import YOLO +from ultralytics.solutions.config import SolutionConfig +from ultralytics.utils import ASSETS_URL, LOGGER, ops +from ultralytics.utils.checks import check_imshow, check_requirements +from ultralytics.utils.plotting import Annotator + + +class BaseSolution: + """A base class for managing Ultralytics Solutions. + + This class provides core functionality for various Ultralytics Solutions, including model loading, object tracking, + and region initialization. It serves as the foundation for implementing specific computer vision solutions such as + object counting, pose estimation, and analytics. + + Attributes: + LineString: Class for creating line string geometries from shapely. + Polygon: Class for creating polygon geometries from shapely. + Point: Class for creating point geometries from shapely. + prep: Prepared geometry function from shapely for optimized spatial operations. + CFG (dict[str, Any]): Configuration dictionary loaded from YAML file and updated with kwargs. + LOGGER: Logger instance for solution-specific logging. + annotator: Annotator instance for drawing on images. + tracks: YOLO tracking results from the latest inference. + track_data: Extracted tracking data (boxes or OBB) from tracks. + boxes (list): Bounding box coordinates from tracking results. + clss (list[int]): Class indices from tracking results. + track_ids (list[int]): Track IDs from tracking results. + confs (list[float]): Confidence scores from tracking results. + track_line: Current track line for storing tracking history. + masks: Segmentation masks from tracking results. + r_s: Region or line geometry object for spatial operations. + frame_no (int): Current frame number for logging purposes. + region (list[tuple[int, int]]): List of coordinate tuples defining region of interest. + line_width (int): Width of lines used in visualizations. + model (YOLO): Loaded YOLO model instance. + names (dict[int, str]): Dictionary mapping class indices to class names. + classes (list[int]): List of class indices to track. + show_conf (bool): Flag to show confidence scores in annotations. + show_labels (bool): Flag to show class labels in annotations. + device (str): Device for model inference. + track_add_args (dict[str, Any]): Additional arguments for tracking configuration. + env_check (bool): Flag indicating whether environment supports image display. + track_history (defaultdict): Dictionary storing tracking history for each object. + profilers (tuple): Profiler instances for performance monitoring. + + Methods: + adjust_box_label: Generate formatted label for bounding box. + extract_tracks: Apply object tracking and extract tracks from input image. + store_tracking_history: Store object tracking history for given track ID and bounding box. + initialize_region: Initialize counting region and line segment based on configuration. + display_output: Display processing results including frames or saved results. + process: Process method to be implemented by each Solution subclass. + + Examples: + >>> solution = BaseSolution(model="yolo26n.pt", region=[(0, 0), (100, 0), (100, 100), (0, 100)]) + >>> solution.initialize_region() + >>> image = cv2.imread("image.jpg") + >>> solution.extract_tracks(image) + >>> solution.display_output(image) + """ + + def __init__(self, is_cli: bool = False, **kwargs: Any) -> None: + """Initialize the BaseSolution class with configuration settings and YOLO model. + + Args: + is_cli (bool): Enable CLI mode if set to True. + **kwargs (Any): Additional configuration parameters that override defaults. + """ + self.CFG = vars(SolutionConfig().update(**kwargs)) + self.LOGGER = LOGGER # Store logger object to be used in multiple solution classes + + check_requirements("shapely>=2.0.0") + from shapely.geometry import LineString, Point, Polygon + from shapely.prepared import prep + + self.LineString = LineString + self.Polygon = Polygon + self.Point = Point + self.prep = prep + self.annotator = None # Initialize annotator + self.tracks = None + self.track_data = None + self.boxes = [] + self.clss = [] + self.track_ids = [] + self.track_line = None + self.masks = None + self.r_s = None + self.frame_no = -1 # Only for logging + + self.LOGGER.info(f"Ultralytics Solutions: ✅ {self.CFG}") + self.region = self.CFG["region"] # Store region data for other classes usage + self.line_width = self.CFG["line_width"] + + # Load Model and store additional information (classes, show_conf, show_label) + if self.CFG["model"] is None: + self.CFG["model"] = "yolo26n.pt" + self.model = YOLO(self.CFG["model"]) + self.names = self.model.names + self.classes = self.CFG["classes"] + self.show_conf = self.CFG["show_conf"] + self.show_labels = self.CFG["show_labels"] + self.device = self.CFG["device"] + + self.track_add_args = { # Tracker additional arguments for advance configuration + k: self.CFG[k] for k in ("iou", "conf", "device", "max_det", "quantize", "tracker", "imgsz") + } # verbose must be passed to track method; setting it False in YOLO still logs the track information. + + if is_cli and self.CFG["source"] is None: + d_s = "solutions_ci_demo.mp4" if "-pose" not in self.CFG["model"] else "solution_ci_pose_demo.mp4" + self.LOGGER.warning(f"source not provided. using default source {ASSETS_URL}/{d_s}") + from ultralytics.utils.downloads import safe_download + + safe_download(f"{ASSETS_URL}/{d_s}") # download source from ultralytics assets + self.CFG["source"] = d_s # set default source + + # Initialize environment and region setup + self.env_check = check_imshow(warn=True) + self.track_history = defaultdict(list) + + self.profilers = ( + ops.Profile(device=self.device), # track + ops.Profile(device=self.device), # solution + ) + + def adjust_box_label(self, cls: int, conf: float, track_id: int | None = None) -> str | None: + """Generate a formatted label for a bounding box. + + This method constructs a label string for a bounding box using the class index and confidence score. Optionally + includes the track ID if provided. The label format adapts based on the display settings defined in + `self.show_conf` and `self.show_labels`. + + Args: + cls (int): The class index of the detected object. + conf (float): The confidence score of the detection. + track_id (int, optional): The unique identifier for the tracked object. + + Returns: + (str | None): The formatted label string if `self.show_labels` is True; otherwise, None. + """ + name = ("" if track_id is None else f"{track_id} ") + self.names[cls] + return (f"{name} {conf:.2f}" if self.show_conf else name) if self.show_labels else None + + def extract_tracks(self, im0: np.ndarray) -> None: + """Apply object tracking and extract tracks from an input image or frame. + + Args: + im0 (np.ndarray): The input image or frame. + + Examples: + >>> solution = BaseSolution() + >>> frame = cv2.imread("path/to/image.jpg") + >>> solution.extract_tracks(frame) + """ + with self.profilers[0]: + self.tracks = self.model.track( + source=im0, persist=True, classes=self.classes, verbose=False, **self.track_add_args + )[0] + is_obb = self.tracks.obb is not None + self.track_data = self.tracks.obb if is_obb else self.tracks.boxes # Extract tracks for OBB or object detection + + if self.track_data and self.track_data.is_track: + self.boxes = (self.track_data.xyxyxyxy if is_obb else self.track_data.xyxy).cpu() + self.clss = self.track_data.cls.cpu().tolist() + self.track_ids = self.track_data.id.int().cpu().tolist() + self.confs = self.track_data.conf.cpu().tolist() + else: + self.LOGGER.warning("No tracks found.") + self.boxes, self.clss, self.track_ids, self.confs = [], [], [], [] + self.forget_tracks([track.track_id for track in self.model.predictor.trackers[0].removed_stracks_frame]) + + def forget_tracks(self, track_ids: list[int]) -> None: + """Drop bookkeeping for IDs retired by the active tracker.""" + for track_id in track_ids: + self.track_history.pop(track_id, None) + + def store_tracking_history(self, track_id: int, box) -> None: + """Store the tracking history of an object. + + This method updates the tracking history for a given object by appending the center point of its bounding box to + the track line. It maintains a maximum of 30 points in the tracking history. + + Args: + track_id (int): The unique identifier for the tracked object. + box (list[float]): The bounding box coordinates of the object in the format [x1, y1, x2, y2]. + + Examples: + >>> solution = BaseSolution() + >>> solution.store_tracking_history(1, [100, 200, 300, 400]) + """ + # Store tracking history + self.track_line = self.track_history[track_id] + self.track_line.append(tuple(box.mean(dim=0)) if box.numel() > 4 else (box[:4:2].mean(), box[1:4:2].mean())) + if len(self.track_line) > 30: + self.track_line.pop(0) + + @staticmethod + def get_enclosing_box(box: torch.Tensor | list[float]) -> torch.Tensor | list[float]: + """Return the axis-aligned box [x1, y1, x2, y2] enclosing a box extracted by `extract_tracks`. + + Boxes from OBB models are (4, 2) xyxyxyxy corner points, while boxes from detection models are already + axis-aligned [x1, y1, x2, y2]. This method normalizes both formats to [x1, y1, x2, y2] for solutions that + require axis-aligned coordinates, e.g. for image slicing or box centers. + + Args: + box (torch.Tensor | list[float]): Bounding box in [x1, y1, x2, y2] format or (4, 2) OBB corner points. + + Returns: + (torch.Tensor | list[float]): Axis-aligned bounding box in [x1, y1, x2, y2] format. + + Examples: + >>> import torch + >>> BaseSolution.get_enclosing_box(torch.tensor([[2.0, 1.0], [4.0, 3.0], [2.0, 5.0], [0.0, 3.0]])) + tensor([0., 1., 4., 5.]) + """ + return torch.cat([box.amin(0), box.amax(0)]) if isinstance(box, torch.Tensor) and box.numel() > 4 else box + + def initialize_region(self) -> None: + """Initialize the counting region and line segment based on configuration settings.""" + if self.region is None: + self.region = [(10, 200), (540, 200), (540, 180), (10, 180)] + self.r_s = ( + self.Polygon(self.region) if len(self.region) >= 3 else self.LineString(self.region) + ) # region or line + + def display_output(self, plot_im: np.ndarray) -> None: + """Display the results of the processing, which could involve showing frames, printing counts, or saving + results. + + This method is responsible for visualizing the output of the object detection and tracking process. It displays + the processed frame with annotations, and allows for user interaction to close the display. + + Args: + plot_im (np.ndarray): The image or frame that has been processed and annotated. + + Examples: + >>> solution = BaseSolution() + >>> frame = cv2.imread("path/to/image.jpg") + >>> solution.display_output(frame) + + Notes: + - This method will only display output if the 'show' configuration is set to True and the environment + supports image display. + - The display can be closed by pressing the 'q' key. + """ + if self.CFG.get("show") and self.env_check: + cv2.imshow("Ultralytics Solutions", plot_im) + if cv2.waitKey(1) & 0xFF == ord("q"): + cv2.destroyAllWindows() # Closes current frame window + return + + def process(self, *args: Any, **kwargs: Any): + """Process method should be implemented by each Solution subclass.""" + + def __call__(self, *args: Any, **kwargs: Any): + """Allow instances to be called like a function with flexible arguments.""" + with self.profilers[1]: + result = self.process(*args, **kwargs) # Call the subclass-specific process method + track_or_predict = "predict" if type(self).__name__ == "ObjectCropper" else "track" + track_or_predict_speed = self.profilers[0].dt * 1e3 + solution_speed = (self.profilers[1].dt - self.profilers[0].dt) * 1e3 # solution time = process - track + result.speed = {track_or_predict: track_or_predict_speed, "solution": solution_speed} + if self.CFG["verbose"]: + self.frame_no += 1 + counts = Counter(self.clss) # Only for logging. + # Use model input shape (reflects imgsz) if predictor is available + if hasattr(self.model, "predictor") and self.model.predictor and hasattr(self.model.predictor, "imgsz"): + input_h, input_w = self.model.predictor.imgsz + else: + input_h, input_w = result.plot_im.shape[:2] + LOGGER.info( + f"{self.frame_no}: {input_h}x{input_w} {solution_speed:.1f}ms," + f" {', '.join([f'{v} {self.names[k]}' for k, v in counts.items()])}\n" + f"Speed: {track_or_predict_speed:.1f}ms {track_or_predict}, " + f"{solution_speed:.1f}ms solution per image at shape " + f"(1, {getattr(self.model, 'channels', 3)}, {input_h}, {input_w})\n" + ) + return result + + +class SolutionAnnotator(Annotator): + """A specialized annotator class for visualizing and analyzing computer vision tasks. + + This class extends the base Annotator class, providing additional methods for drawing regions, centroids, tracking + trails, and visual annotations for Ultralytics Solutions. It offers comprehensive visualization capabilities for + various computer vision applications including object detection, tracking, pose estimation, and analytics. + + Attributes: + im (np.ndarray): The image being annotated. + line_width (int): Thickness of lines used in annotations. + font_size (int): Size of the font used for text annotations. + font (str): Path to the font file used for text rendering. + pil (bool): Whether to use PIL for text rendering. + example (str): Example text used to detect non-ASCII labels for PIL rendering. + + Methods: + draw_region: Draw a region using specified points, colors, and thickness. + queue_counts_display: Display queue counts in the specified region. + display_analytics: Display overall statistics for parking lot management. + estimate_pose_angle: Calculate the angle between three points in an object pose. + draw_specific_kpts: Draw specific keypoints on the image. + plot_workout_information: Draw a labeled text box on the image. + plot_angle_and_count_and_stage: Visualize angle, step count, and stage for workout monitoring. + plot_distance_and_line: Display the distance between centroids and connect them with a line. + display_objects_labels: Annotate bounding boxes with object class labels. + sweep_annotator: Visualize a vertical sweep line and optional label. + visioneye: Map and connect object centroids to a visual "eye" point. + adaptive_label: Draw a circular or rectangle background shape label in center of a bounding box. + + Examples: + >>> annotator = SolutionAnnotator(image) + >>> annotator.draw_region([(0, 0), (100, 100)], color=(0, 255, 0), thickness=5) + >>> annotator.display_analytics( + ... image, text={"Available Spots": 5}, txt_color=(0, 0, 0), bg_color=(255, 255, 255), margin=10 + ... ) + """ + + def __init__( + self, + im: np.ndarray, + line_width: int | None = None, + font_size: int | None = None, + font: str = "Arial.ttf", + pil: bool = False, + example: str = "abc", + ): + """Initialize the SolutionAnnotator class with an image for annotation. + + Args: + im (np.ndarray): The image to be annotated. + line_width (int, optional): Line thickness for drawing on the image. + font_size (int, optional): Font size for text annotations. + font (str): Path to the font file. + pil (bool): Indicates whether to use PIL for rendering text. + example (str): Example text used to detect non-ASCII labels for PIL rendering. + """ + super().__init__(im, line_width, font_size, font, pil, example) + + def draw_region( + self, + reg_pts: list[tuple[int, int]] | None = None, + color: tuple[int, int, int] = (0, 255, 0), + thickness: int = 5, + ): + """Draw a region or line on the image. + + Args: + reg_pts (list[tuple[int, int]], optional): Region points (for line 2 points, for region 4+ points). + color (tuple[int, int, int]): BGR color value for the region (OpenCV format). + thickness (int): Line thickness for drawing the region. + """ + cv2.polylines(self.im, [np.array(reg_pts, dtype=np.int32)], isClosed=True, color=color, thickness=thickness) + + # Draw small circles at the corner points + for point in reg_pts: + cv2.circle(self.im, (point[0], point[1]), thickness * 2, color, -1) # -1 fills the circle + + def queue_counts_display( + self, + label: str, + points: list[tuple[int, int]] | None = None, + region_color: tuple[int, int, int] = (255, 255, 255), + txt_color: tuple[int, int, int] = (0, 0, 0), + ): + """Display queue counts on an image centered at the points with customizable font size and colors. + + Args: + label (str): Queue counts label. + points (list[tuple[int, int]], optional): Region points for center point calculation to display text. + region_color (tuple[int, int, int]): BGR queue region color (OpenCV format). + txt_color (tuple[int, int, int]): BGR text color (OpenCV format). + """ + x_values = [point[0] for point in points] + y_values = [point[1] for point in points] + center_x = sum(x_values) // len(points) + center_y = sum(y_values) // len(points) + + text_size = cv2.getTextSize(label, 0, fontScale=self.sf, thickness=self.tf)[0] + text_width = text_size[0] + text_height = text_size[1] + + rect_width = text_width + 20 + rect_height = text_height + 20 + rect_top_left = (center_x - rect_width // 2, center_y - rect_height // 2) + rect_bottom_right = (center_x + rect_width // 2, center_y + rect_height // 2) + cv2.rectangle(self.im, rect_top_left, rect_bottom_right, region_color, -1) + + text_x = center_x - text_width // 2 + text_y = center_y + text_height // 2 + + # Draw text + cv2.putText( + self.im, + label, + (text_x, text_y), + 0, + fontScale=self.sf, + color=txt_color, + thickness=self.tf, + lineType=cv2.LINE_AA, + ) + + def display_analytics( + self, + im0: np.ndarray, + text: dict[str, Any], + txt_color: tuple[int, int, int], + bg_color: tuple[int, int, int], + margin: int, + ): + """Display overall statistics for Solutions (e.g., parking management and object counting). + + Args: + im0 (np.ndarray): Inference image. + text (dict[str, Any]): Labels dictionary. + txt_color (tuple[int, int, int]): Text color (BGR, OpenCV format). + bg_color (tuple[int, int, int]): Background color (BGR, OpenCV format). + margin (int): Gap between text and rectangle for better display. + """ + horizontal_gap = int(im0.shape[1] * 0.02) + vertical_gap = int(im0.shape[0] * 0.01) + text_y_offset = 0 + for label, value in text.items(): + txt = f"{label}: {value}" + text_size = cv2.getTextSize(txt, 0, self.sf, self.tf)[0] + if text_size[0] < 5 or text_size[1] < 5: + text_size = (5, 5) + text_x = im0.shape[1] - text_size[0] - margin * 2 - horizontal_gap + text_y = text_y_offset + text_size[1] + margin * 2 + vertical_gap + rect_x1 = text_x - margin * 2 + rect_y1 = text_y - text_size[1] - margin * 2 + rect_x2 = text_x + text_size[0] + margin * 2 + rect_y2 = text_y + margin * 2 + cv2.rectangle(im0, (rect_x1, rect_y1), (rect_x2, rect_y2), bg_color, -1) + cv2.putText(im0, txt, (text_x, text_y), 0, self.sf, txt_color, self.tf, lineType=cv2.LINE_AA) + text_y_offset = rect_y2 + + @staticmethod + def _point_xy(point: Any) -> tuple[float, float]: + """Convert a keypoint-like object to an (x, y) tuple of floats.""" + if hasattr(point, "detach"): # torch.Tensor + point = point.detach() + if hasattr(point, "cpu"): # torch.Tensor + point = point.cpu() + if hasattr(point, "numpy"): # torch.Tensor + point = point.numpy() + if hasattr(point, "tolist"): # numpy / torch + point = point.tolist() + return float(point[0]), float(point[1]) + + @staticmethod + @lru_cache(maxsize=256) + def _estimate_pose_angle_cached(a: tuple[float, float], b: tuple[float, float], c: tuple[float, float]) -> float: + """Calculate the angle between three points for workout monitoring (cached).""" + radians = math.atan2(c[1] - b[1], c[0] - b[0]) - math.atan2(a[1] - b[1], a[0] - b[0]) + angle = abs(radians * 180.0 / math.pi) + return angle if angle <= 180.0 else (360 - angle) + + @staticmethod + def estimate_pose_angle(a: Any, b: Any, c: Any) -> float: + """Calculate the angle between three points for workout monitoring. + + Args: + a (Any): The coordinates of the first point (e.g. list/tuple/NumPy array/torch tensor). + b (Any): The coordinates of the second point (vertex). + c (Any): The coordinates of the third point. + + Returns: + (float): The angle in degrees between the three points. + """ + a_xy, b_xy, c_xy = ( + SolutionAnnotator._point_xy(a), + SolutionAnnotator._point_xy(b), + SolutionAnnotator._point_xy(c), + ) + return SolutionAnnotator._estimate_pose_angle_cached(a_xy, b_xy, c_xy) + + def draw_specific_kpts( + self, + keypoints: list[list[float]], + indices: list[int] | None = None, + radius: int = 2, + conf_thresh: float = 0.25, + ) -> np.ndarray: + """Draw specific keypoints for gym steps counting. + + Args: + keypoints (list[list[float]]): Keypoints data to be plotted, each in format [x, y, confidence]. + indices (list[int], optional): Keypoint indices to be plotted. The drawing order follows the order of this + list. + radius (int): Keypoint radius. + conf_thresh (float): Confidence threshold for keypoints. + + Returns: + (np.ndarray): Image with drawn keypoints. + + Notes: + Keypoint format: [x, y] or [x, y, confidence]. + Modifies self.im in-place. + """ + indices = indices or [2, 5, 7] + n = len(keypoints) + points = [ + (int(keypoints[j][0]), int(keypoints[j][1])) + for j in indices + if 0 <= j < n and (float(keypoints[j][2]) if len(keypoints[j]) > 2 else 1.0) >= conf_thresh + ] + + # Draw lines between consecutive points + for start, end in zip(points[:-1], points[1:]): + cv2.line(self.im, start, end, (0, 255, 0), 2, lineType=cv2.LINE_AA) + + # Draw circles for keypoints + for pt in points: + cv2.circle(self.im, pt, radius, (0, 0, 255), -1, lineType=cv2.LINE_AA) + + return self.im + + def plot_workout_information( + self, + display_text: str, + position: tuple[int, int], + color: tuple[int, int, int] = (104, 31, 17), + txt_color: tuple[int, int, int] = (255, 255, 255), + ) -> int: + """Draw workout text with a background on the image. + + Args: + display_text (str): The text to be displayed. + position (tuple[int, int]): Coordinates (x, y) on the image where the text will be placed. + color (tuple[int, int, int]): Text background color. + txt_color (tuple[int, int, int]): Text foreground color. + + Returns: + (int): The height of the text. + """ + (text_width, text_height), _ = cv2.getTextSize(display_text, 0, fontScale=self.sf, thickness=self.tf) + + # Draw background rectangle + cv2.rectangle( + self.im, + (position[0], position[1] - text_height - 5), + (position[0] + text_width + 10, position[1] - text_height - 5 + text_height + 10 + self.tf), + color, + -1, + ) + # Draw text + cv2.putText(self.im, display_text, position, 0, self.sf, txt_color, self.tf) + + return text_height + + def plot_angle_and_count_and_stage( + self, + angle_text: str, + count_text: str, + stage_text: str, + center_kpt: list[int], + color: tuple[int, int, int] = (104, 31, 17), + txt_color: tuple[int, int, int] = (255, 255, 255), + ): + """Plot the pose angle, count value, and step stage for workout monitoring. + + Args: + angle_text (str): Angle value for workout monitoring. + count_text (str): Counts value for workout monitoring. + stage_text (str): Stage decision for workout monitoring. + center_kpt (list[int]): Centroid pose index for workout monitoring. + color (tuple[int, int, int]): Text background color. + txt_color (tuple[int, int, int]): Text foreground color. + """ + # Format text + angle_text, count_text, stage_text = f" {angle_text:.2f}", f"Steps : {count_text}", f" {stage_text}" + + # Draw angle, count and stage text + angle_height = self.plot_workout_information( + angle_text, (int(center_kpt[0]), int(center_kpt[1])), color, txt_color + ) + count_height = self.plot_workout_information( + count_text, (int(center_kpt[0]), int(center_kpt[1]) + angle_height + 20), color, txt_color + ) + self.plot_workout_information( + stage_text, (int(center_kpt[0]), int(center_kpt[1]) + angle_height + count_height + 40), color, txt_color + ) + + def plot_distance_and_line( + self, + pixels_distance: float, + centroids: list[tuple[int, int]], + line_color: tuple[int, int, int] = (104, 31, 17), + centroid_color: tuple[int, int, int] = (255, 0, 255), + ): + """Plot the distance and line between two centroids on the frame. + + Args: + pixels_distance (float): Pixel distance between two bounding-box centroids. + centroids (list[tuple[int, int]]): Bounding box centroids data. + line_color (tuple[int, int, int]): Distance line color. + centroid_color (tuple[int, int, int]): Bounding box centroid color. + """ + # Get the text size + text = f"Pixels Distance: {pixels_distance:.2f}" + (text_width_m, text_height_m), _ = cv2.getTextSize(text, 0, self.sf, self.tf) + + # Define corners with 10-pixel margin and draw rectangle + cv2.rectangle(self.im, (15, 25), (15 + text_width_m + 20, 25 + text_height_m + 20), line_color, -1) + + # Calculate the position for the text with a 10-pixel margin and draw text + text_position = (25, 25 + text_height_m + 10) + cv2.putText( + self.im, + text, + text_position, + 0, + self.sf, + (255, 255, 255), + self.tf, + cv2.LINE_AA, + ) + + cv2.line(self.im, centroids[0], centroids[1], line_color, 3) + cv2.circle(self.im, centroids[0], 6, centroid_color, -1) + cv2.circle(self.im, centroids[1], 6, centroid_color, -1) + + def display_objects_labels( + self, + im0: np.ndarray, + text: str, + txt_color: tuple[int, int, int], + bg_color: tuple[int, int, int], + x_center: float, + y_center: float, + margin: int, + ): + """Display the bounding boxes labels in parking management app. + + Args: + im0 (np.ndarray): Inference image. + text (str): Object/class name. + txt_color (tuple[int, int, int]): Display color for text foreground. + bg_color (tuple[int, int, int]): Display color for text background. + x_center (float): The x position center point for bounding box. + y_center (float): The y position center point for bounding box. + margin (int): The gap between text and rectangle for better display. + """ + text_size = cv2.getTextSize(text, 0, fontScale=self.sf, thickness=self.tf)[0] + text_x = x_center - text_size[0] // 2 + text_y = y_center + text_size[1] // 2 + + rect_x1 = text_x - margin + rect_y1 = text_y - text_size[1] - margin + rect_x2 = text_x + text_size[0] + margin + rect_y2 = text_y + margin + cv2.rectangle( + im0, + (int(rect_x1), int(rect_y1)), + (int(rect_x2), int(rect_y2)), + tuple(map(int, bg_color)), # Ensure color values are int + -1, + ) + + cv2.putText( + im0, + text, + (int(text_x), int(text_y)), + 0, + self.sf, + tuple(map(int, txt_color)), # Ensure color values are int + self.tf, + lineType=cv2.LINE_AA, + ) + + def sweep_annotator( + self, + line_x: int = 0, + line_y: int = 0, + label: str | None = None, + color: tuple[int, int, int] = (221, 0, 186), + txt_color: tuple[int, int, int] = (255, 255, 255), + ): + """Draw a sweep annotation line and an optional label. + + Args: + line_x (int): The x-coordinate of the sweep line. + line_y (int): The y-coordinate limit of the sweep line. + label (str, optional): Text label to be drawn in center of sweep line. If None, no label is drawn. + color (tuple[int, int, int]): BGR color for the line and label background (OpenCV format). + txt_color (tuple[int, int, int]): BGR color for the label text (OpenCV format). + """ + # Draw the sweep line + cv2.line(self.im, (line_x, 0), (line_x, line_y), color, self.tf * 2) + + # Draw label, if provided + if label: + (text_width, text_height), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, self.sf, self.tf) + cv2.rectangle( + self.im, + (line_x - text_width // 2 - 10, line_y // 2 - text_height // 2 - 10), + (line_x + text_width // 2 + 10, line_y // 2 + text_height // 2 + 10), + color, + -1, + ) + cv2.putText( + self.im, + label, + (line_x - text_width // 2, line_y // 2 + text_height // 2), + cv2.FONT_HERSHEY_SIMPLEX, + self.sf, + txt_color, + self.tf, + ) + + def visioneye( + self, + box: list[float], + center_point: tuple[int, int], + color: tuple[int, int, int] = (235, 219, 11), + pin_color: tuple[int, int, int] = (255, 0, 255), + ): + """Perform pinpoint human-vision eye mapping and plotting. + + Args: + box (list[float]): Bounding box coordinates in format [x1, y1, x2, y2]. + center_point (tuple[int, int]): Center point for vision eye view. + color (tuple[int, int, int]): Object centroid and line color. + pin_color (tuple[int, int, int]): Visioneye point color. + """ + center_bbox = int((box[0] + box[2]) / 2), int((box[1] + box[3]) / 2) + cv2.circle(self.im, center_point, self.tf * 2, pin_color, -1) + cv2.circle(self.im, center_bbox, self.tf * 2, color, -1) + cv2.line(self.im, center_point, center_bbox, color, self.tf) + + def adaptive_label( + self, + box: tuple[float, float, float, float], + label: str = "", + color: tuple[int, int, int] = (128, 128, 128), + txt_color: tuple[int, int, int] = (255, 255, 255), + shape: str = "rect", + margin: int = 5, + ): + """Draw a label with a background rectangle or circle centered within a given bounding box. + + Args: + box (tuple[float, float, float, float]): The bounding box coordinates (x1, y1, x2, y2). + label (str): The text label to be displayed. + color (tuple[int, int, int]): The background color of the rectangle (B, G, R). + txt_color (tuple[int, int, int]): The color of the text (B, G, R). + shape (str): Label shape. Options: "circle" or "rect". + margin (int): The margin between the text and the rectangle border. + """ + if shape == "circle" and len(label) > 3: + LOGGER.warning(f"Length of label is {len(label)}, only first 3 letters will be used for circle annotation.") + label = label[:3] + + x_center, y_center = int((box[0] + box[2]) / 2), int((box[1] + box[3]) / 2) # Bounding-box center + text_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, self.sf - 0.15, self.tf)[0] # Get size of the text + text_x, text_y = x_center - text_size[0] // 2, y_center + text_size[1] // 2 # Calculate top-left corner of text + + if shape == "circle": + cv2.circle( + self.im, + (x_center, y_center), + int(((text_size[0] ** 2 + text_size[1] ** 2) ** 0.5) / 2) + margin, # Calculate the radius + color, + -1, + ) + else: + cv2.rectangle( + self.im, + (text_x - margin, text_y - text_size[1] - margin), # Calculate coordinates of the rectangle + (text_x + text_size[0] + margin, text_y + margin), # Calculate coordinates of the rectangle + color, + -1, + ) + + # Draw the text on top of the rectangle + cv2.putText( + self.im, + label, + (text_x, text_y), # Calculate top-left corner of the text + cv2.FONT_HERSHEY_SIMPLEX, + self.sf - 0.15, + self.get_txt_color(color, txt_color), + self.tf, + lineType=cv2.LINE_AA, + ) + + +class SolutionResults: + """A class to encapsulate the results of Ultralytics Solutions. + + This class is designed to store and manage various outputs generated by the solution pipeline, including counts, + angles, workout stages, and other analytics data. It provides a structured way to access and manipulate results from + different computer vision solutions such as object counting, pose estimation, and tracking analytics. + + Attributes: + plot_im (np.ndarray): Processed image with counts, blurred, or other effects from solutions. + in_count (int): The total number of "in" counts in a video stream. + out_count (int): The total number of "out" counts in a video stream. + classwise_count (dict[str, int]): A dictionary containing counts of objects categorized by class. + queue_count (int): The count of objects in a queue or waiting area. + workout_count (list[int]): Per-track workout repetition counts (one entry per currently tracked individual). + workout_angle (list[float]): Per-track exercise angles for currently tracked individuals. + workout_stage (list[str]): Per-track current exercise stage for currently tracked individuals. + pixels_distance (float): The calculated distance in pixels between two points or objects. + available_slots (int): The number of available slots in a monitored area. + filled_slots (int): The number of filled slots in a monitored area. + email_sent (bool): A flag indicating whether an email notification was sent. + total_tracks (int): The total number of tracked objects. + region_counts (dict[str, int]): The count of objects within a specific region. + speed_dict (dict[str, float]): A dictionary containing speed information for tracked objects. + total_crop_objects (int): Total number of cropped objects using ObjectCropper class. + speed (dict[str, float]): Performance timing information for tracking and solution processing. + """ + + def __init__(self, **kwargs): + """Initialize a SolutionResults object with default or user-specified values. + + Args: + **kwargs (Any): Optional arguments to override default attribute values. + """ + self.plot_im = None + self.in_count = 0 + self.out_count = 0 + self.classwise_count = {} + self.queue_count = 0 + self.workout_count = [] + self.workout_angle = [] + self.workout_stage = [] + self.pixels_distance = 0.0 + self.available_slots = 0 + self.filled_slots = 0 + self.email_sent = False + self.total_tracks = 0 + self.region_counts = {} + self.speed_dict = {} # for speed estimation + self.total_crop_objects = 0 + self.speed = {} + + # Override with user-defined values + self.__dict__.update(kwargs) + + def __str__(self) -> str: + """Return a formatted string representation of the SolutionResults object. + + Returns: + (str): A string representation listing non-null attributes. + """ + attrs = { + k: v + for k, v in self.__dict__.items() + if k != "plot_im" and v not in [None, {}, 0, 0.0, False] # Exclude `plot_im` explicitly + } + return ", ".join(f"{k}={v}" for k, v in attrs.items()) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/speed_estimation.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/speed_estimation.py new file mode 100644 index 0000000000000000000000000000000000000000..f74086038dc768d9c9d8dcb2a64a073b342fa8b7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/speed_estimation.py @@ -0,0 +1,123 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from collections import deque +from math import sqrt +from typing import Any + +from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults +from ultralytics.utils.plotting import colors + + +class SpeedEstimator(BaseSolution): + """A class to estimate the speed of objects in a real-time video stream based on their tracks. + + This class extends the BaseSolution class and provides functionality for estimating object speeds using tracking + data in video streams. Speed is calculated based on pixel displacement over time and converted to real-world units + using a configurable meters-per-pixel scale factor. + + Attributes: + fps (float): Video frame rate for time calculations. + frame_count (int): Global frame counter for tracking temporal information. + trk_frame_ids (dict): Maps track IDs to their first frame index. + spd (dict): Final speed per object in km/h once locked. + trk_hist (dict): Maps track IDs to deque of position history. + locked_ids (set): Track IDs whose speed has been finalized. + max_hist (int): Required frame history before computing speed. + meter_per_pixel (float): Real-world meters represented by one pixel for scene scale conversion. + max_speed (int): Maximum allowed object speed; values above this will be capped. + + Methods: + process: Process input frames to estimate object speeds based on tracking data. + store_tracking_history: Store the tracking history for an object. + extract_tracks: Extract tracks from the current frame. + display_output: Display the output with annotations. + + Examples: + Initialize speed estimator and process a frame + >>> estimator = SpeedEstimator(meter_per_pixel=0.04, max_speed=120) + >>> frame = cv2.imread("frame.jpg") + >>> results = estimator.process(frame) + >>> cv2.imshow("Speed Estimation", results.plot_im) + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the SpeedEstimator object with speed estimation parameters and data structures. + + Args: + **kwargs (Any): Additional keyword arguments passed to the parent class. + """ + super().__init__(**kwargs) + + self.fps = self.CFG["fps"] # Video frame rate for time calculations + self.frame_count = 0 # Global frame counter + self.trk_frame_ids = {} # Track ID → first frame index + self.spd = {} # Final speed per object (km/h), once locked + self.trk_hist = {} # Track ID → deque of position history + self.locked_ids = set() # Track IDs whose speed has been finalized + self.max_hist = self.CFG["max_hist"] # Required frame history before computing speed + self.meter_per_pixel = self.CFG["meter_per_pixel"] # Scene scale, depends on camera details + self.max_speed = self.CFG["max_speed"] # Maximum speed adjustment + + def forget_tracks(self, track_ids): + """Drop retired IDs from speed bookkeeping so it doesn't grow across a 24/7 stream (see BaseSolution).""" + super().forget_tracks(track_ids) + for track_id in track_ids: + self.trk_hist.pop(track_id, None) + self.trk_frame_ids.pop(track_id, None) + self.spd.pop(track_id, None) + self.locked_ids.discard(track_id) + + def process(self, im0) -> SolutionResults: + """Process an input frame to estimate object speeds based on tracking data. + + Args: + im0 (np.ndarray): Input image for processing with shape (H, W, C) in OpenCV BGR format. + + Returns: + (SolutionResults): Contains processed image `plot_im` and `total_tracks` (number of tracked objects). + + Examples: + Process a frame for speed estimation + >>> estimator = SpeedEstimator() + >>> image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) + >>> results = estimator.process(image) + """ + self.frame_count += 1 + self.extract_tracks(im0) + annotator = SolutionAnnotator(im0, line_width=self.line_width) + + for box, track_id, _, _ in zip(self.boxes, self.track_ids, self.clss, self.confs): + self.store_tracking_history(track_id, box) + + if track_id not in self.trk_hist: # Initialize history if new track found + self.trk_hist[track_id] = deque(maxlen=self.max_hist) + self.trk_frame_ids[track_id] = self.frame_count + + if track_id not in self.locked_ids: # Update history until speed is locked + trk_hist = self.trk_hist[track_id] + trk_hist.append(self.track_line[-1]) + + # Compute and lock speed once enough history is collected + if len(trk_hist) == self.max_hist: + p0, p1 = trk_hist[0], trk_hist[-1] # First and last points of track + dt = (self.frame_count - self.trk_frame_ids[track_id]) / self.fps # Time in seconds + if dt > 0: + dx, dy = p1[0] - p0[0], p1[1] - p0[1] # Pixel displacement + pixel_distance = sqrt(dx * dx + dy * dy) # Calculate pixel distance + meters = pixel_distance * self.meter_per_pixel # Convert to meters + self.spd[track_id] = int( + min((meters / dt) * 3.6, self.max_speed) + ) # Convert to km/h and store final speed + self.locked_ids.add(track_id) # Prevent further updates + self.trk_hist.pop(track_id, None) # Free memory + self.trk_frame_ids.pop(track_id, None) # Remove frame start reference + + if track_id in self.spd: + speed_label = f"{self.spd[track_id]} km/h" + annotator.box_label(box, label=speed_label, color=colors(track_id, True)) # Draw bounding box + + plot_im = annotator.result() + self.display_output(plot_im) # Display output with base class function + + # Return results with processed image and tracking summary + return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids)) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/streamlit_inference.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/streamlit_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..32a448b0d7ecdf90f23b4fc8c090bfe347b9d93c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/streamlit_inference.py @@ -0,0 +1,260 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import io +import os +from typing import Any + +import cv2 +import torch + +from ultralytics import YOLO +from ultralytics.utils import LOGGER +from ultralytics.utils.checks import check_requirements +from ultralytics.utils.downloads import GITHUB_ASSETS_STEMS + +torch.classes.__path__ = [] # Torch module __path__._path issue: https://github.com/datalab-to/marker/issues/442 + + +class Inference: + """A class to perform object detection, image classification, image segmentation and pose estimation inference. + + This class provides functionalities for loading models, configuring settings, uploading video files, and performing + real-time inference using Streamlit and Ultralytics YOLO models. + + Attributes: + st (module): Streamlit module for UI creation. + temp_dict (dict): Temporary dictionary to store the model path and other configuration. + model_path (str): Path to the loaded model. + model (YOLO): The YOLO model instance. + source (str): Selected video source (webcam or video file). + enable_trk (bool): Enable tracking option. + conf (float): Confidence threshold for detection. + iou (float): IoU threshold for non-maximum suppression. + org_frame (Any): Container for the original frame to be displayed. + ann_frame (Any): Container for the annotated frame to be displayed. + vid_file_name (str | int): Name of the uploaded video file or webcam index. + selected_ind (list[int]): List of selected class indices for detection. + + Methods: + web_ui: Set up the Streamlit web interface with custom HTML elements. + sidebar: Configure the Streamlit sidebar for model and inference settings. + source_upload: Handle video file uploads through the Streamlit interface. + configure: Configure the model and load selected classes for inference. + inference: Perform real-time object detection inference. + + Examples: + Create an Inference instance with a custom model + >>> inf = Inference(model="path/to/model.pt") + >>> inf.inference() + + Create an Inference instance with default settings + >>> inf = Inference() + >>> inf.inference() + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the Inference class, checking Streamlit requirements and setting up the model path. + + Args: + **kwargs (Any): Additional keyword arguments for model configuration. + """ + check_requirements("streamlit>=1.29.0") # scope imports for faster ultralytics package load speeds + import streamlit as st + + self.st = st # Reference to the Streamlit module + self.source = None # Video source selection (webcam or video file) + self.img_file_names = [] # List of image file names + self.enable_trk = False # Flag to toggle object tracking + self.conf = 0.25 # Confidence threshold for detection + self.iou = 0.45 # Intersection-over-Union (IoU) threshold for non-maximum suppression + self.org_frame = None # Container for the original frame display + self.ann_frame = None # Container for the annotated frame display + self.vid_file_name = None # Video file name or webcam index + self.selected_ind: list[int] = [] # List of selected class indices for detection + self.model = None # YOLO model instance + + self.temp_dict = {"model": None, **kwargs} + self.model_path = None # Model file path + if self.temp_dict["model"] is not None: + self.model_path = self.temp_dict["model"] + self.imgsz = self.temp_dict.get("imgsz", 640) + + LOGGER.info(f"Ultralytics Solutions: ✅ {self.temp_dict}") + + def web_ui(self) -> None: + """Set up the Streamlit web interface with custom HTML elements.""" + menu_style_cfg = """""" # Hide main menu style + + # Main title of streamlit application + main_title_cfg = """

Ultralytics YOLO Streamlit Application

""" + + # Subtitle of streamlit application + sub_title_cfg = """
Experience real-time object detection on your webcam, videos, and images + with the power of Ultralytics YOLO! 🚀
""" + + # Set html page configuration and append custom HTML + self.st.set_page_config(page_title="Ultralytics Streamlit App", layout="wide") + self.st.markdown(menu_style_cfg, unsafe_allow_html=True) + self.st.markdown(main_title_cfg, unsafe_allow_html=True) + self.st.markdown(sub_title_cfg, unsafe_allow_html=True) + + def sidebar(self) -> None: + """Configure the Streamlit sidebar for model and inference settings.""" + with self.st.sidebar: # Add Ultralytics LOGO + logo = "https://raw.githubusercontent.com/ultralytics/assets/main/logo/Ultralytics_Logotype_Original.svg" + self.st.image(logo, width=250) + + self.st.sidebar.title("User Configuration") # Add elements to vertical setting menu + self.source = self.st.sidebar.selectbox( + "Source", + ("webcam", "video", "image"), + ) # Add source selection dropdown + if self.source in ["webcam", "video"]: + self.enable_trk = self.st.sidebar.radio("Enable Tracking", ("Yes", "No")) == "Yes" # Enable object tracking + self.conf = float( + self.st.sidebar.slider("Confidence Threshold", 0.0, 1.0, self.conf, 0.01) + ) # Slider for confidence + self.iou = float(self.st.sidebar.slider("IoU Threshold", 0.0, 1.0, self.iou, 0.01)) # Slider for NMS threshold + + if self.source != "image": # Only create columns for video/webcam + col1, col2 = self.st.columns(2) # Create two columns for displaying frames + self.org_frame = col1.empty() # Container for original frame + self.ann_frame = col2.empty() # Container for annotated frame + + def source_upload(self) -> None: + """Handle video file uploads through the Streamlit interface.""" + from ultralytics.data.utils import IMG_FORMATS, VID_FORMATS # scope import + + self.vid_file_name = "" + if self.source == "video": + vid_file = self.st.sidebar.file_uploader("Upload Video File", type=VID_FORMATS) + if vid_file is not None: + g = io.BytesIO(vid_file.read()) # BytesIO Object + with open("ultralytics.mp4", "wb") as out: # Open temporary file as bytes + out.write(g.read()) # Read bytes into file + self.vid_file_name = "ultralytics.mp4" + elif self.source == "webcam": + self.vid_file_name = 0 # Use webcam index 0 + elif self.source == "image": + import tempfile # scope import + + if imgfiles := self.st.sidebar.file_uploader( + "Upload Image Files", type=IMG_FORMATS, accept_multiple_files=True + ): + for imgfile in imgfiles: # Save each uploaded image to a temporary file + with tempfile.NamedTemporaryFile(delete=False, suffix=f".{imgfile.name.split('.')[-1]}") as tf: + tf.write(imgfile.read()) + self.img_file_names.append({"path": tf.name, "name": imgfile.name}) + + def configure(self) -> None: + """Configure the model and load selected classes for inference.""" + # Add dropdown menu for model selection, offering the standard size/task grid in order + available_models = [ + f"{size}{task}".replace("yolo", "YOLO") + for size in ("yolo26n", "yolo26s", "yolo26m", "yolo26l", "yolo26x") + for task in ("", "-seg", "-sem", "-depth", "-pose", "-obb", "-cls") + if f"{size}{task}" in GITHUB_ASSETS_STEMS + ] + if self.model_path: # Insert user provided custom model in available_models + available_models.insert(0, self.model_path) + selected_model = self.st.sidebar.selectbox("Model", available_models) + + with self.st.spinner("Model is downloading..."): + if selected_model.endswith((".pt", ".onnx", ".torchscript", ".mlpackage", ".engine")) or any( + fmt in selected_model for fmt in ("openvino_model", "rknn_model") + ): + model_path = selected_model + else: + model_path = f"{selected_model.lower()}.pt" # Default to .pt if no model provided during function call. + self.model = YOLO(model_path) # Load the YOLO model + class_names = list(self.model.names.values()) # Convert dictionary to list of class names + self.st.success("Model loaded successfully!") + + # Multiselect box with class names and get indices of selected classes + selected_classes = self.st.sidebar.multiselect("Classes", class_names, default=class_names[:3]) + self.selected_ind = [class_names.index(option) for option in selected_classes] + + if not isinstance(self.selected_ind, list): # Ensure selected_options is a list + self.selected_ind = list(self.selected_ind) + + def image_inference(self) -> None: + """Perform inference on uploaded images.""" + for img_info in self.img_file_names: + img_path = img_info["path"] + image = cv2.imread(img_path) # Load and display the original image + if image is not None: + self.st.markdown(f"#### Processed: {img_info['name']}") + col1, col2 = self.st.columns(2) + with col1: + self.st.image(image, channels="BGR", caption="Original Image") + results = self.model(image, conf=self.conf, iou=self.iou, classes=self.selected_ind) + annotated_image = results[0].plot() + with col2: + self.st.image(annotated_image, channels="BGR", caption="Predicted Image") + try: # Clean up temporary file + os.unlink(img_path) + except FileNotFoundError: + pass # File doesn't exist, ignore + else: + self.st.error("Could not load the uploaded image.") + + def inference(self) -> None: + """Perform real-time object detection inference on video or webcam feed.""" + self.web_ui() # Initialize the web interface + self.sidebar() # Create the sidebar + self.source_upload() # Upload the video source + self.configure() # Configure the app + + if self.st.sidebar.button("Start"): + if self.source == "image": + if self.img_file_names: + self.image_inference() + else: + self.st.info("Please upload an image file to perform inference.") + return + + stop_button = self.st.sidebar.button("Stop") # Button to stop the inference + cap = cv2.VideoCapture(self.vid_file_name) # Capture the video + if not cap.isOpened(): + self.st.error("Could not open webcam or video source.") + return + + while cap.isOpened(): + success, frame = cap.read() + if not success: + self.st.warning("Failed to read frame from webcam. Please verify the webcam is connected properly.") + break + + # Process frame with model + if self.enable_trk: + results = self.model.track( + frame, conf=self.conf, iou=self.iou, classes=self.selected_ind, imgsz=self.imgsz, persist=True + ) + else: + results = self.model( + frame, conf=self.conf, iou=self.iou, classes=self.selected_ind, imgsz=self.imgsz + ) + + annotated_frame = results[0].plot() # Add annotations on frame + + if stop_button: + cap.release() # Release the capture + self.st.stop() # Stop streamlit app + + self.org_frame.image(frame, channels="BGR", caption="Original Frame") # Display original frame + self.ann_frame.image(annotated_frame, channels="BGR", caption="Predicted Frame") # Display processed + + cap.release() # Release the capture + cv2.destroyAllWindows() # Destroy all OpenCV windows + + +if __name__ == "__main__": + import sys # Import the sys module for accessing command-line arguments + + # Check if a model name is provided as a command-line argument + args = len(sys.argv) + model = sys.argv[1] if args > 1 else None # Assign first argument as the model name if provided + # Create an instance of the Inference class and run inference + Inference(model=model).inference() diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/templates/similarity-search.html b/.venv/lib/python3.12/site-packages/ultralytics/solutions/templates/similarity-search.html new file mode 100644 index 0000000000000000000000000000000000000000..da34e235382f0c396c0a0a8f0c6298b886c7892f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/templates/similarity-search.html @@ -0,0 +1,156 @@ + + + + + + + + + Semantic Image Search + + + + + +
+ Ultralytics Logo +
+

Semantic Image Search with AI

+ + +
+ + + {% if results %} +
+ + + +
+ {% endif %} +
+ + +
+ {% for img in results %} +
+ Result Image +
+ {% endfor %} +
+ + diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/trackzone.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/trackzone.py new file mode 100644 index 0000000000000000000000000000000000000000..fd4159045c8c74b801700aab87d51a90413bc42e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/trackzone.py @@ -0,0 +1,88 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from typing import Any + +import cv2 +import numpy as np + +from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults +from ultralytics.utils.plotting import colors + + +class TrackZone(BaseSolution): + """A class to manage region-based object tracking in a video stream. + + This class extends the BaseSolution class and provides functionality for tracking objects within a specific region + defined by a polygonal area. Objects outside the region are excluded from tracking. + + Attributes: + region (np.ndarray): The polygonal region for tracking, represented as a convex hull of points. + line_width (int): Width of the lines used for drawing bounding boxes and region boundaries. + names (dict[int, str]): Dictionary mapping class indices to class names. + boxes (list[np.ndarray]): Bounding boxes of tracked objects. + track_ids (list[int]): Unique identifiers for each tracked object. + clss (list[int]): Class indices of tracked objects. + + Methods: + process: Process each frame of the video, applying region-based tracking. + extract_tracks: Extract tracking information from the input frame. + display_output: Display the processed output. + + Examples: + >>> tracker = TrackZone() + >>> frame = cv2.imread("frame.jpg") + >>> results = tracker.process(frame) + >>> cv2.imshow("Tracked Frame", results.plot_im) + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the TrackZone class for tracking objects within a defined region in video streams. + + Args: + **kwargs (Any): Additional keyword arguments passed to the parent class. + """ + super().__init__(**kwargs) + default_region = [(75, 75), (565, 75), (565, 285), (75, 285)] + self.region = cv2.convexHull(np.array(self.region or default_region, dtype=np.int32)) + self.mask = None + + def process(self, im0: np.ndarray) -> SolutionResults: + """Process the input frame to track objects within a defined region. + + This method initializes the annotator, creates a mask for the specified region, extracts tracks only from the + masked area, and updates tracking information. Objects outside the region are ignored. + + Args: + im0 (np.ndarray): The input image or frame to be processed. + + Returns: + (SolutionResults): Contains processed image `plot_im` and `total_tracks` (int) representing the total number + of tracked objects within the defined region. + + Examples: + >>> tracker = TrackZone() + >>> frame = cv2.imread("path/to/image.jpg") + >>> results = tracker.process(frame) + """ + annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator + + if self.mask is None: # Create a mask for the region + self.mask = np.zeros_like(im0[:, :, 0]) + cv2.fillPoly(self.mask, [self.region], 255) + masked_frame = cv2.bitwise_and(im0, im0, mask=self.mask) + self.extract_tracks(masked_frame) + + # Draw the region boundary + cv2.polylines(im0, [self.region], isClosed=True, color=(255, 255, 255), thickness=self.line_width * 2) + + # Iterate over boxes, track ids, classes indexes list and draw bounding boxes + for box, track_id, cls, conf in zip(self.boxes, self.track_ids, self.clss, self.confs): + annotator.box_label( + box, label=self.adjust_box_label(cls, conf, track_id=track_id), color=colors(track_id, True) + ) + + plot_im = annotator.result() + self.display_output(plot_im) # Display output with base class function + + # Return a SolutionResults + return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids)) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/solutions/vision_eye.py b/.venv/lib/python3.12/site-packages/ultralytics/solutions/vision_eye.py new file mode 100644 index 0000000000000000000000000000000000000000..b95320b976d1216d0a48b586d8b1911bea919b40 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/solutions/vision_eye.py @@ -0,0 +1,67 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from typing import Any + +from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults +from ultralytics.utils.plotting import colors + + +class VisionEye(BaseSolution): + """A class to manage object detection and vision mapping in images or video streams. + + This class extends the BaseSolution class and provides functionality for detecting objects, mapping vision points, + and annotating results with bounding boxes and labels. + + Attributes: + vision_point (tuple[int, int]): Coordinates (x, y) where vision will view objects and draw tracks. + + Methods: + process: Process the input image to detect objects, annotate them, and apply vision mapping. + + Examples: + >>> vision_eye = VisionEye() + >>> frame = cv2.imread("frame.jpg") + >>> results = vision_eye.process(frame) + >>> print(f"Total detected instances: {results.total_tracks}") + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the VisionEye class for detecting objects and applying vision mapping. + + Args: + **kwargs (Any): Keyword arguments passed to the parent class and for configuring vision_point. + """ + super().__init__(**kwargs) + # Set the vision point where the system will view objects and draw tracks + self.vision_point = self.CFG["vision_point"] + + def process(self, im0) -> SolutionResults: + """Perform object detection, vision mapping, and annotation on the input image. + + Args: + im0 (np.ndarray): The input image for detection and annotation. + + Returns: + (SolutionResults): Object containing the annotated image and tracking statistics. + - plot_im: Annotated output image with bounding boxes and vision mapping + - total_tracks: Number of tracked objects in the frame + + Examples: + >>> vision_eye = VisionEye() + >>> frame = cv2.imread("image.jpg") + >>> results = vision_eye.process(frame) + >>> print(f"Detected {results.total_tracks} objects") + """ + self.extract_tracks(im0) # Extract tracks (bounding boxes, classes, and masks) + annotator = SolutionAnnotator(im0, self.line_width) + + for cls, t_id, box, conf in zip(self.clss, self.track_ids, self.boxes, self.confs): + # Annotate the image with bounding boxes, labels, and vision mapping + annotator.box_label(box, label=self.adjust_box_label(cls, conf, t_id), color=colors(int(t_id), True)) + annotator.visioneye(self.get_enclosing_box(box), self.vision_point) + + plot_im = annotator.result() + self.display_output(plot_im) # Display the annotated output using the base class function + + # Return a SolutionResults object with the annotated image and tracking statistics + return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids)) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..77ad699d51ac3a06349af3862b15290f562c996d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__init__.py @@ -0,0 +1,19 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .bot_sort import BOTSORT +from .byte_tracker import BYTETracker +from .deep_oc_sort import DeepOCSORT +from .fast_tracker import FASTTracker +from .oc_sort import OCSORT +from .track import register_tracker +from .track_tracker import TRACKTRACK + +__all__ = ( + "BOTSORT", + "OCSORT", + "TRACKTRACK", + "BYTETracker", + "DeepOCSORT", + "FASTTracker", + "register_tracker", +) # allow simpler import diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bebb7725ae38f9885cc6b9be6a3eff967deadba4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/basetrack.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/basetrack.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8c881909d3ba315b17d6845b701497525d955c0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/basetrack.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/bot_sort.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/bot_sort.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc2257c294f2f2031ee2be83532100697fdb846c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/bot_sort.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/byte_tracker.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/byte_tracker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9141570885c781b701e83ce0df19173d232b7e2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/byte_tracker.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/deep_oc_sort.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/deep_oc_sort.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a0211418c1f75d867853b0cff0d7be5d1c1af7f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/deep_oc_sort.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/fast_tracker.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/fast_tracker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50bcd42d9f75eecb7ce6e087455816d0687a4477 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/fast_tracker.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/oc_sort.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/oc_sort.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..935c9c1f751456a8c24165e5fddb7180e2e14639 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/oc_sort.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/track.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/track.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de6773bb116e5a422be7211f1f245ec3aa870a01 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/track.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/track_tracker.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/track_tracker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1f06178dc7795129d6972c272044bfabd87288e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/__pycache__/track_tracker.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/basetrack.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/basetrack.py new file mode 100644 index 0000000000000000000000000000000000000000..1c5158801cbcfe45e49517b2adb2c5efc940974d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/basetrack.py @@ -0,0 +1,102 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Module defines the base classes and structures for object tracking in YOLO.""" + +from typing import Any + + +class TrackState: + """Enumeration class representing the possible states of an object being tracked. + + Attributes: + New (int): State when the object is newly detected. + Tracked (int): State when the object is successfully tracked in subsequent frames. + Lost (int): State when the object is no longer tracked. + Removed (int): State when the object is removed from tracking. + + Examples: + >>> state = TrackState.New + >>> if state == TrackState.New: + ... print("Object is newly detected.") + """ + + New = 0 + Tracked = 1 + Lost = 2 + Removed = 3 + + +class BaseTrack: + """Base class for object tracking, providing foundational attributes and methods. + + Attributes: + _count (int): Class-level counter for unique track IDs. + track_id (int): Unique identifier for the track. + is_activated (bool): Flag indicating whether the track is currently active. + state (TrackState): Current state of the track. + score (float): The confidence score of the tracking. + start_frame (int): The frame number where tracking started. + frame_id (int): The most recent frame ID processed by the track. + + Methods: + end_frame: Returns the ID of the last frame where the object was tracked. + next_id: Increments and returns the next global track ID. + activate: Abstract method to activate the track. + predict: Abstract method to predict the next state of the track. + update: Abstract method to update the track with new data. + mark_lost: Marks the track as lost. + mark_removed: Marks the track as removed. + reset_id: Resets the global track ID counter. + + Examples: + Initialize a new track and mark it as lost: + >>> track = BaseTrack() + >>> track.mark_lost() + >>> print(track.state) # Output: 2 (TrackState.Lost) + """ + + _count = 0 + + def __init__(self): + """Initialize a new track with a unique ID and foundational tracking attributes.""" + self.track_id = 0 + self.is_activated = False + self.state = TrackState.New + self.score = 0 + self.start_frame = 0 + self.frame_id = 0 + + @property + def end_frame(self) -> int: + """Return the ID of the most recent frame where the object was tracked.""" + return self.frame_id + + @staticmethod + def next_id() -> int: + """Increment and return the next unique global track ID for object tracking.""" + BaseTrack._count += 1 + return BaseTrack._count + + def activate(self, *args: Any) -> None: + """Activate the track with provided arguments, initializing necessary attributes for tracking.""" + raise NotImplementedError + + def predict(self) -> None: + """Predict the next state of the track based on the current state and tracking model.""" + raise NotImplementedError + + def update(self, *args: Any, **kwargs: Any) -> None: + """Update the track with new observations and data, modifying its state and attributes accordingly.""" + raise NotImplementedError + + def mark_lost(self) -> None: + """Mark the track as lost by updating its state to TrackState.Lost.""" + self.state = TrackState.Lost + + def mark_removed(self) -> None: + """Mark the track as removed by setting its state to TrackState.Removed.""" + self.state = TrackState.Removed + + @staticmethod + def reset_id() -> None: + """Reset the global track ID counter to its initial value.""" + BaseTrack._count = 0 diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/bot_sort.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/bot_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..cf62e8c8b26bb4dc33c825315f64372c3f78d696 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/bot_sort.py @@ -0,0 +1,212 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any + +import numpy as np + +from .basetrack import TrackState +from .byte_tracker import BYTETracker, STrack +from .utils import matching +from .utils.gmc import GMC +from .utils.kalman_filter import KalmanFilterXYWH +from .utils.reid import build_encoder, smooth_feature +from .utils.stracks import parse_bboxes + + +class BOTrack(STrack): + """An extended version of the STrack class for YOLO, adding object tracking features. + + This class extends the STrack class to include additional functionalities for object tracking, such as feature + smoothing, Kalman filter prediction, and reactivation of tracks. + + Attributes: + shared_kalman (KalmanFilterXYWH): A shared Kalman filter for all instances of BOTrack. + smooth_feat (np.ndarray): Smoothed feature vector. + curr_feat (np.ndarray): Current feature vector. + alpha (float): Smoothing factor for the exponential moving average of features. + mean (np.ndarray): The mean state of the Kalman filter. + covariance (np.ndarray): The covariance matrix of the Kalman filter. + + Methods: + update_features: Update features vector and smooth it using exponential moving average. + predict: Predict the mean and covariance using Kalman filter. + re_activate: Reactivate a track with updated features and optionally new ID. + update: Update the track with new detection and frame ID. + tlwh: Property that gets the current position in tlwh format `(top left x, top left y, width, height)`. + multi_predict: Predict the mean and covariance of multiple object tracks using shared Kalman filter. + convert_coords: Convert tlwh bounding box coordinates to xywh format. + tlwh_to_xywh: Convert bounding box to xywh format `(center x, center y, width, height)`. + + Examples: + Create a BOTrack instance and update its features + >>> bo_track = BOTrack(xywh=np.array([100, 50, 80, 40, 0]), score=0.9, cls=1, feat=np.random.rand(128)) + >>> bo_track.activate(KalmanFilterXYWH(), frame_id=1) + >>> bo_track.predict() + >>> new_track = BOTrack(xywh=np.array([110, 60, 80, 40, 0]), score=0.85, cls=1, feat=np.random.rand(128)) + >>> bo_track.update(new_track, frame_id=2) + """ + + shared_kalman = KalmanFilterXYWH() + + def __init__(self, xywh: np.ndarray, score: float, cls: int, feat: np.ndarray | None = None): + """Initialize a BOTrack object with feature-smoothing state and a Kalman filter. + + Args: + xywh (np.ndarray): Bounding box in `(x, y, w, h, idx)` or `(x, y, w, h, angle, idx)` format, where (x, y) is + the center, (w, h) are width and height, and `idx` is the detection index. + score (float): Confidence score of the detection. + cls (int): Class ID of the detected object. + feat (np.ndarray, optional): Feature vector associated with the detection. + """ + super().__init__(xywh, score, cls) + + self.smooth_feat = None + self.curr_feat = None + self.alpha = 0.9 + if feat is not None: + self.update_features(feat) + + def update_features(self, feat: np.ndarray) -> None: + """Update the current feature and its exponential-moving-average smoothed feature.""" + curr, smooth = smooth_feature(feat, self.smooth_feat, self.alpha) + if curr is not None: + self.curr_feat, self.smooth_feat = curr, smooth + + def predict(self) -> None: + """Predict the object's future state using the Kalman filter to update its mean and covariance.""" + mean_state = self.mean.copy() + if self.state != TrackState.Tracked: + mean_state[6] = 0 + mean_state[7] = 0 + + self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance) + + def re_activate(self, new_track: BOTrack, frame_id: int, new_id: bool = False) -> None: + """Reactivate a track with updated features and optionally assign a new ID.""" + if new_track.curr_feat is not None: + self.update_features(new_track.curr_feat) + super().re_activate(new_track, frame_id, new_id) + + def update(self, new_track: BOTrack, frame_id: int) -> None: + """Update the track with new detection information and the current frame ID.""" + if new_track.curr_feat is not None: + self.update_features(new_track.curr_feat) + super().update(new_track, frame_id) + + @property + def tlwh(self) -> np.ndarray: + """Return the current bounding box position in `(top left x, top left y, width, height)` format.""" + if self.mean is None: + return self._tlwh.copy() + ret = self.mean[:4].copy() + ret[:2] -= ret[2:] / 2 + return ret + + @staticmethod + def multi_predict(stracks: list[BOTrack]) -> None: + """Predict the mean and covariance for multiple object tracks using a shared Kalman filter.""" + if not stracks: + return + multi_mean = np.asarray([st.mean for st in stracks]) + multi_covariance = np.asarray([st.covariance for st in stracks]) + for i, st in enumerate(stracks): + if st.state != TrackState.Tracked: + multi_mean[i][6] = 0 + multi_mean[i][7] = 0 + multi_mean, multi_covariance = BOTrack.shared_kalman.multi_predict(multi_mean, multi_covariance) + for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)): + stracks[i].mean = mean + stracks[i].covariance = cov + + def convert_coords(self, tlwh: np.ndarray) -> np.ndarray: + """Convert tlwh bounding box coordinates to xywh format.""" + return self.tlwh_to_xywh(tlwh) + + @staticmethod + def tlwh_to_xywh(tlwh: np.ndarray) -> np.ndarray: + """Convert bounding box from tlwh (top-left-width-height) to xywh (center-x-center-y-width-height) format.""" + ret = np.asarray(tlwh).copy() + ret[:2] += ret[2:] / 2 + return ret + + +class BOTSORT(BYTETracker): + """An extended version of the BYTETracker class for YOLO, designed for object tracking with ReID and GMC algorithm. + + Attributes: + proximity_thresh (float): Threshold for spatial proximity (IoU) between tracks and detections. + appearance_thresh (float): Threshold for appearance similarity (ReID embeddings) between tracks and detections. + encoder (Any): Object to handle ReID embeddings, set to None if ReID is not enabled. + gmc (GMC): An instance of the GMC algorithm for data association. + args (Any): Parsed command-line arguments containing tracking parameters. + + Methods: + get_kalmanfilter: Return an instance of KalmanFilterXYWH for object tracking. + init_track: Initialize track with detection results and optional image for ReID. + get_dists: Get distances between tracks and detections using IoU and (optionally) ReID. + multi_predict: Predict the mean and covariance of multiple object tracks using a shared Kalman filter. + reset: Reset the BOTSORT tracker to its initial state. + + Examples: + Initialize BOTSORT and process detections + >>> bot_sort = BOTSORT(args) + >>> bot_sort.init_track(results, img) + >>> bot_sort.multi_predict(tracks) + + Notes: + The class is designed to work with a YOLO object detection model and supports ReID only if enabled via args. + """ + + def __init__(self, args: Any): + """Initialize BOTSORT object with ReID module and GMC algorithm. + + Args: + args (Any): Parsed command-line arguments containing tracking parameters. + """ + super().__init__(args) + self.gmc = GMC(method=args.gmc_method) + + # ReID module + self.proximity_thresh = args.proximity_thresh + self.appearance_thresh = args.appearance_thresh + self.encoder = build_encoder(args.with_reid, args.model, getattr(args, "device", None)) + + def get_kalmanfilter(self) -> KalmanFilterXYWH: + """Return an instance of KalmanFilterXYWH for predicting and updating object states in the tracking process.""" + return KalmanFilterXYWH() + + def init_track(self, results, img: np.ndarray | None = None) -> list[BOTrack]: + """Initialize object tracks using detection bounding boxes, scores, class labels, and optional ReID features.""" + if len(results) == 0: + return [] + bboxes = parse_bboxes(results) + if self.args.with_reid and self.encoder is not None and img is not None: + features_keep = self.encoder(img, bboxes) + return [BOTrack(xywh, s, c, f) for (xywh, s, c, f) in zip(bboxes, results.conf, results.cls, features_keep)] + return [BOTrack(xywh, s, c) for (xywh, s, c) in zip(bboxes, results.conf, results.cls)] + + def get_dists(self, tracks: list[BOTrack], detections: list[BOTrack]) -> np.ndarray: + """Calculate distances between tracks and detections using IoU and optionally ReID embeddings.""" + dists = matching.iou_distance(tracks, detections) + dists_mask = dists > (1 - self.proximity_thresh) + + if self.args.fuse_score: + dists = matching.fuse_score(dists, detections) + + if self.args.with_reid and self.encoder is not None: + emb_dists = matching.embedding_distance(tracks, detections) / 2.0 + emb_dists[emb_dists > (1 - self.appearance_thresh)] = 1.0 + emb_dists[dists_mask] = 1.0 + dists = np.minimum(dists, emb_dists) + return dists + + def multi_predict(self, tracks: list[BOTrack]) -> None: + """Predict the mean and covariance of multiple object tracks using a shared Kalman filter.""" + BOTrack.multi_predict(tracks) + + def reset(self) -> None: + """Reset the BOTSORT tracker to its initial state, clearing all tracked objects and internal states.""" + super().reset() + self.gmc.reset_params() diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/byte_tracker.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/byte_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..b9513d3db4ab4d6a81a8d5c33ada0dcf4137c0a3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/byte_tracker.py @@ -0,0 +1,530 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any + +import numpy as np + +from ..utils import LOGGER +from ..utils.ops import xywh2ltwh +from .basetrack import BaseTrack, TrackState +from .utils import matching +from .utils.kalman_filter import KalmanFilterXYAH +from .utils.stracks import joint_stracks, merge_track_pools, multi_gmc, parse_bboxes + + +class STrack(BaseTrack): + """Single object tracking representation that uses Kalman filtering for state estimation. + + This class is responsible for storing all the information regarding individual tracklets and performs state updates + and predictions based on Kalman filter. + + Attributes: + shared_kalman (KalmanFilterXYAH): Shared Kalman filter used across all STrack instances for prediction. + _tlwh (np.ndarray): Private attribute to store top-left corner coordinates and width and height of bounding box. + kalman_filter (KalmanFilterXYAH): Instance of Kalman filter used for this particular object track. + mean (np.ndarray): Mean state estimate vector. + covariance (np.ndarray): Covariance of state estimate. + is_activated (bool): Boolean flag indicating if the track has been activated. + score (float): Confidence score of the track. + tracklet_len (int): Length of the tracklet. + cls (Any): Class label for the object. + idx (int): Index or identifier for the object. + frame_id (int): Current frame ID. + start_frame (int): Frame where the object was first detected. + angle (float | None): Optional angle information for oriented bounding boxes. + + Methods: + predict: Predict the next state of the object using Kalman filter. + multi_predict: Predict the next states for multiple tracks. + activate: Activate a new tracklet. + re_activate: Reactivate a previously lost tracklet. + update: Update the state of a matched track. + convert_coords: Convert bounding box to x-y-aspect-height format. + tlwh_to_xyah: Convert tlwh bounding box to xyah format. + + Examples: + Initialize and activate a new track + >>> track = STrack(xywh=np.array([100, 200, 50, 80, 0]), score=0.9, cls="person") + >>> track.activate(kalman_filter=KalmanFilterXYAH(), frame_id=1) + """ + + shared_kalman = KalmanFilterXYAH() + + def __init__(self, xywh: np.ndarray, score: float, cls: Any): + """Initialize a new STrack instance. + + Args: + xywh (np.ndarray): Bounding box in `(x, y, w, h, idx)` or `(x, y, w, h, angle, idx)` format, where (x, y) is + the center, (w, h) are width and height, and `idx` is the detection index. + score (float): Confidence score of the detection. + cls (Any): Class label for the detected object. + """ + super().__init__() + # xywh+idx or xywha+idx + assert len(xywh) in {5, 6}, f"expected 5 or 6 values but got {len(xywh)}" + self._tlwh = np.asarray(xywh2ltwh(xywh[:4]), dtype=np.float32) + self.kalman_filter = None + self.mean, self.covariance = None, None + self.is_activated = False + + self.score = score + self.tracklet_len = 0 + self.cls = cls + self.idx = xywh[-1] + self.angle = xywh[4] if len(xywh) == 6 else None + + def predict(self): + """Predict the next state (mean and covariance) of the object using the Kalman filter.""" + mean_state = self.mean.copy() + if self.state != TrackState.Tracked: + mean_state[7] = 0 + self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance) + + @staticmethod + def multi_predict(stracks: list[STrack]): + """Perform multi-object predictive tracking using Kalman filter for the provided list of STrack instances.""" + if not stracks: + return + multi_mean = np.asarray([st.mean for st in stracks]) + multi_covariance = np.asarray([st.covariance for st in stracks]) + for i, st in enumerate(stracks): + if st.state != TrackState.Tracked: + multi_mean[i][7] = 0 + multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance) + for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)): + stracks[i].mean = mean + stracks[i].covariance = cov + + def activate(self, kalman_filter: KalmanFilterXYAH, frame_id: int): + """Activate a new tracklet using the provided Kalman filter and initialize its state and covariance.""" + self.kalman_filter = kalman_filter + self.track_id = self.next_id() + self.mean, self.covariance = self.kalman_filter.initiate(self.convert_coords(self._tlwh)) + + self.tracklet_len = 0 + self.state = TrackState.Tracked + if frame_id == 1: + self.is_activated = True + self.frame_id = frame_id + self.start_frame = frame_id + + def re_activate(self, new_track: STrack, frame_id: int, new_id: bool = False): + """Reactivate a previously lost track using new detection data and update its state and attributes.""" + self.mean, self.covariance = self.kalman_filter.update( + self.mean, self.covariance, self.convert_coords(new_track.tlwh) + ) + self.tracklet_len = 0 + self.state = TrackState.Tracked + self.is_activated = True + self.frame_id = frame_id + if new_id: + self.track_id = self.next_id() + self.score = new_track.score + self.cls = new_track.cls + self.angle = new_track.angle + self.idx = new_track.idx + + def update(self, new_track: STrack, frame_id: int): + """Update the state of a matched track. + + Args: + new_track (STrack): The new track containing updated information. + frame_id (int): The ID of the current frame. + + Examples: + Update the state of a track with new detection information + >>> track = STrack(np.array([100, 200, 50, 80, 0]), score=0.9, cls=0) + >>> track.activate(KalmanFilterXYAH(), 1) + >>> new_track = STrack(np.array([105, 205, 55, 85, 0]), score=0.95, cls=0) + >>> track.update(new_track, 2) + """ + self.frame_id = frame_id + self.tracklet_len += 1 + + new_tlwh = new_track.tlwh + self.mean, self.covariance = self.kalman_filter.update( + self.mean, self.covariance, self.convert_coords(new_tlwh) + ) + self.state = TrackState.Tracked + self.is_activated = True + + self.score = new_track.score + self.cls = new_track.cls + self.angle = new_track.angle + self.idx = new_track.idx + + def convert_coords(self, tlwh: np.ndarray) -> np.ndarray: + """Convert a bounding box's top-left-width-height format to its x-y-aspect-height equivalent.""" + return self.tlwh_to_xyah(tlwh) + + @property + def tlwh(self) -> np.ndarray: + """Get the bounding box in top-left-width-height format from the current state estimate.""" + if self.mean is None: + return self._tlwh.copy() + ret = self.mean[:4].copy() + ret[2] *= ret[3] + ret[:2] -= ret[2:] / 2 + return ret + + @property + def xyxy(self) -> np.ndarray: + """Convert bounding box from (top left x, top left y, width, height) to (min x, min y, max x, max y) format.""" + ret = self.tlwh # already a fresh array, safe to mutate + ret[2:] += ret[:2] + return ret + + @staticmethod + def tlwh_to_xyah(tlwh: np.ndarray) -> np.ndarray: + """Convert bounding box from tlwh format to center-x-center-y-aspect-height (xyah) format.""" + ret = np.asarray(tlwh).copy() + ret[:2] += ret[2:] / 2 + ret[2] /= ret[3] + return ret + + @property + def xywh(self) -> np.ndarray: + """Get the current position of the bounding box in (center x, center y, width, height) format.""" + ret = np.asarray(self.tlwh).copy() + ret[:2] += ret[2:] / 2 + return ret + + @property + def xywha(self) -> np.ndarray: + """Get position in (center x, center y, width, height, angle) format, warning if angle is missing.""" + if self.angle is None: + LOGGER.warning("`angle` attr not found, returning `xywh` instead.") + return self.xywh + return np.concatenate([self.xywh, self.angle[None]]) + + @property + def result(self) -> list[float]: + """Get the current tracking results in the appropriate bounding box format.""" + coords = self.xyxy if self.angle is None else self.xywha + return [*coords.tolist(), self.track_id, self.score, self.cls, self.idx] + + def __repr__(self) -> str: + """Return a string representation of the STrack object including start frame, end frame, and track ID.""" + return f"OT_{self.track_id}_({self.start_frame}-{self.end_frame})" + + +class BYTETracker: + """BYTETracker: A tracking algorithm built on top of YOLO for object detection and tracking. + + This class encapsulates the functionality for initializing, updating, and managing the tracks for detected objects + in a video sequence. It maintains the state of tracked, lost, and removed tracks over frames, utilizes Kalman + filtering for predicting the new object locations, and performs data association. + + Attributes: + tracked_stracks (list[STrack]): List of successfully activated tracks. + lost_stracks (list[STrack]): List of lost tracks. + removed_stracks (list[STrack]): List of removed tracks. + frame_id (int): The current frame ID. + args (Namespace): Command-line arguments. + max_frames_lost (int): The maximum frames for a track to be considered as 'lost'. + kalman_filter (KalmanFilterXYAH): Kalman Filter object. + + Methods: + update: Update object tracker with new detections. + get_kalmanfilter: Return a Kalman filter object for tracking bounding boxes. + init_track: Initialize object tracking with detections. + get_dists: Calculate the distance between tracks and detections. + multi_predict: Predict the location of tracks. + reset_id: Reset the ID counter of STrack. + reset: Reset the tracker by clearing all tracks. + joint_stracks: Combine two lists of stracks. + sub_stracks: Filter out the stracks present in the second list from the first list. + remove_duplicate_stracks: Remove duplicate stracks based on IoU. + + Examples: + Initialize BYTETracker and update with detection results + >>> tracker = BYTETracker(args) + >>> results = yolo_model.detect(image) + >>> tracked_objects = tracker.update(results) + """ + + track_class = STrack + + def __init__(self, args): + """Initialize a BYTETracker instance for object tracking. + + Args: + args (Namespace): Command-line arguments containing tracking parameters. + """ + self.tracked_stracks: list[STrack] = [] + self.lost_stracks: list[STrack] = [] + self.removed_stracks: list[STrack] = [] + + self.frame_id = 0 + self.args = args + self.max_frames_lost = args.track_buffer + self.kalman_filter = self.get_kalmanfilter() + self.reset_id() + + def update(self, results, img: np.ndarray | None = None, feats: np.ndarray | None = None, **kwargs) -> np.ndarray: + """Update the tracker with new detections and return the current list of tracked objects.""" + self.frame_id += 1 + activated_stracks = [] + refind_stracks = [] + lost_stracks = [] + removed_stracks = [] + + results_high, results_low, mask_high, mask_low = self._split_detections(results) + detections = self.init_track(results_high, self._input_for(img, feats, mask_high)) + detections_second = self.init_track(results_low, self._input_for(img, feats, mask_low)) + for tracks, mask in ((detections, mask_high), (detections_second, mask_low)): + for track, i in zip(tracks, np.flatnonzero(mask)): + track.idx = i # idx must be in full detection-set space; parse_bboxes only sees the subset + + unconfirmed, tracked_stracks = self._split_tracked() + strack_pool = joint_stracks(tracked_stracks, self.lost_stracks) + self.multi_predict(strack_pool) + self._pre_first_associate(strack_pool, unconfirmed, img, results_high) + + u_track, u_detection = self._first_association(strack_pool, detections, activated_stracks, refind_stracks) + u_track, u_detection = self._post_first_association( + strack_pool, detections, u_track, u_detection, activated_stracks, refind_stracks + ) + self._second_association( + strack_pool, u_track, detections_second, activated_stracks, refind_stracks, lost_stracks + ) + u_detection, detections = self._unconfirmed_association( + unconfirmed, u_detection, detections, activated_stracks, removed_stracks + ) + self._init_new_tracks(u_detection, detections, activated_stracks, refind_stracks) + self._remove_stale_lost(removed_stracks) + + merge_track_pools(self, activated_stracks, refind_stracks, lost_stracks, removed_stracks) + return self._format_output() + + def _split_detections(self, results: Any) -> tuple[Any, Any, np.ndarray, np.ndarray]: + """Split detections into high-confidence and low-confidence subsets, dropping degenerate boxes. + + Args: + results (Any): Results-like object with ``conf`` and ``xywh``/``xywhr`` attributes supporting boolean + indexing. + + Returns: + (tuple[Any, Any, np.ndarray, np.ndarray]): High-confidence results, low-confidence results, high mask, and + low mask. + """ + scores = results.conf + wh = (results.xywhr if hasattr(results, "xywhr") else results.xywh)[:, 2:4] + valid = (wh[:, 0] > 0) & (wh[:, 1] > 0) # tlwh_to_xyah divides by height, so h=0 would give an inf Kalman mean + remain_inds = valid & (scores >= self.args.track_high_thresh) + inds_low = valid & (scores > self.args.track_low_thresh) & (scores < self.args.track_high_thresh) + return results[remain_inds], results[inds_low], remain_inds, inds_low + + def _input_for(self, img: np.ndarray | None, feats: np.ndarray | None, mask: np.ndarray) -> Any: + """Return the per-detection auxiliary input for ``init_track``. + + When ``feats`` is provided it is sliced by the detection mask. Trackers with a native + (``model="auto"``) ReID encoder get None when feats are missing (e.g. user-supplied + detections), so ``init_track`` falls back to the no-encoding path instead of feeding the + BGR frame into the auto encoder. External ReID models always take the frame. + + Args: + img (np.ndarray | None): Current BGR frame. + feats (np.ndarray | None): Optional per-detection features. + mask (np.ndarray): Boolean mask used to slice ``feats``. + + Returns: + (Any): The auxiliary payload (features, image or None) to hand to ``init_track``. + """ + if feats is not None and len(feats): + return feats[mask] + if getattr(self, "encoder", None) is not None and getattr(self.args, "model", "auto") == "auto": + return None + return img + + def _split_tracked(self) -> tuple[list[STrack], list[STrack]]: + """Separate ``self.tracked_stracks`` into confirmed and unconfirmed lists. + + Returns: + (tuple[list[STrack], list[STrack]]): ``(unconfirmed, tracked)`` where ``unconfirmed`` holds tracks whose + ``is_activated`` flag is False. + """ + unconfirmed, tracked = [], [] + for track in self.tracked_stracks: + (unconfirmed if not track.is_activated else tracked).append(track) + return unconfirmed, tracked + + def _pre_first_associate( + self, strack_pool: list[STrack], unconfirmed: list[STrack], img: np.ndarray | None, results_high: Any + ) -> None: + """Hook called after Kalman predict, before first-stage assignment. Default: GMC if available.""" + if hasattr(self, "gmc") and self.gmc.method is not None and img is not None: + try: + warp = self.gmc.apply(img, results_high.xyxy) + except Exception as e: + LOGGER.warning(f"GMC failed, falling back to identity: {e}") + warp = np.eye(2, 3) + multi_gmc(strack_pool, warp) + multi_gmc(unconfirmed, warp) + + def _first_association( + self, strack_pool: list[STrack], detections: list[STrack], activated: list[STrack], refind: list[STrack] + ) -> tuple[list[int], list[int]]: + """First-stage association between track pool and high-score detections. + + Returns: + (tuple[list[int], list[int]]): Unmatched track indices and unmatched detection indices. + """ + dists = self.get_dists(strack_pool, detections) + matches, u_track, u_detection = matching.linear_assignment(dists, thresh=self.args.match_thresh) + self._apply_matches(matches, strack_pool, detections, activated, refind) + return u_track, u_detection + + def _post_first_association( + self, + strack_pool: list[STrack], + detections: list[STrack], + u_track: list[int], + u_detection: list[int], + activated: list[STrack], + refind: list[STrack], + ) -> tuple[list[int], list[int]]: + """Hook executed after the first association stage and before the second. + + Returns: + (tuple[list[int], list[int]]): Potentially modified unmatched track and detection indices. + """ + return u_track, u_detection + + def _apply_matches( + self, + matches: list[list[int]] | np.ndarray, + pool: list[STrack], + detections: list[STrack], + activated: list[STrack], + refind: list[STrack], + ) -> None: + """Apply a list of matched (track, detection) pairs from an association stage.""" + for itracked, idet in matches: + self._apply_match(pool[itracked], detections[idet], activated, refind) + + def _apply_match(self, track: STrack, det: STrack, activated: list[STrack], refind: list[STrack]) -> None: + """Update or re-activate a single track with its matched detection.""" + if track.state == TrackState.Tracked: + track.update(det, self.frame_id) + activated.append(track) + else: + track.re_activate(det, self.frame_id, new_id=False) + refind.append(track) + + def _second_association( + self, + strack_pool: list[STrack], + u_track: list[int], + detections_second: list[STrack], + activated: list[STrack], + refind: list[STrack], + lost: list[STrack], + ) -> None: + """Second-stage association between remaining tracked tracks and low-score detections.""" + r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] + if r_tracked_stracks and detections_second: + # IoU-only by design (ByteTrack paper sec. 3.2): fusing low scores pushes costs above the 0.5 threshold + dists = matching.iou_distance(r_tracked_stracks, detections_second) + matches, u_track, _ = matching.linear_assignment(dists, thresh=0.5) + self._apply_matches(matches, r_tracked_stracks, detections_second, activated, refind) + else: + u_track = list(range(len(r_tracked_stracks))) + + for it in u_track: + track = r_tracked_stracks[it] + if track.state != TrackState.Lost: + track.mark_lost() + lost.append(track) + + def _unconfirmed_association( + self, + unconfirmed: list[STrack], + u_detection: list[int], + detections: list[STrack], + activated: list[STrack], + removed: list[STrack], + ) -> tuple[list[int], list[STrack]]: + """Associate unconfirmed tracks with leftover high-score detections. + + Returns: + (tuple[list[int], list[STrack]]): Unmatched detection indices after association, and the filtered detection + list those indices refer to. + """ + detections = [detections[i] for i in u_detection] + if not unconfirmed: + return list(range(len(detections))), detections + dists = self.get_dists(unconfirmed, detections) + matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) + for itracked, idet in matches: + unconfirmed[itracked].update(detections[idet], self.frame_id) + activated.append(unconfirmed[itracked]) + for it in u_unconfirmed: + track = unconfirmed[it] + track.mark_removed() + removed.append(track) + return u_detection, detections + + def _init_new_tracks( + self, + u_detection: list[int], + detections: list[STrack], + activated: list[STrack], + refind: list[STrack] | None = None, + ) -> None: + """Activate new tracks from detections that survived all association stages.""" + for inew in u_detection: + track = detections[inew] + if track.score < self.args.new_track_thresh: + continue + track.activate(self.kalman_filter, self.frame_id) + activated.append(track) + + def _remove_stale_lost(self, removed: list[STrack]) -> None: + """Remove lost tracks that have exceeded the maximum allowed frames.""" + for track in self.lost_stracks: + if self.frame_id - track.end_frame > self.max_frames_lost: + track.mark_removed() + removed.append(track) + + def _format_output(self) -> np.ndarray: + """Format the current tracked objects into the output array.""" + return np.asarray([x.result for x in self.tracked_stracks if x.is_activated], dtype=np.float32) + + def get_kalmanfilter(self) -> KalmanFilterXYAH: + """Return a Kalman filter object for tracking bounding boxes using KalmanFilterXYAH.""" + return KalmanFilterXYAH() + + def init_track(self, results, img: np.ndarray | None = None) -> list[STrack]: + """Initialize object tracking with given detections, scores, and class labels as STrack instances.""" + if len(results) == 0: + return [] + bboxes = parse_bboxes(results) + return [self.track_class(xywh, s, c) for (xywh, s, c) in zip(bboxes, results.conf, results.cls)] + + def get_dists(self, tracks: list[STrack], detections: list[STrack]) -> np.ndarray: + """Calculate the distance between tracks and detections using IoU and optionally fuse scores.""" + dists = matching.iou_distance(tracks, detections) + if self.args.fuse_score: + dists = matching.fuse_score(dists, detections) + return dists + + def multi_predict(self, tracks: list[STrack]): + """Predict the next states for multiple tracks using Kalman filter.""" + STrack.multi_predict(tracks) + + @staticmethod + def reset_id(): + """Reset the ID counter for STrack instances to ensure unique track IDs across tracking sessions.""" + STrack.reset_id() + + def reset(self): + """Reset the tracker by clearing all tracked, lost, and removed tracks and reinitializing the Kalman filter.""" + self.tracked_stracks = [] + self.lost_stracks = [] + self.removed_stracks = [] + self.frame_id = 0 + self.kalman_filter = self.get_kalmanfilter() + self.reset_id() diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/deep_oc_sort.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/deep_oc_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..6e83f6b74904643eb7d254ca34266d432542d351 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/deep_oc_sort.py @@ -0,0 +1,266 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any + +import numpy as np + +from .byte_tracker import STrack +from .oc_sort import OCSORT, OCSortTrack +from .utils import matching +from .utils.gmc import GMC +from .utils.reid import build_encoder, smooth_feature +from .utils.stracks import parse_bboxes + + +class DeepOCSortTrack(OCSortTrack): + """Track object for Deep OC-SORT with appearance features and observation-centric state management. + + Extends OCSortTrack with ReID embedding storage and exponential moving average smoothing, plus confidence-adaptive + embedding update rates. + + Attributes: + smooth_feat (np.ndarray | None): Smoothed feature vector via EMA. + curr_feat (np.ndarray | None): Current frame's feature vector. + alpha_fixed_emb (float): Base EMA factor for embedding updates. + det_thresh (float): Confidence threshold below which a new embedding is ignored rather than blended. + """ + + def __init__( + self, + xywh: np.ndarray, + score: float, + cls: Any, + delta_t: int = 3, + feat: np.ndarray | None = None, + alpha_fixed_emb: float = 0.95, + det_thresh: float = 0.25, + ): + """Initialize a `DeepOCSortTrack` with optional appearance features. + + Args: + xywh (np.ndarray): Bounding box in `(x, y, w, h, idx)` or `(x, y, w, h, angle, idx)` format. + score (float): Detection confidence in `[0, 1]`. + cls (Any): Class label for the detection. + delta_t (int): Temporal window for OCM velocity direction computation. + feat (np.ndarray | None): Optional appearance feature vector for this detection. + alpha_fixed_emb (float): Base EMA factor for embedding updates; higher = slower updates. + det_thresh (float): Detection-confidence threshold below which the embedding is replaced rather than + blended. + """ + super().__init__(xywh, score, cls, delta_t) + self.smooth_feat = None + self.curr_feat = None + self.alpha_fixed_emb = alpha_fixed_emb + self.det_thresh = det_thresh + if feat is not None: + self.update_features(feat, score) + + def update_features(self, feat: np.ndarray, score: float | None = None) -> None: + """Blend a new appearance feature into `smooth_feat` with confidence-adaptive EMA. + + When `score` exceeds `det_thresh`, the EMA factor `alpha = alpha_fixed_emb + (1 - alpha_fixed_emb) * (1 - trust)` + with `trust = (score - det_thresh) / (1 - det_thresh)`, so a high-confidence detection blends in more strongly. + At or below `det_thresh`, `alpha = 1.0` so the existing `smooth_feat` is kept and the new (low-trust) feature is + ignored — same behavior used by the reference Deep OC-SORT implementation. + + Args: + feat (np.ndarray): New (un-normalized) appearance feature vector. + score (float | None): Detection confidence used to modulate the EMA factor. + """ + if score is not None and score > self.det_thresh: + trust = (score - self.det_thresh) / max(1 - self.det_thresh, 1e-9) + alpha = self.alpha_fixed_emb + (1 - self.alpha_fixed_emb) * (1 - trust) + else: + alpha = 1.0 # keep the existing smooth_feat for low-trust detections + curr, smooth = smooth_feature(feat, self.smooth_feat, alpha) + if curr is not None: + self.curr_feat, self.smooth_feat = curr, smooth + + def update(self, new_track: STrack, frame_id: int) -> None: + """Update track state with a matched detection and refresh appearance features. + + Args: + new_track (STrack): Matched detection for this frame, with optional `curr_feat`. + frame_id (int): Current frame id. + """ + if new_track.curr_feat is not None: + self.update_features(new_track.curr_feat, new_track.score) + super().update(new_track, frame_id) + + def re_activate(self, new_track: STrack, frame_id: int, new_id: bool = False) -> None: + """Re-activate a lost track and refresh appearance features. + + Args: + new_track (STrack): Detection used to revive this track. + frame_id (int): Current frame id. + new_id (bool): If True, assign a fresh track id instead of reusing the old one. + """ + if new_track.curr_feat is not None: + self.update_features(new_track.curr_feat, new_track.score) + super().re_activate(new_track, frame_id, new_id) + + @staticmethod + def multi_gmc(stracks: list[DeepOCSortTrack], H: np.ndarray) -> None: + """Apply global motion compensation correctly for the XYAH Kalman state. + + The standard `multi_gmc` helper from `utils.stracks` would rotate `(a, h)` along with + `(x, y)`, which is wrong for an aspect-ratio dim. This variant only rotates the + position `(x, y)` and the velocity `(vx, vy)` blocks, leaves `(a, h)` and `(va, vh)` + untouched, and also rotates the stored `last_observation` so OCR/ORU stay consistent. + + Args: + stracks (list[DeepOCSortTrack]): Tracks to warp in place. + H (np.ndarray): 2x3 affine homography mapping the previous frame to the current one. + """ + if not stracks: + return + multi_mean = np.asarray([st.mean for st in stracks]) + multi_covariance = np.asarray([st.covariance for st in stracks]) + + R = H[:2, :2] + t = H[:2, 2] + + # Build 8x8 transform: rotate (x,y) and (vx,vy), identity for (a,h) and (va,vh) + R8x8 = np.eye(8) # float64 holds any homography exactly; a narrower one would round the float64 methods + R8x8[:2, :2] = R # rotate position (x, y) + R8x8[4:6, 4:6] = R # rotate velocity (vx, vy) + # indices 2,3 (a,h) and 6,7 (va,vh) remain identity + + multi_mean = np.matmul(R8x8, multi_mean[..., None])[..., 0] + multi_mean[:, :2] += t + # Keep the right operand C-contiguous, as the `utils.stracks` sibling does: an F-contiguous one sends matmul + # into BLAS's transposed-gemm kernel, which on macOS Accelerate leaves FP-exception flags set even for finite + # inputs, and numpy then reports spurious divide-by-zero RuntimeWarnings. + multi_covariance = np.matmul(np.matmul(R8x8, multi_covariance), np.ascontiguousarray(R8x8.T)) + for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)): + stracks[i].mean = mean + stracks[i].covariance = cov + + # Also transform stored observations for OCR/ORU consistency + if stracks[i].last_observation[0] >= 0: + obs = stracks[i].last_observation + # Transform xyxy observation centers + cx, cy = DeepOCSortTrack._xyxy_center(obs) + w, h = obs[2] - obs[0], obs[3] - obs[1] + new_c = R @ np.array([cx, cy]) + t + stracks[i].last_observation = np.array( + [ + new_c[0] - w / 2, + new_c[1] - h / 2, + new_c[0] + w / 2, + new_c[1] + h / 2, + ], + dtype=np.float32, + ) + + +class DeepOCSORT(OCSORT): + """Deep OC-SORT: OC-SORT enhanced with appearance features, GMC, and adaptive weighting. + + Fixes over naive integration: + - GMC correctly handles XYAH state (rotates only x,y positions, not aspect ratio/height) + - Cost combination uses min(IoU, appearance) following BOTSORT's proven approach + - OCR recovery pass also uses appearance features + - ByteTrack-style low-confidence second pass disabled by default + """ + + def __init__(self, args: Any): + """Initialize Deep OC-SORT tracker. + + Args: + args (Namespace | IterableSimpleNamespace): Parsed tracker config providing the OC-SORT keys plus + `gmc_method`, `proximity_thresh`, `appearance_thresh`, `alpha_fixed_emb`, `with_reid`, and `model`. + """ + super().__init__(args) + + # GMC for camera motion compensation + self.gmc = GMC(method=getattr(args, "gmc_method", "sparseOptFlow")) + + # Appearance parameters + self.proximity_thresh = getattr(args, "proximity_thresh", 0.5) + self.appearance_thresh = getattr(args, "appearance_thresh", 0.75) + self.alpha_fixed_emb = getattr(args, "alpha_fixed_emb", 0.95) + + self.encoder = build_encoder( + getattr(args, "with_reid", False), getattr(args, "model", "auto"), getattr(args, "device", None) + ) + + def init_track(self, results, img: np.ndarray | None = None) -> list[DeepOCSortTrack]: + """Build `DeepOCSortTrack` instances, attaching ReID features when enabled. + + When `with_reid=True` and `model="auto"`, `img` should already be a list of native + backbone features (one per detection); for any other `model`, `img` is the source frame + and the configured external ReID encoder is invoked on detection crops. + + Args: + results (Any): Object exposing `xywh` (or `xywhr`), `conf`, and `cls`. + img (np.ndarray | None): Either the BGR frame or pre-extracted feature tensors, depending on the ReID + configuration. + + Returns: + (list[DeepOCSortTrack]): One track per detection, empty if no detections. + """ + if len(results) == 0: + return [] + bboxes = parse_bboxes(results) + + if self.encoder is not None and img is not None: + features = self.encoder(img, bboxes) + return [ + DeepOCSortTrack( + xywh, + s, + c, + self.delta_t, + feat=f, + alpha_fixed_emb=self.alpha_fixed_emb, + det_thresh=self.args.track_high_thresh, + ) + for (xywh, s, c, f) in zip(bboxes, results.conf, results.cls, features) + ] + return [ + DeepOCSortTrack( + xywh, s, c, self.delta_t, alpha_fixed_emb=self.alpha_fixed_emb, det_thresh=self.args.track_high_thresh + ) + for (xywh, s, c) in zip(bboxes, results.conf, results.cls) + ] + + def _pre_first_associate( + self, + strack_pool: list[DeepOCSortTrack], + unconfirmed: list[DeepOCSortTrack], + img: np.ndarray | None, + results_high: Any, + ) -> None: + """Apply GMC warp to Kalman state before first-stage association.""" + if img is None or self.gmc.method is None: + return + try: + warp = self.gmc.apply(img, results_high.xyxy if len(results_high) else np.empty((0, 4))) + except Exception: + warp = np.eye(2, 3) + DeepOCSortTrack.multi_gmc(strack_pool, warp) + DeepOCSortTrack.multi_gmc(unconfirmed, warp) + + def _fuse_appearance( + self, + dists: np.ndarray, + tracks: list[DeepOCSortTrack], + detections: list[DeepOCSortTrack], + iou_dists: np.ndarray | None = None, + ) -> np.ndarray: + """Min-fuse appearance distance into the motion cost (BoT-SORT-style).""" + if self.encoder is None or not tracks or not detections: + return dists + emb_dists = matching.embedding_distance(tracks, detections) / 2.0 + emb_dists[emb_dists > (1 - self.appearance_thresh)] = 1.0 + if iou_dists is not None: + emb_dists[iou_dists > (1 - self.proximity_thresh)] = 1.0 + return np.minimum(dists, emb_dists) + + def reset(self) -> None: + """Reset the Deep OC-SORT tracker, also clearing the GMC warp state.""" + super().reset() + self.gmc.reset_params() diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/fast_tracker.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/fast_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..8bf48ab0bdf122037510eaa0b74bcdb73599a38d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/fast_tracker.py @@ -0,0 +1,350 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from collections import deque +from typing import Any + +import numpy as np + +from ultralytics.utils.metrics import bbox_ioa + +from .basetrack import TrackState +from .byte_tracker import BYTETracker, STrack +from .utils import matching +from .utils.stracks import parse_bboxes + + +class FastSTrack(STrack): + """Single-object track for FastTracker with occlusion-aware state. + + Extends `STrack` with a bounded ring-buffer of recent Kalman means and per-track occlusion + bookkeeping. The history buffer enables rolling the Kalman state back to a pre-occlusion frame + when a neighbor suddenly covers the target. The buffer is a fixed-size `collections.deque`, so memory stays bounded + regardless of track lifetime. + + Attributes: + mean_history (collections.deque): Bounded ring-buffer of recent ``(mean, covariance)`` snapshots, newest last, + capped at ``history_len`` entries. Rolling back both together keeps the Kalman state internally consistent + when a track is restored after an occlusion gap. + not_matched (int): Consecutive frames this track has failed to match a detection. + is_occluded (bool): True while the track is hidden behind another target. + occluded_len (int): Consecutive frames the track has been continuously occluded. + last_occluded_frame (int): Frame id when occlusion was last detected, or -1 if never occluded. + was_recently_occluded (bool): Sticky flag kept for ``occ_reappear_window`` frames, used by `FASTTracker` to + extend the re-find window for tracks that went lost while occluded. + + Examples: + >>> from ultralytics.trackers.utils.kalman_filter import KalmanFilterXYAH + >>> t = FastSTrack(np.array([100, 200, 50, 80, 0]), score=0.9, cls=0, history_len=8) + >>> t.activate(KalmanFilterXYAH(), frame_id=1) + >>> len(t.mean_history) + 1 + """ + + def __init__(self, xywh: np.ndarray, score: float, cls: Any, history_len: int = 16): + """Initialize a FastSTrack. + + Args: + xywh (np.ndarray): Bounding box in ``(x, y, w, h, idx)`` or ``(x, y, w, h, angle, idx)`` format. + score (float): Detection confidence in `[0, 1]`. + cls (Any): Class label for the detection. + history_len (int): Maximum number of past Kalman mean vectors kept for occlusion rollback. + """ + super().__init__(xywh, score, cls) + self.mean_history: deque = deque(maxlen=history_len) + self.not_matched = 0 + self.is_occluded = False + self.occluded_len = 0 + self.last_occluded_frame = -1 + self.was_recently_occluded = False + + def _push_history(self): + """Append `(mean, covariance)` copies of the current Kalman state to the bounded buffer.""" + if self.mean is not None: + self.mean_history.append((self.mean.copy(), self.covariance.copy())) + + def activate(self, kalman_filter, frame_id: int): + """Activate the track and seed its mean history. + + Args: + kalman_filter (KalmanFilterXYAH): Shared Kalman filter instance. + frame_id (int): Frame id at which the track is created. + """ + super().activate(kalman_filter, frame_id) + self._push_history() + + def re_activate(self, new_track, frame_id: int, new_id: bool = False): + """Re-activate a previously lost track and clear any stale occlusion bookkeeping. + + Args: + new_track (FastSTrack): Detection used to revive this track. + frame_id (int): Current frame id. + new_id (bool): If True, assign a fresh track id instead of reusing the old one. + """ + super().re_activate(new_track, frame_id, new_id=new_id) + self.is_occluded = False + self.occluded_len = 0 + self.not_matched = 0 + self.was_recently_occluded = False + self.last_occluded_frame = -1 + self._push_history() + + def update(self, new_track, frame_id: int): + """Update the track with a newly matched detection. + + Args: + new_track (FastSTrack): Matched detection for this frame. + frame_id (int): Current frame id. + """ + super().update(new_track, frame_id) + self._push_history() + + +class FASTTracker(BYTETracker): + """Occlusion-aware ByteTrack-style multi-object tracker. + + Adapted from the reference implementation in the FastTracker paper (arXiv:2508.14370). FastTracker extends + `BYTETracker` with lightweight mechanisms that reduce ID switches through crowd occlusions without sacrificing + throughput. Unmatched tracks whose area is strongly covered by an active neighbor are flagged as occluded and their + Kalman state is rolled back to a pre-occlusion frame, with a one-shot bbox enlargement and dampened motion so they + survive the occlusion. An occluded track is kept alive for an extra grace window before being marked lost, and once + lost it stays re-findable for an extended window beyond the regular ``track_buffer``. New detections that strongly + overlap an already-active track are suppressed at spawn time to prevent ghost IDs. + + All added work uses vectorized IoU / coverage matrices and only runs on unmatched tracks, so the per-frame overhead + over `BYTETracker` stays on the order of a few hundred microseconds. + + Attributes: + reset_velocity_offset_occ (int): Number of frames to look back when restoring Kalman velocity at occlusion + onset. + reset_pos_offset_occ (int): Number of frames to look back when restoring Kalman position at occlusion onset. + enlarge_bbox_occ (float): One-shot multiplier applied to the bbox height when occlusion is first detected. + dampen_motion_occ (float): Multiplier in `[0, 1]` applied to Kalman velocity during occlusion. + active_occ_to_lost_thresh (int): Maximum consecutive occluded frames before a track is marked lost anyway. + init_iou_suppress (float): IoU threshold above which a new detection is prevented from spawning a fresh track. + Set to 1.0 to disable suppression. + occ_cover_thresh (float): Fraction of a track's area that must be covered by another active track to declare + occlusion. + occ_reappear_window (int): Frames a recently-occluded lost track stays re-findable beyond the regular + ``track_buffer``. + + Methods: + update: Consume a frame's detections and return the currently-tracked objects. + init_track: Build `FastSTrack` instances from a ``Results``-like object. + + Examples: + Plug FastTracker into a YOLO model via the bundled config: + >>> from ultralytics import YOLO + >>> model = YOLO("yolo26s.pt") + >>> model.track("video.mp4", tracker="fasttrack.yaml") + + Drive FastTracker directly with your own detections: + >>> from ultralytics.trackers import FASTTracker + >>> from ultralytics.utils import YAML, IterableSimpleNamespace + >>> cfg = IterableSimpleNamespace(**YAML.load("ultralytics/cfg/trackers/fasttrack.yaml")) + >>> tracker = FASTTracker(cfg) + >>> tracks = tracker.update(detections) + """ + + track_class = FastSTrack + + def __init__(self, args): + """Initialize FastTracker with tunables read from ``args``. + + Any FastTracker-specific key missing on ``args`` falls back to a sensible default, so + FastTracker can also be driven by a plain ByteTrack config. + + Args: + args (Namespace | IterableSimpleNamespace): Parsed tracker config. Must provide the BYTETracker keys + (``track_high_thresh``, ``track_low_thresh``, ``new_track_thresh``, ``track_buffer``, ``match_thresh``, + ``fuse_score``) and may provide the FastTracker-specific keys described in the class docstring. + """ + super().__init__(args) + # Occlusion-handling knobs (fall back to sensible defaults if absent on args) + self.reset_velocity_offset_occ = int(getattr(args, "reset_velocity_offset_occ", 5)) + self.reset_pos_offset_occ = int(getattr(args, "reset_pos_offset_occ", 3)) + self.enlarge_bbox_occ = float(getattr(args, "enlarge_bbox_occ", 1.1)) + self.dampen_motion_occ = float(getattr(args, "dampen_motion_occ", 0.5)) + self.active_occ_to_lost_thresh = int(getattr(args, "active_occ_to_lost_thresh", 10)) + self.init_iou_suppress = float(getattr(args, "init_iou_suppress", 0.7)) + self.occ_cover_thresh = float(getattr(args, "occ_cover_thresh", 0.7)) + self.occ_reappear_window = int(getattr(args, "occ_reappear_window", 40)) + # Cap history to the max rollback we'll need + small slack. + self._history_len = max(self.reset_velocity_offset_occ, self.reset_pos_offset_occ) + 4 + + def init_track(self, results, img: np.ndarray | None = None) -> list[FastSTrack]: + """Build `FastSTrack` instances from a ``Results``-like object. + + Args: + results (Any): Object exposing ``xywh`` (or ``xywhr``), ``conf``, and ``cls``. + img (np.ndarray | None): Current BGR frame. Unused by FastTracker; accepted for signature parity with other + trackers. + + Returns: + (list[FastSTrack]): One `FastSTrack` per detection, empty if no detections. + """ + if len(results) == 0: + return [] + bboxes = parse_bboxes(results) + return [ + FastSTrack(xywh, s, c, history_len=self._history_len) + for (xywh, s, c) in zip(bboxes, results.conf, results.cls) + ] + + def _apply_match(self, track: STrack, det: STrack, activated: list[STrack], refind: list[STrack]) -> None: + """Update or re-activate a track and clear any occlusion bookkeeping on a successful match.""" + super()._apply_match(track, det, activated, refind) + track.is_occluded = False + track.not_matched = 0 + track.occluded_len = 0 + + def _second_association( + self, + strack_pool: list[STrack], + u_track: list[int], + detections_second: list[STrack], + activated: list[STrack], + refind: list[STrack], + lost: list[STrack], + ) -> None: + """Second-stage association + occlusion handling (replaces base mark-lost loop).""" + r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] + if r_tracked_stracks and detections_second: + dists = matching.iou_distance(r_tracked_stracks, detections_second) + matches, u_track, _ = matching.linear_assignment(dists, thresh=0.5) + self._apply_matches(matches, r_tracked_stracks, detections_second, activated, refind) + else: + u_track = list(range(len(r_tracked_stracks))) + self._handle_occlusions(r_tracked_stracks, u_track, activated, lost) + + def _init_new_tracks( + self, + u_detection: list[int], + detections: list[STrack], + activated: list[STrack], + refind: list[STrack] | None = None, + ) -> None: + """Activate new tracks, suppressing detections that heavily overlap already-active tracks.""" + active_boxes = [t.xyxy for t in activated if t.is_activated] + if refind: + active_boxes.extend(t.xyxy for t in refind if t.is_activated) + active_boxes.extend(t.xyxy for t in self.tracked_stracks if t.state == TrackState.Tracked) + suppress_on = self.init_iou_suppress < 1.0 + active_stack = ( + np.asarray(active_boxes, dtype=np.float32) if active_boxes else np.empty((0, 4), dtype=np.float32) + ) + for inew in u_detection: + det = detections[inew] + if det.score < self.args.new_track_thresh: + continue + if ( + suppress_on + and len(active_stack) + and bbox_ioa(det.xyxy[None, :], active_stack, iou=True).max() >= self.init_iou_suppress + ): + continue + det.activate(self.kalman_filter, self.frame_id) + activated.append(det) + active_stack = np.concatenate([active_stack, det.xyxy[None, :]], axis=0) + + def _remove_stale_lost(self, removed: list[STrack]) -> None: + """Remove lost tracks, with a grace window for recently-occluded ones.""" + for track in self.lost_stracks: + recently_occluded = track.was_recently_occluded and ( + self.frame_id - track.last_occluded_frame <= self.occ_reappear_window + ) + if not recently_occluded and (self.frame_id - track.end_frame > self.max_frames_lost): + track.mark_removed() + removed.append(track) + + def _format_output(self) -> np.ndarray: + """Only emit tracks updated this frame to avoid stale ``idx`` values.""" + return np.asarray( + [x.result for x in self.tracked_stracks if x.is_activated and x.frame_id == self.frame_id], + dtype=np.float32, + ) + + def _handle_occlusions(self, r_tracked, u_track, activated_stracks, lost_stracks): + """Flag unmatched tracked tracks as occluded when covered by an active neighbor. + + For each unmatched track, computes the fraction of its area covered by any currently-active + track. If coverage exceeds ``occ_cover_thresh``, the track is marked occluded, its Kalman + state is rolled back using the ring-buffer history (velocity from ``reset_velocity_offset_occ`` + frames ago, position from ``reset_pos_offset_occ`` frames ago), the bbox height is scaled by + ``enlarge_bbox_occ`` once, and velocity is dampened by ``dampen_motion_occ``. Tracks that + remain unmatched for more than two frames are transitioned to Lost, except while they are + within the ``active_occ_to_lost_thresh`` occluded-grace window. + + Args: + r_tracked (list[FastSTrack]): Candidate track pool. + u_track (list[int] | np.ndarray): Indices into ``r_tracked`` of tracks still unmatched. + activated_stracks (list[FastSTrack]): Tracks already matched this frame; used as the pool of potential + occluders. + lost_stracks (list[FastSTrack]): Output list; tracks transitioned to Lost are appended. + """ + if len(u_track) == 0: + return + + # Build active-track box array once (vectorized cover check). + active = [t for t in activated_stracks if t.is_activated and not t.is_occluded] + if len(active): + active_boxes = np.asarray([t.xyxy for t in active], dtype=np.float32) + active_ids = np.asarray([t.track_id for t in active]) + else: + active_boxes = np.empty((0, 4), dtype=np.float32) + active_ids = np.empty((0,), dtype=np.int64) + + unmatched = [r_tracked[i] for i in u_track] + unmatched_boxes = ( + np.asarray([t.xyxy for t in unmatched], dtype=np.float32) + if unmatched + else np.empty((0, 4), dtype=np.float32) + ) + + if active_boxes.size and unmatched_boxes.size: + cov = bbox_ioa(active_boxes, unmatched_boxes) # (A, U) = intersection / unmatched-track area + # Avoid self-match: zero out entries that correspond to the same track id. + unm_ids = np.asarray([t.track_id for t in unmatched]) + same = active_ids[:, None] == unm_ids[None, :] + cov[same] = 0.0 + max_cov = cov.max(axis=0) # per unmatched track, max fraction of its area covered by an active track + else: + max_cov = np.zeros(len(unmatched), dtype=np.float32) + + for i, track in enumerate(unmatched): + track.not_matched += 1 + + if max_cov[i] > self.occ_cover_thresh and not track.is_occluded and track.state == TrackState.Tracked: + track.is_occluded = True + track.occluded_len = 1 + track.last_occluded_frame = self.frame_id + track.was_recently_occluded = True + + hist = track.mean_history + if track.mean is not None and hist: + if len(hist) >= self.reset_velocity_offset_occ: + prev_mean, _ = hist[-self.reset_velocity_offset_occ] + track.mean[4:8] = prev_mean[4:8] + if len(hist) >= self.reset_pos_offset_occ: + prev_mean, prev_cov = hist[-self.reset_pos_offset_occ] + track.mean[0:4] = prev_mean[0:4] + track.covariance = prev_cov.copy() + # Enlarge height once to expand search region (XYAH state: a is held, so + # scaling h proportionally scales w via w = a * h). + track.mean[3] *= self.enlarge_bbox_occ + track.mean[4:8] *= self.dampen_motion_occ + elif track.is_occluded: + track.occluded_len += 1 + + if track.was_recently_occluded and (self.frame_id - track.last_occluded_frame > self.occ_reappear_window): + track.was_recently_occluded = False + + # Give occluded tracks a grace period before marking lost. + if ( + track.state != TrackState.Lost + and track.not_matched > 2 + and (not track.is_occluded or track.occluded_len > self.active_occ_to_lost_thresh) + ): + track.mark_lost() + lost_stracks.append(track) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/oc_sort.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/oc_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..1dc9a5282dc626e690fbe41cb5286874b5c4f03e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/oc_sort.py @@ -0,0 +1,351 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any + +import numpy as np + +from ..utils.ops import xyxy2ltwh +from .basetrack import TrackState +from .byte_tracker import BYTETracker, STrack +from .utils import matching +from .utils.stracks import parse_bboxes + + +class OCSortTrack(STrack): + """Track object for OC-SORT with observation-centric state management. + + Extends STrack with storage of real detector observations and velocity computation, enabling the three OC-SORT + components: ORU, OCM, and OCR. + + Attributes: + last_observation (np.ndarray): Last real detection in xyxy format. + observations (dict): Maps frame_id to xyxy observation arrays. + velocity (np.ndarray | None): Observation-centric velocity direction vector (dx, dy). + delta_t (int): Temporal window for velocity computation. + """ + + def __init__(self, xywh: np.ndarray, score: float, cls: Any, delta_t: int = 3): + """Initialize an OCSortTrack with observation storage. + + Args: + xywh (np.ndarray): Bounding box in `(x, y, w, h, idx)` or `(x, y, w, h, angle, idx)` format. + score (float): Detection confidence in `[0, 1]`. + cls (Any): Class label for the detection. + delta_t (int): Temporal window (in frames) used for velocity direction computation. + """ + super().__init__(xywh, score, cls) + self.last_observation = np.array([-1, -1, -1, -1], dtype=np.float32) + self.observations: dict[int, np.ndarray] = {} + self.velocity: np.ndarray | None = None + self.delta_t = delta_t + self._saved_mean: np.ndarray | None = None + self._saved_covariance: np.ndarray | None = None + + def activate(self, kalman_filter, frame_id: int) -> None: + """Activate a new tracklet and seed its observation history. + + Args: + kalman_filter (KalmanFilterXYAH): Shared Kalman filter instance. + frame_id (int): Frame id at which the track is created. + """ + super().activate(kalman_filter, frame_id) + self._record_observation(self.xyxy.astype(np.float32), frame_id) # detection-space precision + self._saved_mean = self.mean.copy() + self._saved_covariance = self.covariance.copy() + + def update(self, new_track: STrack, frame_id: int) -> None: + """Update the track with a matched detection and record the observation. + + Args: + new_track (STrack): Matched detection for this frame. + frame_id (int): Current frame id. + """ + self._record_observation(new_track.xyxy.copy(), frame_id) + super().update(new_track, frame_id) + self._saved_mean = self.mean.copy() + self._saved_covariance = self.covariance.copy() + self.velocity = self._compute_velocity() + + def re_activate(self, new_track: STrack, frame_id: int, new_id: bool = False) -> None: + """Re-activate a previously lost track with a new detection. + + Args: + new_track (STrack): Detection used to revive this track. + frame_id (int): Current frame id. + new_id (bool): If True, assign a fresh track id instead of reusing the old one. + """ + self._record_observation(new_track.xyxy.copy(), frame_id) + super().re_activate(new_track, frame_id, new_id) + self._saved_mean = self.mean.copy() + self._saved_covariance = self.covariance.copy() + self.velocity = self._compute_velocity() + + @staticmethod + def _xyxy_center(xyxy: np.ndarray) -> np.ndarray: + """Return `(cx, cy)` center of an xyxy bounding box.""" + return np.array([(xyxy[0] + xyxy[2]) / 2, (xyxy[1] + xyxy[3]) / 2]) + + def _record_observation(self, obs: np.ndarray, frame_id: int) -> None: + """Store `obs` for `frame_id`, dropping history beyond `delta_t + 2` to bound memory. + + The retained window always covers the frame `_compute_velocity` reaches back to, since at most `delta_t` + distinct frames fall inside `(frame_id - delta_t, frame_id]`. + """ + self.last_observation = obs + self.observations[frame_id] = obs + max_keep = self.delta_t + 2 + if len(self.observations) > max_keep: + for frame in sorted(self.observations)[:-max_keep]: + del self.observations[frame] + + def _compute_velocity(self) -> np.ndarray | None: + """Compute the observation-centric velocity direction from stored observations. + + Returns: + (np.ndarray | None): Normalized `(dx, dy)` direction vector, or None if there are fewer than two usable + observations. + """ + if len(self.observations) < 2: + return None + + current_frame = max(self.observations.keys()) + current_center = self._xyxy_center(self.observations[current_frame]) + + # Find the most recent observation at least delta_t frames before current + prev_obs = None + for frame in sorted(self.observations.keys(), reverse=True): + if frame < current_frame - self.delta_t + 1: + prev_obs = self.observations[frame] + break + + # Fallback: use the earliest observation if nothing is delta_t frames back + if prev_obs is None: + earliest_frame = min(self.observations.keys()) + if earliest_frame == current_frame: + return None + prev_obs = self.observations[earliest_frame] + + direction = current_center - self._xyxy_center(prev_obs) + norm = np.linalg.norm(direction) + if norm < 1e-6: + return np.zeros(2, dtype=np.float32) + return (direction / norm).astype(np.float32) + + def apply_oru(self, new_observation_xyxy: np.ndarray, current_frame_id: int) -> None: + """Repair Kalman state across an occlusion gap by replaying predict-updates on virtual observations.""" + if self._saved_mean is None or not self.observations: + return + + last_frame = max(self.observations.keys()) + gap = current_frame_id - last_frame + if gap <= 1: + return + + # Restore Kalman state to last observation point + self.mean = self._saved_mean.copy() + self.covariance = self._saved_covariance.copy() + + last_obs = self.observations[last_frame] + + # Replay with virtual observations + for t in range(1, gap): + alpha = t / gap + virtual_xyxy = (1 - alpha) * last_obs + alpha * new_observation_xyxy + # Convert xyxy to tlwh then to xyah for Kalman measurement + virtual_xyah = self.tlwh_to_xyah(xyxy2ltwh(virtual_xyxy)) + self.mean, self.covariance = self.kalman_filter.predict(self.mean, self.covariance) + self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance, virtual_xyah) + + # Final predict to reach current frame + self.mean, self.covariance = self.kalman_filter.predict(self.mean, self.covariance) + + +class OCSORT(BYTETracker): + """OC-SORT multi-object tracker with observation-centric association. + + Implements three key components on top of BYTETracker: + - Observation-Centric Re-Update (ORU): repairs Kalman state after occlusion + - Observation-Centric Momentum (OCM): velocity direction consistency cost + - Observation-Centric Recovery (OCR): re-association using last observation position + + Attributes: + delta_t (int): Temporal window for velocity direction computation. + inertia (float): Weight of velocity consistency cost in association. + use_byte (bool): Whether to use ByteTrack-style low-confidence second pass. + """ + + track_class = OCSortTrack + + def __init__(self, args: Any): + """Initialize OC-SORT tracker. + + Args: + args (Namespace | IterableSimpleNamespace): Parsed tracker config providing the BYTE keys plus `delta_t`, + `inertia`, and `use_byte`. + """ + super().__init__(args) + self.delta_t = getattr(args, "delta_t", 3) + self.inertia = getattr(args, "inertia", 0.2) + self.use_byte = getattr(args, "use_byte", False) + + def init_track(self, results, img: np.ndarray | None = None) -> list[OCSortTrack]: + """Build `OCSortTrack` instances from a `Results`-like object.""" + if len(results) == 0: + return [] + bboxes = parse_bboxes(results) + return [OCSortTrack(xywh, s, c, self.delta_t) for (xywh, s, c) in zip(bboxes, results.conf, results.cls)] + + def _fuse_appearance( + self, + dists: np.ndarray, + tracks: list[OCSortTrack], + detections: list[OCSortTrack], + iou_dists: np.ndarray | None = None, + ) -> np.ndarray: + """Hook combining motion cost with appearance cost. Default: pass-through (no ReID).""" + return dists + + def get_dists(self, tracks: list[OCSortTrack], detections: list[OCSortTrack]) -> np.ndarray: + """Cost matrix = IoU (+score-fuse) + inertia·OCM (+ optional appearance, via hook).""" + iou_dists = matching.iou_distance(tracks, detections) + dists = matching.fuse_score(iou_dists, detections) if self.args.fuse_score else iou_dists.copy() + dists = dists + self.inertia * self._velocity_direction_cost(tracks, detections) + return self._fuse_appearance(dists, tracks, detections, iou_dists=iou_dists) + + def _ocr_associate( + self, + tracks: list[OCSortTrack], + dets: list[OCSortTrack], + activated: list[OCSortTrack], + refind: list[OCSortTrack], + ) -> tuple[list[int], list[int]]: + """Run one OCR (last-observation IoU) pass, applying matches in place. + + Returns: + (tuple[list[int], list[int]]): Local indices of unmatched ``tracks`` and unmatched ``dets``. + """ + if not tracks or not dets: + return list(range(len(tracks))), list(range(len(dets))) + iou_dists = self._ocr_distance(tracks, dets) + ocr_dists = matching.fuse_score(iou_dists, dets) if self.args.fuse_score else iou_dists + ocr_dists = self._fuse_appearance(ocr_dists, tracks, dets, iou_dists=iou_dists) + matches, u_track, u_det = matching.linear_assignment(ocr_dists, thresh=self.args.match_thresh) + for itracked, idet in matches: + track, det = tracks[itracked], dets[idet] + if track.state == TrackState.Tracked: + track.update(det, self.frame_id) + activated.append(track) + else: + track.apply_oru(det.xyxy, self.frame_id) + track.re_activate(det, self.frame_id, new_id=False) + refind.append(track) + return list(u_track), list(u_det) + + def _post_first_association( + self, + strack_pool: list[OCSortTrack], + detections: list[OCSortTrack], + u_track: list[int], + u_detection: list[int], + activated: list[OCSortTrack], + refind: list[OCSortTrack], + ) -> tuple[list[int], list[int]]: + """Observation-Centric Recovery (OCR) pass after first-stage association. + + Runs OCR for still-Tracked unmatched tracks first to preserve active-track matching priority, then for + Lost tracks on the detections still unmatched, so a recently-lost track cannot outbid an active one. + """ + ocr_dets = [detections[i] for i in u_detection] + if not ocr_dets: + return u_track, u_detection + + tracked = [i for i in u_track if strack_pool[i].state == TrackState.Tracked] + other = [i for i in u_track if strack_pool[i].state != TrackState.Tracked] + + u_t1, u_d1 = self._ocr_associate([strack_pool[i] for i in tracked], ocr_dets, activated, refind) + remaining = [ocr_dets[j] for j in u_d1] + u_t2, u_d2 = self._ocr_associate([strack_pool[i] for i in other], remaining, activated, refind) + + u_track = [tracked[i] for i in u_t1] + [other[i] for i in u_t2] + u_detection = [u_detection[u_d1[j]] for j in u_d2] + return u_track, u_detection + + def _second_association( + self, + strack_pool: list[OCSortTrack], + u_track: list[int], + detections_second: list[OCSortTrack], + activated: list[OCSortTrack], + refind: list[OCSortTrack], + lost: list[OCSortTrack], + ) -> None: + """Run ByteTrack-style second pass only when ``use_byte`` is enabled.""" + if not self.use_byte: + for i in u_track: + track = strack_pool[i] + if track.state == TrackState.Tracked: + track.mark_lost() + lost.append(track) + return + super()._second_association(strack_pool, u_track, detections_second, activated, refind, lost) + + def _velocity_direction_cost(self, tracks: list[OCSortTrack], detections: list[OCSortTrack]) -> np.ndarray: + """Compute OCM velocity direction consistency cost matrix (vectorized). + + For each track-detection pair, measures the angular difference between + the track's historical motion direction and the direction to the candidate detection. + + Args: + tracks (list[OCSortTrack]): List of tracks. + detections (list[OCSortTrack]): List of detections. + + Returns: + (np.ndarray): Cost matrix of shape (len(tracks), len(detections)). + """ + cost = np.zeros((len(tracks), len(detections)), dtype=np.float32) + if cost.size == 0: + return cost + + # Pre-extract detection centers as (M, 2) array + det_centers = np.array([OCSortTrack._xyxy_center(det.xyxy) for det in detections], dtype=np.float32) + + for i, track in enumerate(tracks): + if track.velocity is None or track.last_observation[0] < 0: + continue + track_center = OCSortTrack._xyxy_center(track.last_observation) + directions = det_centers - track_center # (M, 2) + norms = np.linalg.norm(directions, axis=1) # (M,) + valid = norms > 1e-6 + if not valid.any(): + continue + directions[valid] /= norms[valid, None] + dots = np.clip(directions[valid] @ track.velocity, -1.0, 1.0) + cost[i, valid] = np.arccos(dots) / np.pi + + return cost + + def _ocr_distance(self, tracks: list[OCSortTrack], detections: list[OCSortTrack]) -> np.ndarray: + """Compute IoU distance using tracks' last observation positions instead of Kalman predictions. + + Args: + tracks (list[OCSortTrack]): List of tracks with last_observation attributes. + detections (list[OCSortTrack]): List of detections. + + Returns: + (np.ndarray): Cost matrix based on IoU with last observations (or xywha for OBB). + + Notes: + `last_observation` is stored in xyxy form. For oriented (OBB) tracks no oriented + last-observation is kept, so this method falls back to the Kalman-predicted `xywha` + and the OCR pass degenerates to standard IoU on the predicted box. Standard + (axis-aligned) tracking gets the full OCR benefit. + """ + if tracks and tracks[0].angle is not None: + atlbrs = [t.xywha for t in tracks] + btlbrs = [d.xywha for d in detections] + else: + atlbrs = [t.last_observation if t.last_observation[0] >= 0 else t.xyxy for t in tracks] + btlbrs = [d.xyxy for d in detections] + return matching.iou_distance(atlbrs, btlbrs) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/track.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/track.py new file mode 100644 index 0000000000000000000000000000000000000000..aeb941e0ed0267942e58d4cd401c8a300a026ebe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/track.py @@ -0,0 +1,156 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from functools import partial +from pathlib import Path + +import torch + +from ultralytics.cfg import TASKS +from ultralytics.utils import YAML, IterableSimpleNamespace +from ultralytics.utils.checks import check_yaml + +from .bot_sort import BOTSORT +from .byte_tracker import BYTETracker +from .deep_oc_sort import DeepOCSORT +from .fast_tracker import FASTTracker +from .oc_sort import OCSORT +from .track_tracker import TRACKTRACK + +# A mapping of tracker types to corresponding tracker classes +TRACKER_MAP = { + "bytetrack": BYTETracker, + "botsort": BOTSORT, + "tracktrack": TRACKTRACK, + "fasttrack": FASTTracker, + "ocsort": OCSORT, + "deepocsort": DeepOCSORT, +} + + +def on_predict_start(predictor: object, persist: bool = False) -> None: + """Initialize trackers for object tracking during prediction. + + Args: + predictor (ultralytics.engine.predictor.BasePredictor): The predictor object to initialize trackers for. + persist (bool, optional): Whether to reuse existing trackers if they are already attached. + + Examples: + Initialize trackers for a predictor object + >>> predictor = SomePredictorClass() + >>> on_predict_start(predictor, persist=True) + """ + trackable = ("detect", "segment", "pose", "obb") # tasks whose results carry boxes, in canonical order + if (task := predictor.args.task) in TASKS and task not in trackable: # unknown third-party tasks are left alone + raise ValueError(f"❌ Task '{task}' doesn't support 'mode=track', valid tasks are {', '.join(trackable)}") + + if hasattr(predictor, "trackers") and persist: + return + + tracker = check_yaml(predictor.args.tracker) + cfg = IterableSimpleNamespace(**YAML.load(tracker)) + cfg.device = predictor.device # run any ReID encoder on the predictor's device + + if cfg.tracker_type not in TRACKER_MAP: + raise AssertionError(f"Only {sorted(TRACKER_MAP)} are supported for now, but got '{cfg.tracker_type}'") + + predictor._feats = None # reset ReID pre-hook state + if hasattr(predictor, "_hook"): + predictor._hook.remove() + if hasattr(predictor, "_orig_postprocess"): # restore any raw-preds wrapper left by a prior TRACKTRACK run + predictor.postprocess = predictor._orig_postprocess + del predictor._orig_postprocess + if cfg.tracker_type in {"botsort", "tracktrack", "deepocsort"} and cfg.with_reid and cfg.model == "auto": + from ultralytics.nn.modules.head import Detect + + if not ( + isinstance(predictor.model.model, torch.nn.Module) + and isinstance(predictor.model.model.model[-1], Detect) + and not predictor.model.model.model[-1].end2end + ): + cfg.model = "yolo26n-cls.pt" + else: + # Register hook to extract input of Detect layer + def pre_hook(module, input): + predictor._feats = list(input[0]) # unroll to new list to avoid mutation in forward + + predictor._hook = predictor.model.model.model[-1].register_forward_pre_hook(pre_hook) + + trackers = [] + for _ in range(predictor.dataset.bs): + tracker = TRACKER_MAP[cfg.tracker_type](args=cfg) + trackers.append(tracker) + if predictor.dataset.mode != "stream": # non-stream modes reuse a single tracker + break + predictor.trackers = trackers + predictor.vid_path = [None] * predictor.dataset.bs # used to reset the tracker when switching videos + + tracker_cls = TRACKER_MAP[cfg.tracker_type] + if hasattr(tracker_cls, "setup_predictor"): + tracker_cls.setup_predictor(predictor) + + +def on_predict_postprocess_end(predictor: object, persist: bool = False) -> None: + """Postprocess detected boxes and update with object tracking. + + Args: + predictor (object): The predictor object containing the predictions. + persist (bool, optional): Whether to persist the trackers if they already exist. + + Examples: + Postprocess predictions and update with tracking + >>> predictor = YourPredictorClass() + >>> on_predict_postprocess_end(predictor, persist=True) + """ + is_obb = predictor.args.task == "obb" + is_stream = predictor.dataset.mode == "stream" + + tracker_cls = type(predictor.trackers[0]) + dets_del_list = ( + tracker_cls.compute_frame_extras(predictor) if hasattr(tracker_cls, "compute_frame_extras") else None + ) + + for i, result in enumerate(predictor.results): + tracker = predictor.trackers[i if is_stream else 0] + vid_path = predictor.save_dir / Path(result.path).name + if not persist and predictor.vid_path[i if is_stream else 0] != vid_path: + tracker.reset() + predictor.vid_path[i if is_stream else 0] = vid_path + + det = (src := result.obb if is_obb else result.boxes).cpu().numpy() + kwargs = {"feats": getattr(result, "feats", None)} + if dets_del_list is not None: + kwargs["dets_del"] = dets_del_list[i] + tracks = tracker.update(det, result.orig_img, **kwargs) + if len(tracks) == 0: + continue + idx = tracks[:, -1].astype(int) + predictor.results[i] = result[idx] + + update_args = {"obb" if is_obb else "boxes": torch.as_tensor(tracks[:, :-1], device=src.data.device)} + predictor.results[i].update(**update_args) + + +def register_tracker(model: object, persist: bool) -> None: + """Register or refresh the tracking callbacks on the model for object tracking during prediction. + + Any earlier registration is replaced in place, so repeat calls neither stack callbacks nor keep a stale `persist`. + + Args: + model (object): The model to register tracking callbacks on, exposing a `callbacks` event mapping. + persist (bool): Whether to persist the trackers if they already exist. + + Examples: + Register tracking callbacks to a YOLO model + >>> model = YOLOModel() + >>> register_tracker(model, persist=True) + """ + for event, fn in ( + ("on_predict_start", on_predict_start), + ("on_predict_postprocess_end", on_predict_postprocess_end), + ): + callbacks = model.callbacks[event] + i = next((i for i, cb in enumerate(callbacks) if getattr(cb, "func", None) is fn), None) + if i is None: + model.add_callback(event, partial(fn, persist=persist)) + else: + callbacks[i] = partial(fn, persist=persist) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/track_tracker.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/track_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..d0eaaeb1fb9cdfd18e213a5bda06d3692a9fb690 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/track_tracker.py @@ -0,0 +1,580 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from collections import deque +from functools import wraps +from typing import Any + +import numpy as np +import torch + +from ultralytics.utils.metrics import bbox_ioa + +from ..utils import LOGGER +from .basetrack import TrackState +from .bot_sort import BOTrack +from .utils.gmc import GMC +from .utils.kalman_filter import KalmanFilterXYWH +from .utils.reid import smooth_feature +from .utils.stracks import joint_stracks, merge_track_pools, multi_gmc, parse_bboxes + +# Corner index arrays (LT, LB, RT, RB of an (x1,y1,x2,y2) box) for angle-distance vectorization. +_CORNER_DX_IDX = np.array([0, 0, 2, 2]) +_CORNER_DY_IDX = np.array([1, 3, 1, 3]) + +_LOOSE_NMS_IOU = 0.95 # looser NMS IoU used to recover detections the tight NMS dropped +_LOOSE_NMS_DEDUP_IOU = 0.97 # IoU threshold to consider duplicate detections as "new" + + +def _hmiou_distance(tracks_a: list[TTSTrack], tracks_b: list[TTSTrack]) -> tuple[np.ndarray, np.ndarray]: + """Return (iou_sim, 1 - HMIoU) where HMIoU = HIoU * IoU and HIoU is vertical-overlap / vertical-union.""" + n, m = len(tracks_a), len(tracks_b) + if n == 0 or m == 0: + return np.zeros((n, m), dtype=np.float32), np.ones((n, m), dtype=np.float32) + boxes_a = np.ascontiguousarray([track.xyxy for track in tracks_a], dtype=np.float32) + boxes_b = np.ascontiguousarray([track.xyxy for track in tracks_b], dtype=np.float32) + iou_sim = bbox_ioa(boxes_a, boxes_b, iou=True) + h_over = np.minimum(boxes_a[:, 3:4], boxes_b[:, 3:4].T) - np.maximum(boxes_a[:, 1:2], boxes_b[:, 1:2].T) + h_union = np.maximum(boxes_a[:, 3:4], boxes_b[:, 3:4].T) - np.minimum(boxes_a[:, 1:2], boxes_b[:, 1:2].T) + h_iou = np.clip(h_over / (h_union + 1e-9), 0, 1) + return iou_sim, 1.0 - h_iou * iou_sim + + +def _angle_distance( + tracks: list[TTSTrack], dets: list[TTSTrack], frame_id: int, pairs: tuple[np.ndarray, np.ndarray], delta_t: int = 3 +) -> np.ndarray: + """Return angle distance for the IoU-supported `(track, det)` index `pairs` only. + + `_cost_matrix` overwrites unsupported pairs, so a full `(N, M)` grid would compute discarded work. + """ + track_idx, det_idx = pairs + track_boxes = np.stack([tracks[i].get_history_box(frame_id, delta_t) for i in track_idx]) # (P, 4) + det_boxes = np.stack([dets[i].xyxy for i in det_idx]) # (P, 4) + deltas = det_boxes - track_boxes # (P, 4) + dx = deltas[:, _CORNER_DX_IDX] + dy = deltas[:, _CORNER_DY_IDX] + norms = np.sqrt(dx * dx + dy * dy) + 1e-5 + dx /= norms + dy /= norms + track_velocities = np.stack([tracks[i].velocity for i in track_idx]) # (P, 4, 2) + dot = track_velocities[:, :, 0] * dx + track_velocities[:, :, 1] * dy + dist = np.abs(np.arccos(np.clip(dot, -1, 1))).mean(axis=-1) / np.pi # (P,) + return dist * np.array([dets[i].score for i in det_idx]) + + +def _confidence_distance(tracks: list[TTSTrack], dets: list[TTSTrack]) -> np.ndarray: + """Absolute difference between each track's projected score and each detection's confidence.""" + if len(tracks) == 0 or len(dets) == 0: + return np.ones((len(tracks), len(dets)), dtype=np.float32) + track_prev_scores = np.array([track.prev_score for track in tracks]) + track_curr_scores = np.array([track.score for track in tracks]) + track_proj_scores = track_curr_scores + (track_curr_scores - track_prev_scores) # first-order extrapolation + det_scores = np.array([det.score for det in dets]) + return np.abs(track_proj_scores[:, None] - det_scores[None]) + + +def _iterative_associate(cost: np.ndarray, match_thr: float, reduce_step: float = 0.05) -> tuple[list]: + """Greedy mutually-nearest matching with a threshold that shrinks each iteration. + + Returns (matches, unmatched_tracks, unmatched_dets). + """ + matches = [] + cost = cost.copy() + while cost.shape[0] > 0 and cost.shape[1] > 0: + nearest_det = np.argmin(cost, axis=1) + nearest_track = np.argmin(cost, axis=0) + new_matches = [ + [track_idx, nearest_det[track_idx]] + for track_idx in range(cost.shape[0]) + if nearest_track[nearest_det[track_idx]] == track_idx + and cost[track_idx, nearest_det[track_idx]] < match_thr + ] + if not new_matches: + break + matches.extend(new_matches) + for track_idx, det_idx in new_matches: + cost[track_idx, :] = np.inf + cost[:, det_idx] = np.inf + match_thr -= reduce_step + matched_tracks = {track_idx for track_idx, _ in matches} + matched_dets = {det_idx for _, det_idx in matches} + unmatched_tracks = [i for i in range(cost.shape[0]) if i not in matched_tracks] + unmatched_dets = [i for i in range(cost.shape[1]) if i not in matched_dets] + return matches, unmatched_tracks, unmatched_dets + + +def _track_aware_nms( + tracks: list[TTSTrack], dets: list[TTSTrack], tai_thr: float, new_track_thresh: float +) -> list[bool]: + """TAI NMS: suppress detections that heavily overlap an existing track or a stronger detection.""" + if not dets: + return [] + scores = np.array([det.score for det in dets]) + allow = scores > new_track_thresh + n_tracks, n_dets = len(tracks), len(dets) + if n_tracks + n_dets < 2: + return allow.tolist() + boxes = np.ascontiguousarray([obj.xyxy for obj in tracks + dets], dtype=np.float32) + iou = bbox_ioa(boxes, boxes, iou=True) + + if n_tracks: + allow &= iou[n_tracks:, :n_tracks].max(axis=1) <= tai_thr + + det_iou = iou[n_tracks:, n_tracks:] + order = scores.argsort()[::-1] + for i in order: + if not allow[i]: + continue + suppress = det_iou[i] > tai_thr + suppress[i] = False + allow[suppress] = False + + return allow.tolist() + + +def attach_raw_preds_hook(predictor) -> None: + """Wrap `predictor.postprocess` to capture raw pre-NMS predictions and inputs (idempotent).""" + if hasattr(predictor, "_orig_postprocess"): + return + orig = predictor.postprocess + + @wraps(orig) + def _wrapped(preds, img, orig_imgs, *args, **kwargs): + raw = preds[0] if isinstance(preds, (list, tuple)) else preds # PyTorch models return [inference, extras] + # clone() so the in-place NMS xywh->xyxy conversion can't mutate this capture; keep source device for box_iou + predictor._raw_preds = raw.detach().clone() if isinstance(raw, torch.Tensor) else raw + predictor._postprocess_im = img + predictor._postprocess_im0s = orig_imgs + return orig(preds, img, orig_imgs, *args, **kwargs) + + predictor._orig_postprocess = orig + predictor.postprocess = _wrapped + + +def compute_dets_del(predictor) -> list | None: + """Return per-batch `(xywh, conf, cls)` tuples for detections the tight NMS dropped, or None if unavailable.""" + raw = getattr(predictor, "_raw_preds", None) + if raw is None or not isinstance(raw, torch.Tensor): + return None + from ultralytics.utils import ops + from ultralytics.utils.metrics import box_iou + + loose_results = predictor._orig_postprocess( + raw, predictor._postprocess_im, predictor._postprocess_im0s, iou=_LOOSE_NMS_IOU + ) + + is_obb = predictor.args.task == "obb" + out = [] + for loose, tight in zip(loose_results, predictor.results): + tight_boxes = tight.obb if is_obb else tight.boxes + loose_boxes = loose.obb if is_obb else loose.boxes + if len(loose_boxes) == 0 or len(tight_boxes) == 0: + out.append(None) + continue + max_iou = box_iou(loose_boxes.xyxy, tight_boxes.xyxy).max(dim=1).values + mask = max_iou < _LOOSE_NMS_DEDUP_IOU + if not mask.any(): + out.append(None) + continue + dels = loose_boxes.data[mask].cpu() + if is_obb: + xywh = dels[:, :5].numpy() # xywhr + out.append((xywh, dels[:, 5].numpy(), dels[:, 6].numpy())) + else: + xywh = ops.xyxy2xywh(dels[:, :4]).numpy() + out.append((xywh, dels[:, 4].numpy(), dels[:, 5].numpy())) + + predictor._raw_preds = None + return out + + +def _cosine_distance(tracks: list[TTSTrack], dets: list[TTSTrack]) -> np.ndarray: + """Cosine distance in `[0, 1]` between track and detection embeddings; NaN where either side has no feature. + + A NaN entry signals "no appearance evidence for this pair" so the caller falls back to motion rather than treating a + missing/occlusion-suppressed embedding as maximally dissimilar (which would penalize true matches). + """ + if not tracks or not dets: + return np.ones((len(tracks), len(dets)), dtype=np.float32) + tfeat = [t.smooth_feat if t.smooth_feat is not None else t.curr_feat for t in tracks] + dfeat = [d.curr_feat for d in dets] + dim = next((f.shape[0] for f in (*tfeat, *dfeat) if f is not None), 128) + zeros = np.zeros(dim, dtype=np.float32) + # Pin float32 as `matching.embedding_distance` does: an unpinned stack inherits the encoder's dtype, so a + # half-precision ReID backend (`quantize=16`, or a float16 ONNX model) would decide this cost matrix' precision. + T = np.asarray([f if f is not None else zeros for f in tfeat], dtype=np.float32) + D = np.asarray([f if f is not None else zeros for f in dfeat], dtype=np.float32) + valid = np.array([f is not None for f in tfeat])[:, None] & np.array([f is not None for f in dfeat])[None, :] + return np.where(valid, np.clip(1 - T @ D.T, 0, 1), np.nan).astype(np.float32) + + +class TTSTrack(BOTrack): + """Single-object track for TrackTrack with corner velocity, score history, and ReID features. + + Extends `BOTrack` (XYWH Kalman state and EMA ReID smoothing), adding corner-velocity motion, score history, and + score-adaptive feature smoothing. + + Attributes: + min_track_len (int): Class-level default; overridden by TRACKTRACK from config. + kalman_filter (KalmanFilterXYWH): Per-track Kalman filter used after activation. + mean (np.ndarray): Mean state vector. + covariance (np.ndarray): Covariance matrix. + score (float): Current detection confidence. + prev_score (float): Confidence from the previous update (for score projection). + tracklet_len (int): Successful updates since activation. + velocity (np.ndarray): Per-corner (4,2) unit velocity vectors. + smooth_feat (np.ndarray | None): EMA-smoothed ReID embedding. + curr_feat (np.ndarray | None): Raw ReID embedding from the current frame. + + Examples: + Create and activate a new track + >>> track = TTSTrack(np.array([100, 200, 50, 80, 0]), score=0.9, cls="person") + >>> track.activate(KalmanFilterXYWH(), frame_id=1) + """ + + min_track_len = 3 + _alpha = 0.95 + _delta_t = 3 + + def __init__(self, xywh: np.ndarray, score: float, cls: Any, feat: np.ndarray | None = None): + """Initialize a TTSTrack from a detection bounding box. + + Args: + xywh (np.ndarray): `(x, y, w, h, idx)` or `(x, y, w, h, angle, idx)`, center-based with detection index. + score (float): Detection confidence. + cls (Any): Class label. + feat (np.ndarray | None): Optional ReID feature vector. + """ + super().__init__(xywh, score, cls) # BOTrack sets smooth_feat/curr_feat and the XYWH Kalman state + self.prev_score = score + self.velocity = np.zeros((4, 2), dtype=np.float32) + self._history: deque[tuple[int, np.ndarray]] = deque(maxlen=self._delta_t + 1) + if feat is not None: + self.update_features(feat) + + def update_features(self, feat: np.ndarray) -> None: + """Normalize `feat` and blend it into `smooth_feat` via score-adaptive EMA.""" + beta = self._alpha + (1 - self._alpha) * (1 - self.score) + curr, smooth = smooth_feature(feat, self.smooth_feat, beta) + if curr is not None: + self.curr_feat, self.smooth_feat = curr, smooth + + def get_history_box(self, frame_id: int, dt: int) -> np.ndarray: + """Return the box from `dt` frames back, or the most recent box, or the current box.""" + target = frame_id - dt + for fid, box in self._history: + if fid == target: + return box.copy() + if self._history: + return self._history[-1][1].copy() + return self.xyxy + + def activate(self, kalman_filter: KalmanFilterXYWH, frame_id: int) -> None: + """Initialize Kalman state and promote to New state.""" + self.kalman_filter = kalman_filter + self.track_id = self.next_id() + self.mean, self.covariance = kalman_filter.initiate(self.convert_coords(self._tlwh)) + self._history.append((frame_id, self.xyxy)) + self.tracklet_len = 0 + self.state = TrackState.Tracked if self.min_track_len <= 1 else TrackState.New + self.is_activated = frame_id == 1 or self.state == TrackState.Tracked + self.frame_id = self.start_frame = frame_id + + def re_activate(self, new_track, frame_id: int, new_id: bool = False) -> None: + """Rebind a lost track to a fresh detection via NSA-Kalman.""" + self.prev_score = self.score + self.mean, self.covariance = self.kalman_filter.update( + self.mean, self.covariance, self.convert_coords(new_track.tlwh), confidence=new_track.score + ) + self._history.append((frame_id, self.xyxy)) + self.score = new_track.score # set before update_features so the EMA weight uses the current confidence + if new_track.curr_feat is not None: + self.update_features(new_track.curr_feat) + self.tracklet_len = 0 + self.state = TrackState.Tracked + self.is_activated = True + self.frame_id = frame_id + if new_id: + self.track_id = self.next_id() + self.cls, self.angle, self.idx = new_track.cls, new_track.angle, new_track.idx + + def update(self, new_track, frame_id: int) -> None: + """Update a matched track with a new detection; promote to Tracked after min_track_len.""" + self.frame_id = frame_id + self.tracklet_len += 1 + self.prev_score = self.score + self.mean, self.covariance = self.kalman_filter.update( + self.mean, self.covariance, self.convert_coords(new_track.tlwh), confidence=new_track.score + ) + self._history.append((frame_id, new_track.xyxy)) + + velocity = np.zeros((4, 2), dtype=np.float32) + curr_box = new_track.xyxy + for dt in range(1, self._delta_t + 1): + delta = curr_box - self.get_history_box(frame_id, dt) + dx, dy = delta[_CORNER_DX_IDX], delta[_CORNER_DY_IDX] + norm = np.sqrt(dx * dx + dy * dy) + 1e-5 + velocity += np.stack([dx / norm, dy / norm], axis=-1) / dt + self.velocity = velocity / self._delta_t + + self.score = new_track.score # set before update_features so the EMA weight uses the current confidence + if new_track.curr_feat is not None: + self.update_features(new_track.curr_feat) + + if self.state == TrackState.Tracked or self.tracklet_len + 1 >= self.min_track_len: + self.state = TrackState.Tracked + self.is_activated = True + self.cls, self.angle, self.idx = new_track.cls, new_track.angle, new_track.idx + + def __repr__(self) -> str: + """Short string representation of the track.""" + return f"TT_{self.track_id}_({self.start_frame}-{self.end_frame})" + + +class TRACKTRACK: + """Multi-object tracker implementing Track-Perspective Association and Track-Aware Initialization. + + Detections are partitioned into high, low, and deleted (loose-NMS recovered) sets, then matched against the union of + tracked and lost tracks using a multi-cue cost (HMIoU + cosine ReID + confidence + angle distance) solved with + iterative assignment. Unmatched still-Lost tracks may optionally be re-associated against leftover detections in a + relaxed second pass, and surviving leftover detections spawn new tracks via track-aware NMS. + + Attributes: + tracked_stracks (list[TTSTrack]): Currently tracked tracks. + lost_stracks (list[TTSTrack]): Tracks that lost their detection but remain within the buffer window. + frame_id (int): Current frame index. + args (Any): Parsed tracker configuration. + max_time_lost (int): Frame budget before a lost track is removed (scaled to source frame rate). + kalman_filter (KalmanFilterXYWH): Kalman filter for new-track initialization. + match_thr (float): Cost gate for the main iterative assignment. + lost_match_thr (float): Cost gate for the optional relaxed lost-rebind pass; 0 disables it. + gmc (GMC): Global motion compensation for camera-motion warping. + encoder (Any): ReID encoder, or None when ReID is disabled. + + Methods: + update: Advance the tracker by one frame and return per-object tracking results. + reset: Clear all tracker state. + + Examples: + Initialize and run on a single frame + >>> tracker = TRACKTRACK(args) + >>> tracked_objects = tracker.update(yolo_results, img=image) + """ + + def __init__(self, args): + """Initialize TRACKTRACK from a tracker config (see `ultralytics/cfg/trackers/tracktrack.yaml`). + + Args: + args (Any): Parsed tracker configuration. All knobs are read with `getattr(..., default)` so legacy YAMLs + missing recently added keys still load. + """ + self.tracked_stracks: list[TTSTrack] = [] + self.lost_stracks: list[TTSTrack] = [] + self.removed_stracks: list[TTSTrack] = [] + self.frame_id = 0 + self.args = args + self.max_time_lost = args.track_buffer + self.kalman_filter = KalmanFilterXYWH() + + self.match_thr = getattr(args, "match_thresh", 0.7) + self.lost_match_thr = getattr(args, "lost_match_thr", 0.0) + self.penalty_p = getattr(args, "penalty_p", 0.2) + self.penalty_q = getattr(args, "penalty_q", 0.4) + self.reduce_step = getattr(args, "reduce_step", 0.05) + self.iou_weight = getattr(args, "iou_weight", 0.5) + self.reid_weight = getattr(args, "reid_weight", 0.5) + self.conf_weight = getattr(args, "conf_weight", 0.1) + self.angle_weight = getattr(args, "angle_weight", 0.05) + self.tai_thr = getattr(args, "tai_thr", 0.55) + self.new_track_thresh = getattr(args, "new_track_thresh", 0.7) + self.min_track_len = getattr(args, "min_track_len", 3) + + self.gmc = GMC(method=getattr(args, "gmc_method", "sparseOptFlow")) + + from .utils.reid import build_encoder + + self.encoder = build_encoder( + getattr(args, "with_reid", False), getattr(args, "model", "auto"), getattr(args, "device", None) + ) + + @classmethod + def setup_predictor(cls, predictor): + """Attach the raw-predictions hook for Track-Aware Initialization (detect/obb only). + + Recovered (loose-NMS) detections are box-only and have no row in the post-NMS Results, so on segment/pose + tasks they cannot carry mask/keypoint data and would mis-index downstream; skip recovery (and its + per-frame overhead) for those tasks and RT-DETR predictors, which do not suppress boxes with NMS. + """ + from ultralytics.models.yolo.detect import DetectionPredictor + + if predictor.args.task in {"detect", "obb"} and isinstance(predictor, DetectionPredictor): + attach_raw_preds_hook(predictor) + + @classmethod + def compute_frame_extras(cls, predictor): + """Return per-batch ``(xywh, conf, cls)`` tuples for detections dropped by tight NMS.""" + return compute_dets_del(predictor) + + def _cost_matrix(self, tracks: list[TTSTrack], dets: list[TTSTrack]) -> np.ndarray: + """Return the multi-cue cost matrix (HMIoU + ReID + confidence + angle), gated by IoU support.""" + iou_sim, hmiou_dist = _hmiou_distance(tracks, dets) + if self.encoder is not None: + cos = _cosine_distance(tracks, dets) + # Where appearance is missing (NaN: new track, or occlusion-suppressed detection), fall back to + # pure motion cost for that pair so the embedding neither helps nor penalizes it. + cost = np.where(np.isnan(cos), hmiou_dist, self.iou_weight * hmiou_dist + self.reid_weight * cos) + else: + cost = hmiou_dist + cost += self.conf_weight * _confidence_distance(tracks, dets) + if iou_sim.size > 0: + supported = iou_sim > 0.10 + pairs = np.nonzero(supported) + if len(pairs[0]): + cost[pairs] += self.angle_weight * _angle_distance(tracks, dets, self.frame_id, pairs) + cost[~supported] = 1.0 + return np.clip(cost, 0, 1) + + def _apply_gmc(self, img: np.ndarray, detections: list, pools: list[list[TTSTrack]]) -> None: + """Warp `pools` in place by the current GMC affine.""" + try: + warp = self.gmc.apply(img, [det.xyxy for det in detections]) + except Exception as e: + LOGGER.warning(f"GMC failed, falling back to identity: {e}") + warp = np.eye(2, 3) + for pool in pools: + multi_gmc(pool, warp) + + def update(self, results, img: np.ndarray | None = None, dets_del=None, **kwargs) -> np.ndarray: + """Advance the tracker by one frame and return an `(N, 8)` array of `[x1, y1, x2, y2, id, score, cls, idx]`.""" + self.frame_id += 1 + activated, refind, lost, removed = [], [], [], [] + + scores = np.asarray(results.conf) # keep masks numpy; numpy coerces a 1-element torch bool mask via __index__ + boxes = parse_bboxes(results) + high_mask = scores >= self.args.track_high_thresh + low_mask = (scores > self.args.track_low_thresh) & (scores < self.args.track_high_thresh) + + def _new_track(box, score, cls, feat=None): + track = TTSTrack(box, score, cls, feat) if feat is not None else TTSTrack(box, score, cls) + track.min_track_len = self.min_track_len + return track + + high_boxes, high_scores, high_cls = boxes[high_mask], scores[high_mask], results.cls[high_mask] + feats = kwargs.get("feats") + use_native = getattr(self.args, "model", "auto") == "auto" + encoder_input = None + if self.encoder is not None and len(high_boxes) > 0: + if use_native: + encoder_input = feats[high_mask] if (feats is not None and len(feats)) else None + elif img is not None: + encoder_input = img + + if encoder_input is not None: + features = self.encoder(encoder_input, high_boxes) + dets_high = [_new_track(b, s, c, f) for b, s, c, f in zip(high_boxes, high_scores, high_cls, features)] + else: + dets_high = [_new_track(b, s, c) for b, s, c in zip(high_boxes, high_scores, high_cls)] + dets_low = [_new_track(b, s, c) for b, s, c in zip(boxes[low_mask], scores[low_mask], results.cls[low_mask])] + + dets_recovered: list[TTSTrack] = [] + if dets_del is not None: + del_xywh, del_conf, del_cls = dets_del + mask = del_conf > self.args.track_high_thresh + if mask.any(): + del_boxes = np.concatenate([del_xywh[mask], -np.ones((mask.sum(), 1))], axis=-1) + dets_recovered = [_new_track(b, s, c) for b, s, c in zip(del_boxes, del_conf[mask], del_cls[mask])] + + # Route by state: frame-1 tracks are visible (is_activated) but still New, so they must stay unconfirmed + unconfirmed, tracked = [], [] + for track in self.tracked_stracks: + (tracked if track.state == TrackState.Tracked else unconfirmed).append(track) + pool = joint_stracks(tracked, self.lost_stracks) + + if img is not None and self.gmc.method is not None: + self._apply_gmc(img, dets_high, [pool, unconfirmed]) + TTSTrack.multi_predict(pool) + TTSTrack.multi_predict(unconfirmed) + + # Main association: pool vs (high + low + recovered) detections, with per-bucket cost penalties. + all_dets = dets_high + dets_low + dets_recovered + n_high, n_low = len(dets_high), len(dets_low) + cost = self._cost_matrix(pool, all_dets) + if cost.shape[1] > n_high: + cost[:, n_high : n_high + n_low] += self.penalty_p + if dets_recovered: + cost[:, n_high + n_low :] += self.penalty_q + cost = np.clip(cost, 0, 1) + + matches, unmatched_tracks, unmatched_dets = _iterative_associate(cost, self.match_thr, self.reduce_step) + for track_idx, det_idx in matches: + track, det = pool[track_idx], all_dets[det_idx] + if track.state == TrackState.Tracked: + track.update(det, self.frame_id) + activated.append(track) + else: + track.re_activate(det, self.frame_id, new_id=False) + refind.append(track) + for track_idx in unmatched_tracks: + track = pool[track_idx] + if track.state != TrackState.Lost: + track.mark_lost() + lost.append(track) + + # Second association: unconfirmed tracks vs leftover high-confidence detections. + leftover = [all_dets[i] for i in unmatched_dets if i < n_high] + if unconfirmed and leftover: + uc_cost = self._cost_matrix(unconfirmed, leftover) + uc_matches, uc_unmatched_tracks, uc_unmatched_dets = _iterative_associate( + uc_cost, self.match_thr, self.reduce_step + ) + for track_idx, det_idx in uc_matches: + unconfirmed[track_idx].update(leftover[det_idx], self.frame_id) + activated.append(unconfirmed[track_idx]) + for track_idx in uc_unmatched_tracks: + unconfirmed[track_idx].mark_removed() + removed.append(unconfirmed[track_idx]) + leftover = [leftover[i] for i in uc_unmatched_dets] + else: + for track in unconfirmed: + track.mark_removed() + removed.append(track) + + # Optional relaxed rebind: still-Lost tracks vs leftover detections (disabled when lost_match_thr <= 0). + if self.lost_match_thr > 0 and leftover: + unmatched_lost = [t for t in pool if t.state == TrackState.Lost and t not in lost] + if unmatched_lost: + lost_cost = self._cost_matrix(unmatched_lost, leftover) + lost_matches, _, lost_unmatched = _iterative_associate(lost_cost, self.lost_match_thr, self.reduce_step) + for track_idx, det_idx in lost_matches: + unmatched_lost[track_idx].re_activate(leftover[det_idx], self.frame_id, new_id=False) + refind.append(unmatched_lost[track_idx]) + leftover = [leftover[i] for i in lost_unmatched] + + # TAI: spawn new tracks from leftover detections that survive NMS against existing tracks. + active = [track for track in self.tracked_stracks if track.state == TrackState.Tracked] + activated + for det, ok in zip(leftover, _track_aware_nms(active, leftover, self.tai_thr, self.new_track_thresh)): + if ok: + det.activate(self.kalman_filter, self.frame_id) + activated.append(det) + + for track in self.lost_stracks: + if self.frame_id - track.end_frame > self.max_time_lost: + track.mark_removed() + removed.append(track) + + merge_track_pools(self, activated, refind, lost, removed) + return np.asarray( + [track.result for track in self.tracked_stracks if track.is_activated and track.frame_id == self.frame_id], + dtype=np.float32, + ) + + def reset(self) -> None: + """Clear all tracker state including GMC warp history and the global ID counter.""" + self.tracked_stracks = [] + self.lost_stracks = [] + self.removed_stracks = [] + self.frame_id = 0 + self.kalman_filter = KalmanFilterXYWH() + TTSTrack.reset_id() + self.gmc.reset_params() diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..77a19dcf0f8093de419453747db2e7e719f96349 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__init__.py @@ -0,0 +1 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9a0b4fbc30e9f52201b3d2095b65e25cec77141 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/gmc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/gmc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f084f2b7eaef3d04424c567c87903a9f088a9aa Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/gmc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/kalman_filter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/kalman_filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca30c4dc8671c4e6919281f8cb2dd10b179ddb76 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/kalman_filter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/matching.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/matching.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fa56e3a674b751c27915c9aa11f3d6b48cb1f46 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/matching.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/reid.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/reid.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6ba9cf7d577a5e849da73f4b02b50f1f1ab85ec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/reid.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/stracks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/stracks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5013b77210837dd7da21c21fb50b5f92d6854d7b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/__pycache__/stracks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/gmc.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/gmc.py new file mode 100644 index 0000000000000000000000000000000000000000..cbe91c18224de1ad6c961daa1a387bf29c31ee68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/gmc.py @@ -0,0 +1,341 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import copy + +import cv2 +import numpy as np + +from ultralytics.utils import LOGGER + + +class GMC: + """Generalized Motion Compensation (GMC) class for tracking and object detection in video frames. + + This class provides methods for tracking and detecting objects based on several tracking algorithms including ORB, + SIFT, ECC, and Sparse Optical Flow. It also supports downscaling of frames for computational efficiency. + + Attributes: + method (str | None): The tracking method to use. Options include 'orb', 'sift', 'ecc', 'sparseOptFlow', None. + downscale (int): Factor by which to downscale the frames for processing. + prevFrame (np.ndarray | None): Previous frame for tracking. + prevKeyPoints (tuple | np.ndarray | None): Keypoints from the previous frame. + prevDescriptors (np.ndarray | None): Descriptors from the previous frame. + initializedFirstFrame (bool): Flag indicating if the first frame has been processed. + + Methods: + apply: Apply the chosen method to a raw frame and optionally use provided detections. + apply_ecc: Apply the ECC algorithm to a raw frame. + apply_features: Apply feature-based methods like ORB or SIFT to a raw frame. + apply_sparseoptflow: Apply the Sparse Optical Flow method to a raw frame. + reset_params: Reset the internal parameters of the GMC object. + + Examples: + Create a GMC object and apply it to a frame + >>> gmc = GMC(method="sparseOptFlow", downscale=2) + >>> frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) + >>> warp = gmc.apply(frame) + >>> print(warp.shape) + (2, 3) + """ + + def __init__(self, method: str = "sparseOptFlow", downscale: int = 2) -> None: + """Initialize a Generalized Motion Compensation (GMC) object with tracking method and downscale factor. + + Args: + method (str): The tracking method to use. Options include 'orb', 'sift', 'ecc', 'sparseOptFlow', 'none'. + downscale (int): Downscale factor for processing frames. + """ + super().__init__() + + self.method = method + self.downscale = max(1, downscale) + + if self.method == "orb": + self.detector = cv2.FastFeatureDetector_create(20) + self.extractor = cv2.ORB_create() + self.matcher = cv2.BFMatcher(cv2.NORM_HAMMING) + + elif self.method == "sift": + self.detector = cv2.SIFT_create(nOctaveLayers=3, contrastThreshold=0.02, edgeThreshold=20) + self.extractor = cv2.SIFT_create(nOctaveLayers=3, contrastThreshold=0.02, edgeThreshold=20) + self.matcher = cv2.BFMatcher(cv2.NORM_L2) + + elif self.method == "ecc": + number_of_iterations = 5000 + termination_eps = 1e-6 + self.warp_mode = cv2.MOTION_EUCLIDEAN + self.criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, number_of_iterations, termination_eps) + + elif self.method == "sparseOptFlow": + self.feature_params = { + "maxCorners": 400, # over-determines the 4-DOF transform; optical flow costs one solve per corner + "qualityLevel": 0.01, + "minDistance": 0, # integer-pixel corners: 1 rejects nothing but forces a per-pixel grid + "blockSize": 3, + "useHarrisDetector": False, + "k": 0.04, + } + + elif self.method in {"none", "None", None}: + self.method = None + else: + raise ValueError(f"Unknown GMC method: {method}") + + self.prevFrame = None + self.prevKeyPoints = None + self.prevDescriptors = None + self.initializedFirstFrame = False + + def apply(self, raw_frame: np.ndarray, detections: list | None = None) -> np.ndarray: + """Estimate a 2×3 motion compensation warp for a frame. + + Args: + raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C). + detections (list, optional): List of detections to be used in the processing. + + Returns: + (np.ndarray): Transformation matrix with shape (2, 3). + + Examples: + >>> gmc = GMC(method="sparseOptFlow") + >>> raw_frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) + >>> transformation_matrix = gmc.apply(raw_frame) + >>> print(transformation_matrix.shape) + (2, 3) + """ + if self.method in {"orb", "sift"}: + return self.apply_features(raw_frame, detections) + elif self.method == "ecc": + return self.apply_ecc(raw_frame) + elif self.method == "sparseOptFlow": + return self.apply_sparseoptflow(raw_frame) + else: + return np.eye(2, 3) + + def apply_ecc(self, raw_frame: np.ndarray) -> np.ndarray: + """Apply the ECC (Enhanced Correlation Coefficient) algorithm to a raw frame for motion compensation. + + Args: + raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C). + + Returns: + (np.ndarray): Transformation matrix with shape (2, 3). + + Examples: + >>> gmc = GMC(method="ecc") + >>> raw_frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) + >>> transformation_matrix = gmc.apply_ecc(raw_frame) + >>> print(transformation_matrix.shape) + (2, 3) + """ + height, width, c = raw_frame.shape + frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY) if c == 3 else raw_frame + H = np.eye(2, 3, dtype=np.float32) + + # Downscale image for computational efficiency + if self.downscale > 1.0: + frame = cv2.GaussianBlur(frame, (3, 3), 1.5) + frame = cv2.resize(frame, (width // self.downscale, height // self.downscale)) + + # Handle first frame initialization + if not self.initializedFirstFrame: + self.prevFrame = frame.copy() + self.initializedFirstFrame = True + return H + + # Run the ECC algorithm to find transformation matrix + try: + (_, H) = cv2.findTransformECC(self.prevFrame, frame, H, self.warp_mode, self.criteria, None, 1) + H[:, 2] *= (width / frame.shape[1], height / frame.shape[0]) + except Exception as e: + LOGGER.warning(f"findTransformECC failed; using identity warp. {e}") + + self.prevFrame = frame.copy() + return H + + def apply_features(self, raw_frame: np.ndarray, detections: list | None = None) -> np.ndarray: + """Apply feature-based methods like ORB or SIFT to a raw frame. + + Args: + raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C). + detections (list, optional): List of detections to be used in the processing. + + Returns: + (np.ndarray): Transformation matrix with shape (2, 3). + + Examples: + >>> gmc = GMC(method="orb") + >>> raw_frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) + >>> transformation_matrix = gmc.apply_features(raw_frame) + >>> print(transformation_matrix.shape) + (2, 3) + """ + height, width, c = raw_frame.shape + frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY) if c == 3 else raw_frame + H = np.eye(2, 3) + + # Downscale image for computational efficiency + if self.downscale > 1.0: + frame = cv2.resize(frame, (width // self.downscale, height // self.downscale)) + width = width // self.downscale + height = height // self.downscale + + # Create mask for keypoint detection, excluding border regions + mask = np.zeros_like(frame) + mask[int(0.02 * height) : int(0.98 * height), int(0.02 * width) : int(0.98 * width)] = 255 + + # Exclude detection regions from mask to avoid tracking detected objects + if detections is not None: + for det in detections: + tlbr = (det[:4] / self.downscale).astype(np.int_) + mask[tlbr[1] : tlbr[3], tlbr[0] : tlbr[2]] = 0 + + # Find keypoints and compute descriptors + keypoints = self.detector.detect(frame, mask) + keypoints, descriptors = self.extractor.compute(frame, keypoints) + + # Handle first frame initialization + if not self.initializedFirstFrame: + self.prevFrame = frame.copy() + self.prevKeyPoints = copy.copy(keypoints) + self.prevDescriptors = copy.copy(descriptors) + self.initializedFirstFrame = True + return H + + # Match descriptors between previous and current frame + knnMatches = ( + self.matcher.knnMatch(self.prevDescriptors, descriptors, 2) + if self.prevDescriptors is not None and descriptors is not None + else [] + ) + + # Filter matches based on spatial distance constraints + spatialDistances = [] + maxSpatialDistance = 0.25 * np.array([width, height]) + + # Apply Lowe's ratio test and spatial distance filtering + prevPoints = [] + currPoints = [] + for matches in knnMatches: + if len(matches) < 2: + continue + m, n = matches + if m.distance < 0.9 * n.distance: + prevKeyPointLocation = self.prevKeyPoints[m.queryIdx].pt + currKeyPointLocation = keypoints[m.trainIdx].pt + + spatialDistance = ( + prevKeyPointLocation[0] - currKeyPointLocation[0], + prevKeyPointLocation[1] - currKeyPointLocation[1], + ) + + if (np.abs(spatialDistance[0]) < maxSpatialDistance[0]) and ( + np.abs(spatialDistance[1]) < maxSpatialDistance[1] + ): + spatialDistances.append(spatialDistance) + prevPoints.append(prevKeyPointLocation) + currPoints.append(currKeyPointLocation) + + if not spatialDistances: + self.prevFrame = frame.copy() + self.prevKeyPoints = copy.copy(keypoints) + self.prevDescriptors = copy.copy(descriptors) + return H + + # Filter outliers using statistical analysis + spatialDistances = np.asarray(spatialDistances).reshape(-1, 2) + meanSpatialDistances = np.mean(spatialDistances, 0) + stdSpatialDistances = np.std(spatialDistances, 0) + # Include exact-boundary and zero-variance matches. + inliers = np.abs(spatialDistances - meanSpatialDistances) <= 2.5 * stdSpatialDistances + + # Keep matched point pairs that survive the outlier filter + good = inliers.all(axis=1) + prevPoints = np.asarray(prevPoints).reshape(-1, 2)[good] + currPoints = np.asarray(currPoints).reshape(-1, 2)[good] + + # Estimate transformation matrix using RANSAC + if prevPoints.shape[0] > 4: + H, inliers = cv2.estimateAffinePartial2D(prevPoints, currPoints, cv2.RANSAC) + + # Scale translation components back to original resolution + if self.downscale > 1.0: + H[0, 2] *= self.downscale + H[1, 2] *= self.downscale + else: + LOGGER.warning("not enough matching points") + + # Store current frame data for next iteration + self.prevFrame = frame.copy() + self.prevKeyPoints = copy.copy(keypoints) + self.prevDescriptors = copy.copy(descriptors) + + return H + + def apply_sparseoptflow(self, raw_frame: np.ndarray) -> np.ndarray: + """Apply Sparse Optical Flow method to a raw frame. + + Args: + raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C). + + Returns: + (np.ndarray): Transformation matrix with shape (2, 3). + + Examples: + >>> gmc = GMC() + >>> raw_frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) + >>> transformation_matrix = gmc.apply_sparseoptflow(raw_frame) + >>> print(transformation_matrix.shape) + (2, 3) + """ + height, width, c = raw_frame.shape + frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY) if c == 3 else raw_frame + H = np.eye(2, 3) + + # Downscale image for computational efficiency + if self.downscale > 1.0: + frame = cv2.resize(frame, (width // self.downscale, height // self.downscale)) + + # Find good features to track + keypoints = cv2.goodFeaturesToTrack(frame, mask=None, **self.feature_params) + + # Handle first frame initialization + if not self.initializedFirstFrame or self.prevKeyPoints is None: + self.prevFrame = frame.copy() + self.prevKeyPoints = copy.copy(keypoints) + self.initializedFirstFrame = True + return H + + # Calculate optical flow using Lucas-Kanade method + matchedKeypoints, status, _ = cv2.calcOpticalFlowPyrLK(self.prevFrame, frame, self.prevKeyPoints, None) + + # Extract successfully tracked points + good = status.ravel().astype(bool) + prevPoints = self.prevKeyPoints[good] + currPoints = matchedKeypoints[good] + + # Estimate transformation matrix using RANSAC + if prevPoints.shape[0] > 4: + H, _ = cv2.estimateAffinePartial2D(prevPoints, currPoints, cv2.RANSAC) + + # Scale translation components back to original resolution + if self.downscale > 1.0: + H[0, 2] *= self.downscale + H[1, 2] *= self.downscale + else: + LOGGER.warning("not enough matching points") + + # Store current frame data for next iteration + self.prevFrame = frame.copy() + self.prevKeyPoints = copy.copy(keypoints) + + return H + + def reset_params(self) -> None: + """Reset the internal parameters including previous frame, keypoints, and descriptors.""" + self.prevFrame = None + self.prevKeyPoints = None + self.prevDescriptors = None + self.initializedFirstFrame = False diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/kalman_filter.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/kalman_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..06141a75292007a12170abc1182fc5a691878eb1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/kalman_filter.py @@ -0,0 +1,482 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import numpy as np + + +class KalmanFilterXYAH: + """A KalmanFilterXYAH class for tracking bounding boxes in image space using a Kalman filter. + + Implements a simple Kalman filter for tracking bounding boxes in image space. The 8-dimensional state space (x, y, + a, h, vx, vy, va, vh) contains the bounding box center position (x, y), aspect ratio a, height h, and their + respective velocities. Object motion follows a constant velocity model, and bounding box location (x, y, a, h) is + taken as a direct observation of the state space (linear observation model). + + Attributes: + _motion_mat (np.ndarray): The motion matrix for the Kalman filter. + _update_mat (np.ndarray): The update matrix for the Kalman filter. + _std_weight_position (float): Standard deviation weight for position. + _std_weight_velocity (float): Standard deviation weight for velocity. + + Methods: + initiate: Create a track from an unassociated measurement. + predict: Run the Kalman filter prediction step. + project: Project the state distribution to measurement space. + multi_predict: Run the Kalman filter prediction step (vectorized version). + update: Run the Kalman filter correction step. + gating_distance: Compute the gating distance between state distribution and measurements. + + Examples: + Initialize the Kalman filter and create a track from a measurement + >>> kf = KalmanFilterXYAH() + >>> measurement = np.array([100, 200, 1.5, 50]) + >>> mean, covariance = kf.initiate(measurement) + """ + + def __init__(self): + """Initialize Kalman filter model matrices with motion and observation uncertainty weights. + + The Kalman filter is initialized with an 8-dimensional state space (x, y, a, h, vx, vy, va, vh), where (x, y) + represents the bounding box center position, 'a' is the aspect ratio, 'h' is the height, and their respective + velocities are (vx, vy, va, vh). The filter uses a constant velocity model for object motion and a linear + observation model for bounding box location. + """ + ndim, dt = 4, 1.0 + + # Create Kalman filter model matrices + self._motion_mat = np.eye(2 * ndim, 2 * ndim) + for i in range(ndim): + self._motion_mat[i, ndim + i] = dt + self._update_mat = np.eye(ndim, 2 * ndim) + + # Motion and observation uncertainty are chosen relative to the current state estimate + self._std_weight_position = 1.0 / 20 + self._std_weight_velocity = 1.0 / 160 + + def initiate(self, measurement: np.ndarray): + """Create a track from an unassociated measurement. + + Args: + measurement (np.ndarray): Bounding box coordinates (x, y, a, h) with center position (x, y), aspect ratio a, + and height h. + + Returns: + mean (np.ndarray): Float64 mean vector (8-dimensional) with zero-initialized velocities. + covariance (np.ndarray): Float64 covariance matrix (8x8 dimensional). + + Examples: + >>> kf = KalmanFilterXYAH() + >>> measurement = np.array([100, 50, 1.5, 200]) + >>> mean, covariance = kf.initiate(measurement) + """ + measurement = np.asarray(measurement, dtype=np.float64) + mean_pos = measurement + mean_vel = np.zeros_like(mean_pos) + mean = np.r_[mean_pos, mean_vel] + + std = [ + 2 * self._std_weight_position * measurement[3], + 2 * self._std_weight_position * measurement[3], + 1e-2, + 2 * self._std_weight_position * measurement[3], + 10 * self._std_weight_velocity * measurement[3], + 10 * self._std_weight_velocity * measurement[3], + 1e-5, + 10 * self._std_weight_velocity * measurement[3], + ] + covariance = np.diag(np.square(std)) + return mean, covariance + + def predict(self, mean: np.ndarray, covariance: np.ndarray): + """Run Kalman filter prediction step. + + Args: + mean (np.ndarray): The 8-dimensional mean vector of the object state at the previous time step. + covariance (np.ndarray): The 8x8-dimensional covariance matrix of the object state at the previous time + step. + + Returns: + mean (np.ndarray): Mean vector of the predicted state. + covariance (np.ndarray): Covariance matrix of the predicted state. + + Examples: + >>> kf = KalmanFilterXYAH() + >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0]) + >>> covariance = np.eye(8) + >>> predicted_mean, predicted_covariance = kf.predict(mean, covariance) + """ + std_pos = [ + self._std_weight_position * mean[3], + self._std_weight_position * mean[3], + 1e-2, + self._std_weight_position * mean[3], + ] + std_vel = [ + self._std_weight_velocity * mean[3], + self._std_weight_velocity * mean[3], + 1e-5, + self._std_weight_velocity * mean[3], + ] + motion_cov = np.diag(np.square(np.r_[std_pos, std_vel])) + + mean = np.dot(mean, self._motion_mat.T) + covariance = np.linalg.multi_dot((self._motion_mat, covariance, self._motion_mat.T)) + motion_cov + + return mean, covariance + + def project(self, mean: np.ndarray, covariance: np.ndarray, confidence: float | None = None): + """Project state distribution to measurement space. + + Args: + mean (np.ndarray): The state's mean vector (8 dimensional array). + covariance (np.ndarray): The state's covariance matrix (8x8 dimensional). + confidence (float, optional): Detection confidence; when set, scales measurement noise by max(1 - + confidence, 0.05) (NSA-Kalman). + + Returns: + mean (np.ndarray): Projected mean of the given state estimate. + covariance (np.ndarray): Projected covariance matrix of the given state estimate. + + Examples: + >>> kf = KalmanFilterXYAH() + >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0]) + >>> covariance = np.eye(8) + >>> projected_mean, projected_covariance = kf.project(mean, covariance) + """ + std = [ + self._std_weight_position * mean[3], + self._std_weight_position * mean[3], + 1e-1, + self._std_weight_position * mean[3], + ] + innovation_cov = np.diag(np.square(std)) + if confidence is not None: # NSA-Kalman: scale measurement noise by detection confidence (StrongSORT) + innovation_cov *= max(1.0 - float(confidence), 0.05) + + mean = mean[:4].copy() + covariance = covariance[:4, :4] + return mean, covariance + innovation_cov + + def multi_predict(self, mean: np.ndarray, covariance: np.ndarray): + """Run Kalman filter prediction step for multiple object states (Vectorized version). + + Args: + mean (np.ndarray): The Nx8 dimensional mean matrix of the object states at the previous time step. + covariance (np.ndarray): The Nx8x8 covariance matrix of the object states at the previous time step. + + Returns: + mean (np.ndarray): Mean matrix of the predicted states with shape (N, 8). + covariance (np.ndarray): Covariance matrix of the predicted states with shape (N, 8, 8). + + Examples: + >>> kf = KalmanFilterXYAH() + >>> mean = np.random.rand(10, 8) # 10 object states + >>> covariance = np.random.rand(10, 8, 8) # Covariance matrices for 10 object states + >>> predicted_mean, predicted_covariance = kf.multi_predict(mean, covariance) + """ + std_pos = [ + self._std_weight_position * mean[:, 3], + self._std_weight_position * mean[:, 3], + 1e-2 * np.ones_like(mean[:, 3]), + self._std_weight_position * mean[:, 3], + ] + std_vel = [ + self._std_weight_velocity * mean[:, 3], + self._std_weight_velocity * mean[:, 3], + 1e-5 * np.ones_like(mean[:, 3]), + self._std_weight_velocity * mean[:, 3], + ] + sqr = np.square(np.r_[std_pos, std_vel]).T + + motion_cov = np.zeros((sqr.shape[0], 8, 8)) + motion_cov[:, range(8), range(8)] = sqr + + mean = np.dot(mean, self._motion_mat.T) + left = np.dot(self._motion_mat, covariance).transpose((1, 0, 2)) + covariance = np.dot(left, self._motion_mat.T) + motion_cov + + return mean, covariance + + def update( + self, mean: np.ndarray, covariance: np.ndarray, measurement: np.ndarray, confidence: float | None = None + ): + """Run Kalman filter correction step. + + Args: + mean (np.ndarray): The predicted state's mean vector (8 dimensional). + covariance (np.ndarray): The state's covariance matrix (8x8 dimensional). + measurement (np.ndarray): The 4 dimensional measurement vector (x, y, a, h), where (x, y) is the center + position, a the aspect ratio, and h the height of the bounding box. + confidence (float, optional): Detection confidence; when set, scales measurement noise by max(1 - + confidence, 0.05) (NSA-Kalman). + + Returns: + new_mean (np.ndarray): Measurement-corrected state mean. + new_covariance (np.ndarray): Measurement-corrected state covariance. + + Examples: + >>> kf = KalmanFilterXYAH() + >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0]) + >>> covariance = np.eye(8) + >>> measurement = np.array([1, 1, 1, 1]) + >>> new_mean, new_covariance = kf.update(mean, covariance, measurement) + """ + projected_mean, projected_cov = self.project(mean, covariance, confidence) + + kalman_gain = np.linalg.solve(projected_cov, covariance[:, :4].T).T + innovation = measurement - projected_mean + + new_mean = mean + np.dot(innovation, kalman_gain.T) + new_covariance = covariance - np.linalg.multi_dot((kalman_gain, projected_cov, kalman_gain.T)) + return new_mean, new_covariance + + def gating_distance( + self, + mean: np.ndarray, + covariance: np.ndarray, + measurements: np.ndarray, + only_position: bool = False, + metric: str = "maha", + ) -> np.ndarray: + """Compute gating distance between state distribution and measurements. + + A suitable threshold for the returned squared Mahalanobis distance is the 95th-percentile chi-square value: + 9.4877 for 4 degrees of freedom when `only_position` is False, and 5.9915 for 2 otherwise. The `"gaussian"` + metric returns a squared Euclidean distance, for which this threshold does not apply. + + Args: + mean (np.ndarray): Mean vector over the state distribution (8 dimensional). + covariance (np.ndarray): Covariance of the state distribution (8x8 dimensional). + measurements (np.ndarray): An (N, 4) matrix of N measurements, each in format (x, y, a, h) where (x, y) is + the bounding box center position, a the aspect ratio, and h the height. + only_position (bool, optional): If True, distance computation is done with respect to box center position + only. + metric (str, optional): The metric to use for calculating the distance. Options are 'gaussian' for the + squared Euclidean distance and 'maha' for the squared Mahalanobis distance. + + Returns: + (np.ndarray): Returns an array of length N, where the i-th element contains the squared distance between + (mean, covariance) and `measurements[i]`. + + Examples: + Compute gating distance using Mahalanobis metric: + >>> kf = KalmanFilterXYAH() + >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0]) + >>> covariance = np.eye(8) + >>> measurements = np.array([[1, 1, 1, 1], [2, 2, 1, 1]]) + >>> distances = kf.gating_distance(mean, covariance, measurements, only_position=False, metric="maha") + """ + mean, covariance = self.project(mean, covariance) + if only_position: + mean, covariance = mean[:2], covariance[:2, :2] + measurements = measurements[:, :2] + + d = measurements - mean + if metric == "gaussian": + return np.sum(d * d, axis=1) + elif metric == "maha": + cholesky_factor = np.linalg.cholesky(covariance) + z = np.linalg.solve(cholesky_factor, d.T) + return np.sum(z * z, axis=0) # square maha + else: + raise ValueError("Invalid distance metric") + + +class KalmanFilterXYWH(KalmanFilterXYAH): + """A KalmanFilterXYWH class for tracking bounding boxes in image space using a Kalman filter. + + Implements a Kalman filter for tracking bounding boxes with state space (x, y, w, h, vx, vy, vw, vh), where (x, y) + is the center position, w is the width, h is the height, and vx, vy, vw, vh are their respective velocities. The + object motion follows a constant velocity model, and the bounding box location (x, y, w, h) is taken as a direct + observation of the state space (linear observation model). + + Attributes: + _motion_mat (np.ndarray): The motion matrix for the Kalman filter. + _update_mat (np.ndarray): The update matrix for the Kalman filter. + _std_weight_position (float): Standard deviation weight for position. + _std_weight_velocity (float): Standard deviation weight for velocity. + + Methods: + initiate: Create a track from an unassociated measurement. + predict: Run the Kalman filter prediction step. + project: Project the state distribution to measurement space. + multi_predict: Run the Kalman filter prediction step in a vectorized manner. + update: Run the Kalman filter correction step. + + Examples: + Create a Kalman filter and initialize a track + >>> kf = KalmanFilterXYWH() + >>> measurement = np.array([100, 50, 20, 40]) + >>> mean, covariance = kf.initiate(measurement) + """ + + def initiate(self, measurement: np.ndarray): + """Create track from unassociated measurement. + + Args: + measurement (np.ndarray): Bounding box coordinates (x, y, w, h) with center position (x, y), width, and + height. + + Returns: + mean (np.ndarray): Float64 mean vector (8 dimensional) with zero-initialized velocities. + covariance (np.ndarray): Float64 covariance matrix (8x8 dimensional). + + Examples: + >>> kf = KalmanFilterXYWH() + >>> measurement = np.array([100, 50, 20, 40]) + >>> mean, covariance = kf.initiate(measurement) + """ + measurement = np.asarray(measurement, dtype=np.float64) + mean_pos = measurement + mean_vel = np.zeros_like(mean_pos) + mean = np.r_[mean_pos, mean_vel] + + std = [ + 2 * self._std_weight_position * measurement[2], + 2 * self._std_weight_position * measurement[3], + 2 * self._std_weight_position * measurement[2], + 2 * self._std_weight_position * measurement[3], + 10 * self._std_weight_velocity * measurement[2], + 10 * self._std_weight_velocity * measurement[3], + 10 * self._std_weight_velocity * measurement[2], + 10 * self._std_weight_velocity * measurement[3], + ] + covariance = np.diag(np.square(std)) + return mean, covariance + + def predict(self, mean: np.ndarray, covariance: np.ndarray): + """Run Kalman filter prediction step. + + Args: + mean (np.ndarray): The 8-dimensional mean vector of the object state at the previous time step. + covariance (np.ndarray): The 8x8-dimensional covariance matrix of the object state at the previous time + step. + + Returns: + mean (np.ndarray): Mean vector of the predicted state. + covariance (np.ndarray): Covariance matrix of the predicted state. + + Examples: + >>> kf = KalmanFilterXYWH() + >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0]) + >>> covariance = np.eye(8) + >>> predicted_mean, predicted_covariance = kf.predict(mean, covariance) + """ + std_pos = [ + self._std_weight_position * mean[2], + self._std_weight_position * mean[3], + self._std_weight_position * mean[2], + self._std_weight_position * mean[3], + ] + std_vel = [ + self._std_weight_velocity * mean[2], + self._std_weight_velocity * mean[3], + self._std_weight_velocity * mean[2], + self._std_weight_velocity * mean[3], + ] + motion_cov = np.diag(np.square(np.r_[std_pos, std_vel])) + + mean = np.dot(mean, self._motion_mat.T) + covariance = np.linalg.multi_dot((self._motion_mat, covariance, self._motion_mat.T)) + motion_cov + + return mean, covariance + + def project(self, mean: np.ndarray, covariance: np.ndarray, confidence: float | None = None): + """Project state distribution to measurement space. + + Args: + mean (np.ndarray): The state's mean vector (8 dimensional array). + covariance (np.ndarray): The state's covariance matrix (8x8 dimensional). + confidence (float, optional): Detection confidence; when set, scales measurement noise by max(1 - + confidence, 0.05) (NSA-Kalman). + + Returns: + mean (np.ndarray): Projected mean of the given state estimate. + covariance (np.ndarray): Projected covariance matrix of the given state estimate. + + Examples: + >>> kf = KalmanFilterXYWH() + >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0]) + >>> covariance = np.eye(8) + >>> projected_mean, projected_cov = kf.project(mean, covariance) + """ + std = [ + self._std_weight_position * mean[2], + self._std_weight_position * mean[3], + self._std_weight_position * mean[2], + self._std_weight_position * mean[3], + ] + innovation_cov = np.diag(np.square(std)) + if confidence is not None: # NSA-Kalman: scale measurement noise by detection confidence (StrongSORT) + innovation_cov *= max(1.0 - float(confidence), 0.05) + + mean = mean[:4].copy() + covariance = covariance[:4, :4] + return mean, covariance + innovation_cov + + def multi_predict(self, mean: np.ndarray, covariance: np.ndarray): + """Run Kalman filter prediction step (Vectorized version). + + Args: + mean (np.ndarray): The Nx8 dimensional mean matrix of the object states at the previous time step. + covariance (np.ndarray): The Nx8x8 covariance matrix of the object states at the previous time step. + + Returns: + mean (np.ndarray): Mean matrix of the predicted states with shape (N, 8). + covariance (np.ndarray): Covariance matrix of the predicted states with shape (N, 8, 8). + + Examples: + >>> mean = np.random.rand(5, 8) # 5 objects with 8-dimensional state vectors + >>> covariance = np.random.rand(5, 8, 8) # 5 objects with 8x8 covariance matrices + >>> kf = KalmanFilterXYWH() + >>> predicted_mean, predicted_covariance = kf.multi_predict(mean, covariance) + """ + std_pos = [ + self._std_weight_position * mean[:, 2], + self._std_weight_position * mean[:, 3], + self._std_weight_position * mean[:, 2], + self._std_weight_position * mean[:, 3], + ] + std_vel = [ + self._std_weight_velocity * mean[:, 2], + self._std_weight_velocity * mean[:, 3], + self._std_weight_velocity * mean[:, 2], + self._std_weight_velocity * mean[:, 3], + ] + sqr = np.square(np.r_[std_pos, std_vel]).T + + motion_cov = np.zeros((sqr.shape[0], 8, 8)) + motion_cov[:, range(8), range(8)] = sqr + + mean = np.dot(mean, self._motion_mat.T) + left = np.dot(self._motion_mat, covariance).transpose((1, 0, 2)) + covariance = np.dot(left, self._motion_mat.T) + motion_cov + + return mean, covariance + + def update( + self, mean: np.ndarray, covariance: np.ndarray, measurement: np.ndarray, confidence: float | None = None + ): + """Run Kalman filter correction step. + + Args: + mean (np.ndarray): The predicted state's mean vector (8 dimensional). + covariance (np.ndarray): The state's covariance matrix (8x8 dimensional). + measurement (np.ndarray): The 4 dimensional measurement vector (x, y, w, h), where (x, y) is the center + position, w the width, and h the height of the bounding box. + confidence (float, optional): Detection confidence; when set, scales measurement noise by max(1 - + confidence, 0.05) (NSA-Kalman). + + Returns: + new_mean (np.ndarray): Measurement-corrected state mean. + new_covariance (np.ndarray): Measurement-corrected state covariance. + + Examples: + >>> kf = KalmanFilterXYWH() + >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0]) + >>> covariance = np.eye(8) + >>> measurement = np.array([0.5, 0.5, 1.2, 1.2]) + >>> new_mean, new_covariance = kf.update(mean, covariance, measurement) + """ + return super().update(mean, covariance, measurement, confidence=confidence) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/matching.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/matching.py new file mode 100644 index 0000000000000000000000000000000000000000..00cb2d6af6d91cd101d805e97e6135b77fc52ec8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/matching.py @@ -0,0 +1,167 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import numpy as np + +from ultralytics.utils.metrics import batch_probiou, bbox_ioa + +try: + import lap # for linear_assignment + + assert lap.__version__ # verify package is not directory +except (ImportError, AssertionError, AttributeError): + from ultralytics.utils.checks import check_requirements + + check_requirements("lap>=0.5.12") # https://github.com/gatagat/lap + import lap + + +def linear_assignment(cost_matrix: np.ndarray, thresh: float, use_lap: bool = True): + """Perform linear assignment using either lap.lapjv or the built-in NumPy solver. + + Args: + cost_matrix (np.ndarray): The matrix containing cost values for assignments, with shape (N, M). + thresh (float): Threshold for considering an assignment valid. + use_lap (bool): Use lap.lapjv for the assignment. If False, ops.linear_sum_assignment is used. + + Returns: + matched_indices (list[list[int]] | np.ndarray): Matched indices of shape (K, 2), where K is the number of + matches. + unmatched_a (tuple | list | np.ndarray): Unmatched indices from the first set. + unmatched_b (tuple | list | np.ndarray): Unmatched indices from the second set. + + Examples: + >>> cost_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> thresh = 5.0 + >>> matched_indices, unmatched_a, unmatched_b = linear_assignment(cost_matrix, thresh, use_lap=True) + """ + if cost_matrix.size == 0: + return np.empty((0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(range(cost_matrix.shape[1])) + + if use_lap: + # Use lap.lapjv + # https://github.com/gatagat/lap + _, x, y = lap.lapjv(cost_matrix, extend_cost=True, cost_limit=thresh) + matches = [[ix, mx] for ix, mx in enumerate(x) if mx >= 0] + unmatched_a = np.where(x < 0)[0] + unmatched_b = np.where(y < 0)[0] + else: + from ultralytics.utils.ops import linear_sum_assignment + + x, y = linear_sum_assignment(cost_matrix) # row x, col y + matches = np.asarray([[x[i], y[i]] for i in range(len(x)) if cost_matrix[x[i], y[i]] <= thresh]) + if len(matches) == 0: + unmatched_a = list(np.arange(cost_matrix.shape[0])) + unmatched_b = list(np.arange(cost_matrix.shape[1])) + else: + unmatched_a = list(frozenset(np.arange(cost_matrix.shape[0])) - frozenset(matches[:, 0])) + unmatched_b = list(frozenset(np.arange(cost_matrix.shape[1])) - frozenset(matches[:, 1])) + + return matches, unmatched_a, unmatched_b + + +def iou_distance(atracks: list, btracks: list) -> np.ndarray: + """Compute cost based on Intersection over Union (IoU) between tracks. + + Args: + atracks (list[STrack] | list[np.ndarray]): List of tracks 'a' or bounding boxes. + btracks (list[STrack] | list[np.ndarray]): List of tracks 'b' or bounding boxes. + + Returns: + (np.ndarray): Cost matrix computed based on IoU with shape (len(atracks), len(btracks)). + + Examples: + Compute IoU distance between two sets of tracks + >>> atracks = [np.array([0, 0, 10, 10]), np.array([20, 20, 30, 30])] + >>> btracks = [np.array([5, 5, 15, 15]), np.array([25, 25, 35, 35])] + >>> cost_matrix = iou_distance(atracks, btracks) + """ + if (atracks and isinstance(atracks[0], np.ndarray)) or (btracks and isinstance(btracks[0], np.ndarray)): + atlbrs = atracks + btlbrs = btracks + else: + atlbrs = [track.xywha if track.angle is not None else track.xyxy for track in atracks] + btlbrs = [track.xywha if track.angle is not None else track.xyxy for track in btracks] + + ious = np.zeros((len(atlbrs), len(btlbrs)), dtype=np.float32) + if len(atlbrs) and len(btlbrs): + if len(atlbrs[0]) == 5 and len(btlbrs[0]) == 5: + ious = batch_probiou( + np.ascontiguousarray(atlbrs, dtype=np.float32), + np.ascontiguousarray(btlbrs, dtype=np.float32), + ).numpy() + else: + ious = bbox_ioa( + np.ascontiguousarray(atlbrs, dtype=np.float32), + np.ascontiguousarray(btlbrs, dtype=np.float32), + iou=True, + ) + return 1 - ious # cost matrix + + +def embedding_distance(tracks: list, detections: list) -> np.ndarray: + """Compute cosine distance between tracks and detections based on embeddings. + + Args: + tracks (list[BOTrack]): List of tracks, where each track contains embedding features. + detections (list[BOTrack]): List of detections, where each detection contains embedding features. + + Returns: + (np.ndarray): Cost matrix computed based on embeddings with shape (N, M), where N is the number of tracks and M + is the number of detections. + + Examples: + Compute the embedding distance between tracks and detections using cosine metric + >>> tracks = [BOTrack(...), BOTrack(...)] # List of track objects with embedding features + >>> detections = [BOTrack(...), BOTrack(...)] # List of detection objects with embedding features + >>> cost_matrix = embedding_distance(tracks, detections) + """ + cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float32) + if cost_matrix.size == 0: + return cost_matrix + # A zero-norm embedding is skipped upstream, leaving curr_feat/smooth_feat None. Stack a zero placeholder so the + # array isn't ragged, then (below) force any missing-feature pair to the maximum distance so callers ignore + # appearance and fall back to motion/IoU rather than crashing or treating it as a partial match. + track_feats = [t.smooth_feat for t in tracks] + det_feats = [d.curr_feat for d in detections] + feat_dim = next((len(f) for f in (*track_feats, *det_feats) if f is not None), 0) + zeros = np.zeros(feat_dim, dtype=np.float32) + track_features = np.asarray([f if f is not None else zeros for f in track_feats], dtype=np.float32) + det_features = np.asarray([f if f is not None else zeros for f in det_feats], dtype=np.float32) + track_norm = np.linalg.norm(track_features, axis=1, keepdims=True) + det_norm = np.linalg.norm(det_features, axis=1, keepdims=True).T + cost_matrix = 1 - track_features @ det_features.T / np.maximum( + track_norm * det_norm, np.finfo(track_features.dtype).eps + ) + cost_matrix = np.maximum(0.0, cost_matrix) # Normalized features + missing_t = [i for i, f in enumerate(track_feats) if f is None] + missing_d = [j for j, f in enumerate(det_feats) if f is None] + if missing_t: + cost_matrix[missing_t] = 2.0 # max cosine distance -> caller's /2 then appearance gate ignores the pair + if missing_d: + cost_matrix[:, missing_d] = 2.0 + return cost_matrix + + +def fuse_score(cost_matrix: np.ndarray, detections: list) -> np.ndarray: + """Fuse cost matrix with detection scores to produce a single cost matrix. + + Args: + cost_matrix (np.ndarray): The matrix containing cost values for assignments, with shape (N, M). + detections (list[BaseTrack]): List of detections, each containing a score attribute. + + Returns: + (np.ndarray): Fused cost matrix with shape (N, M). + + Examples: + Fuse a cost matrix with detection scores + >>> cost_matrix = np.random.rand(5, 10) # 5 tracks and 10 detections + >>> detections = [BaseTrack(score=np.random.rand()) for _ in range(10)] + >>> fused_matrix = fuse_score(cost_matrix, detections) + """ + if cost_matrix.size == 0: + return cost_matrix + iou_sim = 1 - cost_matrix + det_scores = np.array([det.score for det in detections]) + det_scores = det_scores[None].repeat(cost_matrix.shape[0], axis=0) + fuse_sim = iou_sim * det_scores + return 1 - fuse_sim # fuse_cost diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/reid.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/reid.py new file mode 100644 index 0000000000000000000000000000000000000000..0a045a771bf8031b266df8f784abe4156b10d5f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/reid.py @@ -0,0 +1,176 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Shared ReID encoder used by BoT-SORT, Deep OC-SORT, and TrackTrack. + +* `.pt` YOLO checkpoints — loaded via `YOLO()`; embeddings are pulled from the second-to-last +layer through the predictor's `embed=[...]` argument (works with classification and ReID +backbones). +* Compatible exported models (`.torchscript`, `.onnx`, `.engine`, OpenVINO model directories, …) — +loaded via `AutoBackend`; the model is expected to output the embedding tensor directly. +""" + +from __future__ import annotations + +import numpy as np +import torch + +from ultralytics.nn.autobackend import AutoBackend +from ultralytics.utils.ops import xywh2xyxy +from ultralytics.utils.plotting import save_one_box +from ultralytics.utils.torch_utils import smart_inference_mode + +REID_ASSETS = frozenset(f"yolo26{k}-reid.onnx" for k in "nsmlx") + + +class ReID: + """ReID encoder. Routes `.pt` to the YOLO predictor path; everything else to `AutoBackend`.""" + + @smart_inference_mode(False) + def __init__(self, model: str, imgsz: int = 224, device: str | torch.device | None = None, fp16: bool = False): + """Initialize encoder for re-identification. + + Args: + model (str): Path to a ReID model. `.pt` runs through the YOLO predictor (embed-layer extraction); other + extensions go through `AutoBackend`. + imgsz (int): Square input size used for crop preprocessing on the AutoBackend path. Overridden by the + model's own static input size when one is detected. + device (str | torch.device | None): Inference device; defaults to CUDA if available. + fp16 (bool): Use half precision when the backend supports it. + """ + self.imgsz = imgsz + self.batch_size = None + self.device = ( + torch.device(device) if device is not None else torch.device("cuda" if torch.cuda.is_available() else "cpu") + ) + self.is_pt = str(model).endswith(".pt") + + if self.is_pt: + from ultralytics import YOLO + + self.model = YOLO(model) + # Initialize predictor with embed=[idx] so subsequent calls return embeddings. + self.model(embed=[len(self.model.model.model) - 2], device=self.device, verbose=False, save=False) + self.fp16 = False + else: + from pathlib import Path + + if Path(str(model)).name in REID_ASSETS: + from ultralytics.utils.downloads import attempt_download_asset + + model = attempt_download_asset(str(model)) + self.model = AutoBackend(str(model), device=self.device, fp16=fp16, verbose=False) + self.fp16 = self.model.fp16 + + # Get model's input size for a fixed batch and crop size or detect dynamic batch and crop sizes. + session = getattr(self.model, "session", None) + shape = session.get_inputs()[0].shape if session is not None else () + if len(shape) == 4: + if isinstance(shape[0], int) and shape[0] > 0: + self.batch_size = shape[0] + if isinstance(shape[2], int) and shape[2] > 0: + self.imgsz = shape[2] + + @staticmethod + def _crop_detections(img: np.ndarray, dets: np.ndarray) -> list[np.ndarray]: + """Crop detection regions from image, converting xywh to xyxy first. + + Args: + img (np.ndarray): BGR image. + dets (np.ndarray): Detections in xywh format (first 4 columns used). + + Returns: + (list[np.ndarray]): Cropped image patches. + """ + return [save_one_box(det, img, save=False) for det in xywh2xyxy(torch.from_numpy(dets[:, :4]))] + + def _crops_to_tensor(self, crops: list[np.ndarray]) -> torch.Tensor: + """Stack a list of valid image crops into a normalized BCHW float tensor at self.imgsz.""" + batch = torch.empty(len(crops), 3, self.imgsz, self.imgsz, dtype=torch.float32) + for i, c in enumerate(crops): + t = torch.from_numpy(np.ascontiguousarray(c[..., ::-1])).permute(2, 0, 1).unsqueeze(0).float() / 255.0 + batch[i] = torch.nn.functional.interpolate( + t, size=(self.imgsz, self.imgsz), mode="bilinear", align_corners=False + )[0] + batch = batch.to(self.device) + return batch.half() if self.fp16 else batch + + @torch.no_grad() + def __call__(self, img: np.ndarray, dets: np.ndarray) -> list[np.ndarray | None]: + """Extract embeddings for detected objects.""" + crops = self._crop_detections(img, dets) + valid = [bool(c.size) for c in crops] + valid_crops = [crop for crop, keep in zip(crops, valid) if keep] + if not valid_crops: + return [None] * len(crops) + + if self.is_pt: + feats = self.model.predictor(valid_crops) + if len(feats) != len(valid_crops) and feats[0].shape[0] == len(valid_crops): + feats = feats[0] # batched prediction with non-PyTorch backend + valid_feats = [f.cpu().numpy() for f in feats] + else: + batch = self._crops_to_tensor(valid_crops) + bs, n = self.batch_size, batch.shape[0] + if bs is None or n == bs: + feats = self.model(batch) + else: # fixed-batch model (e.g. static ONNX): run in chunks of bs, padding the last partial chunk + outs = [] + for s in range(0, n, bs): + chunk = batch[s : s + bs] + if chunk.shape[0] < bs: + chunk = torch.cat([chunk, chunk[-1:].expand(bs - chunk.shape[0], *chunk.shape[1:])], 0) + outs.append(self.model(chunk)) + feats = torch.cat(outs, 0)[:n] + valid_feats = [f.cpu().numpy() for f in feats] + + valid_feats = iter(valid_feats) + return [next(valid_feats) if keep else None for keep in valid] + + +def build_encoder(with_reid: bool, model: str | None, device: str | torch.device | None = None): + """Return a ReID encoder, the native-features pass-through, or None. + + Args: + with_reid (bool): Whether ReID is enabled at all. + model (str | None): `"auto"` returns a callable that converts pre-extracted backbone features to numpy arrays; + any other value loads a `ReID` model from that path. Ignored when `with_reid` is False. + device (str | torch.device | None): Inference device for the ReID model; defaults to CUDA if available. + + Returns: + (Callable | None): A `(img, dets) -> list[np.ndarray | None]` encoder, or None when ReID is disabled. + """ + if not with_reid: + return None + if model == "auto": + + def _auto_encoder(feats, _dets): + if isinstance(feats, np.ndarray): + return [f for f in feats] + return [f.cpu().numpy() for f in feats] + + return _auto_encoder + return ReID(model, device=device) + + +def smooth_feature( + feat: np.ndarray, smooth: np.ndarray | None, alpha: float +) -> tuple[np.ndarray | None, np.ndarray | None]: + """L2-normalize `feat` and blend it into `smooth` via exponential moving average. + + Args: + feat (np.ndarray): New (un-normalized) appearance feature. + smooth (np.ndarray | None): Current smoothed feature, or None on the first update. + alpha (float): EMA weight on the existing `smooth` (``1.0`` keeps it unchanged). + + Returns: + curr (np.ndarray | None): The normalized float32 feature, or None when `feat` has zero norm. + smooth (np.ndarray | None): The updated, normalized float32 feature. + """ + feat = np.asarray(feat, dtype=np.float32) # the stored state is float32 whatever dtype the ReID backend returned + norm = np.linalg.norm(feat) + if norm < 1e-12: # zero-norm feature has no appearance info; signal the caller to keep its current features + return None, smooth + feat = feat / norm + if smooth is None: + return feat, feat.copy() + smooth = alpha * smooth + (1 - alpha) * feat + return feat, smooth / np.linalg.norm(smooth) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/stracks.py b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/stracks.py new file mode 100644 index 0000000000000000000000000000000000000000..308e9efa7a6dcc2f716c8f45bec4b2c20d5e119f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/trackers/utils/stracks.py @@ -0,0 +1,179 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Shared helpers for operating on lists of track objects across trackers. + +These functions are intentionally generic: they only touch attributes that every track +implementation exposes (`track_id`, `frame_id`, `start_frame`, `xyxy`, `mean`, `covariance`). +""" + +from __future__ import annotations + +__all__ = ("joint_stracks", "merge_track_pools", "multi_gmc", "parse_bboxes", "remove_duplicate_stracks", "sub_stracks") + +import numpy as np + +from ..basetrack import TrackState +from . import matching + + +def merge_track_pools( + tracker, + activated: list, + refind: list, + lost: list, + removed: list, + removed_buffer: int = 1000, +) -> None: + """Apply the standard end-of-frame bookkeeping to a tracker's persistent pools in place. + + Merges newly activated and re-found tracks into `tracker.tracked_stracks`, moves the transitioned tracks into + `tracker.lost_stracks`, dedups by IoU, appends removals to `tracker.removed_stracks`, and trims the removed buffer + to `removed_buffer` entries. + + Args: + tracker (Any): Object exposing `tracked_stracks`, `lost_stracks`, `removed_stracks` lists. + activated (list): Tracks updated from the Tracked state this frame. + refind (list): Tracks re-activated from the Lost state this frame. + lost (list): Tracks transitioned to Lost this frame. + removed (list): Tracks transitioned to Removed this frame. + removed_buffer (int): Maximum number of historical removed tracks to retain. + + Examples: + Run end-of-frame bookkeeping inside a tracker's `update` method + >>> merge_track_pools(self, activated_stracks, refind_stracks, lost_stracks, removed_stracks) + """ + tracker.tracked_stracks = [t for t in tracker.tracked_stracks if t.state == TrackState.Tracked] + tracker.tracked_stracks = joint_stracks(tracker.tracked_stracks, activated) + tracker.tracked_stracks = joint_stracks(tracker.tracked_stracks, refind) + tracker.lost_stracks = sub_stracks(tracker.lost_stracks, tracker.tracked_stracks) + tracker.lost_stracks.extend(lost) + tracker.lost_stracks = sub_stracks(tracker.lost_stracks, tracker.removed_stracks) + tracker.tracked_stracks, tracker.lost_stracks = remove_duplicate_stracks( + tracker.tracked_stracks, tracker.lost_stracks + ) + tracker.removed_stracks_frame = removed + tracker.removed_stracks.extend(removed) + if len(tracker.removed_stracks) > removed_buffer: + tracker.removed_stracks = tracker.removed_stracks[-removed_buffer:] + + +def parse_bboxes(results) -> np.ndarray: + """Return detection bounding boxes with appended indices from a Results-like object. + + Args: + results (Any): Object exposing ``xywh`` (or ``xywhr``), ``conf``, and ``cls``. + + Returns: + (np.ndarray): Array of shape ``(N, 5)`` for ``xywh`` or ``(N, 6)`` for ``xywhr``, with the last column + containing the original detection index. + """ + bboxes = results.xywhr if hasattr(results, "xywhr") else results.xywh + return np.concatenate([bboxes, np.arange(len(bboxes)).reshape(-1, 1)], axis=-1) + + +def joint_stracks(atracks: list, btracks: list) -> list: + """Combine two track lists into one, de-duplicating by `track_id`. + + Args: + atracks (list[STrack]): First list of tracks; entries win on `track_id` collisions. + btracks (list[STrack]): Second list of tracks. + + Returns: + (list[STrack]): Union of `atracks` and `btracks` with duplicate `track_id`s removed. + + Examples: + Merge the currently tracked pool with newly activated tracks + >>> merged = joint_stracks(tracked_stracks, activated_stracks) + """ + a_ids = {t.track_id for t in atracks} + return atracks + [t for t in btracks if t.track_id not in a_ids] + + +def sub_stracks(atracks: list, btracks: list) -> list: + """Filter out tracks from `atracks` whose `track_id` appears in `btracks`. + + Args: + atracks (list[STrack]): Source list of tracks to filter. + btracks (list[STrack]): Tracks whose `track_id`s should be excluded from the output. + + Returns: + (list[STrack]): Elements of `atracks` whose `track_id` is not present in `btracks`. + + Examples: + Remove any re-tracked objects from the lost pool + >>> lost_stracks = sub_stracks(lost_stracks, tracked_stracks) + """ + btrack_ids = {t.track_id for t in btracks} + return [t for t in atracks if t.track_id not in btrack_ids] + + +def remove_duplicate_stracks(atracks: list, btracks: list, dup_thresh: float = 0.15) -> tuple[list, list]: + """Remove duplicate tracks across two lists based on Intersection over Union (IoU) distance. + + Track pairs with IoU distance < `dup_thresh` (IoU > `1 - dup_thresh`) are treated as duplicates of the same + object. The shorter-lived track (smaller `frame_id - start_frame`) is dropped; ties drop + from `atracks`. + + Args: + atracks (list[STrack]): First list of tracks; entries must expose `xyxy`, `frame_id`, and `start_frame`. + btracks (list[STrack]): Second list of tracks with the same attribute requirements. + dup_thresh (float): IoU-distance ceiling for treating two tracks as duplicates. Default 0.15 (IoU > 0.85). + + Returns: + resa (list[STrack]): `atracks` with duplicate tracks removed. + resb (list[STrack]): `btracks` with duplicate tracks removed. + + Examples: + De-duplicate the tracked and lost pools at the end of a frame + >>> tracked, lost = remove_duplicate_stracks(tracked_stracks, lost_stracks) + """ + pdist = matching.iou_distance(atracks, btracks) + pairs = np.where(pdist < dup_thresh) + dupa, dupb = [], [] + for p, q in zip(*pairs): + timep = atracks[p].frame_id - atracks[p].start_frame + timeq = btracks[q].frame_id - btracks[q].start_frame + if timep > timeq: + dupb.append(q) + else: + dupa.append(p) + dupa_set, dupb_set = set(dupa), set(dupb) + resa = [t for i, t in enumerate(atracks) if i not in dupa_set] + resb = [t for i, t in enumerate(btracks) if i not in dupb_set] + return resa, resb + + +def multi_gmc(stracks: list, H: np.ndarray) -> None: + """Update multiple track positions and covariances using a 2x3 affine homography. + + The Kalman state is assumed to be laid out as `(*box, *box_velocity)` with the box center `(x, y)` in the first two + dims. `R8x8` rotates all four 2-d pairs block-diagonally; the translation `t` is applied only to the position. + This assumes the state layout is four spatial/velocity pairs (e.g. XYWH); XYAH trackers must override this. + + Args: + stracks (list[STrack]): Tracks to warp in place; each must expose `mean` (shape (8,)) and `covariance` (shape + (8, 8)). + H (np.ndarray): 2x3 affine homography mapping the previous frame to the current one. + + Examples: + Apply camera-motion compensation to the active track pool + >>> warp = gmc.apply(frame, detection_boxes) + >>> multi_gmc(tracked_stracks, warp) + """ + if not stracks: + return + multi_mean = np.asarray([st.mean for st in stracks]) + multi_covariance = np.asarray([st.covariance for st in stracks]) + + R = H[:2, :2] + R8x8 = np.kron(np.eye(4, dtype=np.float32), R) + t = H[:2, 2] + + multi_mean = np.matmul(R8x8, multi_mean[..., None])[..., 0] + multi_mean[:, :2] += t + # Keep the right operand C-contiguous. An F-contiguous one sends matmul into BLAS's transposed-gemm kernel, + # which on macOS Accelerate leaves FP-exception flags set even for finite inputs — numpy then reports spurious + # divide/overflow/invalid RuntimeWarnings — and measures slower here than the untransposed kernel. + multi_covariance = np.matmul(np.matmul(R8x8, multi_covariance), np.ascontiguousarray(R8x8.T)) + for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)): + stracks[i].mean = mean + stracks[i].covariance = cov diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67189945f9d3952418ec88be0ffe1d12010626ef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/__init__.py @@ -0,0 +1,1549 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import contextlib +import importlib.metadata +import inspect +import json +import logging +import os +import platform +import re +import socket +import sys +import threading +import time +import warnings +from functools import lru_cache +from pathlib import Path +from threading import Lock +from types import SimpleNamespace +from urllib.parse import unquote + +import cv2 +import numpy as np +import torch + +from ultralytics import __version__ +from ultralytics.utils.git import GitRepo +from ultralytics.utils.patches import imread as imread # re-export for backwards compatibility +from ultralytics.utils.patches import imread_unicode, imshow, imwrite, torch_save # for patches +from ultralytics.utils.tqdm import TQDM # noqa + + +def env_bool(name: str, default: bool = False) -> bool: + """Parse a boolean environment variable, accepting common truthy strings. + + Accepts "1", "true", "yes", "on", "y", "t" (case-insensitive, whitespace-trimmed) as True; any other set value is + False. The default is returned only when the variable is unset, not when it is set to an empty string. + + Args: + name (str): Environment variable name. + default (bool): Value returned when the variable is unset. + + Returns: + (bool): Parsed boolean value. + + Examples: + >>> env_bool("YOLO_UNSET_EXAMPLE_VAR", True) # returns the default when the variable is unset + True + """ + v = os.environ.get(name) + return default if v is None else v.strip().lower() in {"1", "true", "yes", "on", "y", "t"} + + +# PyTorch Multi-GPU DDP Constants, trusted only in real DDP workers, i.e. WORLD_SIZE > 1 (#16446) +WORLD_SIZE = int(os.getenv("WORLD_SIZE", "1")) +RANK = int(os.getenv("RANK", "-1")) if WORLD_SIZE > 1 else -1 +LOCAL_RANK = int(os.getenv("LOCAL_RANK", "-1")) if WORLD_SIZE > 1 else -1 + +# Other Constants +ARGV = sys.argv or ["", ""] # sometimes sys.argv = [] +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLO +ASSETS = ROOT / "assets" # default images +ASSETS_URL = "https://github.com/ultralytics/assets/releases/download/v0.0.0" # assets GitHub URL +# Configurable Platform URL for debugging (e.g. ULTRALYTICS_PLATFORM_URL=http://localhost:3000) +PLATFORM_URL = os.getenv("ULTRALYTICS_PLATFORM_URL", "https://platform.ultralytics.com").rstrip("/") +DEFAULT_CFG_PATH = ROOT / "cfg/default.yaml" +NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLO multiprocessing threads +AUTOINSTALL = env_bool("YOLO_AUTOINSTALL", True) # global auto-install mode +VERBOSE = env_bool("YOLO_VERBOSE", True) # global verbose mode +SAFE_LOAD = env_bool("ULTRALYTICS_SAFE_LOAD") # opt-in weights_only model loading +LOGGING_NAME = "ultralytics" +MACOS, LINUX, WINDOWS = (platform.system() == x for x in ["Darwin", "Linux", "Windows"]) # environment booleans +MACOS_VERSION = platform.mac_ver()[0] if MACOS else None +NOT_MACOS14 = not (MACOS and MACOS_VERSION.startswith("14.")) +ARM64 = platform.machine() in {"arm64", "aarch64"} # ARM64 booleans +PYTHON_VERSION = platform.python_version() +TORCH_VERSION = str(torch.__version__) # Normalize torch.__version__ (PyTorch>1.9 returns TorchVersion objects) +TORCHVISION_VERSION = importlib.metadata.version("torchvision") # faster than importing torchvision +IS_VSCODE = os.environ.get("TERM_PROGRAM") == "vscode" +RKNN_CHIPS = frozenset( + { + "rk3588", + "rk3576", + "rk3566", + "rk3568", + "rk3562", + "rv1103", + "rv1106", + "rv1103b", + "rv1106b", + "rk2118", + "rv1126b", + } +) # Rockchip processors available for export +QNN_HTP_TARGETS = { + "68": ("htp_arch", "68"), # Snapdragon 888 + "69": ("htp_arch", "69"), # Snapdragon 8 Gen 1 + "73": ("htp_arch", "73"), # Snapdragon 8 Gen 2 / X Elite + "75": ("htp_arch", "75"), # Snapdragon 8 Gen 3 + "79": ("soc_model", "69"), # Snapdragon 8 Elite (SM8750) + "81": ("htp_arch", "81"), # Snapdragon 8 Elite Gen 5 + "iq-8275": ("soc_model", "82"), # Dragonwing IQ-8275 + "qcs8275": ("soc_model", "82"), +} # Qualcomm Hexagon HTP targets and their ONNX Runtime QNN provider option +HELP_MSG = """ + Examples for running Ultralytics: + + 1. Install the ultralytics package: + + pip install ultralytics + + 2. Use the Python SDK: + + from ultralytics import YOLO + + # Load a model + model = YOLO("yolo26n.yaml") # build a new model from scratch + model = YOLO("yolo26n.pt") # load a pretrained model (recommended for training) + + # Use the model + results = model.train(data="coco8.yaml", epochs=3) # train the model + results = model.val() # evaluate model performance on the validation set + results = model("https://ultralytics.com/images/bus.jpg") # predict on an image + success = model.export(format="onnx") # export the model to ONNX format + + 3. Use the command line interface (CLI): + + Ultralytics 'yolo' CLI commands use the following syntax: + + yolo TASK MODE ARGS + + Where TASK (optional) is one of [detect, segment, semantic, classify, pose, obb, depth] + MODE (required) is one of [train, val, predict, export, track, benchmark] + ARGS (optional) are any number of custom "arg=value" pairs like "imgsz=320" that override defaults. + See all ARGS at https://docs.ultralytics.com/usage/cfg or with "yolo cfg" + + - Train a detection model for 10 epochs with an initial learning_rate of 0.01 + yolo detect train data=coco8.yaml model=yolo26n.pt epochs=10 lr0=0.01 + + - Predict a YouTube video using a pretrained segmentation model at image size 320: + yolo segment predict model=yolo26n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320 + + - Val a pretrained detection model at batch-size 1 and image size 640: + yolo detect val model=yolo26n.pt data=coco8.yaml batch=1 imgsz=640 + + - Export a YOLO26n classification model to ONNX format at image size 224 by 128 (no TASK required) + yolo export model=yolo26n-cls.pt format=onnx imgsz=224,128 + + - Run special commands: + yolo help + yolo checks + yolo version + yolo settings + yolo copy-cfg + yolo cfg + + Docs: https://docs.ultralytics.com + Community: https://community.ultralytics.com + GitHub: https://github.com/ultralytics/ultralytics + """ + +# Settings and Environment Variables +torch.set_printoptions(linewidth=320, precision=4, profile="default") +np.set_printoptions(linewidth=320, formatter={"float_kind": "{:11.5g}".format}) # format short g, %precision=5 +cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader) +os.environ["NUMEXPR_MAX_THREADS"] = str(NUM_THREADS) # NumExpr max threads +os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # suppress verbose TF compiler warnings in Colab +os.environ["TORCH_CPP_LOG_LEVEL"] = "ERROR" # suppress "NNPACK.cpp could not initialize NNPACK" warnings +os.environ["KINETO_LOG_LEVEL"] = "5" # suppress verbose PyTorch profiler output when computing FLOPs + +# Centralized warning suppression +warnings.filterwarnings("ignore", message="torch.distributed.reduce_op is deprecated") # PyTorch deprecation +warnings.filterwarnings("ignore", message="The figure layout has changed to tight") # matplotlib>=3.7.2 +warnings.filterwarnings("ignore", category=FutureWarning, module="timm") # mobileclip timm.layers deprecation +warnings.filterwarnings("ignore", category=torch.jit.TracerWarning) # ONNX/TorchScript export tracer warnings +warnings.filterwarnings("ignore", category=UserWarning, message=".*prim::Constant.*") # ONNX shape warning +warnings.filterwarnings("ignore", category=DeprecationWarning, module="coremltools") # CoreML np.bool deprecation +logging.getLogger("coremltools").setLevel(logging.ERROR) # Suppress native binary load failures on non-macOS + +# Precompiled type tuples for faster isinstance() checks +FLOAT_OR_INT = (float, int) +STR_OR_PATH = (str, Path) + + +class DataExportMixin: + """Mixin class for exporting validation metrics or prediction results in various formats. + + This class provides utilities to export performance metrics (e.g., mAP, precision, recall) or prediction results + from classification, object detection, segmentation, or pose estimation tasks into various formats: Polars + DataFrame, CSV, and JSON. + + Methods: + to_df: Convert summary to a Polars DataFrame. + to_csv: Export results as a CSV string. + to_json: Export results as a JSON string. + tojson: Deprecated alias for `to_json()`. + + Examples: + >>> model = YOLO("yolo26n.pt") + >>> results = model("image.jpg") + >>> df = results.to_df() + >>> print(df) + >>> csv_data = results.to_csv() + """ + + def to_df(self, normalize=False, decimals=5): + """Create a Polars DataFrame from the prediction results summary or validation metrics. + + Args: + normalize (bool, optional): Normalize numerical values for easier comparison. + decimals (int, optional): Decimal places to round floats. + + Returns: + (polars.DataFrame): Polars DataFrame containing the summary data. + """ + import polars as pl # scope for faster 'import ultralytics' + + return pl.DataFrame(self.summary(normalize=normalize, decimals=decimals)) + + def to_csv(self, normalize=False, decimals=5): + """Export results or metrics to CSV string format. + + Args: + normalize (bool, optional): Normalize numeric values. + decimals (int, optional): Decimal precision. + + Returns: + (str): CSV content as string. + """ + import polars as pl + + df = self.to_df(normalize=normalize, decimals=decimals) + + try: + return df.write_csv() + except Exception: + # Minimal string conversion for any remaining complex types + def _to_str_simple(v): + if v is None: + return "" + elif isinstance(v, (dict, list, tuple, set)): + return repr(v) + else: + return str(v) + + df_str = df.select( + [pl.col(c).map_elements(_to_str_simple, return_dtype=pl.String).alias(c) for c in df.columns] + ) + return df_str.write_csv() + + def to_json(self, normalize=False, decimals=5): + """Export results to JSON format. + + Args: + normalize (bool, optional): Normalize numeric values. + decimals (int, optional): Decimal precision. + + Returns: + (str): JSON-formatted string of the results. + """ + return self.to_df(normalize=normalize, decimals=decimals).write_json() + + +class SimpleClass: + """A simple base class for creating objects with string representations of their attributes. + + This class provides a foundation for creating objects that can be easily printed or represented as strings, showing + all their non-callable attributes. It's useful for debugging and introspection of object states. + + Methods: + __str__: Return a human-readable string representation of the object. + __repr__: Return a machine-readable string representation of the object. + __getattr__: Provide a custom attribute access error message with helpful information. + + Examples: + >>> class MyClass(SimpleClass): + ... def __init__(self): + ... self.x = 10 + ... self.y = "hello" + >>> obj = MyClass() + >>> text = str(obj) # ".MyClass object with attributes:" followed by "x: 10" and "y: 'hello'" + + Notes: + - This class is designed to be subclassed. It provides a convenient way to inspect object attributes. + - The string representation includes the module and class name of the object. + - Callable attributes and attributes starting with an underscore are excluded from the string representation. + """ + + def __str__(self): + """Return a human-readable string representation of the object.""" + attr = [] + for a in dir(self): + v = getattr(self, a) + if not callable(v) and not a.startswith("_"): + if isinstance(v, SimpleClass): + # Display only the module and class name for subclasses + s = f"{a}: {v.__module__}.{v.__class__.__name__} object" + else: + s = f"{a}: {v!r}" + attr.append(s) + return f"{self.__module__}.{self.__class__.__name__} object with attributes:\n\n" + "\n".join(attr) + + def __repr__(self): + """Return a machine-readable string representation of the object.""" + return self.__str__() + + def __getattr__(self, attr): + """Provide a custom attribute access error message with helpful information.""" + name = self.__class__.__name__ + raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}") + + +class IterableSimpleNamespace(SimpleNamespace): + """An iterable SimpleNamespace class that provides enhanced functionality for attribute access and iteration. + + This class extends the SimpleNamespace class with additional methods for iteration, string representation, and + attribute access. It is designed to be used as a convenient container for storing and accessing configuration + parameters. + + Methods: + __iter__: Return an iterator of key-value pairs from the namespace's attributes. + __str__: Return a human-readable string representation of the object. + __getattr__: Provide a custom attribute access error message with helpful information. + get: Retrieve the value of a specified key, or a default value if the key doesn't exist. + + Examples: + >>> cfg = IterableSimpleNamespace(a=1, b=2, c=3) + >>> for k, v in cfg: + ... print(f"{k}: {v}") + a: 1 + b: 2 + c: 3 + >>> print(cfg) + a=1 + b=2 + c=3 + >>> cfg.get("b") + 2 + >>> cfg.get("d", "default") + 'default' + + Notes: + This class is particularly useful for storing configuration parameters in a more accessible + and iterable format compared to a standard dictionary. + """ + + def __iter__(self): + """Return an iterator of key-value pairs from the namespace's attributes.""" + return iter(vars(self).items()) + + def __str__(self): + """Return a human-readable string representation of the object.""" + return "\n".join(f"{k}={v}" for k, v in vars(self).items()) + + def __getattr__(self, attr): + """Provide a custom attribute access error message with helpful information.""" + name = self.__class__.__name__ + raise AttributeError( + f""" + '{name}' object has no attribute '{attr}'. This may be caused by a modified or out of date ultralytics + 'default.yaml' file.\nPlease update your code with 'pip install -U ultralytics' and if necessary replace + {DEFAULT_CFG_PATH} with the latest version from + https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yaml + """ + ) + + def get(self, key, default=None): + """Return the value of the specified key if it exists; otherwise, return the default value.""" + return getattr(self, key, default) + + +def plt_settings(rcparams=None, backend="Agg"): + """Decorator to temporarily set rc parameters and the backend for a plotting function. + + Args: + rcparams (dict, optional): Dictionary of rc parameters to set. + backend (str, optional): Name of the backend to use. + + Returns: + (Callable): Decorated function with temporarily set rc parameters and backend. + + Examples: + >>> @plt_settings({"font.size": 12}) + ... def plot_function(): + ... plt.figure() + ... plt.plot([1, 2, 3]) + ... plt.show() + + >>> with plt_settings({"font.size": 12}): + ... plt.figure() + ... plt.plot([1, 2, 3]) + ... plt.show() + """ + if rcparams is None: + rcparams = {"font.size": 11} + + def decorator(func): + """Decorator to apply temporary rc parameters and backend to a function.""" + + def wrapper(*args, **kwargs): + """Set rc parameters and backend, call the original function, and restore the settings.""" + import matplotlib.pyplot as plt # scope for faster 'import ultralytics' + + # Prepend Arial Unicode for non-Latin text (CJK, Arabic, etc.); matplotlib falls back if missing + if "font.sans-serif" not in rcparams and not wrapper._fonts_registered: + from matplotlib import font_manager + + # Register any fonts in Ultralytics config dir (e.g. Arial.Unicode.ttf) with matplotlib + known = {f.fname for f in font_manager.fontManager.ttflist} + for f in USER_CONFIG_DIR.glob("*.ttf"): + if str(f) not in known: + font_manager.fontManager.addfont(str(f)) + wrapper._fonts_registered = True + rc = ( + rcparams + if "font.sans-serif" in rcparams + else {**rcparams, "font.sans-serif": ["Arial Unicode MS", *plt.rcParams.get("font.sans-serif", [])]} + ) + + original_backend = plt.get_backend() + switch = backend.lower() != original_backend.lower() + if switch: + # Resolve configured backends first, as get_backend() may return an unavailable backend name + if plt._backend_mod is None: + try: + plt.switch_backend(original_backend) + except ImportError: + original_backend = None + plt.close("all") # auto-close()ing of figures upon backend switching is deprecated since 3.8 + plt.switch_backend(backend) + + # Plot with backend and always revert to original backend + try: + with plt.rc_context(rc): + result = func(*args, **kwargs) + finally: + if switch: + plt.close("all") + if original_backend: + plt.switch_backend(original_backend) + return result + + wrapper._fonts_registered = False + return wrapper + + return decorator + + +def set_logging(name="LOGGING_NAME", verbose=True): + """Set up logging with UTF-8 encoding and configurable verbosity. + + This function configures logging for the Ultralytics library, setting the appropriate logging level and formatter + based on the verbosity flag and the current process rank. It handles special cases for Windows environments where + UTF-8 encoding might not be the default. + + Args: + name (str): Name of the logger. + verbose (bool): Flag to set logging level to INFO if True, ERROR otherwise. + + Returns: + (logging.Logger): Configured logger object. + + Examples: + >>> set_logging(name="ultralytics", verbose=True) + >>> logger = logging.getLogger("ultralytics") + >>> logger.info("This is an info message") + + Notes: + - On Windows, this function attempts to reconfigure stdout to use UTF-8 encoding if possible. + - If reconfiguration is not possible, it falls back to a custom formatter that handles non-UTF-8 environments. + - The function sets up a StreamHandler with the appropriate formatter and level. + - The logger's propagate flag is set to False to prevent duplicate logging in parent loggers. + """ + level = logging.INFO if verbose and RANK in {-1, 0} else logging.ERROR # rank in world for Multi-GPU trainings + + class PrefixFormatter(logging.Formatter): + def format(self, record): + """Format log records with prefixes based on level.""" + # Apply prefixes based on log level + if record.levelno == logging.WARNING: + prefix = "WARNING" if WINDOWS else "WARNING ⚠️" + record.msg = f"{prefix} {record.msg}" + elif record.levelno == logging.ERROR: + prefix = "ERROR" if WINDOWS else "ERROR ❌" + record.msg = f"{prefix} {record.msg}" + + # Handle emojis in message based on platform + formatted_message = super().format(record) + return emojis(formatted_message) + + formatter = PrefixFormatter("%(message)s") + + # Handle Windows UTF-8 encoding issues + if WINDOWS and hasattr(sys.stdout, "encoding") and sys.stdout.encoding != "utf-8": + with contextlib.suppress(Exception): + # Attempt to reconfigure stdout to use UTF-8 encoding if possible + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8") + # For environments where reconfigure is not available, wrap stdout in a TextIOWrapper + elif hasattr(sys.stdout, "buffer"): + import io + + sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") + + # Create and configure the StreamHandler with the appropriate formatter and level + stream_handler = logging.StreamHandler(sys.stdout) + stream_handler.set_name("ultralytics.utils.set_logging") + stream_handler.setFormatter(formatter) + stream_handler.setLevel(level) + + # Set up the logger + logger = logging.getLogger(name) + for h in [h for h in logger.handlers if h.name == stream_handler.name]: + logger.removeHandler(h) + logger.setLevel(level) + logger.addHandler(stream_handler) + logger.propagate = False + return logger + + +# Set logger +LOGGER = set_logging(LOGGING_NAME, verbose=VERBOSE) # define globally (used in train.py, val.py, predict.py, etc.) +logging.getLogger("sentry_sdk").setLevel(logging.CRITICAL + 1) + + +def emojis(string=""): + """Return platform-dependent emoji-safe version of string.""" + return string.encode().decode("ascii", "ignore") if WINDOWS else string + + +class ThreadingLocked: + """A decorator class for ensuring thread-safe execution of a function or method. + + This class can be used as a decorator to make sure that if the decorated function is called from multiple threads, + only one thread at a time will be able to execute the function. + + Attributes: + lock (threading.Lock): A lock object used to manage access to the decorated function. + + Examples: + >>> from ultralytics.utils import ThreadingLocked + >>> @ThreadingLocked() + ... def my_function(): + ... # Your code here + """ + + def __init__(self): + """Initialize the decorator class with a threading lock.""" + self.lock = threading.Lock() + + def __call__(self, f): + """Run thread-safe execution of function or method.""" + from functools import wraps + + @wraps(f) + def decorated(*args, **kwargs): + """Apply thread-safety to the decorated function or method.""" + with self.lock: + return f(*args, **kwargs) + + return decorated + + +class YAML: + """YAML utility class for efficient file operations with automatic C-implementation detection. + + This class provides optimized YAML loading and saving operations using PyYAML's fastest available implementation + (C-based when possible). It implements a singleton pattern with lazy initialization, allowing direct class method + usage without explicit instantiation. The class handles file path creation, validation, and character encoding + issues automatically. + + The implementation prioritizes performance through: + - Automatic C-based loader/dumper selection when available + - Singleton pattern to reuse the same instance + - Lazy initialization to defer import costs until needed + - Fallback mechanisms for handling problematic YAML content + + Attributes: + _instance: Internal singleton instance storage. + yaml: Reference to the PyYAML module. + SafeLoader: Best available YAML loader (CSafeLoader if available). + SafeDumper: Best available YAML dumper (CSafeDumper if available). + + Examples: + >>> data = YAML.load("config.yaml") + >>> data["new_value"] = 123 + >>> YAML.save("updated_config.yaml", data) + >>> YAML.print(data) + """ + + _instance = None + + @classmethod + def _get_instance(cls): + """Initialize singleton instance on first use.""" + if cls._instance is None: + cls._instance = cls() + return cls._instance + + def __init__(self): + """Initialize with optimal YAML implementation (C-based when available).""" + import yaml + + self.yaml = yaml + # Use C-based implementation if available for better performance + try: + self.SafeLoader = yaml.CSafeLoader + self.SafeDumper = yaml.CSafeDumper + except (AttributeError, ImportError): + self.SafeLoader = yaml.SafeLoader + self.SafeDumper = yaml.SafeDumper + + @classmethod + def save(cls, file="data.yaml", data=None, header=""): + """Save Python object as YAML file. + + Args: + file (str | Path): Path to save YAML file. + data (dict | None): Dict or compatible object to save. + header (str): Optional string to add at file beginning. + """ + instance = cls._get_instance() + if data is None: + data = {} + + # Create parent directories if needed + file = Path(file) + file.parent.mkdir(parents=True, exist_ok=True) + + # Convert non-serializable objects to strings + valid_types = int, float, str, bool, list, tuple, dict, type(None) + for k, v in data.items(): + if not isinstance(v, valid_types): + data[k] = str(v) + + # Write YAML file + with open(file, "w", errors="ignore", encoding="utf-8") as f: + if header: + f.write(header) + instance.yaml.dump(data, f, sort_keys=False, allow_unicode=True, Dumper=instance.SafeDumper) + + @classmethod + def load(cls, file="data.yaml", append_filename=False): + """Load YAML file to Python object with robust error handling. + + Args: + file (str | Path): Path to YAML file. + append_filename (bool): Whether to add filename to returned dict. + + Returns: + (dict): Loaded YAML content. + """ + instance = cls._get_instance() + assert str(file).endswith((".yaml", ".yml")), f"Not a YAML file: {file}" + + # Read file content + with open(file, errors="ignore", encoding="utf-8") as f: + s = f.read() + + # Try loading YAML with fallback for problematic characters + try: + data = instance.yaml.load(s, Loader=instance.SafeLoader) + except Exception as e: + # Remove problematic characters and retry + s = re.sub(r"[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+", "", s) + try: + data = instance.yaml.load(s, Loader=instance.SafeLoader) + except Exception: + raise ValueError( + f"YAML syntax error in '{file}': {e}\nVerify YAML with https://ray.run/tools/yaml-formatter" + ) from None + + if data is None: # empty file, comments only, or explicit 'null' + data = {} + elif not isinstance(data, dict): # reject non-mapping YAML (scalar/list) with a clear error, not a cryptic one + raise ValueError( + f"'{file}' is not a valid YAML mapping. Verify YAML with https://ray.run/tools/yaml-formatter" + ) + + # Check for accidental user-error None strings (should be 'null' in YAML) + if "None" in data.values(): + data = {k: None if v == "None" else v for k, v in data.items()} + + if append_filename: + data["yaml_file"] = str(file) + return data + + @classmethod + def print(cls, yaml_file): + """Pretty print YAML file or object to console. + + Args: + yaml_file (str | Path | dict): Path to YAML file or dict to print. + """ + instance = cls._get_instance() + + # Load file if path provided + yaml_dict = cls.load(yaml_file) if isinstance(yaml_file, (str, Path)) else yaml_file + + # Use -1 for unlimited width in C implementation + dump = instance.yaml.dump(yaml_dict, sort_keys=False, allow_unicode=True, width=-1, Dumper=instance.SafeDumper) + + LOGGER.info(f"Printing '{colorstr('bold', 'black', yaml_file)}'\n\n{dump}") + + +# Default configuration +DEFAULT_CFG_DICT = YAML.load(DEFAULT_CFG_PATH) +DEFAULT_CFG_KEYS = DEFAULT_CFG_DICT.keys() +DEFAULT_CFG = IterableSimpleNamespace(**DEFAULT_CFG_DICT) + + +def read_device_model() -> str: + """Read the device model information from the system. + + Returns: + (str): Platform release string in lowercase, used to identify device models like Jetson or Raspberry Pi. + """ + return platform.release().lower() + + +def is_ubuntu() -> bool: + """Check if the OS is Ubuntu. + + Returns: + (bool): True if OS is Ubuntu, False otherwise. + """ + try: + with open("/etc/os-release") as f: + return "ID=ubuntu" in f.read() + except FileNotFoundError: + return False + + +def is_debian(codenames: list[str] | str | None = None) -> list[bool] | bool: + """Check if the OS is Debian. + + Args: + codenames (list[str] | None | str): Specific Debian codename to check for (e.g., 'buster', 'bullseye'). If None, + only checks for Debian. + + Returns: + (list[bool] | bool): List of booleans indicating if OS matches each Debian codename, or a single boolean if no + codenames provided. + """ + try: + with open("/etc/os-release") as f: + content = f.read() + if codenames is None: + return "ID=debian" in content + if isinstance(codenames, str): + codenames = [codenames] + return [ + f"VERSION_CODENAME={codename}" in content if codename else "ID=debian" in content + for codename in codenames + ] + except FileNotFoundError: + return [False] * len(codenames) if codenames else False + + +def is_colab(): + """Check if the current script is running inside a Google Colab notebook. + + Returns: + (bool): True if running inside a Colab notebook, False otherwise. + """ + return "COLAB_RELEASE_TAG" in os.environ or "COLAB_BACKEND_VERSION" in os.environ + + +def is_kaggle(): + """Check if the current script is running inside a Kaggle kernel. + + Returns: + (bool): True if running inside a Kaggle kernel, False otherwise. + """ + return os.environ.get("PWD") == "/kaggle/working" and os.environ.get("KAGGLE_URL_BASE") == "https://www.kaggle.com" + + +def is_jupyter(): + """Check if the current script is running inside a Jupyter Notebook. + + Returns: + (bool): True if running inside a Jupyter Notebook, False otherwise. + + Notes: + - Only works on Colab and Kaggle, other environments like Jupyterlab and Paperspace are not reliably detectable. + - "get_ipython" in globals() method suffers false positives when IPython package installed manually. + """ + return IS_COLAB or IS_KAGGLE + + +def is_runpod(): + """Check if the current script is running inside a RunPod container. + + Returns: + (bool): True if running in RunPod, False otherwise. + """ + return "RUNPOD_POD_ID" in os.environ + + +def is_docker() -> bool: + """Determine if the script is running inside a Docker container. + + Returns: + (bool): True if the script is running inside a Docker container, False otherwise. + """ + try: + return os.path.exists("/.dockerenv") + except Exception: + return False + + +def is_raspberrypi() -> bool: + """Determine if the Python environment is running on a Raspberry Pi. + + Returns: + (bool): True if running on a Raspberry Pi, False otherwise. + """ + return "rpi" in DEVICE_MODEL + + +@lru_cache(maxsize=3) +def is_jetson(jetpack=None) -> bool: + """Determine if the Python environment is running on an NVIDIA Jetson device. + + Args: + jetpack (int | None): If specified, check for specific JetPack version (4, 5, 6). + + Returns: + (bool): True if running on an NVIDIA Jetson device, False otherwise. + """ + jetson = "tegra" in DEVICE_MODEL + if jetson and jetpack: + try: + content = Path("/etc/nv_tegra_release").read_text() + version_map = {4: "R32", 5: "R35", 6: "R36", 7: "R38"} # JetPack to L4T major version mapping + return jetpack in version_map and version_map[jetpack] in content + except Exception: + return False + return jetson + + +def is_dgx() -> bool: + """Check if the current script is running inside a DGX (NVIDIA Data Center GPU), DGX-Ready or DGX Spark system. + + Returns: + (bool): True if running in a DGX or DGX-Ready or DGX Spark system, False otherwise. + """ + try: + with open("/etc/dgx-release") as f: + return "DGX" in f.read() + except FileNotFoundError: + return False + + +def is_online() -> bool: + """Fast online check using DNS (v4/v6) resolution (Cloudflare + Google). + + Returns: + (bool): True if connection is successful, False otherwise. + """ + if env_bool("YOLO_OFFLINE"): + return False + + for host in ("one.one.one.one", "dns.google"): + try: + socket.getaddrinfo(host, 0, socket.AF_UNSPEC, 0, 0, socket.AI_ADDRCONFIG) + return True + except OSError: + continue + return False + + +def is_pip_package(filepath: str = __name__) -> bool: + """Determine if the file at the given filepath is part of a pip package. + + Args: + filepath (str): The filepath to check. + + Returns: + (bool): True if the file is part of a pip package, False otherwise. + """ + import importlib.util + + # Get the spec for the module + spec = importlib.util.find_spec(filepath) + + # Return whether the spec is not None and the origin is not None (indicating it is a package) + return spec is not None and spec.origin is not None + + +def is_dir_writeable(dir_path: str | Path) -> bool: + """Check if a directory is writable. + + Args: + dir_path (str | Path): The path to the directory. + + Returns: + (bool): True if the directory is writable, False otherwise. + """ + return os.access(str(dir_path), os.W_OK) + + +def is_pytest_running(): + """Determine whether pytest is currently running or not. + + Returns: + (bool): True if pytest is running, False otherwise. + """ + return ("PYTEST_CURRENT_TEST" in os.environ) or ("pytest" in sys.modules) or ("pytest" in Path(ARGV[0]).stem) + + +def is_github_action_running() -> bool: + """Determine if the current environment is a GitHub Actions runner. + + Returns: + (bool): True if the current environment is a GitHub Actions runner, False otherwise. + """ + return "GITHUB_ACTIONS" in os.environ and "GITHUB_WORKFLOW" in os.environ and "RUNNER_OS" in os.environ + + +def get_default_args(func): + """Return a dictionary of default arguments for a function. + + Args: + func (callable): The function to inspect. + + Returns: + (dict): A dictionary where each key is a parameter name, and each value is the default value of that parameter. + """ + signature = inspect.signature(func) + return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty} + + +def get_ubuntu_version(): + """Retrieve the Ubuntu version if the OS is Ubuntu. + + Returns: + (str): Ubuntu version or None if not an Ubuntu OS. + """ + if is_ubuntu(): + try: + with open("/etc/os-release") as f: + return re.search(r'VERSION_ID="(\d+\.\d+)"', f.read())[1] + except (FileNotFoundError, AttributeError): + return None + + +def get_user_config_dir(sub_dir="Ultralytics"): + """Return a writable config dir, preferring YOLO_CONFIG_DIR and being OS-aware. + + Args: + sub_dir (str): The name of the subdirectory to create. + + Returns: + (Path): The path to the user config directory. + """ + if env_dir := os.getenv("YOLO_CONFIG_DIR"): + p = Path(env_dir).expanduser() / sub_dir + elif LINUX: + p = Path(os.getenv("XDG_CONFIG_HOME", Path.home() / ".config")) / sub_dir + elif WINDOWS: + p = Path.home() / "AppData" / "Roaming" / sub_dir + elif MACOS: + p = Path.home() / "Library" / "Application Support" / sub_dir + else: + raise ValueError(f"Unsupported operating system: {platform.system()}") + + if p.exists(): # already created → trust it + return p + if is_dir_writeable(p.parent): # create if possible + p.mkdir(parents=True, exist_ok=True) + return p + + # Fallbacks for Docker, GCP/AWS functions where only /tmp is writable + for alt in [Path("/tmp") / sub_dir, Path.cwd() / sub_dir]: + if alt.exists(): + return alt + if is_dir_writeable(alt.parent): + alt.mkdir(parents=True, exist_ok=True) + LOGGER.warning( + f"user config directory '{p}' is not writable, using '{alt}'. Set YOLO_CONFIG_DIR to override." + ) + return alt + + # Last fallback → CWD + p = Path.cwd() / sub_dir + p.mkdir(parents=True, exist_ok=True) + return p + + +# Define constants (required below) +DEVICE_MODEL = read_device_model() # is_jetson() and is_raspberrypi() depend on this constant +ONLINE = is_online() +IS_COLAB = is_colab() +IS_KAGGLE = is_kaggle() +IS_DOCKER = is_docker() +IS_JETSON = is_jetson() +IS_JUPYTER = is_jupyter() +IS_PIP_PACKAGE = is_pip_package() +IS_RASPBERRYPI = is_raspberrypi() +IS_DEBIAN, IS_DEBIAN_BOOKWORM, IS_DEBIAN_TRIXIE = is_debian([None, "bookworm", "trixie"]) +IS_UBUNTU = is_ubuntu() +GIT = GitRepo() +USER_CONFIG_DIR = get_user_config_dir() # Ultralytics settings dir +SETTINGS_FILE = USER_CONFIG_DIR / "settings.json" + + +def colorstr(*input): + r"""Color a string based on the provided color and style arguments using ANSI escape codes. + + This function can be called in two ways: + - colorstr('color', 'style', 'your string') + - colorstr('your string') + + In the second form, 'blue' and 'bold' will be applied by default. + + Args: + *input (str | Path): A sequence of strings where the first n-1 strings are color and style arguments, and the + last string is the one to be colored. + + Returns: + (str): The input string wrapped with ANSI escape codes for the specified color and style. + + Examples: + >>> colorstr("blue", "bold", "hello world") + '\x1b[34m\x1b[1mhello world\x1b[0m' + + Notes: + Supported Colors and Styles: + - Basic Colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' + - Bright Colors: 'bright_black', 'bright_red', 'bright_green', 'bright_yellow', + 'bright_blue', 'bright_magenta', 'bright_cyan', 'bright_white' + - Misc: 'end', 'bold', 'underline' + + References: + https://en.wikipedia.org/wiki/ANSI_escape_code + """ + *args, string = input if len(input) > 1 else ("blue", "bold", input[0]) # color arguments, string + colors = { + "black": "\033[30m", # basic colors + "red": "\033[31m", + "green": "\033[32m", + "yellow": "\033[33m", + "blue": "\033[34m", + "magenta": "\033[35m", + "cyan": "\033[36m", + "white": "\033[37m", + "bright_black": "\033[90m", # bright colors + "bright_red": "\033[91m", + "bright_green": "\033[92m", + "bright_yellow": "\033[93m", + "bright_blue": "\033[94m", + "bright_magenta": "\033[95m", + "bright_cyan": "\033[96m", + "bright_white": "\033[97m", + "end": "\033[0m", # misc + "bold": "\033[1m", + "underline": "\033[4m", + } + return "".join(colors[x] for x in args) + f"{string}" + colors["end"] + + +def remove_colorstr(input_string): + """Remove ANSI escape codes from a string, effectively un-coloring it. + + Args: + input_string (str): The string to remove color and style from. + + Returns: + (str): A new string with all ANSI escape codes removed. + + Examples: + >>> remove_colorstr(colorstr("blue", "bold", "hello world")) + 'hello world' + """ + ansi_escape = re.compile(r"\x1B\[[0-9;]*[A-Za-z]") + return ansi_escape.sub("", input_string) + + +class TryExcept(contextlib.ContextDecorator): + """Ultralytics TryExcept class for handling exceptions gracefully. + + This class can be used as a decorator or context manager to catch exceptions and optionally print warning messages. + It allows code to continue execution even when exceptions occur, which is useful for non-critical operations. + + Attributes: + msg (str): Optional message to display when an exception occurs. + verbose (bool): Whether to print the exception message. + + Examples: + As a decorator: + >>> @TryExcept(msg="Error occurred in func", verbose=True) + ... def func(): + ... # Function logic here + ... pass + + As a context manager: + >>> with TryExcept(msg="Error occurred in block", verbose=True): + ... # Code block here + ... pass + """ + + def __init__(self, msg="", verbose=True): + """Initialize TryExcept class with optional message and verbosity settings.""" + self.msg = msg + self.verbose = verbose + + def __enter__(self): + """Execute when entering TryExcept context, initialize instance.""" + + def __exit__(self, exc_type, value, traceback): + """Define behavior when exiting a 'with' block, print error message if necessary.""" + if self.verbose and value: + LOGGER.warning(f"{self.msg}{': ' if self.msg else ''}{value}") + return True + + +class Retry(contextlib.ContextDecorator): + """Retry class for function execution with exponential backoff. + + This decorator can be used to retry a function on exceptions, up to a specified number of times with an + exponentially increasing delay between retries. It's useful for handling transient failures in network operations or + other unreliable processes. + + Attributes: + times (int): Maximum number of retry attempts. + delay (int): Initial delay between retries in seconds. + + Examples: + Example usage as a decorator: + >>> @Retry(times=3, delay=2) + ... def test_func(): + ... # Replace with function logic that may raise exceptions + ... return True + """ + + def __init__(self, times=3, delay=2, verbose=True): + """Initialize Retry class with specified number of retries and delay.""" + self.times = times + self.delay = delay + self.verbose = verbose # False when the caller's own logging would feed back into its retries + self._attempts = 0 + + def __call__(self, func): + """Decorator implementation for Retry with exponential backoff.""" + + def wrapped_func(*args, **kwargs): + """Apply retries to the decorated function or method.""" + self._attempts = 0 + while self._attempts < self.times: + try: + return func(*args, **kwargs) + except Exception as e: + self._attempts += 1 + if self.verbose: + LOGGER.warning(f"Retry {self._attempts}/{self.times} failed: {e}") + if self._attempts >= self.times: + raise + time.sleep(self.delay * (2**self._attempts)) # exponential backoff delay + + return wrapped_func + + +def threaded(func): + """Multi-thread a target function by default and return the thread or function result. + + This decorator provides flexible execution of the target function, either in a separate thread or synchronously. By + default, the function runs in a thread, but this can be controlled via the 'threaded=False' keyword argument which + is removed from kwargs before calling the function. + + Args: + func (callable): The function to be potentially executed in a separate thread. + + Returns: + (callable): A wrapper function that either returns a thread or the direct function result. The thread is + non-daemon so interpreter shutdown joins it before module teardown, avoiding teardown races. + + Examples: + >>> @threaded + ... def process_data(data): + ... return data + >>> + >>> thread = process_data(my_data) # Runs in background thread + >>> result = process_data(my_data, threaded=False) # Runs synchronously, returns function result + """ + + def wrapper(*args, **kwargs): + """Multi-thread a given function based on 'threaded' kwarg and return the thread or function result.""" + if kwargs.pop("threaded", True): # run in thread + # Non-daemon so interpreter shutdown joins the thread before module teardown; a daemon thread still + # running at exit can be killed mid-C-call, aborting the process (e.g. 'FATAL: exception not rethrown'). + thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=False) + thread.start() + return thread + else: + return func(*args, **kwargs) + + return wrapper + + +def set_sentry(): + """Initialize the Sentry SDK for error tracking and reporting. + + Only used if sentry_sdk package is installed and sync=True in settings. Run 'yolo settings' to see and update + settings. + + Conditions required to send errors (ALL conditions must be met or no errors will be reported): + - sentry_sdk package is installed + - sync=True in YOLO settings + - pytest is not running + - running in a pip package installation + - running in a non-git directory + - running with rank -1 or 0 + - online environment + - CLI used to run package (checked with 'yolo' as the name of the main CLI command) + """ + if ( + not SETTINGS["sync"] + or RANK not in {-1, 0} + or Path(ARGV[0]).name != "yolo" + or TESTS_RUNNING + or not ONLINE + or not IS_PIP_PACKAGE + or GIT.is_repo + ): + return + # If sentry_sdk package is not installed then return and do not use Sentry + try: + import sentry_sdk + except ImportError: + return + + def before_send(event, hint): + """Modify the event before sending it to Sentry based on specific exception types and messages. + + Args: + event (dict): The event dictionary containing information about the error. + hint (dict): A dictionary containing additional information about the error. + + Returns: + (dict | None): The modified event or None if the event should not be sent to Sentry. + """ + if "exc_info" in hint: + exc_type, exc_value, _ = hint["exc_info"] + if exc_type in {KeyboardInterrupt, FileNotFoundError} or "out of memory" in str(exc_value): + return None # do not send event + + event.get("extra", {}).pop("sys.argv", None) + event["tags"] = { + "sys_argv": ARGV[0], + "sys_argv_name": Path(ARGV[0]).name, + "install": "git" if GIT.is_repo else "pip" if IS_PIP_PACKAGE else "other", + "os": ENVIRONMENT, + } + return event + + sentry_sdk.init( + dsn="https://888e5a0778212e1d0314c37d4b9aae5d@o4504521589325824.ingest.us.sentry.io/4504521592406016", + debug=False, + auto_enabling_integrations=False, + include_local_variables=False, + traces_sample_rate=1.0, + release=__version__, + environment="runpod" if is_runpod() else "production", + before_send=before_send, + ignore_errors=[KeyboardInterrupt, FileNotFoundError], + ) + sentry_sdk.set_user({"id": SETTINGS["uuid"]}) # SHA-256 anonymized UUID hash + + +class JSONDict(dict): + """A dictionary-like class that provides JSON persistence for its contents. + + This class extends the built-in dictionary to automatically save its contents to a JSON file whenever they are + modified. It ensures thread-safe operations using a lock and handles JSON serialization of Path objects. + + Attributes: + file_path (Path): The path to the JSON file used for persistence. + lock (threading.Lock): A lock object to ensure thread-safe operations. + + Methods: + _load: Load the data from the JSON file into the dictionary. + _save: Save the current state of the dictionary to the JSON file. + __setitem__: Store a key-value pair and persist it to disk. + __delitem__: Remove an item and update the persistent storage. + update: Update the dictionary and persist changes. + clear: Clear all entries and update the persistent storage. + + Examples: + >>> json_dict = JSONDict("data.json") + >>> json_dict["key"] = "value" + >>> print(json_dict["key"]) + value + >>> del json_dict["key"] + >>> json_dict.update({"new_key": "new_value"}) + >>> json_dict.clear() + """ + + def __init__(self, file_path: str | Path = "data.json"): + """Initialize a JSONDict object with a specified file path for JSON persistence.""" + super().__init__() + self.file_path = Path(file_path) + self.lock = Lock() + self._load() + + def _load(self): + """Load the data from the JSON file into the dictionary.""" + try: + if self.file_path.exists(): + with open(self.file_path) as f: + # Use the base dict update to avoid persisting during reads + super().update(json.load(f)) + except json.JSONDecodeError: + LOGGER.warning(f"Error decoding JSON from {self.file_path}. Starting with an empty dictionary.") + except Exception as e: + LOGGER.error(f"Error reading from {self.file_path}: {e}") + + def _save(self): + """Save the current state of the dictionary to the JSON file.""" + try: + self.file_path.parent.mkdir(parents=True, exist_ok=True) + with open(self.file_path, "w", encoding="utf-8") as f: + json.dump(dict(self), f, indent=2, default=self._json_default) + except Exception as e: + LOGGER.error(f"Error writing to {self.file_path}: {e}") + + @staticmethod + def _json_default(obj): + """Handle JSON serialization of Path objects.""" + if isinstance(obj, Path): + return str(obj) + raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable") + + def __setitem__(self, key, value): + """Store a key-value pair and persist to disk.""" + with self.lock: + super().__setitem__(key, value) + self._save() + + def __delitem__(self, key): + """Remove an item and update the persistent storage.""" + with self.lock: + super().__delitem__(key) + self._save() + + def __str__(self): + """Return a pretty-printed JSON string representation of the dictionary.""" + contents = json.dumps(dict(self), indent=2, ensure_ascii=False, default=self._json_default) + return f'JSONDict("{self.file_path}"):\n{contents}' + + def update(self, *args, **kwargs): + """Update the dictionary and persist changes.""" + with self.lock: + super().update(*args, **kwargs) + self._save() + + def clear(self): + """Clear all entries and update the persistent storage.""" + with self.lock: + super().clear() + self._save() + + +class SettingsManager(JSONDict): + """SettingsManager class for managing and persisting Ultralytics settings. + + This class extends JSONDict to provide JSON persistence for settings, ensuring thread-safe operations and default + values. It validates settings on initialization and provides methods to update or reset settings. The settings + include directories for datasets, weights, and runs, as well as various integration flags. + + Attributes: + file (Path): The path to the JSON file used for persistence. + version (str): The version of the settings schema. + defaults (dict): A dictionary containing default settings. + help_msg (str): A help message for users on how to view and update settings. + + Methods: + _validate_settings: Validate the current settings and reset if necessary. + update: Update settings, validating keys and types. + reset: Reset the settings to default and save them. + + Examples: + Initialize and update settings: + >>> settings = SettingsManager() + >>> settings.update(runs_dir="/new/runs/dir") + >>> print(settings["runs_dir"]) + /new/runs/dir + """ + + def __init__(self, file=SETTINGS_FILE, version="0.0.8"): + """Initialize the SettingsManager with default settings and load user settings.""" + import hashlib + import uuid + + from ultralytics.utils.torch_utils import torch_distributed_zero_first + + root = GIT.root or Path() + datasets_root = (root.parent if GIT.root and is_dir_writeable(root.parent) else root).resolve() + + self.file = Path(file) + self.version = version + self.defaults = { + "settings_version": version, # Settings schema version + "datasets_dir": str(datasets_root / "datasets"), # Datasets directory + "weights_dir": str(root / "weights"), # Model weights directory + "runs_dir": str(root / "runs"), # Experiment runs directory + "uuid": hashlib.sha256(str(uuid.getnode()).encode()).hexdigest(), # SHA-256 anonymized UUID hash + "sync": True, # Enable synchronization + "api_key": "", # Ultralytics API Key + "openai_api_key": "", # OpenAI API Key + "clearml": True, # ClearML integration + "comet": True, # Comet integration + "dvc": True, # DVC integration + "mlflow": True, # MLflow integration + "raytune": True, # Ray Tune integration + "tensorboard": False, # TensorBoard logging + "wandb": False, # Weights & Biases logging + "vscode_msg": True, # VSCode message + "openvino_msg": True, # OpenVINO export on Intel CPU message + } + + self.help_msg = ( + f"\nView Ultralytics Settings with 'yolo settings' or at '{self.file}'" + "\nUpdate Settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'. " + "For help see https://docs.ultralytics.com/usage/settings." + ) + + with torch_distributed_zero_first(LOCAL_RANK): + super().__init__(self.file) + + if not self.file.exists() or not self: # Check if file doesn't exist or is empty + LOGGER.info(f"Creating new Ultralytics Settings v{version} file ✅ {self.help_msg}") + self.reset() + + self._validate_settings() + + def _validate_settings(self): + """Validate settings and migrate valid values to the current schema.""" + correct_keys = frozenset(self.keys()) == frozenset(self.defaults.keys()) + correct_types = all(isinstance(self.get(k), type(v)) for k, v in self.defaults.items()) + correct_version = self.get("settings_version", "") == self.version + + if not (correct_keys and correct_types and correct_version): + LOGGER.warning( + "Ultralytics settings updated to the latest schema. Existing values were preserved where possible. " + f"{self.help_msg}" + ) + valid = {k: v for k, v in self.items() if k in self.defaults and isinstance(v, type(self.defaults[k]))} + if not re.fullmatch(r"ul_[0-9a-f]{40}", valid.get("api_key", "")): + if valid.get("api_key"): + LOGGER.warning( + f"Legacy API key removed. Get a Platform API key from {PLATFORM_URL}/settings?tab=api-keys " + "and run 'yolo login API_KEY'." + ) + valid["api_key"] = "" # discard legacy keys, which cannot authenticate with Platform + valid["settings_version"] = self.version + self.clear() + self.update({**self.defaults, **valid}) + + if self.get("datasets_dir") == self.get("runs_dir"): + LOGGER.warning( + f"Ultralytics setting 'datasets_dir: {self.get('datasets_dir')}' " + f"must be different than 'runs_dir: {self.get('runs_dir')}'. " + f"Please change one to avoid possible issues during training. {self.help_msg}" + ) + + def __setitem__(self, key, value): + """Update one key: value pair.""" + self.update({key: value}) + + def update(self, *args, **kwargs): + """Update settings, validating keys and types.""" + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + for k, v in kwargs.items(): + if k not in self.defaults: + raise KeyError(f"No Ultralytics setting '{k}'. {self.help_msg}") + t = type(self.defaults[k]) + if not isinstance(v, t): + raise TypeError( + f"Ultralytics setting '{k}' must be '{t.__name__}' type, not '{type(v).__name__}'. {self.help_msg}" + ) + super().update(*args, **kwargs) + + def reset(self): + """Reset the settings to default and save them.""" + self.clear() + self.update(self.defaults) + + +def deprecation_warn(arg, new_arg=None): + """Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument.""" + msg = f"'{arg}' is deprecated and will be removed in the future." + if new_arg is not None: + msg += f" Use '{new_arg}' instead." + LOGGER.warning(msg) + + +def clean_url(url): + """Strip auth from URL, i.e. `https://example.com/path/file.txt?auth` -> `https://example.com/path/file.txt`.""" + url = Path(url).as_posix().replace(":/", "://") # Pathlib turns :// -> :/, as_posix() for Windows + return unquote(url).split("?", 1)[0] # '%2F' to '/', split authentication query strings + + +def url2file(url): + """Convert URL to filename, i.e. `https://example.com/path/file.txt?auth` -> `file.txt`.""" + return Path(clean_url(url)).name or "download" + + +def vscode_msg(ext="ultralytics.ultralytics-snippets") -> str: + """Display a message to install Ultralytics-Snippets for VS Code if not already installed.""" + path = (USER_CONFIG_DIR.parents[2] if WINDOWS else USER_CONFIG_DIR.parents[1]) / ".vscode/extensions" + obs_file = path / ".obsolete" # file tracks uninstalled extensions, while source directory remains + installed = any(path.glob(f"{ext}*")) and ext not in (obs_file.read_text("utf-8") if obs_file.exists() else "") + url = "https://docs.ultralytics.com/integrations/vscode" + return "" if installed else f"{colorstr('VS Code:')} view Ultralytics VS Code Extension ⚡ at {url}" + + +# Run below code on utils init ------------------------------------------------------------------------------------ + +# Check first-install steps +PREFIX = colorstr("Ultralytics: ") +SETTINGS = SettingsManager() # initialize settings +DATASETS_DIR = Path(SETTINGS["datasets_dir"]) # global datasets directory +WEIGHTS_DIR = Path(SETTINGS["weights_dir"]) # global weights directory +RUNS_DIR = Path(SETTINGS["runs_dir"]) # global runs directory +ENVIRONMENT = ( + "Colab" + if IS_COLAB + else "Kaggle" + if IS_KAGGLE + else "Jupyter" + if IS_JUPYTER + else "Docker" + if IS_DOCKER + else platform.system() +) +TESTS_RUNNING = is_pytest_running() or is_github_action_running() +set_sentry() + +# Apply monkey patches +torch.save = torch_save +if WINDOWS: + # Apply cv2 patches for non-ASCII and non-UTF characters in image paths + cv2.imread, cv2.imwrite, cv2.imshow = imread_unicode, imwrite, imshow diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82c744a8385b589d757dc7ece04723dc13df1fc8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/autobatch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/autobatch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9c8e0e41e341eb69a8874acac166af18e775761 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/autobatch.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/autodevice.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/autodevice.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd2ae0104940effb3d18c054540fb3b5c4975bad Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/autodevice.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/benchmarks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/benchmarks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7e48df1c23046326a4068d54bd6e59519bace68 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/benchmarks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/checks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/checks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d519a5f4fd66e87c8f2099ee8cabd43a96a284f6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/checks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/cpu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/cpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c034992562d5e4aaa2eb2f389fb93db048fe8411 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/cpu.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/dist.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/dist.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ea8c28e453c00c60f679321c99cf5416e255c62 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/dist.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/downloads.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/downloads.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60947ea1984a0a18792bdebd451a54422ea53450 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/downloads.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/events.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/events.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b60cc7796a6d247bdffd19b732afafc9e9be858 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/events.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/files.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/files.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e16ca3750732c8d7e5802fb87dbd866d05a31a49 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/files.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/git.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/git.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbe3678a941ccb30b584c40b8c5716dcde17a043 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/git.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/instance.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/instance.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd135225ebca6e67e6e01bde0bf51c4f5beb75eb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/instance.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/logger.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/logger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..533c857f857b715a1b0818de927e8c57579a9255 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/logger.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/loss.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/loss.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3df83dac8d28ffe64c7a42dca54030ceaaf334af Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/loss.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/metrics.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..322ddd64fc0addd42d659de1e21c5dd46e738713 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/metrics.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0608cbfb0fa87f738d429f76bcee62d90244974b863c75d51a4fdc90cbde5318 +size 121533 diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/nms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/nms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a13f660e5d3f9fec4370570c434728850878680b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/nms.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38b91ce18f5b28dd96af8e27183c58aa39007975 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/ops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/patches.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/patches.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a46f9e002d71a6311be708c7fdf1d0eeb99b061 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/patches.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/plotting.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/plotting.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4a896d8d71fbf9162eea29e57c11ea79fde9ac8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/plotting.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/tal.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/tal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21fa0dfa5226fb7128568cc3fef2cbb960a8d46b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/tal.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/torch_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/torch_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..387928a5981d04ea6d622ec984504f9781da7ec2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/torch_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/tqdm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/tqdm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06f71a68fc175251ee35afc8ee363f96ca3080a4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/tqdm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/triton.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/triton.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a76de9a366b1c3022c657732d03ac597c377086 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/triton.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/tuner.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/tuner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3ad191b269df3b2e44ddc2bf44e6d2cc4562f88 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/tuner.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/uploads.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/uploads.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a78de8487957b4539a58d2ffcd08b9fde2b13650 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/__pycache__/uploads.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/autobatch.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/autobatch.py new file mode 100644 index 0000000000000000000000000000000000000000..f5daf1f7144cef9024201040d4a8492805184bba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/autobatch.py @@ -0,0 +1,142 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Functions for estimating the best YOLO batch size to use a fraction of the available GPU memory in PyTorch.""" + +from __future__ import annotations + +from copy import deepcopy + +import numpy as np +import torch + +from ultralytics.utils import DEFAULT_CFG, LOGGER, colorstr +from ultralytics.utils.torch_utils import autocast, get_torch_device_backend, profile_ops + + +def check_train_batch_size( + model: torch.nn.Module, + imgsz: int = 640, + amp: bool | torch.dtype = True, + batch: float = -1, + max_num_obj: int = 1, + dataset_size: int = 0, +) -> int: + """Compute optimal YOLO training batch size using the autobatch() function. + + Args: + model (torch.nn.Module): YOLO model to check batch size for. + imgsz (int, optional): Image size used for training. + amp (bool | torch.dtype, optional): Whether to use mixed precision, or the autocast dtype. + batch (int | float, optional): Fraction of GPU memory to use. If -1, use default. + max_num_obj (int, optional): The maximum number of objects from dataset. + dataset_size (int, optional): Total number of training images. If > 0, batch size will not exceed this value. + + Returns: + (int): Optimal batch size computed using the autobatch() function. + + Raises: + RuntimeError: If no candidate batch size produces a usable profile. + + Notes: + If 0.0 < batch < 1.0, it's used as the fraction of GPU memory to use. + Otherwise, a default fraction of 0.6 is used. + """ + with autocast(enabled=amp, device=next(model.parameters()).device.type): + return autobatch( + deepcopy(model).train(), + imgsz, + fraction=batch if 0.0 < batch < 1.0 else 0.6, + max_num_obj=max_num_obj, + dataset_size=dataset_size, + ) + + +def autobatch( + model: torch.nn.Module, + imgsz: int = 640, + fraction: float = 0.60, + batch_size: int = DEFAULT_CFG.batch, + max_num_obj: int = 1, + dataset_size: int = 0, +) -> int: + """Automatically estimate the best YOLO batch size to use a fraction of the available GPU memory. + + Args: + model (torch.nn.Module): YOLO model to compute batch size for. + imgsz (int, optional): The image size used as input for the YOLO model. + fraction (float, optional): The fraction of available CUDA memory to use. + batch_size (int, optional): The default batch size to use if an error is detected. + max_num_obj (int, optional): The maximum number of objects from dataset. + dataset_size (int, optional): Total number of training images. If > 0, batch size will not exceed this value. + + Returns: + (int): The optimal batch size. + + Raises: + RuntimeError: If no candidate batch size produces a usable profile. + """ + # Check device + prefix = colorstr("AutoBatch: ") + LOGGER.info(f"{prefix}Computing optimal batch size for imgsz={imgsz} at {fraction * 100}% GPU memory utilization.") + device = next(model.parameters()).device # get model device + if device.type in {"cpu", "mps"}: + LOGGER.warning(f"{prefix}intended for GPU devices, using default batch-size {batch_size}") + return batch_size + if device.type == "cuda" and torch.backends.cudnn.benchmark: + LOGGER.warning(f"{prefix}Requires torch.backends.cudnn.benchmark=False, using default batch-size {batch_size}") + return batch_size + + # Inspect GPU memory + accelerator = get_torch_device_backend(device) + gb = 1 << 30 # bytes to GiB (1024 ** 3) + d = f"{device.type.upper()}:{device.index}" + properties = accelerator.get_device_properties(device) # device properties + t = properties.total_memory / gb # GiB total + r = accelerator.memory_reserved(device) / gb # GiB reserved + a = accelerator.memory_allocated(device) / gb # GiB allocated + f = t - (r + a) # GiB free + LOGGER.info(f"{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free") + + # Profile batch sizes + batch_sizes = [1, 2, 4, 8, 16] if t < 16 else [1, 2, 4, 8, 16, 32, 64] + if dataset_size > 0: + batch_sizes = [b for b in batch_sizes if b <= dataset_size] + ch = model.yaml.get("channels", 3) + try: + img = [torch.empty(b, ch, imgsz, imgsz) for b in batch_sizes] + results = profile_ops(img, model, n=1, device=device, max_num_obj=max_num_obj) + + # Fit a solution + xy = [ + [x, y[2]] + for i, (x, y) in enumerate(zip(batch_sizes, results)) + if y # valid result + and isinstance(y[2], (int, float)) # is numeric + and 0 < y[2] < t # between 0 and GPU limit + and (i == 0 or not results[i - 1] or y[2] > results[i - 1][2]) # first item or increasing memory + ] + if xy: + fit_x, fit_y = zip(*xy) + p = np.polyfit(fit_x, fit_y, deg=1) # first-degree (linear) polynomial fit + b = int((round(f * fraction) - p[1]) / p[0]) # y intercept (optimal batch size) + oom = next((i for i, y in enumerate(results) if not y and batch_sizes[i] > fit_x[0]), None) + if oom is not None and b >= batch_sizes[oom]: # first failure above a success is the memory ceiling + b = batch_sizes[oom - 1] # select prior safe point + if b < 1 or b > 1024: # b outside of safe range + LOGGER.warning(f"{prefix}batch={b} outside safe range, using default batch-size {batch_size}.") + b = batch_size + if dataset_size > 0: + b = min(b, dataset_size) + + fraction = (np.polyval(p, b) + r + a) / t # predicted fraction + LOGGER.info(f"{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅") + return b + except Exception as e: + LOGGER.warning(f"{prefix}error detected: {e}, using default batch-size {batch_size}.") + return batch_size + finally: + accelerator.empty_cache() + + raise RuntimeError( + f"{prefix}no usable batch size found while profiling batch={batch_sizes}. " + f"See the errors above, free GPU memory, reduce imgsz, or set batch explicitly." + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/autodevice.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/autodevice.py new file mode 100644 index 0000000000000000000000000000000000000000..c5247ebda4cd43fb2f73574f73bedb80f8cc207c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/autodevice.py @@ -0,0 +1,214 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import random +from typing import Any + +from ultralytics.utils import LOGGER + + +class GPUInfo: + """Manages NVIDIA GPU information via pynvml with robust error handling. + + Provides methods to query detailed GPU statistics (utilization, memory, temp, power) and select the most idle GPUs + based on configurable criteria. It safely handles the absence or initialization failure of the pynvml library by + logging warnings and disabling related features, preventing application crashes. + + Includes fallback logic using `torch.cuda` for basic device counting if NVML is unavailable during GPU + selection. Manages NVML initialization and shutdown internally. + + Attributes: + pynvml (module | None): The `pynvml` module if successfully imported and initialized, otherwise `None`. + nvml_available (bool): Indicates if `pynvml` is ready for use. True if `nvmlInit()` succeeded, False otherwise. + gpu_stats (list[dict[str, Any]]): A list of dictionaries, each holding stats for one GPU, populated on + initialization and by `refresh_stats()`. Keys include: 'index', 'name', 'utilization' (%), 'memory_used' (MiB), + 'memory_total' (MiB), 'memory_free' (MiB), 'temperature' (C), 'power_draw' (W), 'power_limit' (W or 'N/A'). + Empty if NVML is unavailable or queries fail. + + Methods: + refresh_stats: Refresh the internal gpu_stats list by querying NVML. + print_status: Print GPU status in a compact table format using current stats. + select_idle_gpu: Select the most idle GPUs based on utilization and free memory. + shutdown: Shut down NVML if it was initialized. + + Examples: + Initialize GPUInfo and print status + >>> gpu_info = GPUInfo() + >>> gpu_info.print_status() + + Select idle GPUs with minimum memory requirements + >>> selected = gpu_info.select_idle_gpu(count=2, min_memory_fraction=0.2) + >>> print(f"Selected GPU indices: {selected}") + """ + + def __init__(self): + """Initialize GPUInfo, attempting to import and initialize pynvml.""" + self.pynvml: Any | None = None + self.nvml_available: bool = False + self.gpu_stats: list[dict[str, Any]] = [] + + try: + import pynvml # scoped as slow import + + self.pynvml = pynvml + pynvml.nvmlInit() + self.nvml_available = True + self.refresh_stats() + except Exception as e: + LOGGER.warning(f"Failed to initialize pynvml, GPU stats disabled: {e}") + + def __del__(self): + """Ensure NVML is shut down when the object is garbage collected.""" + self.shutdown() + + def shutdown(self): + """Shut down NVML if it was initialized.""" + if self.nvml_available and self.pynvml: + try: + self.pynvml.nvmlShutdown() + except Exception: + pass + self.nvml_available = False + + def refresh_stats(self): + """Refresh the internal gpu_stats list by querying NVML.""" + self.gpu_stats = [] + if not self.nvml_available or not self.pynvml: + return + + try: + device_count = self.pynvml.nvmlDeviceGetCount() + self.gpu_stats.extend(self._get_device_stats(i) for i in range(device_count)) + except Exception as e: + LOGGER.warning(f"Error during device query: {e}") + self.gpu_stats = [] + + def _get_device_stats(self, index: int) -> dict[str, Any]: + """Get stats for a single GPU device.""" + handle = self.pynvml.nvmlDeviceGetHandleByIndex(index) + memory = self.pynvml.nvmlDeviceGetMemoryInfo(handle) + util = self.pynvml.nvmlDeviceGetUtilizationRates(handle) + + def safe_get(func, *args, default=-1, divisor=1): + try: + val = func(*args) + return val // divisor if divisor != 1 and isinstance(val, (int, float)) else val + except Exception: + return default + + temp_type = getattr(self.pynvml, "NVML_TEMPERATURE_GPU", -1) + + return { + "index": index, + "name": self.pynvml.nvmlDeviceGetName(handle), + "utilization": util.gpu if util else -1, + "memory_used": memory.used >> 20 if memory else -1, # Convert bytes to MiB + "memory_total": memory.total >> 20 if memory else -1, + "memory_free": memory.free >> 20 if memory else -1, + "temperature": safe_get(self.pynvml.nvmlDeviceGetTemperature, handle, temp_type), + "power_draw": safe_get(self.pynvml.nvmlDeviceGetPowerUsage, handle, divisor=1000), # Convert mW to W + "power_limit": safe_get(self.pynvml.nvmlDeviceGetEnforcedPowerLimit, handle, divisor=1000), + } + + def print_status(self): + """Print GPU status in a compact table format using current stats.""" + self.refresh_stats() + if not self.gpu_stats: + LOGGER.warning("No GPU stats available.") + return + + stats = self.gpu_stats + name_len = max(len(gpu.get("name", "N/A")) for gpu in stats) + hdr = f"{'Idx':<3} {'Name':<{name_len}} {'Util':>6} {'Mem (MiB)':>15} {'Temp':>5} {'Pwr (W)':>10}" + LOGGER.info(f"\n--- GPU Status ---\n{hdr}\n{'-' * len(hdr)}") + + for gpu in stats: + u = f"{gpu['utilization']:>5}%" if gpu["utilization"] >= 0 else " N/A " + m = f"{gpu['memory_used']:>6}/{gpu['memory_total']:<6}" if gpu["memory_used"] >= 0 else " N/A / N/A " + t = f"{gpu['temperature']}C" if gpu["temperature"] >= 0 else " N/A " + p = f"{gpu['power_draw']:>3}/{gpu['power_limit']:<3}" if gpu["power_draw"] >= 0 else " N/A " + + LOGGER.info(f"{gpu.get('index'):<3d} {gpu.get('name', 'N/A'):<{name_len}} {u:>6} {m:>15} {t:>5} {p:>10}") + + LOGGER.info(f"{'-' * len(hdr)}\n") + + def select_idle_gpu( + self, + count: int = 1, + min_memory_fraction: float = 0, + min_util_fraction: float = 0, + indices: list[int] | None = None, + ) -> list[int]: + """Select the most idle GPUs based on utilization and free memory. + + Args: + count (int): The number of idle GPUs to select. + min_memory_fraction (float): Minimum free memory required as a fraction of total memory. + min_util_fraction (float): Minimum free utilization rate required from 0.0 - 1.0. + indices (list[int] | None): Restrict selection to these GPU indices, e.g. the GPUs visible under an external + CUDA_VISIBLE_DEVICES restriction. None searches all GPUs. + + Returns: + (list[int]): Indices of the selected GPUs, sorted by idleness (lowest utilization first). + + Notes: + Returns fewer than 'count' if not enough qualify or exist. + Returns empty list if NVML stats are unavailable or no GPUs meet the criteria. + """ + assert min_memory_fraction <= 1.0, f"min_memory_fraction must be <= 1.0, got {min_memory_fraction}" + assert min_util_fraction <= 1.0, f"min_util_fraction must be <= 1.0, got {min_util_fraction}" + criteria = ( + f"free memory >= {min_memory_fraction * 100:.1f}% and free utilization >= {min_util_fraction * 100:.1f}%" + ) + LOGGER.info(f"Searching for {count} idle GPUs with {criteria}...") + + if count <= 0: + return [] + + self.refresh_stats() + if not self.gpu_stats: + LOGGER.warning("NVML stats unavailable.") + return [] + + # Filter and sort eligible GPUs + eligible_gpus = [ + gpu + for gpu in self.gpu_stats + if (indices is None or gpu["index"] in indices) + and gpu.get("memory_free", 0) / gpu.get("memory_total", 1) >= min_memory_fraction + and (100 - gpu.get("utilization", 100)) >= min_util_fraction * 100 + ] + # Random tiebreaker prevents race conditions when multiple processes start simultaneously + # and all GPUs appear equally idle (same utilization and free memory) + eligible_gpus.sort(key=lambda x: (x.get("utilization", 101), -x.get("memory_free", 0), random.random())) + + # Select top 'count' indices + selected = [gpu["index"] for gpu in eligible_gpus[:count]] + + if selected: + if len(selected) < count: + LOGGER.warning(f"Requested {count} GPUs but only {len(selected)} met the idle criteria.") + LOGGER.info(f"Selected idle CUDA devices {selected}") + else: + LOGGER.warning(f"No GPUs met criteria ({criteria}).") + + return selected + + +if __name__ == "__main__": + required_free_mem_fraction = 0.2 # Require 20% free VRAM + required_free_util_fraction = 0.2 # Require 20% free utilization + num_gpus_to_select = 1 + + gpu_info = GPUInfo() + gpu_info.print_status() + + if selected := gpu_info.select_idle_gpu( + count=num_gpus_to_select, + min_memory_fraction=required_free_mem_fraction, + min_util_fraction=required_free_util_fraction, + ): + print(f"\n==> Using selected GPU indices: {selected}") + devices = [f"cuda:{idx}" for idx in selected] + print(f" Target devices: {devices}") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/benchmarks.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/benchmarks.py new file mode 100644 index 0000000000000000000000000000000000000000..5b69f8d6501f3fc5c01934237dfc598f26d077ed --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/benchmarks.py @@ -0,0 +1,633 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Benchmark YOLO model formats for speed and accuracy. + +Usage: + from ultralytics.utils.benchmarks import ProfileModels, benchmark + ProfileModels(['yolo26n.yaml', 'yolov8s.yaml']).run() + benchmark(model='yolo26n.pt', imgsz=160) + +Format | `format=argument` | Model +--- | --- | --- +PyTorch | - | yolo26n.pt +TorchScript | `torchscript` | yolo26n.torchscript +ONNX | `onnx` | yolo26n.onnx +OpenVINO | `openvino` | yolo26n_openvino_model/ +TensorRT | `engine` | yolo26n.engine +CoreML | `coreml` | yolo26n.mlpackage +TensorFlow SavedModel | `saved_model` | yolo26n_saved_model/ +TensorFlow GraphDef | `pb` | yolo26n.pb +TensorFlow Edge TPU | `edgetpu` | yolo26n_edgetpu.tflite +PaddlePaddle | `paddle` | yolo26n_paddle_model/ +MNN | `mnn` | yolo26n.mnn +NCNN | `ncnn` | yolo26n_ncnn_model/ +IMX | `imx` | yolo26n_imx_model/ +RKNN | `rknn` | yolo26n_rknn_model/ +ExecuTorch | `executorch` | yolo26n_executorch_model/ +Axelera AI | `axelera` | yolo26n_axelera_model/ +""" + +from __future__ import annotations + +import glob +import platform +import shutil +import time +from copy import deepcopy +from pathlib import Path + +import numpy as np +import torch.cuda + +from ultralytics import RTDETR, YOLO, YOLOWorld +from ultralytics.cfg import TASK2DATA, TASK2METRIC +from ultralytics.engine.exporter import export_formats +from ultralytics.nn.modules import Segment26 +from ultralytics.utils import ( + ARM64, + ASSETS, + IS_DOCKER, + IS_JETSON, + LINUX, + LOGGER, + MACOS, + TQDM, + WEIGHTS_DIR, + is_github_action_running, +) +from ultralytics.utils.checks import IS_PYTHON_MINIMUM_3_13, check_imgsz, check_yolo, is_rockchip +from ultralytics.utils.files import file_size +from ultralytics.utils.torch_utils import get_cpu_info, select_device + + +def benchmark( + model=WEIGHTS_DIR / "yolo26n.pt", + data=None, + imgsz=160, + quantize=None, + device="cpu", + verbose=False, + eps=1e-3, + format="", + **kwargs, +): + """Benchmark a YOLO model across different formats for speed and accuracy. + + Args: + model (str | Path): Path to the model file or directory. + data (str | None): Dataset to evaluate on, inherited from TASK2DATA if not passed. + imgsz (int): Image size for the benchmark. + quantize (int | str | None): Requested precision: 16 (FP16), 8 (INT8), or None/32 (FP32). Exported rows apply it + at export, where a format may reject an explicit 32 or fall back to the precision it requires; the native + PyTorch row is not exported and only 16 affects it, selecting FP16 inference. Each format then runs + inference at its own runtime precision. + device (str): Device to run the benchmark on, either 'cpu' or 'cuda'. + verbose (bool | float): If True or a float, assert benchmarks pass with given metric. + eps (float): Epsilon value for divide by zero prevention. + format (str): Export format for benchmarking. If not supplied all formats are benchmarked. + **kwargs (Any): Export options; nms selects the same head for native and exported benchmarks. + + Returns: + (polars.DataFrame): A Polars DataFrame with benchmark results for each format, including file size, metric, and + inference time. + + Examples: + Benchmark a YOLO model with default settings: + >>> from ultralytics.utils.benchmarks import benchmark + >>> benchmark(model="yolo26n.pt", imgsz=640) + """ + from ultralytics.cfg import _handle_deprecation + + kwargs = _handle_deprecation(kwargs) + imgsz = check_imgsz(imgsz) + assert imgsz[0] == imgsz[1] if isinstance(imgsz, list) else True, "benchmark() only supports square imgsz." + + import polars as pl # scope for faster 'import ultralytics' + + pl.Config.set_tbl_cols(-1) # Show all columns + pl.Config.set_tbl_rows(-1) # Show all rows + pl.Config.set_tbl_width_chars(-1) # No width limit + pl.Config.set_tbl_hide_column_data_types(True) # Hide data types + pl.Config.set_tbl_hide_dataframe_shape(True) # Hide shape info + pl.Config.set_tbl_formatting("ASCII_BORDERS_ONLY_CONDENSED") + + device = select_device(device, verbose=False) + if isinstance(model, (str, Path)): + model = YOLO(model) + data = data or TASK2DATA[model.task] # task to dataset, i.e. coco8.yaml for task=detect + key = TASK2METRIC[model.task] # task to metric, i.e. metrics/mAP50-95(B) for task=detect + + y = [] + t0 = time.time() + + format_arg = format.lower() + if format_arg: + formats = frozenset(export_formats()["Argument"]) + assert format_arg in formats, f"Expected format to be one of {formats}, but got '{format_arg}'." + for name, export_format, suffix, cpu, gpu, valid_args, _ in zip(*export_formats().values()): + emoji, filename = "❌", None # export defaults + try: + if format_arg and format_arg != export_format: + continue + if IS_PYTHON_MINIMUM_3_13 and not format_arg and export_format in {"saved_model", "pb", "edgetpu"}: + continue + + # Checks + if export_format == "pb": + assert model.task != "obb", "TensorFlow GraphDef not supported for OBB task" + elif export_format == "edgetpu": + assert LINUX and not ARM64, "Edge TPU export only supported on non-aarch64 Linux" + assert shutil.which("edgetpu_compiler"), "Edge TPU benchmark requires edgetpu_compiler" + elif export_format == "coreml": + assert MACOS or (LINUX and not ARM64), "CoreML export only supported on macOS and non-aarch64 Linux" + # coremltools deadlocks after OpenVINO on macOS Python 3.13 (conflicting OpenMP runtimes); CoreML + # is still benchmarked on non-aarch64 Linux Python 3.13. + assert not (MACOS and IS_PYTHON_MINIMUM_3_13), ( + "CoreML not benchmarked on macOS Python>=3.13 (coremltools/OpenVINO OpenMP deadlock)" + ) + if export_format in {"saved_model", "pb", "edgetpu"}: + assert not isinstance(model, YOLOWorld), "YOLOWorldv2 TensorFlow exports not supported by onnx2tf yet" + if export_format == "paddle": + assert not isinstance(model, YOLOWorld), "YOLOWorldv2 Paddle exports not supported yet" + assert (LINUX and not IS_JETSON) or MACOS, "Windows and Jetson Paddle exports not supported yet" + # PaddlePaddle export works standalone on Python 3.13 but its native protobuf clashes with the + # protobuf>=6.31.1 that TensorFlow loads earlier in this shared benchmark process, causing a segfault. + assert not IS_PYTHON_MINIMUM_3_13, ( + "PaddlePaddle not benchmarked on Python>=3.13 (protobuf ABI conflict with TensorFlow)" + ) + if export_format == "mnn": + assert not isinstance(model, YOLOWorld), "YOLOWorldv2 MNN exports not supported yet" + # MNN export works standalone on Python 3.13 but its ONNX-parsing protobuf clashes with the + # protobuf>=6.31.1 that TensorFlow loads earlier in this shared benchmark process, aborting the run. + assert not IS_PYTHON_MINIMUM_3_13, ( + "MNN not benchmarked on Python>=3.13 (protobuf ABI conflict with TensorFlow)" + ) + if export_format == "ncnn": + assert not isinstance(model, YOLOWorld), "YOLOWorldv2 NCNN exports not supported yet" + if export_format == "imx": + assert not isinstance(model, YOLOWorld), "YOLOWorldv2 IMX exports not supported" + assert model.task in {"detect", "classify", "pose", "segment"}, ( + "IMX export is only supported for detection, classification, pose estimation and segmentation tasks" + ) + assert "C2f" in model.__str__(), "IMX only supported for YOLOv8n and YOLO11n" + if export_format == "rknn": + assert not isinstance(model, YOLOWorld), "YOLOWorldv2 RKNN exports not supported yet" + assert LINUX, "RKNN only supported on Linux" + assert not is_rockchip(), "RKNN Inference only supported on Rockchip devices" + if export_format == "executorch": + assert not isinstance(model, YOLOWorld), "YOLOWorldv2 ExecuTorch exports not supported yet" + if export_format == "axelera": + assert not isinstance(model, YOLOWorld), "YOLOWorldv2 Axelera exports not supported" + assert LINUX and not (ARM64 and IS_DOCKER), ( + "export is only supported on Linux and is not supported on ARM64 Docker." + ) + assert not (model.task == "segment" and any(isinstance(m, Segment26) for m in model.model.modules())), ( + "Axelera export does not currently support YOLO26 segmentation models" + ) + if export_format == "litert": + assert MACOS or (LINUX and not ARM64), "LiteRT benchmark only supported on Linux x86 and macOS" + # benchmark() deadlocks on the ai-edge-litert/TensorFlow abseil mutex (RAW: Lock blocking) on macOS CI + # when litert runs after other TF-based formats in the shared process; still benchmarked locally. + assert not (MACOS and is_github_action_running()), ( + "LiteRT not benchmarked on macOS CI (ai-edge-litert/TF abseil mutex deadlock)" + ) + if "cpu" in device.type: + assert cpu, "inference not supported on CPU" + if "cuda" in device.type: + assert gpu, "inference not supported on GPU" + + # Export + if export_format == "-": + filename = model.pt_path or model.ckpt_path or model.model_name + exported_model = deepcopy(model) # PyTorch format + else: + export_data = data if "data" in valid_args else None + filename = model.export( + imgsz=imgsz, + format=export_format, + quantize=quantize, + data=export_data, + device=device, + verbose=False, + **kwargs, + ) + exported_model = RTDETR(filename) if isinstance(model, RTDETR) else YOLO(filename, task=model.task) + assert suffix in str(filename), "export failed" + emoji = "❎" # indicates export succeeded + + # Predict + assert model.task != "pose" or export_format != "pb", "GraphDef Pose inference is not supported" + assert export_format != "edgetpu", "inference not supported" + assert export_format != "coreml" or platform.system() == "Darwin", "inference requires macOS>=10.13" + assert export_format != "axelera", "inference only supported on Axelera hardware" + exported_model.predict( + ASSETS / "bus.jpg", + imgsz=imgsz, + device=device, + quantize=quantize, + nms=kwargs.get("nms"), + verbose=False, + ) + + # Validate + results = exported_model.val( + data=data, + batch=1, + imgsz=imgsz, + rect=False, + plots=False, + device=device, + quantize=quantize, + nms=kwargs.get("nms"), + verbose=False, + conf=0.001, # all the pre-set benchmark mAP values are based on conf=0.001 + ) + metric, speed = results.results_dict[key], results.speed["inference"] + fps = round(1000 / (speed + eps), 2) # frames per second + y.append([name, "✅", round(file_size(filename), 1), round(metric, 4), round(speed, 2), fps]) + except Exception as e: + if verbose: + assert type(e) is AssertionError, f"Benchmark failure for {name}: {e}" + LOGGER.error(f"Benchmark failure for {name}: {e}") + y.append([name, emoji, round(file_size(filename), 1), None, None, None]) # mAP, t_inference + + # Print results + check_yolo(device=device) # print system info + df = pl.DataFrame(y, schema=["Format", "Status❔", "Size (MB)", key, "Inference time (ms/im)", "FPS"], orient="row") + df = df.with_row_index(" ", offset=1) # add index info + df_display = df.with_columns(pl.all().cast(pl.String).fill_null("-")) + + name = model.model_name + dt = time.time() - t0 + legend = "Benchmarks legend: - ✅ Success - ❎ Export passed but validation failed - ❌️ Export failed" + s = f"\nBenchmarks complete for {name} on {data} at imgsz={imgsz} ({dt:.2f}s)\n{legend}\n{df_display}\n" + LOGGER.info(s) + with open("benchmarks.log", "a", errors="ignore", encoding="utf-8") as f: + f.write(s) + + if verbose and isinstance(verbose, float): + metrics = df[key].to_numpy() # values to compare to floor + floor = verbose # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n + assert all(x > floor for x in metrics if not np.isnan(x)), f"Benchmark failure: metric(s) < floor {floor}" + + return df_display + + +class ProfileModels: + """ProfileModels class for profiling different models on ONNX and TensorRT. + + This class profiles the performance of different models, returning results such as model speed and FLOPs. + + Attributes: + paths (list[str]): Paths of the models to profile. + num_timed_runs (int): Number of timed runs for the profiling. + num_warmup_runs (int): Number of warmup runs before profiling. + min_time (float): Minimum number of seconds to profile for. + imgsz (int): Image size used in the models. + quantize (int | str | None): Export precision for TensorRT profiling, e.g. 16 (FP16) or 8 (INT8). + trt (bool): Flag to indicate whether to profile using TensorRT. + device (torch.device): Device used for profiling. + + Methods: + run: Profile YOLO models for speed and accuracy across various formats. + get_files: Get all relevant model files. + get_onnx_model_info: Extract metadata from an ONNX model. + iterative_sigma_clipping: Apply sigma clipping to remove outliers. + profile_tensorrt_model: Profile a TensorRT model. + profile_onnx_model: Profile an ONNX model. + generate_table_row: Generate a table row with model metrics. + generate_results_dict: Generate a dictionary of profiling results. + print_table: Print a formatted table of results. + + Examples: + Profile models and print results + >>> from ultralytics.utils.benchmarks import ProfileModels + >>> profiler = ProfileModels(["yolo26n.yaml", "yolov8s.yaml"], imgsz=640) + >>> profiler.run() + """ + + def __init__( + self, + paths: list[str], + num_timed_runs: int = 100, + num_warmup_runs: int = 10, + min_time: float = 60, + imgsz: int = 640, + quantize: int | str | None = 16, + trt: bool = True, + device: torch.device | str | None = None, + ): + """Initialize the ProfileModels class for profiling models. + + Args: + paths (list[str]): List of paths of the models to be profiled. + num_timed_runs (int): Number of timed runs for the profiling. + num_warmup_runs (int): Number of warmup runs before the actual profiling starts. + min_time (float): Minimum time in seconds for profiling a model. + imgsz (int): Size of the image used during profiling. + quantize (int | str | None): Export precision for TensorRT profiling, e.g. 16 (FP16, default) or 8 (INT8). + trt (bool): Flag to indicate whether to profile using TensorRT. + device (torch.device | str | None): Device used for profiling. If None, it is determined automatically. + + Notes: + quantize applies only to the TensorRT profiling export; ONNX profiling stays FP32 (FP16 is slower on CPU). + """ + self.paths = paths + self.num_timed_runs = num_timed_runs + self.num_warmup_runs = num_warmup_runs + self.min_time = min_time + self.imgsz = imgsz + self.quantize = quantize + self.trt = trt # run TensorRT profiling + self.device = select_device(device, verbose=False) + + def run(self): + """Profile YOLO models for speed and accuracy across various formats including ONNX and TensorRT. + + Returns: + (list[dict]): List of dictionaries containing profiling results for each model. + + Examples: + Profile models and print results + >>> from ultralytics.utils.benchmarks import ProfileModels + >>> profiler = ProfileModels(["yolo26n.yaml", "yolo11s.yaml"]) + >>> results = profiler.run() + """ + files = self.get_files() + + if not files: + LOGGER.warning("No matching *.pt or *.onnx files found.") + return [] + + table_rows = [] + output = [] + for file in files: + engine_file = file.with_suffix(".engine") + if file.suffix in {".pt", ".yaml", ".yml"}: + model = YOLO(str(file)) + model.fuse(verbose=False) + model_info = model.info(imgsz=self.imgsz) + if self.trt and self.device.type != "cpu" and not engine_file.is_file(): + engine_file = model.export( + format="engine", + quantize=self.quantize, + imgsz=self.imgsz, + device=self.device, + verbose=False, + ) + onnx_file = model.export( + format="onnx", + imgsz=self.imgsz, + device=self.device, + verbose=False, + ) + elif file.suffix == ".onnx": + model_info = self.get_onnx_model_info(file) + onnx_file = file + else: + continue + + t_engine = self.profile_tensorrt_model(str(engine_file)) + t_onnx = self.profile_onnx_model(str(onnx_file)) + table_rows.append(self.generate_table_row(file.stem, t_onnx, t_engine, model_info)) + output.append(self.generate_results_dict(file.stem, t_onnx, t_engine, model_info)) + + self.print_table(table_rows) + return output + + def get_files(self): + """Return a list of paths for all relevant model files given by the user. + + Returns: + (list[Path]): List of Path objects for the model files. + """ + files = [] + for path in self.paths: + path = Path(path) + if path.is_dir(): + extensions = ["*.pt", "*.onnx", "*.yaml"] + files.extend([file for ext in extensions for file in glob.glob(str(path / ext))]) + elif path.suffix in {".pt", ".yaml", ".yml"}: # add non-existing + files.append(str(path)) + else: + files.extend(glob.glob(str(path))) + + LOGGER.info(f"Profiling: {sorted(files)}") + return [Path(file) for file in sorted(files)] + + @staticmethod + def get_onnx_model_info(onnx_file: str): + """Extract metadata from an ONNX model file including layers, parameters, gradients, and FLOPs.""" + return 0.0, 0.0, 0.0, 0.0 # return (num_layers, num_params, num_gradients, num_flops) + + @staticmethod + def iterative_sigma_clipping(data: np.ndarray, sigma: float = 2, max_iters: int = 3): + """Apply iterative sigma clipping to data to remove outliers. + + Args: + data (np.ndarray): Input data array. + sigma (float): Number of standard deviations to use for clipping. + max_iters (int): Maximum number of iterations for the clipping process. + + Returns: + (np.ndarray): Clipped data array with outliers removed. + """ + data = np.array(data) + for _ in range(max_iters): + mean, std = np.mean(data), np.std(data) + # Include exact-boundary and zero-variance samples. + clipped_data = data[(data >= mean - sigma * std) & (data <= mean + sigma * std)] + if len(clipped_data) == len(data): + break + data = clipped_data + return data + + def profile_tensorrt_model(self, engine_file: str, eps: float = 1e-3): + """Profile YOLO model performance with TensorRT, measuring average run time and standard deviation. + + Args: + engine_file (str): Path to the TensorRT engine file. + eps (float): Small epsilon value to prevent division by zero. + + Returns: + (tuple[float, float]): Mean and standard deviation of inference time in milliseconds. + """ + if not self.trt or not Path(engine_file).is_file(): + return 0.0, 0.0 + + # Model and input + model = YOLO(engine_file) + input_data = np.zeros((self.imgsz, self.imgsz, 3), dtype=np.uint8) # use uint8 for Classify + + # Warmup runs + elapsed = 0.0 + for _ in range(3): + start_time = time.perf_counter() + for _ in range(self.num_warmup_runs): + model(input_data, imgsz=self.imgsz, verbose=False) + elapsed = time.perf_counter() - start_time + + # Compute number of runs as higher of min_time or num_timed_runs + num_runs = max(round(self.min_time / (elapsed + eps) * self.num_warmup_runs), self.num_timed_runs * 50) + + # Timed runs + run_times = [] + for _ in TQDM(range(num_runs), desc=engine_file): + results = model(input_data, imgsz=self.imgsz, verbose=False) + run_times.append(results[0].speed["inference"]) # Convert to milliseconds + + run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=3) # sigma clipping + return np.mean(run_times), np.std(run_times) + + @staticmethod + def check_dynamic(tensor_shape): + """Check whether the tensor shape in the ONNX model is dynamic.""" + return not all(isinstance(dim, int) and dim >= 0 for dim in tensor_shape) + + def profile_onnx_model(self, onnx_file: str, eps: float = 1e-3): + """Profile an ONNX model, measuring average inference time and standard deviation across multiple runs. + + Args: + onnx_file (str): Path to the ONNX model file. + eps (float): Small epsilon value to prevent division by zero. + + Returns: + (tuple[float, float]): Mean and standard deviation of inference time in milliseconds. + """ + import onnxruntime as ort + + from ultralytics.nn.backends import ONNXBackend + + # Session options for consistent benchmarking + sess_options = ort.SessionOptions() + sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL + sess_options.intra_op_num_threads = 8 # Limit the number of threads + + # Initialize ONNXBackend with CPU device for consistent benchmarking + backend = ONNXBackend(onnx_file, device=torch.device("cpu"), fp16=False, session_options=sess_options) + + # Prepare input data dictionary for multi-input models + input_data_dict = {} + for input_tensor in backend.session.get_inputs(): + input_type = input_tensor.type + if self.check_dynamic(input_tensor.shape): + if len(input_tensor.shape) != 4 and self.check_dynamic(input_tensor.shape[1:]): + raise ValueError(f"Unsupported dynamic shape {input_tensor.shape} of {input_tensor.name}") + input_shape = ( + (1, 3, self.imgsz, self.imgsz) if len(input_tensor.shape) == 4 else (1, *input_tensor.shape[1:]) + ) + else: + input_shape = input_tensor.shape + + # Mapping ONNX datatype to numpy datatype + if "float16" in input_type: + input_dtype = np.float16 + elif "float" in input_type: + input_dtype = np.float32 + elif "double" in input_type: + input_dtype = np.float64 + elif "int64" in input_type: + input_dtype = np.int64 + elif "int32" in input_type: + input_dtype = np.int32 + else: + raise ValueError(f"Unsupported ONNX datatype {input_type}") + + input_data_dict[input_tensor.name] = np.random.rand(*input_shape).astype(input_dtype) + + # Warmup runs + elapsed = 0.0 + for _ in range(3): + start_time = time.perf_counter() + for _ in range(self.num_warmup_runs): + backend.forward(input_data_dict) + elapsed = time.perf_counter() - start_time + + # Compute number of runs as higher of min_time or num_timed_runs + num_runs = max(round(self.min_time / (elapsed + eps) * self.num_warmup_runs), self.num_timed_runs) + + # Timed runs + run_times = [] + for _ in TQDM(range(num_runs), desc=onnx_file): + start_time = time.perf_counter() + backend.forward(input_data_dict) + run_times.append((time.perf_counter() - start_time) * 1000) # Convert to milliseconds + + run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=5) # sigma clipping + return np.mean(run_times), np.std(run_times) + + def generate_table_row( + self, + model_name: str, + t_onnx: tuple[float, float], + t_engine: tuple[float, float], + model_info: tuple[float, float, float, float], + ): + """Generate a table row string with model performance metrics. + + Args: + model_name (str): Name of the model. + t_onnx (tuple): ONNX model inference time statistics (mean, std). + t_engine (tuple): TensorRT engine inference time statistics (mean, std). + model_info (tuple): Model information (layers, params, gradients, flops). + + Returns: + (str): Formatted table row string with model metrics. + """ + _layers, params, _gradients, flops = model_info + return ( + f"| {model_name:18s} | {self.imgsz} | - | {t_onnx[0]:.1f}±{t_onnx[1]:.1f} ms | {t_engine[0]:.1f}±" + f"{t_engine[1]:.1f} ms | {params / 1e6:.1f} | {flops:.1f} |" + ) + + @staticmethod + def generate_results_dict( + model_name: str, + t_onnx: tuple[float, float], + t_engine: tuple[float, float], + model_info: tuple[float, float, float, float], + ): + """Generate a dictionary of profiling results. + + Args: + model_name (str): Name of the model. + t_onnx (tuple): ONNX model inference time statistics (mean, std). + t_engine (tuple): TensorRT engine inference time statistics (mean, std). + model_info (tuple): Model information (layers, params, gradients, flops). + + Returns: + (dict): Dictionary containing profiling results. + """ + _layers, params, _gradients, flops = model_info + return { + "model/name": model_name, + "model/parameters": params, + "model/GFLOPs": round(flops, 3), + "model/speed_ONNX(ms)": round(t_onnx[0], 3), + "model/speed_TensorRT(ms)": round(t_engine[0], 3), + } + + @staticmethod + def print_table(table_rows: list[str]): + """Print a formatted table of model profiling results. + + Args: + table_rows (list[str]): List of formatted table row strings. + """ + gpu = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "GPU" + headers = [ + "Model", + "size
(pixels)", + "mAPval
50-95", + f"Speed
CPU ({get_cpu_info()}) ONNX
(ms)", + f"Speed
{gpu} TensorRT
(ms)", + "params
(M)", + "FLOPs
(B)", + ] + header = "|" + "|".join(f" {h} " for h in headers) + "|" + separator = "|" + "|".join("-" * (len(h) + 2) for h in headers) + "|" + + LOGGER.info(f"\n\n{header}") + LOGGER.info(separator) + for row in table_rows: + LOGGER.info(row) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..920cc4fad9d6fa2b7b99707d2fe33941e4612e5b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__init__.py @@ -0,0 +1,5 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .base import add_integration_callbacks, default_callbacks, get_default_callbacks + +__all__ = "add_integration_callbacks", "default_callbacks", "get_default_callbacks" diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..997c1d18809d3e94e84d19bcfa3a73997862de10 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0c93864806e2ea4f871d6c20565df5f3bb5dd2e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/base.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/clearml.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/clearml.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6793b359ed84891612cf1a41e8e66562dc68e6e1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/clearml.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/comet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/comet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c54b05f009ad23dfe8283862e1ef1b6dc248c86 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/comet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/dvc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/dvc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79b9d60ccfda7bbe1e721bda06cbe38fc417ef60 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/dvc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/mlflow.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/mlflow.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfd4f6620d0a4b61e263306ac0a623880ffbc65a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/mlflow.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/platform.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/platform.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30b250ced9b40dce4470c67cb1159084c9041ead Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/platform.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/raytune.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/raytune.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd26e877aafa183b9c2f2840c5623ebad3a631f9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/raytune.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/tensorboard.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/tensorboard.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11bef37a915acea69b7f16c57d80d8477fbecfb2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/tensorboard.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/wb.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/wb.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ed09fc92195b63f662d580484fe421a3d8ee4ce Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/__pycache__/wb.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/base.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/base.py new file mode 100644 index 0000000000000000000000000000000000000000..3e2a215f06d1d9c1624d81509a861a8428383285 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/base.py @@ -0,0 +1,206 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Base callbacks for Ultralytics training, validation, prediction, and export processes.""" + +from collections import defaultdict +from copy import deepcopy + +# Trainer callbacks ---------------------------------------------------------------------------------------------------- + + +def on_pretrain_routine_start(trainer): + """Called at the beginning of the pre-training routine, before data loading and model setup.""" + + +def on_pretrain_routine_end(trainer): + """Called at the end of the pre-training routine, after data loading and model setup are complete.""" + + +def on_train_start(trainer): + """Called when the training starts, before the first epoch begins.""" + + +def on_train_epoch_start(trainer): + """Called at the start of each training epoch, before batch iteration begins.""" + + +def on_train_batch_start(trainer): + """Called at the start of each training batch, before the forward pass.""" + + +def optimizer_step(trainer): + """Called during the optimizer step. Reserved for custom integrations; not called by default.""" + + +def on_before_zero_grad(trainer): + """Called before the gradients are set to zero. Reserved for custom integrations; not called by default.""" + + +def on_train_batch_end(trainer): + """Called at the end of each training batch, after the backward pass. Optimizer step may be deferred by + accumulation. + """ + + +def on_train_epoch_end(trainer): + """Called at the end of each training epoch, after all batches but before validation.""" + + +def on_fit_epoch_end(trainer): + """Called at the end of each fit epoch (train + val), after validation and any checkpoint save.""" + + +def on_model_save(trainer): + """Called when the model checkpoint is saved, after validation.""" + + +def on_train_end(trainer): + """Called when the training ends, after final evaluation of the best model.""" + + +def on_params_update(trainer): + """Called when the model parameters are updated. Reserved for custom integrations; not called by default.""" + + +def teardown(trainer): + """Called during the teardown of the training process.""" + + +# Validator callbacks -------------------------------------------------------------------------------------------------- + + +def on_val_start(validator): + """Called when the validation starts.""" + + +def on_val_batch_start(validator): + """Called at the start of each validation batch.""" + + +def on_val_batch_end(validator): + """Called at the end of each validation batch.""" + + +def on_val_end(validator): + """Called when the validation ends.""" + + +# Predictor callbacks -------------------------------------------------------------------------------------------------- + + +def on_predict_start(predictor): + """Called when the prediction starts.""" + + +def on_predict_batch_start(predictor): + """Called at the start of each prediction batch.""" + + +def on_predict_batch_end(predictor): + """Called at the end of each prediction batch.""" + + +def on_predict_postprocess_end(predictor): + """Called after the post-processing of the prediction ends.""" + + +def on_predict_end(predictor): + """Called when the prediction ends.""" + + +# Exporter callbacks --------------------------------------------------------------------------------------------------- + + +def on_export_start(exporter): + """Called when the model export starts.""" + + +def on_export_end(exporter): + """Called when the model export ends.""" + + +default_callbacks = { + # Run in trainer + "on_pretrain_routine_start": [on_pretrain_routine_start], + "on_pretrain_routine_end": [on_pretrain_routine_end], + "on_train_start": [on_train_start], + "on_train_epoch_start": [on_train_epoch_start], + "on_train_batch_start": [on_train_batch_start], + "optimizer_step": [optimizer_step], + "on_before_zero_grad": [on_before_zero_grad], + "on_train_batch_end": [on_train_batch_end], + "on_train_epoch_end": [on_train_epoch_end], + "on_fit_epoch_end": [on_fit_epoch_end], # fit = train + val + "on_model_save": [on_model_save], + "on_train_end": [on_train_end], + "on_params_update": [on_params_update], + "teardown": [teardown], + # Run in validator + "on_val_start": [on_val_start], + "on_val_batch_start": [on_val_batch_start], + "on_val_batch_end": [on_val_batch_end], + "on_val_end": [on_val_end], + # Run in predictor + "on_predict_start": [on_predict_start], + "on_predict_batch_start": [on_predict_batch_start], + "on_predict_postprocess_end": [on_predict_postprocess_end], + "on_predict_batch_end": [on_predict_batch_end], + "on_predict_end": [on_predict_end], + # Run in exporter + "on_export_start": [on_export_start], + "on_export_end": [on_export_end], +} + + +def get_default_callbacks(): + """Get the default callbacks for Ultralytics training, validation, prediction, and export processes. + + Returns: + (dict): Dictionary of default callbacks for various training events. Each key represents an event during the + training process, and the corresponding value is a list of callback functions executed when that + event occurs. + + Examples: + >>> callbacks = get_default_callbacks() + >>> print(list(callbacks.keys())) # show all available callback events + ['on_pretrain_routine_start', 'on_pretrain_routine_end', ...] + """ + return defaultdict(list, deepcopy(default_callbacks)) + + +def add_integration_callbacks(instance): + """Add integration callbacks to the instance's callbacks dictionary. + + This function loads and adds analytics callbacks to every instance. Trainer instances also receive Platform and + experiment logger callbacks for ClearML, Comet, DVC, MLflow, Ray Tune, TensorBoard, and Weights & Biases. + + Args: + instance (Trainer | Predictor | Validator | Exporter): The object instance to which callbacks will be added. The + type of instance determines which callbacks are loaded. + + Examples: + >>> from ultralytics.engine.trainer import BaseTrainer + >>> trainer = BaseTrainer() + >>> add_integration_callbacks(trainer) + """ + from ultralytics.utils.events import callbacks as events_cb + + callbacks_list = [events_cb] + + # Load training callbacks + if "Trainer" in instance.__class__.__name__: + from .clearml import callbacks as clear_cb + from .comet import callbacks as comet_cb + from .dvc import callbacks as dvc_cb + from .mlflow import callbacks as mlflow_cb + from .platform import callbacks as platform_cb + from .raytune import callbacks as tune_cb + from .tensorboard import callbacks as tb_cb + from .wb import callbacks as wb_cb + + callbacks_list.extend([platform_cb, clear_cb, comet_cb, dvc_cb, mlflow_cb, tune_cb, tb_cb, wb_cb]) + + # Add the callbacks to the callbacks dictionary + for callbacks in callbacks_list: + for k, v in callbacks.items(): + if v not in instance.callbacks[k]: + instance.callbacks[k].append(v) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/clearml.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/clearml.py new file mode 100644 index 0000000000000000000000000000000000000000..29d7a8b327ceca76050a6d992192108964eea4a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/clearml.py @@ -0,0 +1,146 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from ultralytics.utils import LOGGER, SETTINGS, TESTS_RUNNING + +try: + assert not TESTS_RUNNING # do not log pytest + assert SETTINGS["clearml"] is True # verify integration is enabled + import clearml + from clearml import Task + + assert hasattr(clearml, "__version__") # verify package is not directory + +except (ImportError, AssertionError): + clearml = None + + +def _log_debug_samples(files, title: str = "Debug Samples") -> None: + """Log files (images) as debug samples in the ClearML task. + + Args: + files (list[Path]): A list of file paths in PosixPath format. + title (str): A title that groups together images with the same values. + """ + import re + + if task := Task.current_task(): + for f in files: + if f.exists(): + it = re.search(r"_batch(\d+)", f.name) + iteration = int(it.groups()[0]) if it else 0 + task.get_logger().report_image( + title=title, series=f.name.replace(it.group(), ""), local_path=str(f), iteration=iteration + ) + + +def _log_plot(title: str, plot_path: str) -> None: + """Log an image as a plot in the plot section of ClearML. + + Args: + title (str): The title of the plot. + plot_path (str | Path): The path to the saved image file. + """ + import matplotlib.image as mpimg + import matplotlib.pyplot as plt + + img = mpimg.imread(plot_path) + fig = plt.figure() + ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect="auto", xticks=[], yticks=[]) # no ticks + ax.imshow(img) + + Task.current_task().get_logger().report_matplotlib_figure( + title=title, series="", figure=fig, report_interactive=False + ) + + +def on_pretrain_routine_start(trainer) -> None: + """Initialize and connect ClearML task at the start of pretraining routine.""" + try: + if task := Task.current_task(): + # WARNING: make sure the automatic pytorch and matplotlib bindings are disabled! + # We are logging these plots and model files manually in the integration + from clearml.binding.frameworks.pytorch_bind import PatchPyTorchModelIO + from clearml.binding.matplotlib_bind import PatchedMatplotlib + + PatchPyTorchModelIO.update_current_task(None) + PatchedMatplotlib.update_current_task(None) + else: + task = Task.init( + project_name=str(trainer.args.project or "Ultralytics").lstrip("/") or "Ultralytics", + task_name=trainer.args.name, + tags=["Ultralytics"], + output_uri=True, + reuse_last_task_id=False, + auto_connect_frameworks={"pytorch": False, "matplotlib": False}, + ) + LOGGER.warning( + "ClearML Initialized a new task. If you want to run remotely, " + "please add clearml-init and connect your arguments before initializing YOLO." + ) + task.connect(vars(trainer.args), name="General", ignore_remote_overrides=True) + except Exception as e: + LOGGER.warning(f"ClearML installed but not initialized correctly, not logging this run. {e}") + + +def on_train_epoch_end(trainer) -> None: + """Log debug samples for the first epoch and report current training progress.""" + if task := Task.current_task(): + # Log debug samples for first epoch only + if trainer.epoch == 1: + _log_debug_samples(sorted(trainer.save_dir.glob("train_batch*.jpg")), "Mosaic") + # Report the current training progress + for k, v in trainer.label_loss_items(trainer.tloss, prefix="train").items(): + task.get_logger().report_scalar("train", k, v, iteration=trainer.epoch) + for k, v in trainer.lr.items(): + task.get_logger().report_scalar("lr", k, v, iteration=trainer.epoch) + + +def on_fit_epoch_end(trainer) -> None: + """Report model information and metrics to logger at the end of an epoch.""" + if task := Task.current_task(): + # Report epoch time and validation metrics + task.get_logger().report_scalar( + title="Epoch Time", series="Epoch Time", value=trainer.epoch_time, iteration=trainer.epoch + ) + for k, v in trainer.metrics.items(): + title = k.split("/")[0] + task.get_logger().report_scalar(title, k, v, iteration=trainer.epoch) + if trainer.epoch == 0: + from ultralytics.utils.torch_utils import model_info_for_loggers + + for k, v in model_info_for_loggers(trainer).items(): + task.get_logger().report_single_value(k, v) + + +def on_val_end(validator) -> None: + """Log validation results including labels and predictions.""" + if Task.current_task(): + # Log validation labels and predictions + _log_debug_samples(sorted(validator.save_dir.glob("val*.jpg")), "Validation") + + +def on_train_end(trainer) -> None: + """Log final model and training results on training completion.""" + if task := Task.current_task(): + # Log final results, confusion matrix and PR plots + for f in [*trainer.plots.keys(), *trainer.validator.plots.keys()]: + if "batch" not in f.name: + _log_plot(title=f.stem, plot_path=f) + # Report final metrics + for k, v in trainer.validator.metrics.results_dict.items(): + task.get_logger().report_single_value(k, v) + # Log the final model + task.update_output_model(model_path=str(trainer.best), model_name=trainer.args.name, auto_delete_file=False) + + +callbacks = ( + { + "on_pretrain_routine_start": on_pretrain_routine_start, + "on_train_epoch_end": on_train_epoch_end, + "on_fit_epoch_end": on_fit_epoch_end, + "on_val_end": on_val_end, + "on_train_end": on_train_end, + } + if clearml + else {} +) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/comet.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/comet.py new file mode 100644 index 0000000000000000000000000000000000000000..1d3277681702eebd9b3d940510a862fd58deef0f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/comet.py @@ -0,0 +1,622 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from collections.abc import Callable +from types import SimpleNamespace +from typing import Any + +import cv2 +import numpy as np + +from ultralytics.utils import LOGGER, RANK, SETTINGS, TESTS_RUNNING, env_bool, ops +from ultralytics.utils.metrics import ClassifyMetrics, DetMetrics, OBBMetrics, PoseMetrics, SegmentMetrics + +try: + assert not TESTS_RUNNING # do not log pytest + assert SETTINGS["comet"] is True # verify integration is enabled + import comet_ml + + assert hasattr(comet_ml, "__version__") # verify package is not directory + + import os + from pathlib import Path + + # Ensures certain logging functions only run for supported tasks + COMET_SUPPORTED_TASKS = ["detect", "segment"] + + # Names of plots created by Ultralytics that are logged to Comet + CONFUSION_MATRIX_PLOT_NAMES = "confusion_matrix", "confusion_matrix_normalized" + EVALUATION_PLOT_NAMES = "F1_curve", "P_curve", "R_curve", "PR_curve" + LABEL_PLOT_NAMES = ["labels"] + SEGMENT_METRICS_PLOT_PREFIX = "Box", "Mask" + POSE_METRICS_PLOT_PREFIX = "Box", "Pose" + DETECTION_METRICS_PLOT_PREFIX = ["Box"] + RESULTS_TABLE_NAME = "results.csv" + ARGS_YAML_NAME = "args.yaml" + + _comet_image_prediction_count = 0 + +except (ImportError, AssertionError): + comet_ml = None + + +def _get_comet_mode() -> str: + """Return the Comet mode from environment variables, defaulting to 'online'.""" + comet_mode = os.getenv("COMET_MODE") + if comet_mode is not None: + LOGGER.warning( + "The COMET_MODE environment variable is deprecated. " + "Please use COMET_START_ONLINE to set the Comet experiment mode. " + "To start an offline Comet experiment, use 'export COMET_START_ONLINE=0'. " + "If COMET_START_ONLINE is not set or is set to '1', an online Comet experiment will be created." + ) + return comet_mode + + return "online" + + +def _get_comet_model_name() -> str: + """Return the Comet model name from environment variable or default to 'Ultralytics'.""" + return os.getenv("COMET_MODEL_NAME", "Ultralytics") + + +def _get_eval_batch_logging_interval() -> int: + """Get the evaluation batch logging interval from environment variable or use default value 1.""" + return int(os.getenv("COMET_EVAL_BATCH_LOGGING_INTERVAL", "1")) + + +def _get_max_image_predictions_to_log() -> int: + """Get the maximum number of image predictions to log from environment variables.""" + return int(os.getenv("COMET_MAX_IMAGE_PREDICTIONS", "100")) + + +def _scale_confidence_score(score: float) -> float: + """Scale the confidence score by a factor specified in environment variable.""" + scale = float(os.getenv("COMET_MAX_CONFIDENCE_SCORE", "100.0")) + return score * scale + + +def _should_log_confusion_matrix() -> bool: + """Determine if the confusion matrix should be logged based on environment variable settings.""" + return env_bool("COMET_EVAL_LOG_CONFUSION_MATRIX", False) + + +def _should_log_image_predictions() -> bool: + """Determine whether to log image predictions based on environment variable.""" + return env_bool("COMET_EVAL_LOG_IMAGE_PREDICTIONS", True) + + +def _resume_or_create_experiment(args: SimpleNamespace) -> None: + """Resume CometML experiment or create a new experiment based on args. + + Ensures that the experiment object is only created in a single process during distributed training. + + Args: + args (SimpleNamespace): Training arguments containing project configuration and other parameters. + """ + if RANK not in {-1, 0}: + return + + # Set environment variable (if not set by the user) to configure the Comet experiment's online mode under the hood. + # IF COMET_START_ONLINE is set by the user it will override COMET_MODE value. + if os.getenv("COMET_START_ONLINE") is None: + comet_mode = _get_comet_mode() + os.environ["COMET_START_ONLINE"] = "1" if comet_mode != "offline" else "0" + + try: + _project_name = os.getenv("COMET_PROJECT_NAME", args.project) + experiment = comet_ml.start(project_name=_project_name) + experiment.log_parameters(vars(args)) + experiment.log_others( + { + "eval_batch_logging_interval": _get_eval_batch_logging_interval(), + "log_confusion_matrix_on_eval": _should_log_confusion_matrix(), + "log_image_predictions": _should_log_image_predictions(), + "max_image_predictions": _get_max_image_predictions_to_log(), + } + ) + experiment.log_other("Created from", "ultralytics") + + except Exception as e: + LOGGER.warning(f"Comet installed but not initialized correctly, not logging this run. {e}") + + +def _fetch_trainer_metadata(trainer) -> dict: + """Return metadata for YOLO training including epoch and asset saving status. + + Args: + trainer (ultralytics.engine.trainer.BaseTrainer): The YOLO trainer object containing training state and config. + + Returns: + (dict): Dictionary containing current epoch, step, save assets flag, and final epoch flag. + """ + curr_epoch = trainer.epoch + 1 + + train_num_steps_per_epoch = len(trainer.train_loader.dataset) // trainer.batch_size + curr_step = curr_epoch * train_num_steps_per_epoch + final_epoch = curr_epoch == trainer.epochs + + save = trainer.args.save + save_period = trainer.args.save_period + save_interval = curr_epoch % save_period == 0 + save_assets = save and save_period > 0 and save_interval and not final_epoch + + return {"curr_epoch": curr_epoch, "curr_step": curr_step, "save_assets": save_assets, "final_epoch": final_epoch} + + +def _scale_bounding_box_to_original_image_shape( + box, resized_image_shape, original_image_shape, ratio_pad +) -> list[float]: + """Scale bounding box from resized image coordinates to original image coordinates. + + YOLO resizes images during training and the label values are normalized based on this resized shape. This function + rescales the bounding box labels to the original image shape. + + Args: + box (torch.Tensor): Bounding box in normalized xywh format. + resized_image_shape (tuple): Shape of the resized image (height, width). + original_image_shape (tuple): Shape of the original image (height, width). + ratio_pad (tuple): Ratio and padding information for scaling. + + Returns: + (list[float]): Scaled bounding box coordinates in xywh format with top-left corner adjustment. + """ + resized_image_height, resized_image_width = resized_image_shape + + # Convert normalized xywh format predictions to xyxy in resized scale format + box = ops.xywhn2xyxy(box, h=resized_image_height, w=resized_image_width) + # Scale box predictions from resized image scale back to original image scale + box = ops.scale_boxes(resized_image_shape, box, original_image_shape, ratio_pad) + # Convert bounding box format from xyxy to xywh for Comet logging + box = ops.xyxy2xywh(box) + # Adjust xy center to correspond top-left corner + box[:2] -= box[2:] / 2 + box = box.tolist() + + return box + + +def _format_ground_truth_annotations_for_detection(img_idx, image_path, batch, class_name_map=None) -> dict | None: + """Format ground truth annotations for object detection. + + This function processes ground truth annotations from a batch of images for object detection tasks. It extracts + bounding boxes, class labels, and other metadata for a specific image in the batch, and formats them for + visualization or evaluation. + + Args: + img_idx (int): Index of the image in the batch to process. + image_path (str | Path): Path to the image file. + batch (dict): Batch dictionary containing detection data with keys: + - 'batch_idx': Tensor of batch indices + - 'bboxes': Tensor of bounding boxes in normalized xywh format + - 'cls': Tensor of class labels + - 'ori_shape': Original image shapes + - 'resized_shape': Resized image shapes + - 'ratio_pad': Ratio and padding information + class_name_map (dict, optional): Mapping from class indices to class names. + + Returns: + (dict | None): Formatted ground truth annotations with keys 'name' and 'data', where 'data' is a list of + annotation dicts each containing 'boxes', 'label', and 'score' keys. Returns None if no bounding boxes are + found for the image. + """ + indices = batch["batch_idx"] == img_idx + bboxes = batch["bboxes"][indices] + if len(bboxes) == 0: + LOGGER.debug(f"Comet Image: {image_path} has no bounding boxes labels") + return None + + cls_labels = batch["cls"][indices].squeeze(1).tolist() + if class_name_map: + cls_labels = [str(class_name_map[label]) for label in cls_labels] + + original_image_shape = batch["ori_shape"][img_idx] + resized_image_shape = batch["resized_shape"][img_idx] + ratio_pad = batch["ratio_pad"][img_idx] + + data = [] + for box, label in zip(bboxes, cls_labels): + box = _scale_bounding_box_to_original_image_shape(box, resized_image_shape, original_image_shape, ratio_pad) + data.append( + { + "boxes": [box], + "label": f"gt_{label}", + "score": _scale_confidence_score(1.0), + } + ) + + return {"name": "ground_truth", "data": data} + + +def _format_prediction_annotations(image_path, metadata, class_label_map=None, class_map=None) -> dict | None: + """Format YOLO predictions for object detection visualization. + + Args: + image_path (Path): Path to the image file. + metadata (dict): Prediction metadata containing bounding boxes and class information. + class_label_map (dict, optional): Mapping from class indices to class names. + class_map (dict, optional): Additional class mapping for label conversion. + + Returns: + (dict | None): Formatted prediction annotations or None if no predictions exist. + """ + stem = image_path.stem + image_id = int(stem) if stem.isnumeric() else stem + + predictions = metadata.get(image_id) + if not predictions: + LOGGER.debug(f"Comet Image: {image_path} has no bounding boxes predictions") + return None + + # apply the mapping that was used to map the predicted classes when the JSON was created + if class_label_map and class_map: + class_label_map = {class_map[k]: v for k, v in class_label_map.items()} + try: + # import faster_coco_eval utilities to decompress annotations for various tasks, e.g. segmentation + from faster_coco_eval.core.mask import decode + except ImportError: + decode = None + + data = [] + for prediction in predictions: + boxes = prediction["bbox"] + score = _scale_confidence_score(prediction["score"]) + cls_label = prediction["category_id"] + if class_label_map: + cls_label = str(class_label_map[cls_label]) + + annotation_data = {"boxes": [boxes], "label": cls_label, "score": score} + + if decode is not None: + # do segmentation processing only if we are able to decode it + segments = prediction.get("segmentation", None) + if segments is not None: + segments = _extract_segmentation_annotation(segments, decode) + if segments is not None: + annotation_data["points"] = segments + + data.append(annotation_data) + + return {"name": "prediction", "data": data} + + +def _extract_segmentation_annotation(segmentation_raw: str, decode: Callable) -> list[list[Any]] | None: + """Extract segmentation annotation from compressed segmentations as list of polygons. + + Args: + segmentation_raw (str): Raw segmentation data in compressed format. + decode (Callable): Function to decode the compressed segmentation data. + + Returns: + (list[list[Any]] | None): List of polygon points or None if extraction fails. + """ + try: + mask = decode(segmentation_raw) + contours, _ = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) + annotations = [np.array(polygon).squeeze() for polygon in contours if len(polygon) >= 3] + return [annotation.ravel().tolist() for annotation in annotations] + except Exception as e: + LOGGER.warning(f"Comet Failed to extract segmentation annotation: {e}") + return None + + +def _fetch_annotations(img_idx, image_path, batch, prediction_metadata_map, class_label_map, class_map) -> list | None: + """Join the ground truth and prediction annotations if they exist. + + Args: + img_idx (int): Index of the image in the batch. + image_path (Path): Path to the image file. + batch (dict): Batch data containing ground truth annotations. + prediction_metadata_map (dict): Map of prediction metadata by image ID. + class_label_map (dict): Mapping from class indices to class names. + class_map (dict): Additional class mapping for label conversion. + + Returns: + (list | None): List of annotation dictionaries or None if no annotations exist. + """ + ground_truth_annotations = _format_ground_truth_annotations_for_detection( + img_idx, image_path, batch, class_label_map + ) + prediction_annotations = _format_prediction_annotations( + image_path, prediction_metadata_map, class_label_map, class_map + ) + + annotations = [ + annotation for annotation in [ground_truth_annotations, prediction_annotations] if annotation is not None + ] + return [annotations] if annotations else None + + +def _create_prediction_metadata_map(model_predictions) -> dict: + """Create metadata map for model predictions by grouping them based on image ID.""" + pred_metadata_map = {} + for prediction in model_predictions: + pred_metadata_map.setdefault(prediction["image_id"], []) + pred_metadata_map[prediction["image_id"]].append(prediction) + + return pred_metadata_map + + +def _log_confusion_matrix(experiment, trainer, curr_step, curr_epoch) -> None: + """Log the confusion matrix to Comet experiment.""" + conf_mat = trainer.validator.confusion_matrix.matrix + names = [*list(trainer.data["names"].values()), "background"] + experiment.log_confusion_matrix( + matrix=conf_mat, labels=names, max_categories=len(names), epoch=curr_epoch, step=curr_step + ) + + +def _log_images(experiment, image_paths, curr_step: int | None, annotations=None) -> None: + """Log images to the experiment with optional annotations. + + This function logs images to a Comet ML experiment, optionally including annotation data for visualization such as + bounding boxes or segmentation masks. + + Args: + experiment (comet_ml.CometExperiment): The Comet ML experiment to log images to. + image_paths (list[Path]): List of paths to images that will be logged. + curr_step (int | None): Current training step/iteration for tracking in the experiment timeline. + annotations (list[list[dict]], optional): Nested list of annotation dictionaries for each image. Each annotation + contains visualization data like bounding boxes, labels, and confidence scores. + """ + if annotations: + for image_path, annotation in zip(image_paths, annotations): + experiment.log_image(image_path, name=image_path.stem, step=curr_step, annotations=annotation) + + else: + for image_path in image_paths: + experiment.log_image(image_path, name=image_path.stem, step=curr_step) + + +def _log_image_predictions(experiment, validator, curr_step) -> None: + """Log image predictions to a Comet ML experiment during model validation. + + This function processes validation data and formats both ground truth and prediction annotations for visualization + in the Comet dashboard. The function respects configured limits on the number of images to log. + + Args: + experiment (comet_ml.CometExperiment): The Comet ML experiment to log to. + validator (BaseValidator): The validator instance containing validation data and predictions. + curr_step (int): The current training step for logging timeline. + + Notes: + This function uses global state to track the number of logged predictions across calls. + It only logs predictions for supported tasks defined in COMET_SUPPORTED_TASKS. + The number of logged images is limited by the COMET_MAX_IMAGE_PREDICTIONS environment variable. + """ + global _comet_image_prediction_count + + task = validator.args.task + if task not in COMET_SUPPORTED_TASKS: + return + + jdict = validator.jdict + if not jdict: + return + + predictions_metadata_map = _create_prediction_metadata_map(jdict) + dataloader = validator.dataloader + class_label_map = validator.names + class_map = getattr(validator, "class_map", None) + + batch_logging_interval = _get_eval_batch_logging_interval() + max_image_predictions = _get_max_image_predictions_to_log() + + for batch_idx, batch in enumerate(dataloader): + if (batch_idx + 1) % batch_logging_interval != 0: + continue + + image_paths = batch["im_file"] + for img_idx, image_path in enumerate(image_paths): + if _comet_image_prediction_count >= max_image_predictions: + return + + image_path = Path(image_path) + annotations = _fetch_annotations( + img_idx, + image_path, + batch, + predictions_metadata_map, + class_label_map, + class_map=class_map, + ) + _log_images( + experiment, + [image_path], + curr_step, + annotations=annotations, + ) + _comet_image_prediction_count += 1 + + +def _log_plots(experiment, trainer) -> None: + """Log evaluation plots and label plots for the experiment. + + This function logs various evaluation plots and confusion matrices to the experiment tracking system. It handles + different types of metrics (SegmentMetrics, PoseMetrics, DetMetrics, OBBMetrics) and logs the appropriate plots for + each type. + + Args: + experiment (comet_ml.CometExperiment): The Comet ML experiment to log plots to. + trainer (ultralytics.engine.trainer.BaseTrainer): The trainer object containing validation metrics and save + directory information. + + Examples: + >>> from ultralytics.utils.callbacks.comet import _log_plots + >>> _log_plots(experiment, trainer) + """ + plot_filenames = None + if isinstance(trainer.validator.metrics, SegmentMetrics): + plot_filenames = [ + trainer.save_dir / f"{prefix}{plots}.png" + for plots in EVALUATION_PLOT_NAMES + for prefix in SEGMENT_METRICS_PLOT_PREFIX + ] + elif isinstance(trainer.validator.metrics, PoseMetrics): + plot_filenames = [ + trainer.save_dir / f"{prefix}{plots}.png" + for plots in EVALUATION_PLOT_NAMES + for prefix in POSE_METRICS_PLOT_PREFIX + ] + elif isinstance(trainer.validator.metrics, (DetMetrics, OBBMetrics)): + plot_filenames = [ + trainer.save_dir / f"{prefix}{plots}.png" + for plots in EVALUATION_PLOT_NAMES + for prefix in DETECTION_METRICS_PLOT_PREFIX + ] + + if plot_filenames is not None: + _log_images(experiment, plot_filenames, None) + + confusion_matrix_filenames = [trainer.save_dir / f"{plots}.png" for plots in CONFUSION_MATRIX_PLOT_NAMES] + _log_images(experiment, confusion_matrix_filenames, None) + + if not isinstance(trainer.validator.metrics, ClassifyMetrics): + label_plot_filenames = [trainer.save_dir / f"{labels}.jpg" for labels in LABEL_PLOT_NAMES] + _log_images(experiment, label_plot_filenames, None) + + +def _log_model(experiment, trainer) -> None: + """Log the best-trained model to Comet.ml.""" + model_name = _get_comet_model_name() + experiment.log_model(model_name, file_or_folder=str(trainer.best), file_name="best.pt", overwrite=True) + + +def _log_image_batches(experiment, trainer, curr_step: int) -> None: + """Log samples of image batches for train and validation.""" + _log_images(experiment, trainer.save_dir.glob("train_batch*.jpg"), curr_step) + _log_images(experiment, trainer.save_dir.glob("val_batch*.jpg"), curr_step) + + +def _log_asset(experiment, asset_path) -> None: + """Logs a specific asset file to the given experiment. + + This function facilitates logging an asset, such as a file, to the provided + experiment. It enables integration with experiment tracking platforms. + + Args: + experiment (comet_ml.CometExperiment): The experiment instance to which the asset will be logged. + asset_path (Path): The file path of the asset to log. + """ + experiment.log_asset(asset_path) + + +def _log_table(experiment, table_path) -> None: + """Logs a table to the provided experiment. + + This function is used to log a table file to the given experiment. The table is identified by its file path. + + Args: + experiment (comet_ml.CometExperiment): The experiment object where the table file will be logged. + table_path (Path): The file path of the table to be logged. + """ + experiment.log_table(str(table_path)) + + +def on_pretrain_routine_start(trainer) -> None: + """Create or resume a CometML experiment at the start of a YOLO pre-training routine.""" + _resume_or_create_experiment(trainer.args) + + +def on_train_epoch_end(trainer) -> None: + """Log metrics and save batch images at the end of training epochs.""" + experiment = comet_ml.get_running_experiment() + if not experiment: + return + + metadata = _fetch_trainer_metadata(trainer) + curr_epoch = metadata["curr_epoch"] + curr_step = metadata["curr_step"] + + experiment.log_metrics(trainer.label_loss_items(trainer.tloss, prefix="train"), step=curr_step, epoch=curr_epoch) + + +def on_fit_epoch_end(trainer) -> None: + """Log model assets at the end of each epoch during training. + + This function is called at the end of each training epoch to log metrics, learning rates, and model information to a + Comet ML experiment. It also logs model assets, confusion matrices, and image predictions based on configuration + settings. + + The function retrieves the current Comet ML experiment and logs various training metrics. If it's the first epoch, + it also logs model information. On specified save intervals, it logs the model, confusion matrix (if enabled), and + image predictions (if enabled). + + Args: + trainer (BaseTrainer): The YOLO trainer object containing training state, metrics, and configuration. + + Examples: + >>> # Inside a training loop + >>> on_fit_epoch_end(trainer) # Log metrics and assets to Comet ML + """ + experiment = comet_ml.get_running_experiment() + if not experiment: + return + + metadata = _fetch_trainer_metadata(trainer) + curr_epoch = metadata["curr_epoch"] + curr_step = metadata["curr_step"] + save_assets = metadata["save_assets"] + + experiment.log_metrics(trainer.metrics, step=curr_step, epoch=curr_epoch) + experiment.log_metrics(trainer.lr, step=curr_step, epoch=curr_epoch) + if curr_epoch == 1: + from ultralytics.utils.torch_utils import model_info_for_loggers + + experiment.log_metrics(model_info_for_loggers(trainer), step=curr_step, epoch=curr_epoch) + + if not save_assets: + return + + _log_model(experiment, trainer) + if _should_log_confusion_matrix(): + _log_confusion_matrix(experiment, trainer, curr_step, curr_epoch) + if _should_log_image_predictions(): + _log_image_predictions(experiment, trainer.validator, curr_step) + + +def on_train_end(trainer) -> None: + """Perform operations at the end of training.""" + experiment = comet_ml.get_running_experiment() + if not experiment: + return + + metadata = _fetch_trainer_metadata(trainer) + curr_epoch = metadata["curr_epoch"] + curr_step = metadata["curr_step"] + plots = trainer.args.plots + + _log_model(experiment, trainer) + if plots: + _log_plots(experiment, trainer) + + _log_confusion_matrix(experiment, trainer, curr_step, curr_epoch) + _log_image_predictions(experiment, trainer.validator, curr_step) + _log_image_batches(experiment, trainer, curr_step) + # log results table + table_path = trainer.save_dir / RESULTS_TABLE_NAME + if table_path.exists(): + _log_table(experiment, table_path) + + # log arguments YAML + args_path = trainer.save_dir / ARGS_YAML_NAME + if args_path.exists(): + _log_asset(experiment, args_path) + + experiment.end() + + global _comet_image_prediction_count + _comet_image_prediction_count = 0 + + +callbacks = ( + { + "on_pretrain_routine_start": on_pretrain_routine_start, + "on_train_epoch_end": on_train_epoch_end, + "on_fit_epoch_end": on_fit_epoch_end, + "on_train_end": on_train_end, + } + if comet_ml + else {} +) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/dvc.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/dvc.py new file mode 100644 index 0000000000000000000000000000000000000000..b6ce8853621272e22813975aecea485886829b64 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/dvc.py @@ -0,0 +1,197 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from pathlib import Path + +from ultralytics.utils import LOGGER, SETTINGS, TESTS_RUNNING, checks + +try: + assert not TESTS_RUNNING # do not log pytest + assert SETTINGS["dvc"] is True # verify integration is enabled + import dvclive + + assert checks.check_version("dvclive", "2.11.0", verbose=True) + + import os + import re + + # DVCLive logger instance + live = None + _processed_plots = {} + + # `on_fit_epoch_end` is called on final validation (probably need to be fixed) for now this is the way we + # distinguish final evaluation of the best model vs last epoch validation + _training_epoch = False + +except (ImportError, AssertionError, TypeError): + dvclive = None + + +def _log_images(path: Path, prefix: str = "") -> None: + """Log images at specified path with an optional prefix using DVCLive. + + This function logs images found at the given path to DVCLive, organizing them by batch to enable slider + functionality in the UI. It processes image filenames to extract batch information and restructures the path + accordingly. + + Args: + path (Path): Path to the image file to be logged. + prefix (str, optional): Optional prefix to add to the image name when logging. + + Examples: + >>> from pathlib import Path + >>> _log_images(Path("runs/train/exp/val_batch0_pred.jpg"), prefix="validation") + """ + if live: + name = path.name + + # Group images by batch to enable sliders in UI + if m := re.search(r"_batch(\d+)", name): + ni = m[1] + new_stem = re.sub(r"_batch(\d+)", "_batch", path.stem) + name = (Path(new_stem) / ni).with_suffix(path.suffix) + + live.log_image(os.path.join(prefix, name), path) + + +def _log_plots(plots: dict, prefix: str = "") -> None: + """Log plot images for training progress if they have not been previously processed. + + Args: + plots (dict): Dictionary containing plot information with timestamps. + prefix (str, optional): Optional prefix to add to the logged image paths. + """ + for name, params in plots.items(): + timestamp = params["timestamp"] + if _processed_plots.get(name) != timestamp: + _log_images(name, prefix) + _processed_plots[name] = timestamp + + +def _log_confusion_matrix(validator) -> None: + """Log confusion matrix for a validator using DVCLive. + + This function processes the confusion matrix from a validator object and logs it to DVCLive by converting the matrix + into lists of target and prediction labels. + + Args: + validator (BaseValidator): The validator object containing the confusion matrix and class names. Must have + attributes confusion_matrix.matrix, confusion_matrix.task, and names. + """ + targets = [] + preds = [] + matrix = validator.confusion_matrix.matrix + names = list(validator.names.values()) + if validator.confusion_matrix.task in {"detect", "obb"}: + names += ["background"] + + for ti, pred in enumerate(matrix.T.astype(int)): + for pi, num in enumerate(pred): + targets.extend([names[ti]] * num) + preds.extend([names[pi]] * num) + + live.log_sklearn_plot("confusion_matrix", targets, preds, name="cf.json", normalized=True) + + +def on_pretrain_routine_start(trainer) -> None: + """Initialize DVCLive logger for training metadata during pre-training routine.""" + try: + global live + live = dvclive.Live(save_dvc_exp=True, cache_images=True) + LOGGER.info("DVCLive is detected and auto logging is enabled (run 'yolo settings dvc=False' to disable).") + except Exception as e: + LOGGER.warning(f"DVCLive installed but not initialized correctly, not logging this run. {e}") + + +def on_pretrain_routine_end(trainer) -> None: + """Log plots related to the training process at the end of the pretraining routine.""" + _log_plots(trainer.plots, "train") + + +def on_train_start(trainer) -> None: + """Log the training parameters if DVCLive logging is active.""" + if live: + live.log_params(trainer.args) + + +def on_train_epoch_start(trainer) -> None: + """Set the global variable _training_epoch value to True at the start of each training epoch.""" + global _training_epoch + _training_epoch = True + + +def on_fit_epoch_end(trainer) -> None: + """Log training metrics, model info, and advance to next step at the end of each fit epoch. + + This function is called at the end of each fit epoch during training. It logs various metrics including training + loss items, validation metrics, and learning rates. On the first epoch, it also logs model + information. Additionally, it logs training and validation plots and advances the DVCLive step counter. + + Args: + trainer (BaseTrainer): The trainer object containing training state, metrics, and plots. + + Notes: + This function only performs logging operations when DVCLive logging is active and during a training epoch. + The global variable _training_epoch is used to track whether the current epoch is a training epoch. + """ + global _training_epoch + if live and _training_epoch: + all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics, **trainer.lr} + for metric, value in all_metrics.items(): + live.log_metric(metric, value) + + if trainer.epoch == 0: + from ultralytics.utils.torch_utils import model_info_for_loggers + + for metric, value in model_info_for_loggers(trainer).items(): + live.log_metric(metric, value, plot=False) + + _log_plots(trainer.plots, "train") + _log_plots(trainer.validator.plots, "val") + + live.next_step() + _training_epoch = False + + +def on_train_end(trainer) -> None: + """Log best metrics, plots, and confusion matrix at the end of training. + + This function is called at the conclusion of the training process to log final metrics, visualizations, and model + artifacts if DVCLive logging is active. It captures the best model performance metrics, training plots, validation + plots, and confusion matrix for later analysis. + + Args: + trainer (BaseTrainer): The trainer object containing training state, metrics, and validation results. + + Examples: + >>> # Inside a custom training loop + >>> from ultralytics.utils.callbacks.dvc import on_train_end + >>> on_train_end(trainer) # Log final metrics and artifacts + """ + if live: + # At the end log the best metrics. It runs validator on the best model internally. + all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics, **trainer.lr} + for metric, value in all_metrics.items(): + live.log_metric(metric, value, plot=False) + + _log_plots(trainer.plots, "val") + _log_plots(trainer.validator.plots, "val") + _log_confusion_matrix(trainer.validator) + + if trainer.best.exists(): + live.log_artifact(trainer.best, copy=True, type="model") + + live.end() + + +callbacks = ( + { + "on_pretrain_routine_start": on_pretrain_routine_start, + "on_pretrain_routine_end": on_pretrain_routine_end, + "on_train_start": on_train_start, + "on_train_epoch_start": on_train_epoch_start, + "on_fit_epoch_end": on_fit_epoch_end, + "on_train_end": on_train_end, + } + if dvclive + else {} +) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/mlflow.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/mlflow.py new file mode 100644 index 0000000000000000000000000000000000000000..d37636ae765cf71f6b6afde7fccbbd40c8f69c7e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/mlflow.py @@ -0,0 +1,161 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +MLflow Logging for Ultralytics YOLO. + +This module enables MLflow logging for Ultralytics YOLO. It logs metrics, parameters, and model artifacts. +For setting up, a tracking URI should be specified. The logging can be customized using environment variables. + +Commands: + 1. To set a project name: + `export MLFLOW_EXPERIMENT_NAME=` or use the project= argument + + 2. To set a run name: + `export MLFLOW_RUN=` or use the name= argument + + 3. To start a local MLflow server: + mlflow server --backend-store-uri runs/mlflow + It will by default start a local server at http://127.0.0.1:5000. + To specify a different URI, set the MLFLOW_TRACKING_URI environment variable. + +""" + +import os +from pathlib import Path + +from ultralytics.utils import LOGGER, RUNS_DIR, SETTINGS, TESTS_RUNNING, colorstr, env_bool + +PREFIX = colorstr("MLflow: ") + +try: + import mlflow + + assert hasattr(mlflow, "__version__") # verify package is not a local directory +except (ImportError, AssertionError): + mlflow = None + + +def sanitize_dict(x: dict) -> dict: + """Sanitize dictionary keys by removing parentheses and converting values to floats.""" + return {k.replace("(", "").replace(")", ""): float(v) for k, v in x.items()} + + +def on_pretrain_routine_end(trainer): + """Log training parameters to MLflow at the end of the pretraining routine. + + This function sets up MLflow logging based on environment variables and trainer arguments. It sets the tracking URI, + experiment name, and run name, then starts the MLflow run if not already active. It finally logs the parameters from + the trainer. + + Args: + trainer (ultralytics.engine.trainer.BaseTrainer): The training object with arguments and parameters to log. + + Notes: + MLFLOW_TRACKING_URI: The URI for MLflow tracking. If not set, defaults to 'runs/mlflow'. + MLFLOW_EXPERIMENT_NAME: The name of the MLflow experiment. If not set, defaults to trainer.args.project. + MLFLOW_RUN: The name of the MLflow run. If not set, defaults to trainer.args.name. + MLFLOW_KEEP_RUN_ACTIVE: Whether to keep the MLflow run active after training ends. Truthy values are + "1", "true", "yes", "on", "y", "t" (case-insensitive); anything else is False. + """ + # Resolve enablement at call time (not import time) so test/training order can never permanently disable MLflow: + # `add_integration_callbacks` imports this module on the first training, which may run with mlflow off. + if not mlflow or SETTINGS["mlflow"] is not True: + return + if TESTS_RUNNING and "test_mlflow" not in os.environ.get("PYTEST_CURRENT_TEST", ""): + return # do not log during unrelated pytest tests + + uri = os.environ.get("MLFLOW_TRACKING_URI") or str(RUNS_DIR / "mlflow") + LOGGER.debug(f"{PREFIX} tracking uri: {uri}") + + # Set experiment and run names + experiment_name = os.environ.get("MLFLOW_EXPERIMENT_NAME") or trainer.args.project or "/Shared/Ultralytics" + run_name = os.environ.get("MLFLOW_RUN") or trainer.args.name + + trainer._mlflow_active = False + trainer._mlflow_started_run = False + try: + mlflow.set_tracking_uri(uri) + mlflow.set_experiment(experiment_name) + mlflow.autolog() + active_run = mlflow.active_run() + if active_run is None: + active_run = mlflow.start_run(run_name=run_name) + trainer._mlflow_started_run = True + LOGGER.info(f"{PREFIX}logging run_id({active_run.info.run_id}) to {uri}") + if Path(uri).is_dir(): + LOGGER.info(f"{PREFIX}view at http://127.0.0.1:5000 with 'mlflow server --backend-store-uri {uri}'") + LOGGER.info(f"{PREFIX}disable with 'yolo settings mlflow=False'") + mlflow.log_params(dict(trainer.args)) + trainer._mlflow_active = True + except Exception as e: + LOGGER.warning(f"{PREFIX}Failed to initialize: {e}") + LOGGER.warning(f"{PREFIX}Not tracking this run") + if trainer._mlflow_started_run: + try: + mlflow.end_run() + except Exception: + pass + + +def _log_metrics(trainer, metrics): + """Log metrics to MLflow, disabling tracking for this run on failure so it never crashes training.""" + try: + mlflow.log_metrics(metrics=metrics, step=trainer.epoch) + except Exception as e: + LOGGER.warning(f"{PREFIX}metric logging failed, disabling tracking for this run: {e}") + trainer._mlflow_active = False + + +def on_train_epoch_end(trainer): + """Log training metrics at the end of each train epoch to MLflow.""" + if mlflow and getattr(trainer, "_mlflow_active", False): + _log_metrics( + trainer, + { + **sanitize_dict(trainer.lr), + **sanitize_dict(trainer.label_loss_items(trainer.tloss, prefix="train")), + }, + ) + + +def on_fit_epoch_end(trainer): + """Log training metrics at the end of each fit epoch to MLflow.""" + if mlflow and getattr(trainer, "_mlflow_active", False): + _log_metrics(trainer, sanitize_dict(trainer.metrics)) + + +def on_train_end(trainer): + """Log model artifacts at the end of training and close any run this callback opened.""" + if not mlflow: + return + if getattr(trainer, "_mlflow_active", False): + try: + mlflow.log_artifact(str(trainer.best.parent)) # log save_dir/weights directory with best.pt and last.pt + for f in trainer.save_dir.glob("*"): # log all other files in save_dir + if f.suffix in {".png", ".jpg", ".csv", ".pt", ".yaml"}: + mlflow.log_artifact(str(f)) + LOGGER.info( + f"{PREFIX}results logged to {mlflow.get_tracking_uri()}\n{PREFIX}disable with 'yolo settings mlflow=False'" + ) + except Exception as e: + LOGGER.warning(f"{PREFIX}failed to log artifacts: {e}") + if getattr(trainer, "_mlflow_started_run", False): # only close a run we created + if env_bool("MLFLOW_KEEP_RUN_ACTIVE"): + LOGGER.info(f"{PREFIX}mlflow run still alive, remember to close it using mlflow.end_run()") + else: + try: + mlflow.end_run() + LOGGER.debug(f"{PREFIX}mlflow run ended") + except Exception: + pass + + +callbacks = ( + { + "on_pretrain_routine_end": on_pretrain_routine_end, + "on_train_epoch_end": on_train_epoch_end, + "on_fit_epoch_end": on_fit_epoch_end, + "on_train_end": on_train_end, + } + if mlflow + else {} +) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/platform.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/platform.py new file mode 100644 index 0000000000000000000000000000000000000000..166889167cc3b17b2e9cc09ab9aafe3a907be7f2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/platform.py @@ -0,0 +1,517 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import os +import platform +import re +import socket +import sys +from concurrent.futures import ThreadPoolExecutor +from math import isfinite +from pathlib import Path +from time import time + +from ultralytics.utils import ( + ENVIRONMENT, + GIT, + LOGGER, + PLATFORM_URL, + PYTHON_VERSION, + SETTINGS, + TESTS_RUNNING, + colorstr, +) + +PREFIX = colorstr("Platform: ") +_api_key = None +_executor = ThreadPoolExecutor(max_workers=10) + + +def slugify(text): + """Convert text to URL-safe slug (e.g., 'My Project 1' -> 'my-project-1').""" + if not text: + return text + return re.sub(r"-+", "-", re.sub(r"[^a-z0-9\s-]", "", str(text).lower()).replace(" ", "-")).strip("-")[:128] + + +def _interp_plot(plot, n=101): + """Interpolate plot curve data to n points to reduce storage size.""" + import numpy as np + + if not plot.get("x") or not plot.get("y"): + return plot # No interpolation needed (e.g., confusion_matrix) + + x, y = np.array(plot["x"]), np.array(plot["y"]) + if len(x) <= n: + return plot # Already small enough + + # New x values (101 points gives clean 0.01 increments: 0, 0.01, 0.02, ..., 1.0) + x_new = np.linspace(x[0], x[-1], n) + + # Interpolate y values (handle both 1D and 2D arrays) + if y.ndim == 1: + y_new = np.interp(x_new, x, y) + else: + y_new = np.array([np.interp(x_new, x, yi) for yi in y]) + + # Also interpolate ap if present (for PR curves) + result = {**plot, "x": x_new.tolist(), "y": y_new.tolist()} + if "ap" in plot: + result["ap"] = plot["ap"] # Keep AP values as-is (per-class scalars) + + return result + + +def _validation_payload(image_metrics, sample_limit=5_000, extremes_limit=100): + """Return exact F1 extremes and an evenly ranked sample for correlation analysis.""" + ranked = sorted(image_metrics.items(), key=lambda item: (item[1]["f1"], item[0])) + if len(ranked) > sample_limit: + sample = [ranked[round(i * (len(ranked) - 1) / (sample_limit - 1))] for i in range(sample_limit)] + else: + sample = ranked + + def rows(items): + return [[Path(name).stem.split("_", 1)[0], metric["tp"], metric["fp"], metric["fn"]] for name, metric in items] + + return { + "population": len(ranked), + "sampling": "f1_rank", + "rows": rows(sample), + "extremes": {"worst": rows(ranked[:extremes_limit]), "best": rows(reversed(ranked[-extremes_limit:]))}, + } + + +def _sanitize_json_value(value): + """Replace non-finite floats in payloads with None so JSON encoding succeeds.""" + if isinstance(value, dict): + return {k: _sanitize_json_value(v) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [_sanitize_json_value(v) for v in value] + if isinstance(value, float): + return value if isfinite(value) else None # avoid "Out of range float values are not JSON compliant" warnings + return value + + +def _send(event, data, project, name, model_id=None, retry=2, timeout=30): + """Send a training event using the SDK's retry policy.""" + global _api_key + if not _api_key: + return None + import httpx + + from ultralytics import APIError, Platform + + identity = {"model_id": model_id} if model_id else {"project": project, "name": name} + try: + with Platform( + api_key=_api_key, + base_url=PLATFORM_URL, + max_retries=retry - 1, + retry_methods=("POST",), + http_client=httpx.Client(follow_redirects=True), + ) as client: + response = client.training.metrics( + event=event, data=_sanitize_json_value(data), timeout=timeout, **identity + ) + return response if isinstance(response, dict) else None + except Exception as error: + if isinstance(error, APIError) and error.status_code == 401: + _api_key = None + # Console errors must not generate another console event; clearing the key makes 401 safe to log. + if event != "console_output" or not _api_key: + detail = f"HTTP {error.status_code}" if isinstance(error, APIError) else str(error) + LOGGER.warning(f"{PREFIX}Failed to send {event}: {detail}") + return None + + +def _handle_control_response(trainer, ctx, response): + """Apply centralized stop signals returned by Platform webhook responses. + + Notes: + ``ctx["cancelled"]`` is the durable cancellation signal. During startup, trainer setup later resets + ``trainer.stop``, so early stop requests still rely on ``on_pretrain_routine_end()`` to reapply the flag after + setup completes. + """ + if response and response.get("cancelled"): + ctx["cancelled"] = True + trainer.stop = True + LOGGER.info(f"{PREFIX}Training cancelled from Platform ⚠️") + + +def _upload_model(model_path, project, name, progress=False, retry=1, model_id=None, run_id=None): + """Publish a model checkpoint to its configured Platform storage location.""" + from ultralytics.utils.uploads import safe_upload + + if not _api_key: + return None + model_path = Path(model_path) + if not model_path.exists(): + LOGGER.warning(f"{PREFIX}Model file not found: {model_path}") + return None + model_size = model_path.stat().st_size + import httpx + + from ultralytics import APIError, Platform + + identity = {"model_id": model_id} if model_id else {"project": project, "name": name} + if run_id: + identity["run_id"] = run_id + + try: + with Platform( + api_key=_api_key, + base_url=PLATFORM_URL, + max_retries=2, + retry_methods=("POST",), + http_client=httpx.Client(follow_redirects=True), + ) as client: + data = client.models.upload_checkpoint(filename=model_path.name, timeout=30, **identity) + if not isinstance(data, dict): + raise TypeError("Invalid Platform upload response") + except Exception as error: + detail = f"HTTP {error.status_code}" if isinstance(error, APIError) else str(error) + LOGGER.warning(f"{PREFIX}Failed to get upload URL: {detail}") + return None + + # Upload to GCS using safe_upload with retry logic and optional progress bar + if safe_upload(file=model_path, url=data["uploadUrl"], retry=retry, progress=progress): + gcs_path = data.get("gcsPath") + if gcs_path and run_id: + saved = _send( + "checkpoint_saved", + { + "modelPath": gcs_path, + "runId": run_id, + "uploadPath": data.get("uploadPath"), + }, + project, + name, + model_id, + timeout=90, + ) + return {"modelPath": gcs_path, "modelSize": model_size} if saved else None + return {"modelPath": gcs_path, "modelSize": model_size} + return None + + +def _get_environment_info(): + """Collect comprehensive environment info using existing ultralytics utilities.""" + import shutil + + import psutil + import torch + + from ultralytics import __version__ + from ultralytics.utils.torch_utils import get_cpu_info, get_gpu_info + + # Get RAM and disk totals + memory = psutil.virtual_memory() + disk_usage = shutil.disk_usage("/") + + env = { + "ultralyticsVersion": __version__, + "hostname": socket.gethostname(), + "os": platform.platform(), + "environment": ENVIRONMENT, + "pythonVersion": PYTHON_VERSION, + "pythonExecutable": sys.executable, + "cpuCount": os.cpu_count() or 0, + "cpu": get_cpu_info(), + "command": " ".join(sys.argv), + "totalRamGb": round(memory.total / (1 << 30), 1), # Total RAM in GB + "totalDiskGb": round(disk_usage.total / (1 << 30), 1), # Total disk in GB + } + + # Git info using cached GIT singleton (no subprocess calls) + try: + if GIT.is_repo: + if GIT.origin: + env["gitRepository"] = GIT.origin + if GIT.branch: + env["gitBranch"] = GIT.branch + if GIT.commit: + env["gitCommit"] = GIT.commit[:12] # Short hash + if GIT.message: + env["gitCommitMessage"] = GIT.message + except Exception: + pass + + # GPU info + try: + if torch.cuda.is_available(): + env["gpuCount"] = torch.cuda.device_count() + env["gpuType"] = get_gpu_info(0) if torch.cuda.device_count() > 0 else None + except Exception: + pass + + return env + + +def _get_project_name(trainer): + """Get slugified project and name from trainer args.""" + raw = str(trainer.args.project) + parts = raw.split("/", 1) + project = f"{parts[0]}/{slugify(parts[1].replace('/', '-'))}" if len(parts) == 2 else slugify(raw) + return project, slugify(str(trainer.args.name or "train")) + + +def _get_system_metrics(ctx): + """Sample the run's system logger without making optional host monitoring a training dependency.""" + try: + if not ctx["system_logger"]: + from ultralytics.utils.logger import SystemLogger + + ctx["system_logger"] = SystemLogger(all_drives=True) + return ctx["system_logger"].get_metrics(rates=True) + except Exception: + return None + + +def on_pretrain_routine_start(trainer): + """Initialize Platform logging at training start.""" + global _api_key + if TESTS_RUNNING or not trainer.args.project: + return + _api_key = os.getenv("ULTRALYTICS_API_KEY") or SETTINGS.get("api_key") + if not _api_key: + return + if sys.version_info < (3, 11): + LOGGER.warning( + f"{PREFIX}Platform integration requires Python 3.11 or newer. Training will continue without tracking." + ) + return + + project, name = _get_project_name(trainer) + LOGGER.info(f"{PREFIX}Streaming training metrics to Platform") + + from ultralytics.utils.logger import ConsoleLogger + + # Single dict for all platform callback state + ctx = { + "model_id": None, + "run_id": None, + "last_upload": time(), + "checkpoint_upload": None, + "cancelled": False, + "console_logger": None, + "system_logger": None, + } + trainer.platform = ctx + + # Create callback to send console output to Platform + def send_console_output(content, line_count, chunk_id): + """Send batched console output and live progress bar frames to Platform webhook.""" + _executor.submit( + _send, + "console_output", + { + "chunkId": chunk_id, + "content": content, + "lineCount": line_count, + "progress": ctx["console_logger"].progress_sent, + }, + project, + name, + ctx["model_id"], + ) + + # Console capture with batching (5 lines or 5 seconds). Built here, but not started until Platform + # has accepted the run below: capturing first left the user's stdout redirected through a dead + # integration whenever training_started failed, and its final flush would post a console chunk + # carrying no model_id. + ctx["console_logger"] = ConsoleLogger(batch_size=5, flush_interval=5.0, on_flush=send_console_output) + + # Collect environment info (W&B-style metadata) + environment = _get_environment_info() + + # Build trainArgs - callback runs before get_dataset() so args.data is still original (e.g., ul:// URIs) + # Note: model_info is sent later in on_fit_epoch_end (epoch 0) when the model is actually loaded + train_args = {k: str(v) for k, v in vars(trainer.args).items()} + + # Send synchronously to get modelId for subsequent webhooks (critical, more retries) + response = _send( + "training_started", + { + "trainArgs": train_args, + "epochs": trainer.epochs, + "device": str(trainer.device), + "environment": environment, + "system": _get_system_metrics(ctx), + }, + project, + name, + retry=4, + ) + if response and response.get("modelId"): + ctx["model_id"] = response["modelId"] + ctx["run_id"] = response.get("runId") + # Server returns actual slug (may differ from requested name due to auto-increment, e.g. "train" → "train-2") + if response.get("modelSlug"): + ctx["model_slug"] = response["modelSlug"] + url = f"{PLATFORM_URL}/{project}/{ctx['model_slug']}" + LOGGER.info(f"{PREFIX}View model at {url}") + ctx["console_logger"].start_capture() # only now: the run is tracked and model_id is known + # Note: trainer.stop is set in on_pretrain_routine_end (after _setup_train resets it) + _handle_control_response(trainer, ctx, response) + else: + LOGGER.warning(f"{PREFIX}Training will not be tracked on Platform") + trainer.platform = None # Disable further callbacks + + +def on_pretrain_routine_end(trainer): + """Apply pre-start cancellation after _setup_train resets trainer.stop.""" + ctx = getattr(trainer, "platform", None) + if ctx and ctx["cancelled"]: + LOGGER.info(f"{PREFIX}Training cancelled from Platform before starting ✅") + trainer.stop = True + + +def on_fit_epoch_end(trainer): + """Log training and system metrics at epoch end.""" + ctx = getattr(trainer, "platform", None) + if not ctx: + return + + project, name = _get_project_name(trainer) + metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics} + + if trainer.optimizer and trainer.optimizer.param_groups: + metrics["lr"] = trainer.optimizer.param_groups[0]["lr"] + + # Extract model info at epoch 0 (sent as separate field, not in metrics) + model_info = None + if trainer.epoch == 0: + try: + from ultralytics.utils.torch_utils import model_info_for_loggers + + info = model_info_for_loggers(trainer) + model_info = { + "parameters": info.get("model/parameters", 0), + "gflops": info.get("model/GFLOPs", 0), + "speedMs": info.get("model/speed_PyTorch(ms)", 0), + } + except Exception: + pass + + payload = { + "epoch": trainer.epoch, + "metrics": metrics, + "system": _get_system_metrics(ctx), + "fitness": trainer.fitness, + "best_fitness": trainer.best_fitness, + } + if model_info: + payload["modelInfo"] = model_info + + def _send_and_check_cancel(): + """Send epoch_end and check response for cancellation (runs in background thread).""" + response = _send("epoch_end", payload, project, name, ctx["model_id"], retry=1) + _handle_control_response(trainer, ctx, response) + + _executor.submit(_send_and_check_cancel) + + +def on_model_save(trainer): + """Upload model checkpoint (rate limited to every 15 min).""" + ctx = getattr(trainer, "platform", None) + if not ctx: + return + # Rate limit to every 15 minutes (900 seconds) + if time() - ctx["last_upload"] < 900: + return + if ctx["checkpoint_upload"] and not ctx["checkpoint_upload"].done(): + return + + model_path = trainer.best if trainer.best and Path(trainer.best).exists() else trainer.last + if not model_path: + return + + project, name = _get_project_name(trainer) + ctx["checkpoint_upload"] = _executor.submit( + _upload_model, model_path, project, name, model_id=ctx["model_id"], run_id=ctx["run_id"] + ) + ctx["last_upload"] = time() + + +def on_train_end(trainer): + """Log final training results and upload the best model to Platform.""" + ctx = getattr(trainer, "platform", None) # set only by on_pretrain_routine_start, so unset without an API key + if not ctx: + return + + project, name = _get_project_name(trainer) + + if ctx["cancelled"]: + LOGGER.info(f"{PREFIX}Uploading partial results for cancelled training") + + # Stop console capture + if ctx["console_logger"]: + ctx["console_logger"].stop_capture() + ctx["console_logger"] = None + + # Upload best model (blocking with progress bar to ensure it completes) + artifact = None + if trainer.best and Path(trainer.best).exists(): + if ctx["checkpoint_upload"]: + ctx["checkpoint_upload"].result() + artifact = _upload_model( + trainer.best, + project, + name, + progress=True, + retry=3, + model_id=ctx["model_id"], + run_id=ctx["run_id"], + ) + if not artifact: + LOGGER.warning(f"{PREFIX}Model will not be available for download on Platform (upload failed)") + + # Collect plots from trainer and validator, deduplicating by type + plots_by_type = {} + for info in getattr(trainer, "plots", {}).values(): + if info.get("data") and info["data"].get("type"): + plots_by_type[info["data"]["type"]] = info["data"] + for info in getattr(getattr(trainer, "validator", None), "plots", {}).values(): + if info.get("data") and info["data"].get("type"): + plots_by_type.setdefault(info["data"]["type"], info["data"]) # Don't overwrite trainer plots + plots = [_interp_plot(p) for p in plots_by_type.values()] # Interpolate curves to reduce size + + # Get class names + names = getattr(getattr(trainer, "validator", None), "names", None) or (trainer.data or {}).get("names") + class_names = list(names.values()) if isinstance(names, dict) else list(names) if names else None + + # stopper.best_epoch is 1-indexed; -1 aligns with the 0-indexed `epoch` field + best_epoch = max(0, getattr(getattr(trainer, "stopper", None), "best_epoch", trainer.epoch + 1) - 1) + + image_metrics = trainer.validator.metrics.box.image_metrics if trainer.args.task == "detect" else {} + validation = _validation_payload(image_metrics) + _send( + "training_complete", + { + "results": { + "metrics": {**trainer.metrics, "fitness": trainer.fitness}, + "bestEpoch": best_epoch, + "bestFitness": trainer.best_fitness, + **({"calibration": c} if (c := getattr(trainer, "depth_calibration", None)) else {}), + **({"validation": validation} if validation["rows"] else {}), + **(artifact or {}), + }, + "classNames": class_names, + "plots": plots, + "runId": ctx["run_id"], + }, + project, + name, + ctx["model_id"], + retry=4, # Critical, more retries + ) + url = f"{PLATFORM_URL}/{project}/{ctx.get('model_slug', name)}" + LOGGER.info(f"{PREFIX}View results at {url}") + + +callbacks = { + "on_pretrain_routine_start": on_pretrain_routine_start, + "on_pretrain_routine_end": on_pretrain_routine_end, + "on_fit_epoch_end": on_fit_epoch_end, + "on_model_save": on_model_save, + "on_train_end": on_train_end, +} diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/raytune.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/raytune.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb638a9fdb2dfd1652512c7b9facbf944537aee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/raytune.py @@ -0,0 +1,40 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from ultralytics.utils import SETTINGS + +try: + assert SETTINGS["raytune"] is True # verify integration is enabled + from ray import tune + + assert hasattr(tune, "get_context") # verify Ray>=2.41 Tune API, also required by tuner.run_ray_tune +except (ImportError, AssertionError): + tune = None + + +def on_fit_epoch_end(trainer): + """Report training metrics to Ray Tune at epoch end when a Ray session is active. + + Captures metrics from the trainer object and sends them to Ray Tune with the current epoch number, enabling + hyperparameter tuning optimization. Only executes when within an active Ray Tune session. + + Args: + trainer (ultralytics.engine.trainer.BaseTrainer): The Ultralytics trainer object containing metrics and epochs. + + Examples: + >>> # Called automatically by the Ultralytics training loop + >>> on_fit_epoch_end(trainer) + + References: + Ray Tune docs: https://docs.ray.io/en/latest/tune/index.html + """ + if tune.get_context().get_trial_id(): # check if Ray Tune session is active + tune.report({**trainer.metrics, "epoch": trainer.epoch + 1}) + + +callbacks = ( + { + "on_fit_epoch_end": on_fit_epoch_end, + } + if tune + else {} +) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/tensorboard.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/tensorboard.py new file mode 100644 index 0000000000000000000000000000000000000000..12de79401d5a8afb4854f6d6c4f1f62e72552002 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/tensorboard.py @@ -0,0 +1,126 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from ultralytics.utils import LOGGER, SETTINGS, TESTS_RUNNING, colorstr, torch_utils +from ultralytics.utils.torch_utils import smart_inference_mode + +try: + assert not TESTS_RUNNING # do not log pytest + assert SETTINGS["tensorboard"] is True # verify integration is enabled + WRITER = None # TensorBoard SummaryWriter instance + PREFIX = colorstr("TensorBoard: ") + + # Imports below only required if TensorBoard enabled + from copy import deepcopy + + import torch + from torch.utils.tensorboard import SummaryWriter + +except (ImportError, AssertionError, TypeError, AttributeError): + # TypeError for handling 'Descriptors cannot not be created directly.' protobuf errors in Windows + # AttributeError: module 'tensorflow' has no attribute 'io' if 'tensorflow' not installed + SummaryWriter = None + + +def _log_scalars(scalars: dict, step: int = 0) -> None: + """Log scalar values to TensorBoard. + + Args: + scalars (dict): Dictionary of scalar values to log to TensorBoard. Keys are scalar names and values are the + corresponding scalar values. + step (int): Global step value to record with the scalar values. Used for x-axis in TensorBoard graphs. + + Examples: + Log training metrics + >>> metrics = {"loss": 0.5, "accuracy": 0.95} + >>> _log_scalars(metrics, step=100) + """ + if WRITER: + for k, v in scalars.items(): + WRITER.add_scalar(k, v, step) + + +@smart_inference_mode() +def _log_tensorboard_graph(trainer) -> None: + """Log model graph to TensorBoard. + + This function attempts to visualize the model architecture in TensorBoard by tracing the model with a dummy input + tensor. It first tries a simple method suitable for YOLO models, and if that fails, falls back to a more complex + approach for models like RTDETR that may require special handling. + + Args: + trainer (ultralytics.engine.trainer.BaseTrainer): The trainer object containing the model to visualize. Must + have attributes model and args with imgsz. + + Notes: + This function requires TensorBoard integration to be enabled and the global WRITER to be initialized. + It handles potential warnings from the PyTorch JIT tracer and attempts to gracefully handle different + model architectures. + """ + # Input image + imgsz = trainer.args.imgsz + ch = trainer.data.get("channels", 3) + imgsz = (imgsz, imgsz) if isinstance(imgsz, int) else imgsz + p = next(trainer.model.parameters()) # for device, type + im = torch.zeros((1, ch, *imgsz), device=p.device, dtype=p.dtype) # input image (must be zeros, not empty) + + # Try simple method first (YOLO) + try: + trainer.model.eval() # place in .eval() mode to avoid BatchNorm statistics changes + WRITER.add_graph(torch.jit.trace(torch_utils.unwrap_model(trainer.model), im, strict=False), []) + LOGGER.info(f"{PREFIX}model graph visualization added ✅") + return + except Exception as e1: + # Fallback to TorchScript export steps (RTDETR) + try: + model = deepcopy(torch_utils.unwrap_model(trainer.model)) + model.eval() + model = model.fuse(verbose=False) + for m in model.modules(): + if hasattr(m, "export"): # Detect, RTDETRDecoder (Segment and Pose use Detect base class) + m.export = True + m.format = "torchscript" + model(im) # dry run + WRITER.add_graph(torch.jit.trace(model, im, strict=False), []) + LOGGER.info(f"{PREFIX}model graph visualization added ✅") + except Exception as e2: + LOGGER.warning(f"{PREFIX}TensorBoard graph visualization failure: {e1} -> {e2}") + + +def on_pretrain_routine_start(trainer) -> None: + """Initialize TensorBoard logging with SummaryWriter.""" + if SummaryWriter: + try: + global WRITER + WRITER = SummaryWriter(str(trainer.save_dir)) + LOGGER.info(f"{PREFIX}Start with 'tensorboard --logdir {trainer.save_dir}', view at http://localhost:6006/") + except Exception as e: + LOGGER.warning(f"{PREFIX}TensorBoard not initialized correctly, not logging this run. {e}") + + +def on_train_start(trainer) -> None: + """Log TensorBoard graph.""" + if WRITER: + _log_tensorboard_graph(trainer) + + +def on_train_epoch_end(trainer) -> None: + """Log scalar statistics at the end of a training epoch.""" + _log_scalars(trainer.label_loss_items(trainer.tloss, prefix="train"), trainer.epoch + 1) + _log_scalars(trainer.lr, trainer.epoch + 1) + + +def on_fit_epoch_end(trainer) -> None: + """Log epoch metrics at end of training epoch.""" + _log_scalars(trainer.metrics, trainer.epoch + 1) + + +callbacks = ( + { + "on_pretrain_routine_start": on_pretrain_routine_start, + "on_train_start": on_train_start, + "on_fit_epoch_end": on_fit_epoch_end, + "on_train_epoch_end": on_train_epoch_end, + } + if SummaryWriter + else {} +) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/wb.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/wb.py new file mode 100644 index 0000000000000000000000000000000000000000..05a414cbaadc140e526d0ae2ec1823eda91535c3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/wb.py @@ -0,0 +1,199 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from ultralytics.utils import SETTINGS, TESTS_RUNNING +from ultralytics.utils.torch_utils import model_info_for_loggers + +try: + assert not TESTS_RUNNING # do not log pytest + assert SETTINGS["wandb"] is True # verify integration is enabled + import wandb as wb + + assert hasattr(wb, "__version__") # verify package is not directory + _processed_plots = {} + +except (ImportError, AssertionError): + wb = None + + +def _custom_table(x, y, classes, title="Precision Recall Curve", x_title="Recall", y_title="Precision"): + """Create and log a custom metric visualization table. + + This function crafts a custom metric visualization that mimics the behavior of the default wandb precision-recall + curve while allowing for enhanced customization. The visual metric is useful for monitoring model performance across + different classes. + + Args: + x (list): Values for the x-axis; expected to have length N. + y (list): Corresponding values for the y-axis; also expected to have length N. + classes (list): Labels identifying the class of each point; length N. + title (str, optional): Title for the plot. + x_title (str, optional): Label for the x-axis. + y_title (str, optional): Label for the y-axis. + + Returns: + (wandb.Object): A wandb object suitable for logging, showcasing the crafted metric visualization. + """ + import polars as pl # scope for faster 'import ultralytics' + import polars.selectors as cs + + df = pl.DataFrame({"class": classes, "y": y, "x": x}).with_columns(cs.numeric().round(3)) + data = df.select(["class", "y", "x"]).rows() + + fields = {"x": "x", "y": "y", "class": "class"} + string_fields = {"title": title, "x-axis-title": x_title, "y-axis-title": y_title} + return wb.plot_table( + "wandb/area-under-curve/v0", + wb.Table(data=data, columns=["class", "y", "x"]), + fields=fields, + string_fields=string_fields, + ) + + +def _plot_curve( + x, + y, + names=None, + id="precision-recall", + title="Precision Recall Curve", + x_title="Recall", + y_title="Precision", + num_x=100, + only_mean=False, +): + """Log a metric curve visualization. + + This function generates a metric curve based on input data and logs the visualization to wandb. The curve can + represent aggregated data (mean) or individual class data, depending on the 'only_mean' flag. + + Args: + x (np.ndarray): Data points for the x-axis with length N. + y (np.ndarray): Corresponding data points for the y-axis with shape (C, N), where C is the number of classes. + names (list, optional): Names of the classes corresponding to the y-axis data; length C. + id (str, optional): Unique identifier for the logged data in wandb. + title (str, optional): Title for the visualization plot. + x_title (str, optional): Label for the x-axis. + y_title (str, optional): Label for the y-axis. + num_x (int, optional): Number of interpolated data points for visualization. + only_mean (bool, optional): Flag to indicate if only the mean curve should be plotted. + + Notes: + The function leverages the '_custom_table' function to generate the actual visualization. + """ + import numpy as np + + # Create new x + if names is None: + names = [] + x_new = np.linspace(x[0], x[-1], num_x).round(5) + + # Create arrays for logging + x_log = x_new.tolist() + y_log = np.interp(x_new, x, np.mean(y, axis=0)).round(3).tolist() + + if only_mean: + table = wb.Table(data=list(zip(x_log, y_log)), columns=[x_title, y_title]) + wb.run.log({title: wb.plot.line(table, x_title, y_title, title=title)}) + else: + classes = ["mean"] * len(x_log) + for i, yi in enumerate(y): + x_log.extend(x_new) # add new x + y_log.extend(np.interp(x_new, x, yi)) # interpolate y to new x + classes.extend([names[i]] * len(x_new)) # add class names + wb.log({id: _custom_table(x_log, y_log, classes, title, x_title, y_title)}, commit=False) + + +def _log_plots(plots, step): + """Log plots to WandB at a specific step if they haven't been logged already. + + This function checks each plot in the input dictionary against previously processed plots and logs new or updated + plots to WandB at the specified step. + + Args: + plots (dict): Dictionary of plots to log, where keys are plot names and values are dictionaries containing plot + metadata including timestamps. + step (int): The step/epoch at which to log the plots in the WandB run. + + Notes: + The function uses a shallow copy of the plots dictionary to prevent modification during iteration. + Plots are identified by their stem name (filename without extension). + Each plot is logged as a WandB Image object. + """ + for name, params in plots.copy().items(): # shallow copy to prevent plots dict changing during iteration + timestamp = params["timestamp"] + if _processed_plots.get(name) != timestamp: + wb.run.log({name.stem: wb.Image(str(name))}, step=step) + _processed_plots[name] = timestamp + + +def on_pretrain_routine_start(trainer): + """Initialize and start wandb project if module is present.""" + if not wb.run: + from datetime import datetime + from pathlib import Path + + name = str(trainer.args.name).replace("/", "-").replace(" ", "_") + latest_run = Path(trainer.save_dir) / "wandb" / "latest-run" + resuming = trainer.args.resume and latest_run.exists() + wb.init( + project=str(trainer.args.project).replace("/", "-") if trainer.args.project else "Ultralytics", + name=name, + config=vars(trainer.args), + id=latest_run.resolve().name.split("-", 2)[2] + if resuming + else f"{name[:64]}_{datetime.now().astimezone().strftime('%Y%m%d_%H%M%S')}", + resume="allow" if resuming else None, + dir=str(trainer.save_dir), + ) + + +def on_fit_epoch_end(trainer): + """Log training metrics and model information at the end of an epoch.""" + _log_plots(trainer.plots, step=trainer.epoch + 1) + _log_plots(trainer.validator.plots, step=trainer.epoch + 1) + if trainer.epoch == 0: + wb.run.log(model_info_for_loggers(trainer), step=trainer.epoch + 1) + wb.run.log(trainer.metrics, step=trainer.epoch + 1, commit=True) # commit forces sync + + +def on_train_epoch_end(trainer): + """Log metrics and save images at the end of each training epoch.""" + wb.run.log(trainer.label_loss_items(trainer.tloss, prefix="train"), step=trainer.epoch + 1) + wb.run.log(trainer.lr, step=trainer.epoch + 1) + if trainer.epoch == 1: + _log_plots(trainer.plots, step=trainer.epoch + 1) + + +def on_train_end(trainer): + """Save the best model as an artifact and log final plots at the end of training.""" + _log_plots(trainer.validator.plots, step=trainer.epoch + 1) + _log_plots(trainer.plots, step=trainer.epoch + 1) + if trainer.args.save and trainer.best.exists(): + art = wb.Artifact(type="model", name=f"run_{wb.run.id}_model") + art.add_file(trainer.best) + wb.run.log_artifact(art, aliases=["best"]) + # Check if we actually have plots to save + if trainer.args.plots and hasattr(trainer.validator.metrics, "curves_results"): + for curve_name, curve_values in zip(trainer.validator.metrics.curves, trainer.validator.metrics.curves_results): + x, y, x_title, y_title = curve_values + _plot_curve( + x, + y, + names=list(trainer.validator.metrics.names.values()), + id=f"curves/{curve_name}", + title=curve_name, + x_title=x_title, + y_title=y_title, + ) + wb.run.finish() # required or run continues on dashboard + + +callbacks = ( + { + "on_pretrain_routine_start": on_pretrain_routine_start, + "on_train_epoch_end": on_train_epoch_end, + "on_fit_epoch_end": on_fit_epoch_end, + "on_train_end": on_train_end, + } + if wb + else {} +) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/checks.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/checks.py new file mode 100644 index 0000000000000000000000000000000000000000..3e8d9d05e917fb4d83c9874775ed257753654cdd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/checks.py @@ -0,0 +1,1199 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import ast +import functools +import glob +import inspect +import math +import os +import platform +import re +import shlex +import shutil +import subprocess +import sys +import time +from importlib import metadata +from pathlib import Path +from types import SimpleNamespace + +import cv2 +import numpy as np +import torch + +from ultralytics.utils import ( + ARM64, + ASSETS, + ASSETS_URL, + AUTOINSTALL, + GIT, + IS_COLAB, + IS_DOCKER, + IS_JETSON, + IS_KAGGLE, + IS_PIP_PACKAGE, + LINUX, + LOGGER, + MACOS, + ONLINE, + PLATFORM_URL, + PYTHON_VERSION, + RKNN_CHIPS, + ROOT, + TORCH_VERSION, + TORCHVISION_VERSION, + USER_CONFIG_DIR, + WINDOWS, + Retry, + ThreadingLocked, + TryExcept, + clean_url, + colorstr, + downloads, + env_bool, + is_github_action_running, + url2file, +) + +REMOTE_FILE_PREFIXES = ("https://", "http://", "rtsp://", "rtmp://", "tcp://", "ul://", "gs://") + + +def normalize_platform_uri(uri): + """Rewrite an Ultralytics Platform web URL to its ul:// URI so it can be loaded directly as data or model. + + Args: + uri (str | Path): Resource identifier, e.g. an Ultralytics Platform web URL ending in "/user/datasets/slug". + + Returns: + (str | Path): "ul://user/datasets/slug" for Platform web URLs, otherwise the input unchanged. + """ + s = str(uri) + return f"ul://{s[len(PLATFORM_URL) + 1 :].strip('/')}" if s.startswith(f"{PLATFORM_URL}/") else uri + + +def resolve_platform_uri(uri, hard=True): + """Resolve ul:// URIs to signed URLs by authenticating with Ultralytics Platform. + + Formats: + ul://username/datasets/slug -> Returns signed URL to NDJSON file + ul://username/project/model -> Returns signed URL to .pt file + + Args: + uri (str): Platform URI starting with "ul://". + hard (bool): Whether to raise an error if resolution fails. + + Returns: + (str | None): Signed URL on success, None if not found and hard=False. + + Raises: + ValueError: If the API key or URI is invalid. + PermissionError: If access is denied. + RuntimeError: If the resource is not ready or Platform returns another error. + FileNotFoundError: If the resource is not found and hard=True. + ConnectionError: If the request fails and hard=True. + """ + from ultralytics import APIConnectionError, APIError, Platform + from ultralytics.utils import SETTINGS + + parts = str(uri)[5:].split("/") + if len(parts) != 3 or not all(parts): + raise ValueError(f"Invalid Platform URI: {uri}. Use ul://user/datasets/name or ul://user/project/model") + api_key = os.getenv("ULTRALYTICS_API_KEY") or SETTINGS.get("api_key") + if not api_key: + raise ValueError(f"ULTRALYTICS_API_KEY required for '{uri}'. Get a key at {PLATFORM_URL}/settings") + + import httpx + + dataset = parts[1] == "datasets" + try: + with Platform( + api_key=api_key, + base_url=PLATFORM_URL, + timeout=httpx.Timeout(3600 if dataset else 90, connect=10), + max_retries=4, + ) as client: + if dataset: + return client.datasets.export(parts[0], parts[2])["downloadUrl"] + files = client.models.files(*parts)["files"] + if files: + return files[0]["downloadUrl"] + except APIConnectionError as error: + if hard: + raise ConnectionError(f"Failed to resolve {uri}: {error}") from error + LOGGER.warning(f"Failed to resolve {uri}: {error}") + return None + except APIError as error: + # APIError.body may contain a proxy page echoing credentials; show only bounded JSON errors. + detail = str(error.json.get("error", "")).strip()[:500] if isinstance(error.json, dict) else "" + if error.status_code == 401: + raise ValueError(f"Invalid ULTRALYTICS_API_KEY for '{uri}'. {detail}") from None + if error.status_code == 403: + raise PermissionError(f"Access denied for '{uri}'. {detail}") from None + if error.status_code in {408, 429} or error.status_code >= 500: + message = f"Failed to resolve {uri} (HTTP {error.status_code}). {detail}" + if hard: + raise ConnectionError(message) from None + LOGGER.warning(message) + return None + if error.status_code != 404: + raise RuntimeError(f"Platform error for '{uri}' (HTTP {error.status_code}). {detail}") from None + + if hard: + raise FileNotFoundError(f"No dataset or model weights found on Platform: {uri}") + LOGGER.warning(f"No dataset or model weights found on Platform: {uri}") + return None + + +def parse_requirements(file_path=ROOT.parent / "requirements.txt", package=""): + """Parse a requirements.txt file, ignoring lines that start with '#' and any text after '#'. + + Args: + file_path (Path): Path to the requirements.txt file. + package (str, optional): Python package to use instead of requirements.txt file. + + Returns: + requirements (list[SimpleNamespace]): List of parsed requirements as SimpleNamespace objects with `name` and + `specifier` attributes. + + Examples: + >>> from ultralytics.utils.checks import parse_requirements + >>> parse_requirements(package="ultralytics") + """ + if package: + requires = [x for x in metadata.distribution(package).requires if "extra == " not in x] + else: + requires = Path(file_path).read_text().splitlines() + + requirements = [] + for line in requires: + line = line.strip() + if line and not line.startswith("#"): + line = line.partition("#")[0].strip() # ignore inline comments + if match := re.match(r"([a-zA-Z0-9-_]+)\s*([<>!=~]+.*)?", line): + requirements.append(SimpleNamespace(name=match[1], specifier=match[2].strip() if match[2] else "")) + + return requirements + + +def get_distribution_name(import_name: str) -> str: + """Get the pip distribution name for a given import name (e.g., 'cv2' -> 'opencv-python-headless').""" + for dist in metadata.distributions(): + top_level = (dist.read_text("top_level.txt") or "").split() + if import_name in top_level: + return dist.metadata["Name"] + return import_name + + +@functools.lru_cache +def parse_version(version="0.0.0") -> tuple: + """Convert a version string to a tuple of integers from its release segments, ignoring prefixes and suffixes. + + Not PEP 440: pre-release/dev/post/local suffixes are dropped, so '1.0rc1', '1.0.post1', and '1.0+cu118' all compare + equal to '1.0'. Use the `packaging` library where exact pre-release ordering matters. + + Args: + version (str): Version string, i.e. '2.0.1+cpu', '4.13.0.92', or 'v2.1' + + Returns: + (tuple): Tuple of integers representing the release segments, at least 3 long, i.e. (2, 0, 1) + """ + try: + nums = [int(x) for x in re.search(r"\d+(?:\.\d+)*", version).group(0).split(".")] + return tuple(nums + [0] * (3 - len(nums))) # keep all release segments, ignore 'v' prefix and '+cu118'/'rc1' + except Exception as e: + LOGGER.warning(f"failure for parse_version({version}), returning (0, 0, 0): {e}") + return 0, 0, 0 + + +def is_ascii(s) -> bool: + """Check if a string is composed of only ASCII characters. + + Args: + s (str | list | tuple | dict): Input to be checked (all are converted to string for checking). + + Returns: + (bool): True if the string is composed only of ASCII characters, False otherwise. + """ + return str(s).isascii() + + +def check_imgsz(imgsz, stride=32, min_dim=1, max_dim=2, floor=0): + """Verify image size is a multiple of the given stride in each dimension. If the image size is not a multiple of the + stride, update it to the nearest multiple of the stride that is greater than or equal to the given floor value. + + Args: + imgsz (int | list[int]): Image size. + stride (int): Stride value. + min_dim (int): Minimum number of dimensions. + max_dim (int): Maximum number of dimensions. + floor (int): Minimum allowed value for image size. + + Returns: + (list[int] | int): Updated image size. + """ + # Convert stride to integer if it is a tensor + stride = int(stride.max() if isinstance(stride, torch.Tensor) else stride) + + # Convert image size to list if it is an integer + if isinstance(imgsz, int): + imgsz = [imgsz] + elif isinstance(imgsz, (list, tuple)): + imgsz = list(imgsz) + elif isinstance(imgsz, str): # i.e. '640' or '[640,640]' + try: + imgsz = [int(imgsz)] if imgsz.isnumeric() else ast.literal_eval(imgsz) + except (ValueError, SyntaxError): + raise ValueError( + f"'imgsz={imgsz}' is not a valid image size. " + f"Valid imgsz values are int i.e. 'imgsz=640' or list i.e. 'imgsz=[640,640]'" + ) from None + else: + raise TypeError( + f"'imgsz={imgsz}' is of invalid type {type(imgsz).__name__}. " + f"Valid imgsz types are int i.e. 'imgsz=640' or list i.e. 'imgsz=[640,640]'" + ) + + # Apply max_dim + if len(imgsz) > max_dim: + msg = ( + "'train' and 'val' imgsz must be an integer, while 'predict' and 'export' imgsz may be a [h, w] list " + "or an integer, i.e. 'yolo export imgsz=640,480' or 'yolo export imgsz=640'" + ) + if max_dim != 1: + raise ValueError(f"imgsz={imgsz} is not a valid image size. {msg}") + LOGGER.warning(f"updating to 'imgsz={max(imgsz)}'. {msg}") + imgsz = [max(imgsz)] + # Make image size a multiple of the stride + sz = [max(math.ceil(x / stride) * stride, floor, stride) for x in imgsz] # at least one stride, i.e. imgsz=0 + + # Print warning message if image size was updated + if sz != imgsz: + LOGGER.warning(f"imgsz={imgsz} must be multiple of max stride {stride}, updating to {sz}") + + # Add missing dimensions if necessary + sz = [sz[0], sz[0]] if min_dim == 2 and len(sz) == 1 else sz[0] if min_dim == 1 and len(sz) == 1 else sz + + return sz + + +@functools.lru_cache +def check_uv(): + """Check if uv package manager is installed and can run successfully.""" + try: + return subprocess.run(["uv", "-V"], capture_output=True, check=False).returncode == 0 + except FileNotFoundError: + return False + + +@functools.lru_cache +def check_version( + current: str = "0.0.0", + required: str = "0.0.0", + name: str = "version", + hard: bool = False, + verbose: bool = False, + msg: str = "", +) -> bool: + """Check current version against the required version or range. + + Args: + current (str): Current version or package name to get version from. + required (str): Required version or range (in pip-style format). + name (str): Name to be used in warning message. + hard (bool): If True, raise a ModuleNotFoundError if the requirement is not met. + verbose (bool): If True, print warning message if requirement is not met. + msg (str): Extra message to display if verbose. + + Returns: + (bool): True if requirement is met, False otherwise. + + Examples: + Check if current version is exactly 22.04 + >>> check_version(current="22.04", required="==22.04") + + Check if current version is greater than or equal to 22.04 + >>> check_version(current="22.10", required="22.04") # assumes '>=' inequality if none passed + + Check if current version is less than or equal to 22.04 + >>> check_version(current="22.04", required="<=22.04") + + Check if current version is between 20.04 (inclusive) and 22.04 (exclusive) + >>> check_version(current="21.10", required=">20.04,<22.04") + """ + if not current: # if current is '' or None + LOGGER.warning(f"invalid check_version({current}, {required}) requested, please check values.") + return True + elif not current[0].isdigit(): # current is package name rather than version string, i.e. current='ultralytics' + try: + name = current # assigned package name to 'name' arg + current = metadata.version(current) # get version string from package name + except metadata.PackageNotFoundError as e: + if re.fullmatch( + r"v\d+(\.\d+)*([-_.]?(a|b|c|rc|alpha|beta|pre|preview)[-_.]?\d*)?" + r"([-_.]?(post|rev|r)[-_.]?\d*)?([-_.]?dev[-_.]?\d*)?(\+[\w.-]+)?", + current, + re.IGNORECASE, + ): + pass + elif hard: + raise ModuleNotFoundError(f"{current} package is required but not installed") from e + else: + return False + + if not required: # if required is '' or None + return True + + if "sys_platform" in required and ( # i.e. required='<2.4.0,>=1.8.0; sys_platform == "win32"' + (WINDOWS and "win32" not in required) + or (LINUX and "linux" not in required) + or (MACOS and "macos" not in required and "darwin" not in required) + ): + return True + + result = True + c = parse_version(current) # '1.2.3' -> (1, 2, 3) + for r in required.strip(",").split(","): + op, version = re.match(r"([^0-9]*)([\d.]+)", r).groups() # split '>=22.04' -> ('>=', '22.04') + if not op: + op = ">=" # assume >= if no op passed + v = parse_version(version) # '1.2.3' -> (1, 2, 3) + n = max(len(c), len(v)) # pad to equal length so 4-segment pins like '!=4.13.0.90' compare exactly + cn, vn = c + (0,) * (n - len(c)), v + (0,) * (n - len(v)) + if ( + (op == "==" and cn != vn) + or (op == "!=" and cn == vn) + or (op == ">=" and not (cn >= vn)) + or (op == "<=" and not (cn <= vn)) + or (op == ">" and not (cn > vn)) + or (op == "<" and not (cn < vn)) + ): + result = False + if not result: + warning = f"{name}{required} is required, but {name}=={current} is currently installed {msg}" + if hard: + raise ModuleNotFoundError(warning) # assert version requirements met + if verbose: + LOGGER.warning(warning) + return result + + +def check_latest_pypi_version(package_name="ultralytics"): + """Return the latest version of a PyPI package without downloading or installing it. + + Args: + package_name (str): The name of the package to find the latest version for. + + Returns: + (str | None): The latest version of the package, or None if unavailable. + """ + import requests # scoped as slow import + + try: + requests.packages.urllib3.disable_warnings() # Disable the InsecureRequestWarning + response = requests.get(f"https://pypi.org/pypi/{package_name}/json", timeout=3) + if response.status_code == 200: + return response.json()["info"]["version"] + except Exception: + return None + + +def check_pip_update_available(): + """Check if a new version of the ultralytics package is available on PyPI. + + Returns: + (bool): True if an update is available, False otherwise. + """ + if ONLINE and IS_PIP_PACKAGE: + try: + from ultralytics import __version__ + + latest = check_latest_pypi_version() + if check_version(__version__, f"<{latest}"): # check if current version is < latest version + LOGGER.info( + f"New https://pypi.org/project/ultralytics/{latest} available 😃 " + f"Update with 'pip install -U ultralytics'" + ) + return True + except Exception: + pass + return False + + +@ThreadingLocked() +@functools.lru_cache +def check_font(font="Arial.ttf"): + """Find font locally or download to user's configuration directory if it does not already exist. + + Args: + font (str): Path or name of font. + + Returns: + (Path | str): Resolved font file path. + """ + from matplotlib import font_manager # scope for faster 'import ultralytics' + + # Check USER_CONFIG_DIR + name = Path(font).name + file = USER_CONFIG_DIR / name + if file.exists(): + return file + + # Check system fonts in matplotlib's cached list, findSystemFonts() rescans the OS in every process (7s on macOS) + matches = [f.fname for f in font_manager.fontManager.ttflist if font in f.fname and os.path.exists(f.fname)] + if not matches: # font installed after matplotlib's cached list was built, rescan the OS + matches = [f for f in font_manager.findSystemFonts() if font in f] + if any(matches): + return matches[0] + + # Download to USER_CONFIG_DIR if missing + url = f"{ASSETS_URL}/{name}" + if downloads.is_url(url, check=True): + downloads.safe_download(url=url, file=file) + return file + + +def check_python(minimum: str = "3.8.0", hard: bool = True, verbose: bool = False) -> bool: + """Check current python version against the required minimum version. + + Args: + minimum (str): Required minimum version of python. + hard (bool): If True, raise a ModuleNotFoundError if the requirement is not met. + verbose (bool): If True, print warning message if requirement is not met. + + Returns: + (bool): Whether the installed Python version meets the minimum constraints. + """ + return check_version(PYTHON_VERSION, minimum, name="Python", hard=hard, verbose=verbose) + + +@TryExcept() +def check_apt_requirements(requirements): + """Check if apt packages are installed and install missing ones. + + Args: + requirements (list[str]): List of apt package names to check and install. + """ + prefix = colorstr("red", "bold", "apt requirements:") + # Check which packages are missing + missing_packages = [] + for package in requirements: + try: + # Use dpkg -l to check if package is installed + result = subprocess.run(["dpkg", "-l", package], capture_output=True, text=True, check=False) + # Check if package is installed (look for "ii" status) + if result.returncode != 0 or not any( + line.startswith("ii") and package in line for line in result.stdout.splitlines() + ): + missing_packages.append(package) + except Exception: + # If check fails, assume package is not installed + missing_packages.append(package) + + # Install missing packages if any + if missing_packages: + if not AUTOINSTALL: # check environment variable + LOGGER.warning( + f"{prefix} Ultralytics requirement{'s' * (len(missing_packages) > 1)} {missing_packages} not found, " + f"AutoUpdate disabled by YOLO_AUTOINSTALL=False. Install with 'apt install {' '.join(missing_packages)}'" + ) + return + LOGGER.info( + f"{prefix} Ultralytics requirement{'s' * (len(missing_packages) > 1)} {missing_packages} not found, attempting AutoUpdate..." + ) + # Optionally update package list first + cmd = (["sudo"] if is_sudo_available() else []) + ["apt", "update"] + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + + # Build and run the install command + cmd = (["sudo"] if is_sudo_available() else []) + ["apt", "install", "-y"] + missing_packages + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + + LOGGER.info(f"{prefix} AutoUpdate success ✅") + LOGGER.warning(f"{prefix} {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n") + + +@TryExcept() +def check_requirements(requirements=ROOT.parent / "requirements.txt", exclude=(), install=True, cmds="", constrain=()): + """Check if installed dependencies meet Ultralytics YOLO models requirements and attempt to auto-update if needed. + + Args: + requirements (Path | str | list[str|tuple] | tuple[str]): Path to a requirements.txt file, a single package + requirement as a string, a list of package requirements as strings, or a list containing strings and tuples + of interchangeable packages. + exclude (tuple): Tuple of package names to exclude from checking. + install (bool): If True, attempt to auto-update packages that don't meet requirements. + cmds (str): Additional commands to pass to the pip install command when auto-updating. + constrain (tuple | list): Extra version constraints always appended to the install command even if already + satisfied, preventing the resolver from upgrading those packages during install. + + Examples: + >>> from ultralytics.utils.checks import check_requirements + + Check a requirements.txt file + >>> check_requirements("path/to/requirements.txt") + + Check a single package + >>> check_requirements("ultralytics>=8.3.200", cmds="--index-url https://download.pytorch.org/whl/cpu") + + Check multiple packages + >>> check_requirements(["numpy", "ultralytics"]) + + Check with interchangeable packages + >>> check_requirements([("onnxruntime", "onnxruntime-gpu"), "numpy"]) + """ + prefix = colorstr("red", "bold", "requirements:") + + if env_bool("ULTRALYTICS_SKIP_REQUIREMENTS_CHECKS"): + LOGGER.info(f"{prefix} ULTRALYTICS_SKIP_REQUIREMENTS_CHECKS detected, skipping requirements check.") + return True + + if isinstance(requirements, Path): # requirements.txt file + file = requirements.resolve() + assert file.exists(), f"{prefix} {file} not found, check failed." + requirements = [f"{x.name}{x.specifier}" for x in parse_requirements(file) if x.name not in exclude] + elif isinstance(requirements, str): + requirements = [requirements] + + pkgs = [] + for r in requirements: + candidates = r if isinstance(r, (list, tuple)) else [r] + satisfied = False + + for candidate in candidates: + r_stripped = candidate.rpartition("/")[-1].replace(".git", "") # replace git+https://org/repo.git -> 'repo' + match = re.match(r"([a-zA-Z0-9-_]+)([<>!=~]+.*)?", r_stripped) + name, required = match[1], match[2].strip() if match[2] else "" + try: + if check_version(metadata.version(name), required): + satisfied = True + break + except (AssertionError, metadata.PackageNotFoundError): + continue + + if not satisfied: + pkg = candidates[0] + if "git+" in pkg: # strip version constraints from git URLs for pip + url, sep, marker = pkg.partition(";") + pkg = re.sub(r"[<>!=~]+.*$", "", url) + sep + marker + pkgs.append(pkg) + + @Retry(times=2, delay=1) + def attempt_install(packages, commands, use_uv): + """Attempt package installation with uv if available, falling back to pip.""" + if use_uv: + # Use --python to explicitly target current interpreter (venv or system) + # This ensures correct installation when VIRTUAL_ENV env var isn't set + return subprocess.check_output( + [ + "uv", + "pip", + "install", + "--no-cache-dir", + "--python", + sys.executable, + *packages, + *shlex.split(commands), + "--index-strategy=unsafe-best-match", + "--break-system-packages", + ], + stderr=subprocess.STDOUT, + text=True, + ) + return subprocess.check_output( + [sys.executable, "-m", "pip", "install", "--no-cache-dir", *packages, *shlex.split(commands)], + stderr=subprocess.STDOUT, + text=True, + ) + + if pkgs: + packages = [*pkgs, *constrain] + if install and AUTOINSTALL: # check environment variable + # Note uv fails on arm64 macOS and Raspberry Pi runners + n = len(pkgs) # number of packages updates + LOGGER.info(f"{prefix} Ultralytics requirement{'s' * (n > 1)} {pkgs} not found, attempting AutoUpdate...") + try: + t = time.time() + assert ONLINE, "AutoUpdate skipped (offline)" + use_uv = not ARM64 and check_uv() # uv fails on ARM64 + LOGGER.info(attempt_install(packages, cmds, use_uv=use_uv)) + dt = time.time() - t + LOGGER.info(f"{prefix} AutoUpdate success ✅ {dt:.1f}s") + LOGGER.warning( + f"{prefix} {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n" + ) + except Exception as e: + msg = f"{prefix} ❌ {e}" + if hasattr(e, "output") and e.output: + msg += f"\n{e.output}" + LOGGER.warning(msg) + return False + else: + if install: # AutoUpdate disabled by environment variable + LOGGER.warning( + f"{prefix} Ultralytics requirement{'s' * (len(pkgs) > 1)} {pkgs} not found, AutoUpdate disabled by YOLO_AUTOINSTALL=False" + ) + return False + + return True + + +def check_executorch_requirements(): + """Check and install ExecuTorch requirements including platform-specific dependencies.""" + # BUG executorch build on arm64 Docker requires packaging>=22.0 https://github.com/pypa/setuptools/issues/4483 + if LINUX and ARM64 and IS_DOCKER: + check_requirements("packaging>=22.0") + + # executorch>=1.5 no longer declares its torch floor and its runtime fails below torch 2.13 with "tensor does not + # have a device", so cap it where pip can no longer pair the two itself + executorch = "executorch" if check_version(TORCH_VERSION, "2.13.0") else "executorch<1.5" + check_requirements(executorch, cmds=f"torch=={TORCH_VERSION.split('+')[0]}") + + +def check_tensorrt(min_version: str = "7.0.0"): + """Check and install TensorRT requirements including platform-specific dependencies. + + Args: + min_version (str): Minimum supported TensorRT version (default: "7.0.0"). + """ + if LINUX: + cuda_version = torch.version.cuda.split(".")[0] + check_requirements(f"tensorrt-cu{cuda_version}>={min_version},!=10.2.0") + + +def check_torchvision(): + """Check the installed versions of PyTorch and Torchvision to ensure they're compatible. + + This function checks the installed versions of PyTorch and Torchvision, and warns if they're incompatible according + to the compatibility table based on: https://github.com/pytorch/vision#installation. + """ + compatibility_table = { + "2.10": ["0.25"], + "2.9": ["0.24"], + "2.8": ["0.23"], + "2.7": ["0.22"], + "2.6": ["0.21"], + "2.5": ["0.20"], + "2.4": ["0.19"], + "2.3": ["0.18"], + "2.2": ["0.17"], + "2.1": ["0.16"], + "2.0": ["0.15"], + "1.13": ["0.14"], + "1.12": ["0.13"], + } + + # Check major and minor versions + v_torch = ".".join(TORCH_VERSION.split("+", 1)[0].split(".")[:2]) + if v_torch in compatibility_table: + compatible_versions = compatibility_table[v_torch] + v_torchvision = ".".join(TORCHVISION_VERSION.split("+", 1)[0].split(".")[:2]) + if all(v_torchvision != v for v in compatible_versions): + LOGGER.warning( + f"torchvision=={v_torchvision} is incompatible with torch=={v_torch}.\n" + f"Run 'pip install torchvision=={compatible_versions[0]}' to fix torchvision or " + "'pip install -U torch torchvision' to update both.\n" + "For a full compatibility table see https://github.com/pytorch/vision#installation" + ) + + +def check_suffix(file="yolo26n.pt", suffix=".pt", msg=""): + """Check file(s) for acceptable suffix. + + Args: + file (str | list[str]): File or list of files to check. + suffix (str | tuple): Acceptable suffix or tuple of suffixes. + msg (str): Additional message to display in case of error. + """ + if file and suffix: + if isinstance(suffix, str): + suffix = {suffix} + for f in file if isinstance(file, (list, tuple)) else [file]: + if s := clean_url(f).rpartition(".")[-1].lower().strip(): # file suffix + assert f".{s}" in suffix, f"{msg}{f} acceptable suffix is {suffix}, not .{s}" + + +def check_yolov5u_filename(file: str, verbose: bool = True) -> str: + """Replace legacy YOLOv5 filenames with updated YOLOv5u filenames. + + Args: + file (str): Filename to check and potentially update. + verbose (bool): Whether to print information about the replacement. + + Returns: + (str): Updated filename. + """ + if "yolov3" in file or "yolov5" in file: + if "u.yaml" in file: + file = file.replace("u.yaml", ".yaml") # i.e. yolov5nu.yaml -> yolov5n.yaml + elif ".pt" in file and "u" not in file: + original_file = file + file = re.sub(r"(.*yolov5([nsmlx]))\.pt", "\\1u.pt", file) # i.e. yolov5n.pt -> yolov5nu.pt + file = re.sub(r"(.*yolov5([nsmlx])6)\.pt", "\\1u.pt", file) # i.e. yolov5n6.pt -> yolov5n6u.pt + file = re.sub(r"(.*yolov3(|-tiny|-spp))\.pt", "\\1u.pt", file) # i.e. yolov3-spp.pt -> yolov3-sppu.pt + if file != original_file and verbose: + LOGGER.info( + f"PRO TIP 💡 Replace 'model={original_file}' with new 'model={file}'.\nYOLOv5 'u' models are " + f"trained with https://github.com/ultralytics/ultralytics and feature improved performance vs " + f"standard YOLOv5 models trained with https://github.com/ultralytics/yolov5." + ) + return file + + +def check_model_file_from_stem(model: str = "yolo11n") -> str | Path: + """Return a model filename from a valid model stem. + + Args: + model (str): Model stem to check. + + Returns: + (str | Path): Model filename with appropriate suffix. + """ + path = Path(model) + if not path.suffix and path.stem in downloads.GITHUB_ASSETS_STEMS: + return path.with_suffix(".pt") # add suffix, i.e. yolo26n -> yolo26n.pt + return model + + +def check_file(file, suffix="", download=True, download_dir=".", hard=True): + """Search/download file (if necessary), check suffix (if provided), and return path. + + Args: + file (str): File name or path, URL, platform URI (ul://), or GCS path (gs://). + suffix (str | tuple): Acceptable suffix or tuple of suffixes to validate against the file. + download (bool): Whether to download the file if it doesn't exist locally. + download_dir (str): Directory to download the file to. + hard (bool): Whether to raise an error if the file is not found. + + Returns: + (str | list): Path to the file, or an empty list if not found. + """ + file = normalize_platform_uri(file) # accept Platform web URLs (rewritten to ul://) + check_suffix(file, suffix) # optional + file = str(file).strip() # convert to string and strip spaces + file = check_yolov5u_filename(file) # yolov5n -> yolov5nu + if ( + not file + or ("://" not in file and Path(file).exists()) # '://' check required in Windows Python<3.10 + or file.lower().startswith("grpc://") + ): # file exists or gRPC Triton images + return file + elif download and file.lower().startswith("ul://"): # Ultralytics Platform URI + url = resolve_platform_uri(file, hard=hard) # Convert to signed HTTPS URL + if url is None: + return [] # Not found, soft fail (consistent with file search behavior) + # Use URI path for unique directory structure: ul://user/project/model -> user/project/model/filename.pt + uri_path = Path(file[5:]) # Remove "ul://" + if uri_path.is_absolute() or ".." in uri_path.parts: + raise ValueError(f"Unsafe Ultralytics Platform URI path: {file}") + local_file = Path(download_dir) / uri_path / url2file(url) + if local_file.exists(): + LOGGER.info(f"Found {clean_url(url)} locally at {local_file}") + else: + local_file.parent.mkdir(parents=True, exist_ok=True) + downloads.safe_download(url=url, file=local_file, unzip=False) + return str(local_file) + elif download and file.lower().startswith(REMOTE_FILE_PREFIXES): # download + if file.startswith("gs://"): + file = "https://storage.googleapis.com/" + file[5:] # convert gs:// to public HTTPS URL + url = file # warning: Pathlib turns :// -> :/ + file = Path(download_dir) / url2file(file) # '%2F' to '/', split authentication query strings + if file.exists(): + LOGGER.info(f"Found {clean_url(url)} locally at {file}") # file already exists + else: + downloads.safe_download(url=url, file=file, unzip=False) + return str(file) + else: # search + files = glob.glob(str(ROOT / "**" / file), recursive=True) or glob.glob(str(ROOT.parent / file)) # find file + if not files and hard: + raise FileNotFoundError(f"'{file}' does not exist") + elif len(files) > 1 and hard: + raise FileNotFoundError(f"Multiple files match '{file}', specify exact path: {files}") + return files[0] if len(files) else [] # return file + + +def check_yaml(file, suffix=(".yaml", ".yml"), hard=True): + """Search/download YAML file (if necessary) and return path, checking suffix. + + Args: + file (str | Path): File name or path. + suffix (tuple): Tuple of acceptable YAML file suffixes. + hard (bool): Whether to raise an error if the file is not found or multiple files are found. + + Returns: + (str): Path to the YAML file. + """ + return check_file(file, suffix, hard=hard) + + +def check_is_path_safe(basedir: Path | str, path: Path | str) -> bool: + """Check if the resolved path is under the intended directory to prevent path traversal. + + Args: + basedir (Path | str): The intended directory. + path (Path | str): The path to check. + + Returns: + (bool): True if the path is safe, False otherwise. + """ + base_dir_resolved = Path(basedir).resolve() + path_resolved = Path(path).resolve() + + return path_resolved.exists() and path_resolved.parts[: len(base_dir_resolved.parts)] == base_dir_resolved.parts + + +@functools.lru_cache +def check_imshow(warn=False): + """Check if environment supports image displays. + + Args: + warn (bool): Whether to warn if environment doesn't support image displays. + + Returns: + (bool): True if environment supports image displays, False otherwise. + """ + try: + if LINUX: + assert not IS_COLAB and not IS_KAGGLE + assert "DISPLAY" in os.environ, "The DISPLAY environment variable isn't set." + cv2.imshow("test", np.zeros((8, 8, 3), dtype=np.uint8)) # show a small 8-pixel image + cv2.waitKey(1) + cv2.destroyAllWindows() + cv2.waitKey(1) + return True + except Exception as e: + if warn: + LOGGER.warning(f"Environment does not support cv2.imshow() or PIL Image.show()\n{e}") + return False + + +def check_yolo(verbose=True, device=""): + """Print a human-readable YOLO software and hardware summary. + + Args: + verbose (bool): Whether to print verbose information. + device (str | torch.device): Device to use for YOLO. + """ + import psutil # scoped as slow import + + from ultralytics.utils.torch_utils import select_device + + if IS_COLAB: + shutil.rmtree("sample_data", ignore_errors=True) # remove colab /sample_data directory + + if verbose: + # System info + gib = 1 << 30 # bytes per GiB + ram = psutil.virtual_memory().total + total, _used, free = shutil.disk_usage("/") + s = f"({os.cpu_count()} CPUs, {ram / gib:.1f} GB RAM, {(total - free) / gib:.1f}/{total / gib:.1f} GB disk)" + try: + from IPython import display + + display.clear_output() # clear display if notebook + except ImportError: + pass + else: + s = "" + + if GIT.is_repo: + check_multiple_install() # check conflicting installation if using local clone + + select_device(device=device, newline=False) + LOGGER.info(f"Setup complete ✅ {s}") + + +def collect_system_info(): + """Collect and print relevant system information including OS, Python, RAM, CPU, and CUDA. + + Returns: + (dict): Dictionary containing system information. + """ + import psutil # scoped as slow import + + from ultralytics.utils import ENVIRONMENT # scope to avoid circular import + from ultralytics.utils.torch_utils import get_cpu_info, get_gpu_info + + gib = 1 << 30 # bytes per GiB + cuda = torch.cuda.is_available() + check_yolo() + total, _, free = shutil.disk_usage("/") + + info_dict = { + "OS": platform.platform(), + "Environment": ENVIRONMENT, + "Python": PYTHON_VERSION, + "Install": "git" if GIT.is_repo else "pip" if IS_PIP_PACKAGE else "other", + "Path": str(ROOT), + "RAM": f"{psutil.virtual_memory().total / gib:.2f} GB", + "Disk": f"{(total - free) / gib:.1f}/{total / gib:.1f} GB", + "CPU": get_cpu_info(), + "CPU count": os.cpu_count(), + "GPU": get_gpu_info(index=0) if cuda else None, + "GPU count": torch.cuda.device_count() if cuda else None, + "CUDA": torch.version.cuda if cuda else None, + } + LOGGER.info("\n" + "\n".join(f"{k:<23}{v}" for k, v in info_dict.items()) + "\n") + + package_info = {} + for r in parse_requirements(package=get_distribution_name("ultralytics")): + try: + current = metadata.version(r.name) + is_met = "✅ " if check_version(current, str(r.specifier), name=r.name) else "❌ " + except metadata.PackageNotFoundError: + current = "(not installed)" + is_met = "❌ " + package_info[r.name] = f"{is_met}{current}{r.specifier}" + LOGGER.info(f"{r.name:<23}{package_info[r.name]}") + + info_dict["Package Info"] = package_info + + if is_github_action_running(): + github_info = { + "RUNNER_OS": os.getenv("RUNNER_OS"), + "GITHUB_EVENT_NAME": os.getenv("GITHUB_EVENT_NAME"), + "GITHUB_WORKFLOW": os.getenv("GITHUB_WORKFLOW"), + "GITHUB_ACTOR": os.getenv("GITHUB_ACTOR"), + "GITHUB_REPOSITORY": os.getenv("GITHUB_REPOSITORY"), + "GITHUB_REPOSITORY_OWNER": os.getenv("GITHUB_REPOSITORY_OWNER"), + } + LOGGER.info("\n" + "\n".join(f"{k}: {v}" for k, v in github_info.items())) + info_dict["GitHub Info"] = github_info + + return info_dict + + +def check_amp(model): + """Check the PyTorch Automatic Mixed Precision (AMP) functionality of a YOLO model. + + If the checks fail, it means there are anomalies with AMP on the system that may cause NaN losses or zero-mAP + results, so AMP will be disabled during training. + + Args: + model (torch.nn.Module): A YOLO model instance. + + Returns: + (bool): Returns True if the AMP functionality works correctly with YOLO model, else False. + + Examples: + >>> from ultralytics import YOLO + >>> from ultralytics.utils.checks import check_amp + >>> model = YOLO("yolo26n.pt").model.cuda() + >>> check_amp(model) + """ + from ultralytics.utils.torch_utils import autocast + + device = next(model.parameters()).device # get model device + prefix = colorstr("AMP: ") + if device.type in {"cpu", "mps"}: + return False # AMP only used on accelerator devices + elif device.type == "cuda": + # GPUs that have issues with AMP + pattern = re.compile( + r"(nvidia|geforce|quadro|tesla).*?(1660|1650|1630|t400|t550|t600|t1000|t1200|t2000|k40m)", re.IGNORECASE + ) + + gpu = torch.cuda.get_device_name(device) + if bool(pattern.search(gpu)): + LOGGER.warning( + f"{prefix}checks failed ❌. AMP training on {gpu} GPU may cause " + f"NaN losses or zero-mAP results, so AMP will be disabled during training." + ) + return False + + def amp_allclose(m, im): + """All close FP32 vs AMP results.""" + batch = [im] * 8 + imgsz = max(256, int(model.stride.max() * 4)) # max stride P5-32 and P6-64 + a = m(batch, imgsz=imgsz, device=device, verbose=False)[0].boxes.data # FP32 inference + with autocast(enabled=True, device=device.type): + b = m(batch, imgsz=imgsz, device=device, verbose=False)[0].boxes.data # AMP inference + del m + return a.shape == b.shape and torch.allclose(a, b.float(), atol=0.5) # close to 0.5 absolute tolerance + + im = ASSETS / "bus.jpg" # image to check + LOGGER.info(f"{prefix}running Automatic Mixed Precision (AMP) checks...") + warning_msg = "Setting 'amp=True'. If you experience zero-mAP or NaN losses you can disable AMP with amp=False." + try: + from ultralytics import YOLO + from ultralytics.utils import WEIGHTS_DIR + + amp_weights = WEIGHTS_DIR / "yolo26n.pt" + if not amp_weights.is_file(): + LOGGER.info(f"{prefix}downloading yolo26n.pt for AMP checks (one-time, not used for training)...") + assert amp_allclose(YOLO(amp_weights), im) + LOGGER.info(f"{prefix}checks passed ✅") + except ConnectionError: + LOGGER.warning(f"{prefix}checks skipped. Offline and unable to download YOLO26n for AMP checks. {warning_msg}") + except (AttributeError, ModuleNotFoundError): + LOGGER.warning( + f"{prefix}checks skipped. " + f"Unable to load YOLO26n for AMP checks due to possible Ultralytics package modifications. {warning_msg}" + ) + except AssertionError: + LOGGER.error( + f"{prefix}checks failed. Anomalies were detected with AMP on your system that may lead to " + f"NaN losses or zero-mAP results, so AMP will be disabled during training." + ) + return False + return True + + +def check_multiple_install(): + """Check if there are multiple Ultralytics installations.""" + import sys + + try: + result = subprocess.run( + [sys.executable, "-m", "pip", "show", "ultralytics"], capture_output=True, text=True, check=False + ) + install_msg = ( + f"Install your local copy in editable mode with 'pip install -e {ROOT.parent}' to avoid " + "issues. See https://docs.ultralytics.com/quickstart" + ) + if result.returncode != 0: + if "not found" in result.stderr.lower(): # Package not pip-installed but locally imported + LOGGER.warning(f"Ultralytics not found via pip but importing from: {ROOT}. {install_msg}") + return + yolo_path = ( + Path(re.findall(r"location:\s+(.+)", result.stdout, flags=re.IGNORECASE)[-1]) / "ultralytics" + ).resolve() + if not yolo_path.samefile(ROOT.resolve()): + LOGGER.warning( + f"Multiple Ultralytics installations detected. The `yolo` command uses: {yolo_path}, " + f"but current session imports from: {ROOT}. This may cause version conflicts. {install_msg}" + ) + except Exception: + return + + +def print_args(args: dict | None = None, show_file=True, show_func=False): + """Print function arguments (optional args dict). + + Args: + args (dict, optional): Arguments to print. + show_file (bool): Whether to show the file name. + show_func (bool): Whether to show the function name. + """ + + def strip_auth(v): + """Clean longer URLs by stripping potential authentication information.""" + return clean_url(v) if (isinstance(v, str) and v.startswith("http") and len(v) > 100) else v + + x = inspect.currentframe().f_back # previous frame + file, _, func, _, _ = inspect.getframeinfo(x) + if args is None: # get args automatically + args, _, _, frm = inspect.getargvalues(x) + args = {k: v for k, v in frm.items() if k in args} + try: + file = Path(file).resolve().relative_to(ROOT).with_suffix("") + except ValueError: + file = Path(file).stem + s = (f"{file}: " if show_file else "") + (f"{func}: " if show_func else "") + LOGGER.info(colorstr(s) + ", ".join(f"{k}={strip_auth(v)}" for k, v in sorted(args.items()))) + + +def cuda_device_count() -> int: + """Get the number of NVIDIA GPUs available in the environment. + + Returns: + (int): The number of NVIDIA GPUs available. + """ + if IS_JETSON: + # NVIDIA Jetson does not fully support nvidia-smi and therefore use PyTorch instead + return torch.cuda.device_count() + else: + try: + # Run the nvidia-smi command and capture its output + output = subprocess.check_output( + ["nvidia-smi", "--query-gpu=count", "--format=csv,noheader,nounits"], encoding="utf-8" + ) + + # Take the first line and strip any leading/trailing white space + first_line = output.strip().split("\n", 1)[0] + + return int(first_line) + except (subprocess.CalledProcessError, FileNotFoundError, ValueError): + # If the command fails, nvidia-smi is not found, or output is not an integer, assume no GPUs are available + return 0 + + +def cuda_is_available() -> bool: + """Check if CUDA is available in the environment. + + Returns: + (bool): True if one or more NVIDIA GPUs are available, False otherwise. + """ + return cuda_device_count() > 0 + + +def is_rockchip(): + """Check if the current environment is running on a Rockchip SoC. + + Returns: + (bool): True if running on a Rockchip SoC, False otherwise. + """ + if LINUX and ARM64: + try: + with open("/proc/device-tree/compatible") as f: + dev_str = f.read() + *_, soc = dev_str.split(",") + if soc.replace("\x00", "").split("-", 1)[0] in RKNN_CHIPS: + return True + except OSError: + return False + else: + return False + + +def is_intel(): + """Check if the system has Intel hardware (CPU or GPU). + + Returns: + (bool): True if Intel hardware is detected, False otherwise. + """ + from ultralytics.utils.torch_utils import get_cpu_info + + # Check CPU + if "intel" in get_cpu_info().lower(): + return True + + # Check GPU via xpu-smi + try: + result = subprocess.run(["xpu-smi", "discovery"], capture_output=True, text=True, timeout=5, check=False) + return "intel" in result.stdout.lower() + except Exception: # broad clause to capture all Intel GPU exception types + return False + + +def is_sudo_available() -> bool: + """Check if the sudo command is available in the environment. + + Returns: + (bool): True if the sudo command is available, False otherwise. + """ + if WINDOWS: + return False + cmd = "sudo --version" + return ( + subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False).returncode + == 0 + ) + + +# Run checks and define constants +check_python("3.8", hard=False, verbose=True) # check python version +check_torchvision() # check torch-torchvision compatibility + +# Define constants +IS_PYTHON_3_8 = PYTHON_VERSION.startswith("3.8") +IS_PYTHON_3_9 = PYTHON_VERSION.startswith("3.9") +IS_PYTHON_3_10 = PYTHON_VERSION.startswith("3.10") +IS_PYTHON_3_12 = PYTHON_VERSION.startswith("3.12") +IS_PYTHON_3_13 = PYTHON_VERSION.startswith("3.13") + +IS_PYTHON_MINIMUM_3_9 = check_python("3.9", hard=False) +IS_PYTHON_MINIMUM_3_10 = check_python("3.10", hard=False) +IS_PYTHON_MINIMUM_3_12 = check_python("3.12", hard=False) +IS_PYTHON_MINIMUM_3_13 = check_python("3.13", hard=False) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/cpu.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/cpu.py new file mode 100644 index 0000000000000000000000000000000000000000..a7812dcd968ae85bcecc247dde23fd593d43762f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/cpu.py @@ -0,0 +1,104 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import ctypes +import platform +import re +import sys +from pathlib import Path + + +class CPUInfo: + """Provide cross-platform CPU brand and model information. + + Query platform-specific sources to retrieve a human-readable CPU descriptor and normalize it for consistent + presentation across macOS, Linux, and Windows. If platform-specific probing fails, generic platform identifiers are + used to ensure a stable string is always returned. + + Methods: + name: Return the normalized CPU name using platform-specific sources with robust fallbacks. + _sysctl: Read a macOS sysctl string through libc. + _clean: Normalize and prettify common vendor brand strings and frequency patterns. + __str__: Return the normalized CPU name for string contexts. + + Examples: + >>> name = CPUInfo.name() + >>> text = str(CPUInfo()) + """ + + @staticmethod + def _sysctl(key: str) -> str: + """Read a macOS sysctl string through libc, since spawning `sysctl` costs milliseconds.""" + libc = ctypes.CDLL(None) + libc.sysctlbyname.restype = ctypes.c_int + libc.sysctlbyname.argtypes = [ + ctypes.c_char_p, + ctypes.c_void_p, + ctypes.POINTER(ctypes.c_size_t), + ctypes.c_void_p, + ctypes.c_size_t, + ] + name, n = key.encode(), ctypes.c_size_t(0) + if libc.sysctlbyname(name, None, ctypes.byref(n), None, 0) or not n.value: # size probe + return "" + buf = ctypes.create_string_buffer(n.value) + if libc.sysctlbyname(name, buf, ctypes.byref(n), None, 0): + return "" + return buf.value.decode(errors="ignore").strip() + + @staticmethod + def name() -> str: + """Return a normalized CPU model string from platform-specific sources.""" + try: + if sys.platform == "darwin": + # Query macOS sysctl for the CPU brand string + s = CPUInfo._sysctl("machdep.cpu.brand_string") + if s: + return CPUInfo._clean(s) + elif sys.platform.startswith("linux"): + # Parse /proc/cpuinfo for the first "model name" entry, streaming since a many-core host + # repeats a full block per logical CPU and only the first is needed + p = Path("/proc/cpuinfo") + if p.exists(): + with p.open(errors="ignore") as f: + for line in f: + if "model name" in line: + return CPUInfo._clean(line.split(":", 1)[1]) + elif sys.platform.startswith("win"): + try: + import winreg as wr + + with wr.OpenKey(wr.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") as k: + val, _ = wr.QueryValueEx(k, "ProcessorNameString") + if val: + return CPUInfo._clean(val) + except Exception: + # Fall through to generic platform fallbacks on Windows registry access failure + pass + # Generic platform fallbacks + s = platform.processor() or getattr(platform.uname(), "processor", "") or platform.machine() + return CPUInfo._clean(s or "Unknown CPU") + except Exception: + # Ensure a string is always returned even on unexpected failures + s = platform.processor() or platform.machine() or "" + return CPUInfo._clean(s or "Unknown CPU") + + @staticmethod + def _clean(s: str) -> str: + """Normalize and prettify a raw CPU descriptor string.""" + s = re.sub(r"\s+", " ", s.strip()) + s = s.replace("(TM)", "").replace("(tm)", "").replace("(R)", "").replace("(r)", "").strip() + if m := re.search(r"(Intel.*?i\d[\w-]*) CPU @ ([\d.]+GHz)", s, re.IGNORECASE): + return f"{m.group(1)} {m.group(2)}" + if m := re.search(r"(AMD.*?Ryzen.*?[\w-]*) CPU @ ([\d.]+GHz)", s, re.IGNORECASE): + return f"{m.group(1)} {m.group(2)}" + return s + + def __str__(self) -> str: + """Return the normalized CPU name.""" + return self.name() + + +if __name__ == "__main__": + print(CPUInfo.name()) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/dist.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/dist.py new file mode 100644 index 0000000000000000000000000000000000000000..63949a26f766d077b4748a412018b3caf3944407 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/dist.py @@ -0,0 +1,159 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import os +import shutil +import sys +import tempfile +from pathlib import Path +from typing import TYPE_CHECKING + +from . import USER_CONFIG_DIR +from .patches import torch_save +from .torch_utils import TORCH_1_9 + +if TYPE_CHECKING: + from ultralytics.engine.trainer import BaseTrainer + + +def find_free_network_port() -> int: + """Find a free port on localhost. + + It is useful in single-node training when we don't want to connect to a real main node but have to set the + `MASTER_PORT` environment variable. + + Returns: + (int): The available network port number. + + Notes: + Candidates are drawn below the default OS ephemeral floor (32768 on Linux, 49152 on macOS and Windows) + because the port is released here and rebound later by the DDP subprocess. An ephemeral port can be handed to + any outbound connection in that window, which surfaces as an EADDRINUSE rendezvous failure at launch. + """ + import random + import socket + + # SystemRandom as init_seeds() seeds the global RNG earlier in this process, which would hand every concurrent + # DDP launch on a host the same candidate list + for port in random.SystemRandom().sample(range(10000, 32768), 10): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + try: + s.bind(("127.0.0.1", port)) + return port + except OSError: + continue # in use by an explicit listener, try the next candidate + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) # no non-ephemeral candidate available, fall back to an ephemeral port + return s.getsockname()[1] + + +def generate_ddp_file(trainer: BaseTrainer) -> str: + """Generate a DDP (Distributed Data Parallel) file for multi-GPU training. + + This function creates a temporary Python file that enables distributed training across multiple GPUs. The file + contains the necessary configuration to initialize the trainer in a distributed environment. + + Args: + trainer (ultralytics.engine.trainer.BaseTrainer): The trainer containing training configuration and arguments. + Must have args attribute and be a class instance. + + Returns: + (str): Path to the generated temporary DDP file. + + Notes: + The generated file is saved in the USER_CONFIG_DIR/DDP directory and includes: + - Trainer class and callback reconstruction + - Configuration overrides from the trainer arguments + - Training initialization code + """ + import cloudpickle + + (USER_CONFIG_DIR / "DDP").mkdir(exist_ok=True) + with tempfile.NamedTemporaryFile( + prefix="_temp_", + suffix=f"{id(trainer)}.py", + mode="w+", + encoding="utf-8", + dir=USER_CONFIG_DIR / "DDP", + delete=False, + ) as file: + path = Path(file.name).with_suffix(".pt") + torch_save( + { + "trainer": type(trainer), + "args": vars(trainer.args), + "model": trainer.model, + "callbacks": trainer.callbacks, + }, + path, + pickle_module=cloudpickle, + ) + file.write( + f""" +# Ultralytics Multi-GPU training temp file (should be automatically deleted after use) +if __name__ == "__main__": + import sys + sys.path = {sys.path!r} + + from ultralytics.utils import DEFAULT_CFG_DICT + from ultralytics.utils.patches import torch_load + + state = torch_load({str(path)!r}, map_location="cpu") + + cfg = DEFAULT_CFG_DICT.copy() + cfg.update(save_dir='') # handle the extra key 'save_dir' + trainer = state["trainer"](cfg=cfg, overrides=state["args"], _callbacks=state["callbacks"]) + trainer.model = state["model"] + trainer.train() +""" + ) + return file.name + + +def generate_ddp_command(trainer: BaseTrainer) -> tuple[list[str], str]: + """Generate command for distributed training. + + Args: + trainer (ultralytics.engine.trainer.BaseTrainer): The trainer containing configuration for distributed training. + + Returns: + cmd (list[str]): The command to execute for distributed training. + file (str): Path to the temporary file created for DDP training. + """ + if not trainer.resume: + shutil.rmtree(trainer.save_dir) # remove the save_dir + file = generate_ddp_file(trainer) + dist_cmd = "torch.distributed.run" if TORCH_1_9 else "torch.distributed.launch" + port = find_free_network_port() + cmd = [ + sys.executable, + "-m", + dist_cmd, + "--nproc_per_node", + f"{trainer.world_size}", + "--master_port", + f"{port}", + file, + ] + return cmd, file + + +def ddp_cleanup(trainer: BaseTrainer, file: str) -> None: + """Delete temporary file if created during distributed data parallel (DDP) training. + + This function checks if the provided file contains the trainer's ID in its name, indicating it was created as a + temporary file for DDP training, and deletes it if so. + + Args: + trainer (ultralytics.engine.trainer.BaseTrainer): The trainer used for distributed training. + file (str): Path to the file that might need to be deleted. + + Examples: + >>> trainer = YOLOTrainer() + >>> file = "/tmp/ddp_temp_123456789.py" + >>> ddp_cleanup(trainer, file) + """ + if f"{id(trainer)}.py" in file: # if temp_file suffix in file + os.remove(file) + Path(file).with_suffix(".pt").unlink(missing_ok=True) # the state written for the workers diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/downloads.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/downloads.py new file mode 100644 index 0000000000000000000000000000000000000000..8b811b48221d2857d384cd4e368c896aad79e40e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/downloads.py @@ -0,0 +1,662 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import re +import shutil +import subprocess +import tarfile +import zlib +from itertools import repeat +from multiprocessing.pool import ThreadPool +from pathlib import Path +from urllib import parse +from uuid import uuid4 + +from ultralytics.utils import ASSETS_URL, LOGGER, TQDM, checks, clean_url, emojis, is_online, url2file + +# Define Ultralytics GitHub assets maintained at https://github.com/ultralytics/assets +GITHUB_ASSETS_REPO = "ultralytics/assets" +GITHUB_ASSETS_NAMES = frozenset( + [f"yolov8{k}{suffix}.pt" for k in "nsmlx" for suffix in ("", "-cls", "-seg", "-pose", "-obb", "-oiv7")] + + [f"yolo11{k}{suffix}.pt" for k in "nsmlx" for suffix in ("", "-cls", "-seg", "-pose", "-obb")] + + [f"yolo12{k}{suffix}.pt" for k in "nsmlx" for suffix in ("",)] # detect models only currently + + [f"yolo26{k}{suffix}.pt" for k in "nsmlx" for suffix in ("", "-cls", "-seg", "-sem", "-pose", "-obb", "-depth")] + + [f"yolo26{k}-objv1{suffix}.pt" for k in "nsmlx" for suffix in ("-150", "-seg")] + + [f"yolo26{k}-{suffix}.pt" for k in "nsmlx" for suffix in ("distill", "sem-ade20k")] + + [f"yolo26{k}-reid.onnx" for k in "nsmlx"] + + [f"yolov5{k}{resolution}u.pt" for k in "nsmlx" for resolution in ("", "6")] + + [f"yolov3{k}u.pt" for k in ("", "-spp", "-tiny")] + + [f"yolov8{k}-world.pt" for k in "smlx"] + + [f"yolov8{k}-worldv2.pt" for k in "smlx"] + + [f"yoloe-v8{k}{suffix}.pt" for k in "sml" for suffix in ("-seg", "-seg-pf")] + + [f"yoloe-11{k}{suffix}.pt" for k in "sml" for suffix in ("-seg", "-seg-pf")] + + [f"yoloe-26{k}{suffix}.pt" for k in "nsmlx" for suffix in ("-seg", "-seg-pf")] + + [f"yolov9{k}.pt" for k in "tsmce"] + + [f"yolov9{k}-seg.pt" for k in "ce"] + + [f"yolov10{k}.pt" for k in "nsmblx"] + + [f"yolo_nas_{k}.pt" for k in "sml"] + + [f"sam_{k}.pt" for k in "bl"] + + [f"sam2_{k}.pt" for k in "blst"] + + [f"sam2.1_{k}.pt" for k in "blst"] + + [f"FastSAM-{k}.pt" for k in "sx"] + + [f"rtdetr-{k}.pt" for k in "lx"] + + [ + "mobile_sam.pt", + "mobileclip_blt.ts", + "mobileclip2_b.ts", + "yolo11n-grayscale.pt", + "yolov8x-pose-p6.pt", + "calibration_image_sample_data_20x128x128x3_float32.npy.zip", + ] +) +GITHUB_ASSETS_STEMS = frozenset(k.rpartition(".")[0] for k in GITHUB_ASSETS_NAMES) + + +def is_url(url: str | Path, check: bool = False) -> bool: + """Validate if the given string is a URL and optionally check if the URL exists online. + + Args: + url (str | Path): The string to be validated as a URL. + check (bool, optional): If True, performs an additional check to see if the URL exists online. + + Returns: + (bool): True for a valid URL. If 'check' is True, also returns True if the URL exists online. + + Examples: + >>> valid = is_url("https://www.example.com") + >>> valid_and_exists = is_url("https://www.example.com", check=True) + """ + try: + url = str(url) + result = parse.urlparse(url) + if not (result.scheme and result.netloc): + return False + if check: + import requests # scoped as slow import + + return requests.head(url, timeout=3, allow_redirects=True).ok + return True + except Exception: + return False + + +def delete_dsstore(path: str | Path, files_to_delete: tuple[str, ...] = (".DS_Store", "__MACOSX")) -> None: + """Delete all specified system files and directories in a directory. + + Args: + path (str | Path): The directory path where the files should be deleted. + files_to_delete (tuple[str, ...]): Names of files and directories to delete. + + Examples: + >>> from ultralytics.utils.downloads import delete_dsstore + >>> delete_dsstore("path/to/dir") + + Notes: + ".DS_Store" files are created by the Apple operating system and contain metadata about folders and files. They + are hidden system files and can cause issues when transferring files between different operating systems. + """ + for file in files_to_delete: + matches = sorted(Path(path).rglob(file), key=lambda x: len(x.parts), reverse=True) + LOGGER.info(f"Deleting {file} files: {matches}") + for f in matches: + if f.is_dir() and not f.is_symlink(): + shutil.rmtree(f) + else: + f.unlink() + + +def zip_directory( + directory: str | Path, + compress: bool = True, + exclude: tuple[str, ...] = (".DS_Store", "__MACOSX"), + progress: bool = True, +) -> Path: + """Zip the contents of a directory, excluding specified files. + + The resulting zip file is named after the directory and placed alongside it. + + Args: + directory (str | Path): The path to the directory to be zipped. + compress (bool): Whether to compress the files while zipping. + exclude (tuple[str, ...], optional): A tuple of filename strings to be excluded. + progress (bool, optional): Whether to display a progress bar. + + Returns: + (Path): The path to the resulting zip file. + + Examples: + >>> from ultralytics.utils.downloads import zip_directory + >>> file = zip_directory("path/to/dir") + """ + from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile + + delete_dsstore(directory) + directory = Path(directory) + if not directory.is_dir(): + raise FileNotFoundError(f"Directory '{directory}' does not exist.") + + # Zip with progress bar + files = [f for f in directory.rglob("*") if f.is_file() and all(x not in f.name for x in exclude)] # files to zip + zip_file = directory.with_suffix(".zip") + compression = ZIP_DEFLATED if compress else ZIP_STORED + with ZipFile(zip_file, "w", compression) as f: + for file in TQDM(files, desc=f"Zipping {directory} to {zip_file}...", unit="files", disable=not progress): + f.write(file, file.relative_to(directory)) + + return zip_file # return path to zip file + + +def unzip_file( + file: str | Path, + path: str | Path | None = None, + exclude: tuple[str, ...] = (".DS_Store", "__MACOSX"), + exist_ok: bool = False, + progress: bool = True, +) -> Path: + """Unzip a *.zip file to the specified path, excluding specified files. + + If the zipfile does not contain a single top-level directory, the function will create a new directory with the same + name as the zipfile (without the extension) to extract its contents. If a path is not provided, the function will + use the parent directory of the zipfile as the default path. + + Args: + file (str | Path): The path to the zipfile to be extracted. + path (str | Path, optional): The path to extract the zipfile to. + exclude (tuple[str, ...], optional): A tuple of filename strings to be excluded. + exist_ok (bool, optional): Whether to overwrite existing contents if they exist. + progress (bool, optional): Whether to display a progress bar. + + Returns: + (Path): The path to the directory where the zipfile was extracted. + + Raises: + BadZipFile: If the provided file does not exist or is not a valid zipfile. + + Examples: + >>> from ultralytics.utils.downloads import unzip_file + >>> directory = unzip_file("path/to/file.zip") + """ + from zipfile import BadZipFile, ZipFile, is_zipfile + + if not (Path(file).exists() and is_zipfile(file)): + raise BadZipFile(f"File '{file}' does not exist or is a bad zip file.") + if path is None: + path = Path(file).parent # default path + + # Unzip the file contents + with ZipFile(file) as zipObj: + files = [f for f in zipObj.namelist() if all(x not in f for x in exclude)] + top_level_dirs = {Path(f).parts[0] for f in files} + + # Decide to unzip directly or unzip into a directory + unzip_as_dir = len(top_level_dirs) == 1 # (len(files) > 1 and not files[0].endswith("/")) + if unzip_as_dir: + # Zip has 1 top-level directory + extract_path = path # i.e. ../datasets + path = Path(path) / next(iter(top_level_dirs)) # i.e. extract coco8/ dir to ../datasets/ + else: + # Zip has multiple files at top level + path = extract_path = Path(path) / Path(file).stem # i.e. extract multiple files to ../datasets/coco8/ + + # Skip existing files or non-empty directories unless overwriting + if path.exists() and (path.is_file() or any(path.iterdir())) and not exist_ok: + LOGGER.warning(f"Skipping {file} unzip as destination path {path} already exists.") + return path + + extract_path = Path(extract_path).resolve() + for f in TQDM(files, desc=f"Unzipping {file} to {Path(path).resolve()}...", unit="files", disable=not progress): + f_path = Path(f) + target = (extract_path / f_path).resolve() + if ( + f_path.is_absolute() + or ".." in f_path.parts + or target.parts[: len(extract_path.parts)] != extract_path.parts + ): + LOGGER.warning(f"Potentially insecure file path: {f}, skipping extraction.") + continue + zipObj.extract(f, extract_path) + + return path # return unzip dir + + +def check_disk_space( + file_bytes: int, + path: str | Path | None = None, + sf: float = 1.5, + hard: bool = True, +) -> bool: + """Check if there is sufficient disk space to download and store a file. + + Args: + file_bytes (int): The file size in bytes. + path (str | Path, optional): The path or drive to check the available free space on. + sf (float, optional): Safety factor, the multiplier for the required free space. + hard (bool, optional): Whether to throw an error or not on insufficient disk space. + + Returns: + (bool): True if there is sufficient disk space, False otherwise. + """ + total, _used, free = shutil.disk_usage(path or Path.cwd()) # bytes + # A filesystem that cannot report usage returns 0 total blocks; free == 0 against a valid total is genuinely + # full and must still be caught, since `free` counts blocks available to an unprivileged process. + if not total or file_bytes * sf < free: + return True # sufficient space + + def fmt_bytes(b): + if b < (1 << 20): # without a KB tier every value under 51 KB renders "0.0 MB", hiding how full the disk is + return f"{b / (1 << 10):.1f} KB" + return f"{b / (1 << 20):.1f} MB" if b < (1 << 30) else f"{b / (1 << 30):.3f} GB" + + # Insufficient space + text = ( + f"Insufficient free disk space {fmt_bytes(free)} < {fmt_bytes(int(file_bytes * sf))} required, " + f"Please free {fmt_bytes(int(file_bytes * sf - free))} additional disk space and try again." + ) + if hard: + raise MemoryError(text) + LOGGER.warning(text) + return False + + +def get_google_drive_file_info(link: str) -> tuple[str, str | None]: + """Retrieve the direct download link and filename for a shareable Google Drive file link. + + Args: + link (str): The shareable link of the Google Drive file. + + Returns: + url (str): Direct download URL for the Google Drive file. + filename (str | None): Original filename of the Google Drive file. If filename extraction fails, returns None. + + Examples: + >>> from ultralytics.utils.downloads import get_google_drive_file_info + >>> link = "https://drive.google.com/file/d/1cqT-cJgANNrhIHCrEufUYhQ4RqiWG_lJ/view?usp=drive_link" + >>> url, filename = get_google_drive_file_info(link) + """ + import requests # scoped as slow import + + file_id = link.split("/d/")[1].split("/view", 1)[0] + drive_url = f"https://drive.google.com/uc?export=download&id={file_id}" + filename = None + + # Start session + with requests.Session() as session: + response = session.get(drive_url, stream=True) + if "quota exceeded" in str(response.content.lower()): + raise ConnectionError( + emojis( + f"❌ Google Drive file download quota exceeded. " + f"Please try again later or download this file manually at {link}." + ) + ) + for k, v in response.cookies.items(): + if k.startswith("download_warning"): + drive_url += f"&confirm={v}" # v is token + if cd := response.headers.get("content-disposition"): + filename = re.findall('filename="(.+)"', cd)[0] + return drive_url, filename + + +def safe_download( + url: str | Path, + file: str | Path | None = None, + dir: str | Path | None = None, + unzip: bool = True, + delete: bool = False, + curl: bool = False, + retry: int = 3, + min_bytes: float = 1e0, + exist_ok: bool = False, + progress: bool = True, +) -> Path | str: + """Download files from a URL with options for retrying, unzipping, and deleting the downloaded file. Enhanced with + robust partial download detection using Content-Length validation. + + Args: + url (str | Path): The URL of the file to be downloaded. + file (str | Path, optional): The filename of the downloaded file. If not provided, the file will be saved with + the same name as the URL. + dir (str | Path, optional): The directory to save the downloaded file. If not provided, the file will be saved + in the current working directory. + unzip (bool, optional): Whether to unzip the downloaded file. + delete (bool, optional): Whether to delete the downloaded file after unzipping. + curl (bool, optional): Whether to use curl command line tool for downloading. + retry (int, optional): The number of times to retry the download in case of failure. + min_bytes (float, optional): The minimum number of bytes that the downloaded file should have, to be considered + a successful download. + exist_ok (bool, optional): Whether to overwrite existing contents during unzipping. + progress (bool, optional): Whether to display a progress bar during the download. + + Returns: + (Path | str): The path to the downloaded file or extracted directory. + + Examples: + >>> from ultralytics.utils.downloads import safe_download + >>> link = "https://ultralytics.com/assets/bus.jpg" + >>> path = safe_download(link) + """ + url = str(url) + if "://" not in url and Path(url).is_file(): # local file path ('://' check required in Windows Python<3.10) + f = Path(url) + else: + import requests # scoped as slow import + + gdrive = url.startswith("https://drive.google.com/") # check if the URL is a Google Drive link + if gdrive: + url, file = get_google_drive_file_info(url) + url = url.replace(" ", "%20") # encode spaces for curl compatibility + + f = Path(dir or ".") / (file or url2file(url)) # URL converted to filename + if not f.is_file(): # URL and file do not exist + uri = (url if gdrive else clean_url(url)).replace(ASSETS_URL, "https://ultralytics.com/assets") # clean + desc = f"Downloading {uri} to '{f}'" + f.parent.mkdir(parents=True, exist_ok=True) # make directory if missing + target = f + f = target.with_name(f".{target.name}.{uuid4().hex}.part") # publish only after size validation + curl_installed = shutil.which("curl") + expected_size = 0 # total bytes from Content-Length, kept across retries to validate them + # Both transports save the body as sent, so Content-Length and Range describe the file even when the server + # encodes it despite `Accept-Encoding: identity`, e.g. gzip objects on S3; it is decoded once complete + encoding = "" + for i in range(retry + 1): + try: + resume = f.stat().st_size if f.exists() else 0 # partial bytes kept from a failed attempt + if (curl or i > 0) and not resume and curl_installed: # curl download or fallback + s = "sS" * (not progress) # silent + # Stall bounds (not a total-transfer cap): abort if <1 B/s for 300 s so a dead connection + # cannot block interpreter shutdown while a non-daemon plot thread waits on a font download + args = ["--retry", "4", "--connect-timeout", "30", "--speed-limit", "1", "--speed-time", "300"] + # -f is required: without it curl writes the server error page as the file and exits 0 + r = subprocess.run( + ["curl", "-#", f"-{s}fL", url, "-o", f, "-D", "-", *args], + check=False, + stdout=subprocess.PIPE, + ) + if r.returncode: + raise ConnectionError(f"Curl return value {r.returncode}") + # Final response, after any redirect, proxy or retry blocks and before any trailer block + final_headers = [h for h in r.stdout.split(b"\r\n\r\n") if h.startswith(b"HTTP/")][-1] + encoding = ( + b"".join(re.findall(rb"(?im)^content-encoding:\s*(\S+)", final_headers)).decode().lower() + ) + else: # requests download; timeout bounds connect and per-chunk read gaps, not total transfer + headers = {"Accept-Encoding": "identity"} + if resume: + headers["Range"] = f"bytes={resume}-" + with requests.get(url, stream=True, headers=headers, timeout=(30, 300)) as response: + if response.status_code == 416: # nothing left to resume, so the next retry restarts + f.unlink() + response.raise_for_status() + encoding = response.headers.get("Content-Encoding", "").lower() + if response.status_code != 206: # Range ignored, e.g. transcoded GCS objects, so restart + resume = 0 + expected_size = int(response.headers.get("Content-Length", 0)) or expected_size + elif not expected_size: # partial left by curl, so take the total from 'bytes 5-9/10' + total = response.headers.get("Content-Range", "").rpartition("/")[2] + expected_size = int(total) if total.isdigit() else 0 + if i == 0 and expected_size > 1048576: + check_disk_space(expected_size, path=f.parent) + buffer_size = max(8192, min(1048576, expected_size // 1000)) if expected_size else 8192 + with TQDM( + total=expected_size, + desc=desc, + disable=not progress, + unit="B", + unit_scale=True, + unit_divisor=1024, + initial=resume, + ) as pbar, open(f, "ab" if resume else "wb") as f_opened: + for data in response.raw.stream(buffer_size, decode_content=False): + f_opened.write(data) + pbar.update(len(data)) + + if f.exists(): + file_size = f.stat().st_size + if expected_size and file_size != expected_size: # only if Content-Length is known + LOGGER.warning( + f"Partial download: {file_size}/{expected_size} bytes ({file_size / expected_size * 100:.1f}%)" + ) + else: + if encoding not in {"", "identity"}: # undo the transfer encoding of the complete body + decoded = f.with_name(f"{f.name}.decoded") + try: + with open(f, "rb") as src, open(decoded, "wb") as dst: + wbits = 47 # detects a gzip or zlib header + try: + zlib.decompressobj(wbits).decompress(src.read(1024)) + except zlib.error: # some servers send 'deflate' as raw DEFLATE without one + wbits = -15 + src.seek(0) + d = zlib.decompressobj(wbits) + for chunk in iter(lambda: src.read(1048576), b""): + while chunk: + if d.eof: # next gzip member, after any zero padding + chunk = chunk.lstrip(b"\0") + if not chunk: + break + d = zlib.decompressobj(wbits) + dst.write(d.decompress(chunk)) + chunk = d.unused_data + if not d.eof: # not an assert, which `python -O` removes + raise ConnectionError("Encoded body ended before its end-of-stream marker") + # A gzip encoding under a gzip name means the gzip is the file itself, e.g. a + # .tar.gz object stored with a gzip Content-Encoding, so keep its verified bytes + if encoding != "gzip" or target.suffix not in {".gz", ".tgz"}: + decoded.replace(f) + finally: + decoded.unlink(missing_ok=True) + if f.stat().st_size > min_bytes: + f.replace(target) + f = target + break # success + f.unlink() # remove partial downloads + except MemoryError: + raise # Re-raise immediately - no point retrying if insufficient disk space + except Exception as e: + # Only on the terminal failure: retries resume the partial file via a Range request, but leaving + # one behind makes the `not f.is_file()` guard above serve it as a complete cache hit forever. + if i == 0 and not is_online(): + f.unlink(missing_ok=True) + raise ConnectionError( + emojis(f"❌ Download failure for {uri}. Environment may be offline.") + ) from e + elif i >= retry: + f.unlink(missing_ok=True) + raise ConnectionError( + emojis(f"❌ Download failure for {uri}. Retry limit reached. {e}") + ) from e + LOGGER.warning(f"Download failure, retrying {i + 1}/{retry} {uri}... {e}") + else: # no attempt reached `break`, so every one failed size validation and unlinked its download + raise ConnectionError(emojis(f"❌ Download failure for {uri}. Retry limit reached.")) + + if unzip and f.exists() and f.suffix in {"", ".zip", ".tar", ".gz"}: + from zipfile import is_zipfile + + unzip_dir = Path(dir or f.parent).resolve() # unzip to dir if provided else unzip in place + if is_zipfile(f): + unzip_dir = unzip_file(file=f, path=unzip_dir, exist_ok=exist_ok, progress=progress) # unzip + elif f.suffix in {".tar", ".gz"}: + LOGGER.info(f"Unzipping {f} to {unzip_dir}...") + top_level_dirs = set() + with tarfile.open(f, "r:*") as tar: + for m in tar: + if not (m.isfile() or m.isdir()) or m.issym() or m.islnk(): + LOGGER.warning(f"Potentially insecure tar member: {m.name}, skipping extraction.") + continue + m_path = Path(m.name) + target = (unzip_dir / m_path).resolve() + if ( + m_path.is_absolute() + or ".." in m_path.parts + or target.parts[: len(unzip_dir.parts)] != unzip_dir.parts + ): + LOGGER.warning(f"Potentially insecure file path: {m.name}, skipping extraction.") + continue + top_level_dirs.update(m_path.parts[:1]) # slice as './' root entries have no parts + if m.isdir(): + target.mkdir(parents=True, exist_ok=True) + elif source := tar.extractfile(m): + target.parent.mkdir(parents=True, exist_ok=True) + with source, open(target, "wb") as out: # 'f' is the archive path, deleted below + shutil.copyfileobj(source, out) + if len(top_level_dirs) == 1 and (unzip_dir / (top := next(iter(top_level_dirs)))).is_dir(): + unzip_dir /= top # tar has 1 top-level directory, i.e. coco8/ extracted to ../datasets/ + else: + unzip_dir = f # neither a zip nor a tar, i.e. an HTML error page served as .zip, so return the file + if delete: + f.unlink() # remove archive + return unzip_dir + return f + + +def get_github_assets( + repo: str = "ultralytics/assets", + version: str = "latest", + retry: bool = False, +) -> tuple[str, list[str]]: + """Retrieve the specified version's tag and assets from a GitHub repository. + + If the version is not specified, the function fetches the latest release assets. + + Args: + repo (str, optional): The GitHub repository in the format 'owner/repo'. + version (str, optional): The release version to fetch assets from. + retry (bool, optional): Flag to retry the request in case of a failure. + + Returns: + tag (str): The release tag. + assets (list[str]): A list of asset names. + + Examples: + >>> tag, assets = get_github_assets(repo="ultralytics/assets", version="latest") + """ + import requests # scoped as slow import + + if version != "latest": + version = f"tags/{version}" # i.e. tags/v6.2 + url = f"https://api.github.com/repos/{repo}/releases/{version}" + attempts = 2 if retry else 1 # retry once on transient network errors or non-200 responses + for attempt in range(attempts): + try: + r = requests.get(url, timeout=30) # github api + except requests.exceptions.RequestException as e: + if attempt < attempts - 1: + continue # transient network error, try again + LOGGER.warning(f"GitHub assets check failure for {url}: {e}") + return "", [] + if r.status_code == 200 or r.reason == "rate limit exceeded": # do not retry 403 rate limits + break + if r.status_code != 200: + LOGGER.warning(f"GitHub assets check failure for {url}: {r.status_code} {r.reason}") + return "", [] + data = r.json() + return data["tag_name"], [x["name"] for x in data["assets"]] # tag, assets i.e. ['yolo26n.pt', 'yolo11s.pt', ...] + + +def attempt_download_asset( + file: str | Path, + repo: str = "ultralytics/assets", + release: str = "v8.4.0", + **kwargs, +) -> str: + """Attempt to download a file from GitHub release assets if it is not found locally. + + Args: + file (str | Path): The filename or file path to be downloaded. + repo (str, optional): The GitHub repository in the format 'owner/repo'. + release (str, optional): The specific release version to be downloaded. + **kwargs (Any): Additional keyword arguments for the download process. + + Returns: + (str): The path to the downloaded file. + + Examples: + >>> file_path = attempt_download_asset("yolo26n.pt", repo="ultralytics/assets", release="latest") + """ + from ultralytics.utils import SETTINGS # scoped for circular import + + # YOLOv3/5u updates + file = str(file) + file = checks.check_yolov5u_filename(file) + file = Path(file.strip().replace("'", "")) + if file.exists(): + return str(file) + elif (SETTINGS["weights_dir"] / file).exists(): + return str(SETTINGS["weights_dir"] / file) + else: + # URL specified + name = Path(parse.unquote(str(file))).name # decode '%2F' to '/' etc. + download_url = f"https://github.com/{repo}/releases/download" + if str(file).startswith(("http:/", "https:/")): # download + url = str(file).replace(":/", "://") # Pathlib turns :// -> :/ + file = url2file(name) # parse authentication query strings + if Path(file).is_file(): + LOGGER.info(f"Found {clean_url(url)} locally at {file}") # file already exists + else: + safe_download(url=url, file=file, min_bytes=1e5, **kwargs) + + elif repo == GITHUB_ASSETS_REPO and name in GITHUB_ASSETS_NAMES: + safe_download(url=f"{download_url}/{release}/{name}", file=file, min_bytes=1e5, **kwargs) + + else: + tag, assets = get_github_assets(repo, release) + if not assets: + tag, assets = get_github_assets(repo) # latest release + if name in assets: + safe_download(url=f"{download_url}/{tag}/{name}", file=file, min_bytes=1e5, **kwargs) + + return str(file) + + +def download( + url: str | list[str] | Path, + dir: Path | None = None, + unzip: bool = True, + delete: bool = False, + curl: bool = False, + threads: int = 1, + retry: int = 3, + exist_ok: bool = False, +) -> None: + """Download files from specified URLs to a given directory. + + Supports concurrent downloads if multiple threads are specified. + + Args: + url (str | list[str] | Path): The URL or list of URLs of the files to be downloaded. + dir (Path, optional): The directory where the files will be saved. + unzip (bool, optional): Flag to unzip the files after downloading. + delete (bool, optional): Flag to delete the zip files after extraction. + curl (bool, optional): Flag to use curl for downloading. + threads (int, optional): Number of threads to use for concurrent downloads. + retry (int, optional): Number of retries in case of download failure. + exist_ok (bool, optional): Whether to overwrite existing contents during unzipping. + + Examples: + >>> download("https://github.com/ultralytics/assets/releases/download/v0.0.0/bus.jpg", dir="path/to/dir") + """ + dir = Path(dir or Path.cwd()) + dir.mkdir(parents=True, exist_ok=True) # make directory + urls = [url] if isinstance(url, (str, Path)) else url + if threads > 1: + LOGGER.info(f"Downloading {len(urls)} file(s) with {threads} threads to {dir}...") + with ThreadPool(threads) as pool: + pool.map( + lambda x: safe_download( + url=x[0], + dir=x[1], + unzip=unzip, + delete=delete, + curl=curl, + retry=retry, + exist_ok=exist_ok, + progress=True, + ), + zip(urls, repeat(dir)), + ) + pool.close() + pool.join() + else: + for u in urls: + safe_download(url=u, dir=dir, unzip=unzip, delete=delete, curl=curl, retry=retry, exist_ok=exist_ok) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/events.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/events.py new file mode 100644 index 0000000000000000000000000000000000000000..ac86224614b474e79745f67f1c796d5d11931f24 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/events.py @@ -0,0 +1,237 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import json +import random +import time +from pathlib import Path +from threading import Thread +from urllib.request import Request, urlopen + +from ultralytics import SETTINGS, __version__ +from ultralytics.cfg import MODES, TASKS +from ultralytics.utils import ( + ARGV, + ENVIRONMENT, + GIT, + IS_PIP_PACKAGE, + ONLINE, + PYTHON_VERSION, + RANK, + TESTS_RUNNING, + TORCH_VERSION, +) +from ultralytics.utils.torch_utils import get_cpu_info, get_gpu_info, unwrap_model + + +def _post(url: str, data: dict, timeout: float = 5.0) -> None: + """Send a one-shot JSON POST request.""" + try: + body = json.dumps(data, separators=(",", ":")).encode() # compact JSON + req = Request(url, data=body, headers={"Content-Type": "application/json"}) + urlopen(req, timeout=timeout).close() + except Exception: + pass + + +def _arch(model): + """Return the architecture a model is built from, i.e. 'yolo11n-seg', or None if it cannot be determined. + + The config travels inside a checkpoint, so fine-tuned models report the architecture they descend from however many + generations back. + """ + desc = f"{getattr(model, 'description', '')}".split() # exported models name the arch here instead of a YAML + # a trainer holds the config on the model itself, a predictor one level down on the backend; SAM has no .model + yaml = getattr(model, "yaml", None) or getattr(getattr(model, "model", None), "yaml", None) or {} + stem = Path(yaml.get("yaml_file", "")).stem or (desc[1] if len(desc) > 1 else "") + return stem.lower()[:100] or None # lowercased so one arch cannot split into two cells; 100 is the GA4 limit + + +class Events: + """Collect and send anonymous usage analytics with rate-limiting. + + Event collection and transmission are enabled when sync is enabled in settings, the current process is rank -1 or 0, + tests are not running, the environment is online, and the installation source is either pip or the official + Ultralytics GitHub repository. + + Attributes: + url (str): Measurement Protocol endpoint for receiving anonymous events. + events (list[dict]): In-memory queue of event payloads awaiting transmission. + rate_limit (float): Minimum time in seconds between POST requests. + t (float): Timestamp of the last transmission in seconds since the epoch. + metadata (dict): Static metadata describing runtime, installation source, and environment. + enabled (bool): Flag indicating whether analytics collection is active. + + Methods: + __init__: Initialize the event queue, rate limiter, and runtime metadata. + __call__: Queue an event and trigger a non-blocking send when the rate limit elapses. + """ + + url = "https://www.google-analytics.com/mp/collect?measurement_id=G-X8NCJYTQXM&api_secret=QLQrATrNSwGRFRLE-cbHJw" + + def __init__(self) -> None: + """Initialize the Events instance with queue, rate limiter, and environment metadata.""" + self.events = [] # pending events + self.rate_limit = 30.0 # rate limit (seconds) + self.t = 0.0 # last send timestamp (seconds) + self.metadata = { + "cli": Path(ARGV[0]).name == "yolo", + "install": "git" if GIT.is_repo else "pip" if IS_PIP_PACKAGE else "other", + "python": PYTHON_VERSION.rsplit(".", 1)[0], # i.e. 3.13 + "torch": TORCH_VERSION, + "CPU": get_cpu_info(), + "version": __version__, + "env": ENVIRONMENT, + "session_id": round(random.random() * 1e15), + "engagement_time_msec": 1000, + } + self.enabled = ( + SETTINGS["sync"] + and RANK in {-1, 0} + and not TESTS_RUNNING + and ONLINE + and (IS_PIP_PACKAGE or GIT.origin == "https://github.com/ultralytics/ultralytics.git") + ) + + def __call__(self, cfg, device=None, run=None) -> None: + """Queue an event and flush the queue asynchronously when the rate limit elapses. + + Args: + cfg (IterableSimpleNamespace): The configuration object containing mode and task information. + device (torch.device | str, optional): The device type (e.g., 'cpu', 'cuda'). + run (BasePredictor | BaseTrainer, optional): The completed run, read for the mode's result fields. + """ + # An event is named for its mode, so an arbitrary mode becomes an arbitrary event name, and GA4 drops every new + # name once a property reaches 500 of them - eventually the real ones. + if not self.enabled or cfg.mode not in MODES or cfg.task not in TASKS: + return + + # Attempt to enqueue a new event + if len(self.events) < 25: # Queue limited to 25 events to bound memory and traffic + params = { + **self.metadata, + "task": cfg.task, + "model": Path(str(cfg.model)).name[:100] if cfg.model else None, # basename, never a path + "device": str(device), + } + if cfg.mode == "export": + params["format"] = cfg.format + elif cfg.mode == "train": + # Guarded and ordered exactly as predict below, for the same reasons + try: + # grouping key; stem unifies YAML and directory, and isinstance keeps a dict repr's path out + params["data"] = Path(cfg.data).stem[:100] if isinstance(cfg.data, (str, Path)) else None + params["imgsz"] = cfg.imgsz + # epochs this session, to stay consistent with hours; a resumed run restores an absolute epoch + params["epochs_done"] = run.epoch + 1 - run.start_epoch + params["batch"] = run.batch_size # resolved, since autobatch and OOM retries both move it + params["hours"] = round((time.time() - run.train_time_start) / 3600, 4) + params["n"] = len(run.train_loader.dataset) # train split size, matching predict's n + if run.best_fitness is not None: # None when a run never validated + # a per-task composite: mAP50-95 for detect, box+mask for segment, so compare within a task + params["fitness"] = round(float(run.best_fitness), 5) + # both resolved: the default 'auto' fits its own optimizer and lr0, ignoring cfg.lr0 + params["optimizer"] = type(run.optimizer).__name__ + # min, since MuSGD splits every group in two and puts the finetuning lr*3 half first + params["lr0"] = min(g["initial_lr"] for g in run.optimizer.param_groups) + flags = { + "pretrained": bool(cfg.pretrained), + "cos_lr": cfg.cos_lr, + "amp": run.amp, # as applied: check_amp() turns a requested True off on unsupported hardware + "rect": cfg.rect, + "multi_scale": bool(cfg.multi_scale), + "freeze": bool(cfg.freeze), # freeze=0 and freeze=[] both freeze nothing + "dropout": cfg.dropout > 0, + "early_stop": run.epoch + 1 < run.epochs, # .stop is also set on the last planned epoch + "resume": bool(cfg.resume), # fitness carries over, epochs and hours do not + } + params["flags"] = ",".join(k for k, v in flags.items() if v) or None + params["arch"] = _arch(unwrap_model(run.model)) # DDP and EMA both wrap away the .yaml + params["ngpu"] = run.world_size if run.world_size > 1 else None # only a count above one informs + if device.type == "cuda": # makes hours comparable + params["GPU"] = get_gpu_info(device.index or 0).rsplit(", ", 1)[0] + except Exception: + pass + elif cfg.mode in {"predict", "track"}: # track runs the predictor too, and is most of the video inference + # Reads inside the guard so nothing can raise into a user's run, cheapest first; order is drop order + try: + params["n"] = run.seen # predictor state this file's own owner sets, so it cannot raise + params["pixels"] = run.pixels # mean inference area, which FLOPs scale with; sqrt for a side + for k, v in (run.speed or {}).items(): # absent when a run processed no images + params[f"{k}_ms"] = round(v, 3) + params["batch"] = min(getattr(run.dataset, "bs", 0), run.seen) or None + model = run.model + params["format"] = model.format + params["nc"] = len(getattr(model, "names", None) or ()) or None # drives head width and NMS + # toggles that move inference time, as applied: compile replaces .model, end2end reflects the backend output + flags = { + "compile": hasattr(model, "_orig_mod"), + "end2end": getattr(model, "end2end", False), + "augment": cfg.augment, + } + params["flags"] = ",".join(k for k, v in flags.items() if v) or None + params["arch"] = _arch(model) # reads into model.description and model.model.yaml + meta = getattr(model, "metadata", None) or {} + params["quantize"] = str(meta.get("args", {}).get("quantize") or cfg.quantize or 32) + if device.type == "cuda": # CUDA is already initialized here, so this costs nothing + params["GPU"] = get_gpu_info(device.index or 0).rsplit(", ", 1)[0] + session = getattr(model, "session", None) # ONNX Runtime provider, else OpenVINO device + ov = getattr(model, "ov_compiled_model", None) # an Arc GPU run must not look like CPU + devices = session.get_providers() if session else ov.get_property("EXECUTION_DEVICES") if ov else [] + params["provider"] = devices[0] if devices else None # last: least reliable read + except Exception: + pass + # nulls are dropped anyway, and an event over 25 params is rejected outright, so cap rather than lose it + params = dict([(k, v) for k, v in params.items() if v is not None][:25]) + self.events.append({"name": cfg.mode, "params": params}) + + # Check rate limit and return early if under limit + t = time.time() + if (t - self.t) < self.rate_limit: + return + + # Overrate limit: send a snapshot of queued events in a background thread + payload_events = list(self.events) # snapshot to avoid race with queue reset + Thread( + target=_post, + args=(self.url, {"client_id": SETTINGS["uuid"], "events": payload_events}), # SHA-256 anonymized + daemon=True, + ).start() + + # Reset queue and rate limit timer + self.events = [] + self.t = t + + +events = Events() + + +def on_train_end(trainer): + """Record an anonymous training event after final metrics are available.""" + events(trainer.args, trainer.device, trainer) + + +def on_val_start(validator): + """Record an anonymous standalone validation event. + + A trainer's final validation retains mode=train, so the guard prevents a duplicate train event. + """ + if validator.args.mode == "val": + events(validator.args, validator.device) + + +def on_predict_end(predictor): + """Record an anonymous prediction event after per-image speeds are available.""" + events(predictor.args, predictor.device, predictor) + + +def on_export_start(exporter): + """Record an anonymous export event.""" + events(exporter.args, exporter.device) + + +callbacks = { + "on_train_end": on_train_end, + "on_val_start": on_val_start, + "on_predict_end": on_predict_end, + "on_export_start": on_export_start, +} diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d1b1df587c25566cd05f7c9ea3143a93e507a529 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__init__.py @@ -0,0 +1,40 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .ascend import onnx2ascend +from .axelera import torch2axelera +from .coreai import torch2coreai +from .coreml import torch2coreml +from .deepx import onnx2deepx +from .engine import onnx2engine, torch2onnx +from .executorch import torch2executorch +from .imx import torch2imx +from .mnn import onnx2mnn +from .ncnn import torch2ncnn +from .openvino import torch2openvino +from .paddle import torch2paddle +from .qnn import onnx2qnn +from .rknn import onnx2rknn +from .tensorflow import keras2pb, onnx2saved_model, tflite2edgetpu +from .torchscript import torch2torchscript + +__all__ = [ + "keras2pb", + "onnx2ascend", + "onnx2deepx", + "onnx2engine", + "onnx2mnn", + "onnx2qnn", + "onnx2rknn", + "onnx2saved_model", + "tflite2edgetpu", + "torch2axelera", + "torch2coreai", + "torch2coreml", + "torch2executorch", + "torch2imx", + "torch2ncnn", + "torch2onnx", + "torch2openvino", + "torch2paddle", + "torch2torchscript", +] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28e7f11ca70cd1900bf3421aeb04614427d16cdc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/ascend.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/ascend.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6f4ae45062e5f949587fd8308903fb91070dedf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/ascend.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/axelera.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/axelera.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c7c61fa04ec116b3c41dfd48c63aa9cdd4d55bd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/axelera.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/coreai.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/coreai.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a721fd8691749ac4d740a12ca6dc258a9803ea02 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/coreai.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/coreml.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/coreml.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00ceb51bda9349ce98872ad09bfac25e54c94340 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/coreml.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/deepx.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/deepx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81f180f28a5d3505d0f1bc8df6e64d79e2c99f94 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/deepx.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/engine.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/engine.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e30e25e5d67e8b5bb7f68f3514ca50a6f0ed887 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/engine.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/executorch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/executorch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e62d7dc39a687286e898bd6f889d71bac40ef8ef Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/executorch.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/imx.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/imx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4683be2522da011730c4e8c99c6b93faeb0cee4b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/imx.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/litert.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/litert.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43df1fa0cec509836a9abbf62cf76a4acb8fbf84 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/litert.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/mnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/mnn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d278fd182d138d5decec17ac3c87d6c51a1fa20a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/mnn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/ncnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/ncnn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39180b2d0bfdcfb259ef250ecbe6c1f80bc95809 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/ncnn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/onnx.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/onnx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5e813bc742677a5cb7e2a1322b26cc3089d97d5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/onnx.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/openvino.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/openvino.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44667b84d51543f0abeaf3ec0f4da30e8b1bfac3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/openvino.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/paddle.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/paddle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43f702e9ec49f28fdb6a9fe82dda99369e282e81 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/paddle.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/qnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/qnn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4957538549d382da94425d17bb284d53d0cb56f2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/qnn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/rknn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/rknn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e51c2a72d45dff3e0cde051a869087664ec74bd8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/rknn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/tensorflow.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/tensorflow.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e119118f177995272aef6ce95cb18f9ad1564b4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/tensorflow.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/torchscript.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/torchscript.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c1dc321e5419341f155d401337eec27983a187d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/__pycache__/torchscript.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/ascend.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/ascend.py new file mode 100644 index 0000000000000000000000000000000000000000..82ec529177922904a2b5f1ca32d503e0314d747d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/ascend.py @@ -0,0 +1,71 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import shlex +import shutil +import subprocess +import tempfile +from pathlib import Path + +from ultralytics.utils import LOGGER, YAML + + +def _check_atc() -> None: + """Raise if the CANN ATC compiler is not on PATH.""" + if not shutil.which("atc"): + raise FileNotFoundError( + "Ascend export requires the CANN toolkit 'atc' compiler, which was not found on PATH. Install CANN and " + "source its environment, e.g. `source /usr/local/Ascend/ascend-toolkit/set_env.sh`. " + "See https://docs.ultralytics.com/integrations/ascend" + ) + + +def onnx2ascend( + onnx_file: str | Path, + output_dir: str | Path, + name: str, + imgsz: tuple[int, int], + batch: int = 1, + channels: int = 3, + metadata: dict | None = None, + prefix: str = "", +) -> str: + """Convert an ONNX model to a Huawei Ascend offline model (.om) with the CANN ATC compiler. + + Args: + onnx_file (str | Path): Input ONNX model path. + output_dir (str | Path): Directory to write the compiled .om model into. + name (str): Target Ascend SoC passed to ATC as ``--soc_version``, e.g. ``"Ascend310B4"``. + imgsz (tuple[int, int]): Export image size as ``(height, width)``. + batch (int, optional): Static batch size baked into the offline model. Defaults to 1. + channels (int, optional): Input channel count, matching the traced ONNX graph. Defaults to 3. + metadata (dict | None, optional): Optional metadata to save as YAML. Defaults to None. + prefix (str, optional): Logging prefix. Defaults to "". + + Returns: + (str): Path to the exported Ascend model directory. + """ + _check_atc() + output_dir = Path(output_dir).resolve() + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "atc", + f"--model={Path(onnx_file).resolve()}", # absolute: ATC runs with cwd=output_dir + "--framework=5", # 5 = ONNX + f"--output={output_dir / f'{Path(onnx_file).stem}_{name}'}", # ATC appends the .om suffix + "--input_format=NCHW", + f"--input_shape=images:{batch},{channels},{imgsz[0]},{imgsz[1]}", + f"--soc_version={name}", + "--precision_mode=force_fp16", # Ascend AI Core convolutions reject FP32 inputs + ] # argv list avoids shell metacharacter issues in onnx_file/output_dir paths + LOGGER.info(f"\n{prefix} starting export with ATC for {name}...") + LOGGER.info(f"{prefix} running '{shlex.join(cmd)}'") + with tempfile.TemporaryDirectory() as scratch: # ATC drops kernel_meta/ and fusion_result.json in its CWD + subprocess.run(cmd, check=True, cwd=scratch) + + if metadata is not None: + YAML.save(output_dir / "metadata.yaml", metadata) + + return str(output_dir) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/axelera.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/axelera.py new file mode 100644 index 0000000000000000000000000000000000000000..7de09036f97937aefe3dcc4b16ca441e8b822112 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/axelera.py @@ -0,0 +1,126 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import os +import shutil +import sysconfig +import tempfile +import threading +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from ultralytics.utils import LOGGER, YAML +from ultralytics.utils.checks import check_requirements + +AXELERA_SDK = "1.8.0" + +# Axelera exports mutate process-global state (the PROTOCOL_BUFFERS env var below, plus any working-directory +# files the compiler emits), so a module-level lock serializes concurrent in-process exports. Cross-process +# Platform workers each hold their own lock and never contend. +_AXELERA_EXPORT_LOCK = threading.Lock() + + +def torch2axelera( + model: torch.nn.Module, + output_dir: Path | str, + calibration_dataset: torch.utils.data.DataLoader, + transform_fn: Callable[[Any], np.ndarray], + model_name: str = "model", + metadata: dict | None = None, + prefix: str = "", +) -> str: + """Convert a YOLO model to Axelera format. + + Args: + model (torch.nn.Module): Source YOLO model for quantization. + output_dir (Path | str): Directory to save the exported Axelera model. + calibration_dataset (torch.utils.data.DataLoader): Calibration dataloader for quantization. + transform_fn (Callable[[Any], np.ndarray]): Calibration preprocessing transform function. + model_name (str, optional): Name for the compiled model. Defaults to "model". + metadata (dict | None, optional): Optional metadata to save as YAML. Defaults to None. + prefix (str, optional): Prefix for log messages. Defaults to "". + + Returns: + (str): Path to exported Axelera model directory. + """ + # Serialize within the process: the steps below mutate process-global state (the protobuf and PATH env + # vars, plus any working-directory files the compiler writes), so concurrent in-process exports must + # not overlap. + with _AXELERA_EXPORT_LOCK: + prev_env = {key: os.environ.get(key) for key in ("PATH", "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION")} + try: + os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python" + # The compiler runs `axkernelcc` from PATH, which is missing when the interpreter is launched + # by absolute path instead of through an activated environment. + os.environ["PATH"] = os.pathsep.join(filter(None, (sysconfig.get_path("scripts"), prev_env["PATH"]))) + if not check_requirements( + f"axelera-devkit=={AXELERA_SDK}", + cmds="--extra-index-url https://software.axelera.ai/artifactory/api/pypi/axelera-pypi/simple", + ): + raise ModuleNotFoundError(f"Axelera export requires axelera-devkit=={AXELERA_SDK}.") + check_requirements("omnimalloc==0.5.0") + from axelera import compiler + from axelera.compiler import CompilerConfig + from axelera.compiler.config.model_specific import extract_ultralytics_metadata + + LOGGER.info(f"\n{prefix} starting export with Axelera compiler...") + + # Resolve to an absolute path so the relative compile dir below can never alias it. + output_dir = Path(output_dir).resolve() + if output_dir.exists(): + shutil.rmtree(output_dir) + + axelera_model_metadata = extract_ultralytics_metadata(model) + config = CompilerConfig( + model_metadata=axelera_model_metadata, + model_name=model_name, + resources_used=0.25, + aipu_cores_used=1, + multicore_mode="batch", + output_axm_format=True, + ) + qmodel = compiler.quantize( + model=model, + calibration_dataset=calibration_dataset, + config=config, + transform_fn=transform_fn, + ) + + # The Axelera compiler emits invalid artifacts for absolute output paths, so compile into a local + # relative directory. TemporaryDirectory gives it a unique name (so back-to-back exports of identically + # named models never collide) in the current working directory, and removes it on exit even if + # compilation raises; passing its relative basename keeps it from aliasing the absolute output_dir, so + # cleanup can never delete the result. + with tempfile.TemporaryDirectory(prefix="axelera_compile_", dir=".") as compile_root: + compile_dir = Path(Path(compile_root).name) + compiler.compile(model=qmodel, config=config, output_dir=compile_dir) + + output_dir.mkdir(parents=True, exist_ok=True) + for artifact in [f"{model_name}.axm", "compiler_config_final.toml"]: + for artifact_path in [compile_dir / artifact, Path(artifact)]: + if artifact_path.exists(): + artifact_path.replace(output_dir / artifact_path.name) + break + + # Remove intermediate compiler artifacts, keeping only the compiled model and config. + keep_suffixes = {".axm"} + keep_names = {"compiler_config_final.toml", "metadata.yaml"} + for f in output_dir.iterdir(): + if f.is_file() and f.suffix not in keep_suffixes and f.name not in keep_names: + f.unlink() + + if metadata is not None: + YAML.save(output_dir / "metadata.yaml", metadata) + + return str(output_dir) + finally: + for key, value in prev_env.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/coreai.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/coreai.py new file mode 100644 index 0000000000000000000000000000000000000000..8d429d32deddacf8caf8d39a370f246baf315c87 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/coreai.py @@ -0,0 +1,81 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import torch + +from ultralytics.utils import LOGGER +from ultralytics.utils.checks import check_requirements + + +def _remainder_scalar(x: torch.Tensor, s: float) -> torch.Tensor: + """Decompose aten.remainder.Scalar, which Core AI has no lowering for. + + Floor division, not torch.fmod: fmod takes the sign of the dividend where remainder takes the sign of the divisor, + so fmod is only equivalent for non-negative inputs. + """ + if x.dtype in {torch.int64, torch.int32, torch.int16, torch.int8}: + return x - s * torch.div(x, s, rounding_mode="floor") + return x - s * torch.floor(x / s) + + +def torch2coreai( + model: torch.nn.Module, + im: torch.Tensor, + output_file: Path | str, + quantize: int | None = None, + metadata: dict | None = None, + prefix: str = "", +) -> str: + """Export a PyTorch model to an Apple Core AI `.aimodel` asset. + + Args: + model (torch.nn.Module): Model to export. + im (torch.Tensor): Example input driving `torch.export`. + output_file (Path | str): Destination `.aimodel` asset directory. + quantize (int | None): 16 for an FP16 asset, None or 32 for FP32. + metadata (dict | None): Ultralytics metadata, written into the asset's own metadata.json. + prefix (str): Log message prefix. + + Returns: + (str): Path to the exported asset. + """ + check_requirements("coreai-torch>=0.4.2") + import coreai_torch + from coreai.runtime import AIModelAssetMetadata + from coreai_torch import TorchConverter + + LOGGER.info(f"\n{prefix} starting export with coreai-torch {coreai_torch.__version__}...") + + if quantize == 16: + model, im = model.half(), im.half() + + with torch.no_grad(): + ep = torch.export.export(model, (im,)) + table = coreai_torch.get_decomp_table() + table[torch.ops.aten.remainder.Scalar] = _remainder_scalar # (index % nc) in the end2end head + ep = ep.run_decompositions(table) + + converter = TorchConverter() + n_outputs = len(ep.graph_signature.user_outputs) + converter.add_exported_program( + ep, + entrypoint_name="main", + input_names=["images"], + output_names=[f"output{i}" for i in range(n_outputs)], + ) + program = converter.to_coreai() + program.optimize() + + asset_metadata = AIModelAssetMetadata() + asset_metadata.author = "Ultralytics" + asset_metadata.license = "AGPL-3.0 License (https://ultralytics.com/license)" + asset_metadata.model_description = (metadata or {}).get("description", "") + for k, v in (metadata or {}).items(): + asset_metadata.set_custom(k, str(v)) # matches the CoreML exporter; set_custom rejects nested dicts + + output_file = Path(output_file) + program.save_asset(output_file, metadata=asset_metadata) + return str(output_file) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/coreml.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/coreml.py new file mode 100644 index 0000000000000000000000000000000000000000..90799671f98f790dcdefc16c369741a527e8ea51 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/coreml.py @@ -0,0 +1,265 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import types +from pathlib import Path +from typing import Any + +import torch +from torch import nn + +from ultralytics.nn.modules import Detect +from ultralytics.utils import LOGGER +from ultralytics.utils.checks import check_requirements + + +class IOSDetectModel(nn.Module): + """Wrap an Ultralytics YOLO model for Apple iOS CoreML export.""" + + def __init__(self, model: nn.Module, im: torch.Tensor, mlprogram: bool = True): + """Initialize the IOSDetectModel class with a YOLO model and example image. + + Args: + model (nn.Module): The YOLO model to wrap. + im (torch.Tensor): Example input tensor with shape (B, C, H, W). + mlprogram (bool): Whether exporting to MLProgram format. + """ + super().__init__() + _, _, h, w = im.shape # batch, channel, height, width + self.model = model + self.nc = len(model.names) # number of classes + self.mlprogram = mlprogram + if w == h: + self.normalize = 1.0 / w # scalar + else: + self.normalize = torch.tensor( + [1.0 / w, 1.0 / h, 1.0 / w, 1.0 / h], # broadcast (slower, smaller) + device=next(model.parameters()).device, + ) + + def forward(self, x: torch.Tensor): + """Normalize predictions of object detection model with input size-dependent factors.""" + xywh, cls = self.model(x)[0].transpose(0, 1).split((4, self.nc), 1) + if self.mlprogram and self.nc % 80 != 0: # NMS bug https://github.com/ultralytics/ultralytics/issues/22309 + pad_length = int(((self.nc + 79) // 80) * 80) - self.nc # pad class length to multiple of 80 + cls = torch.nn.functional.pad(cls, (0, pad_length, 0, 0), "constant", 0) + return cls, xywh * self.normalize + + +def pipeline_coreml( + model: Any, + output_shape: tuple[int, ...], + metadata: dict, + mlmodel: bool = False, + iou: float = 0.45, + conf: float = 0.25, + agnostic_nms: bool = False, + weights_dir: Path | str | None = None, + prefix: str = "", +): + """Create CoreML pipeline with NMS for YOLO detection models. + + Args: + model: CoreML model. + output_shape (tuple[int, ...]): Output shape tuple from the exporter. + metadata (dict): Model metadata. + mlmodel (bool): Whether the model is an MLModel (vs MLProgram). + iou (float): IoU threshold for NMS. + conf (float): Confidence threshold for NMS. + agnostic_nms (bool): Whether to use class-agnostic NMS. + weights_dir (Path | str | None): Weights directory for MLProgram models. + prefix (str): Prefix for log messages. + + Returns: + CoreML pipeline model. + """ + import coremltools as ct + + LOGGER.info(f"{prefix} starting pipeline with coremltools {ct.__version__}...") + + spec = model.get_spec() + outs = list(iter(spec.description.output)) + if mlmodel: # mlmodel doesn't infer shapes automatically + outs[0].type.multiArrayType.shape[:] = output_shape[2], output_shape[1] - 4 + outs[1].type.multiArrayType.shape[:] = output_shape[2], 4 + + names = metadata["names"] + nx = spec.description.input[0].type.imageType.width + ny = spec.description.input[0].type.imageType.height + nc = outs[0].type.multiArrayType.shape[-1] + if len(names) != nc: # Hack fix for MLProgram NMS bug https://github.com/ultralytics/ultralytics/issues/22309 + names = {**names, **{i: str(i) for i in range(len(names), nc)}} + + model = ct.models.MLModel(spec, weights_dir=weights_dir, skip_model_load=True) + + # Create NMS protobuf + nms_spec = ct.proto.Model_pb2.Model() + nms_spec.specificationVersion = spec.specificationVersion + for i in range(len(outs)): + decoder_output = model._spec.description.output[i].SerializeToString() + nms_spec.description.input.add() + nms_spec.description.input[i].ParseFromString(decoder_output) + nms_spec.description.output.add() + nms_spec.description.output[i].ParseFromString(decoder_output) + + output_names = ["confidence", "coordinates"] + for i, name in enumerate(output_names): + nms_spec.description.output[i].name = name + + for i, out in enumerate(outs): + ma_type = nms_spec.description.output[i].type.multiArrayType + ma_type.shapeRange.sizeRanges.add() + ma_type.shapeRange.sizeRanges[0].lowerBound = 0 + ma_type.shapeRange.sizeRanges[0].upperBound = -1 + ma_type.shapeRange.sizeRanges.add() + ma_type.shapeRange.sizeRanges[1].lowerBound = out.type.multiArrayType.shape[-1] + ma_type.shapeRange.sizeRanges[1].upperBound = out.type.multiArrayType.shape[-1] + del ma_type.shape[:] + + nms = nms_spec.nonMaximumSuppression + nms.confidenceInputFeatureName = outs[0].name # 1x507x80 + nms.coordinatesInputFeatureName = outs[1].name # 1x507x4 + nms.confidenceOutputFeatureName = output_names[0] + nms.coordinatesOutputFeatureName = output_names[1] + nms.iouThresholdInputFeatureName = "iouThreshold" + nms.confidenceThresholdInputFeatureName = "confidenceThreshold" + nms.iouThreshold = iou + nms.confidenceThreshold = conf + nms.pickTop.perClass = not agnostic_nms + nms.stringClassLabels.vector.extend(names.values()) + nms_model = ct.models.MLModel(nms_spec, skip_model_load=True) + + # Pipeline models together + pipeline = ct.models.pipeline.Pipeline( + input_features=[ + ("image", ct.models.datatypes.Array(3, ny, nx)), + ("iouThreshold", ct.models.datatypes.Double()), + ("confidenceThreshold", ct.models.datatypes.Double()), + ], + output_features=output_names, + ) + pipeline.add_model(model) + pipeline.add_model(nms_model) + + # Correct datatypes + pipeline.spec.description.input[0].ParseFromString(model._spec.description.input[0].SerializeToString()) + pipeline.spec.description.output[0].ParseFromString(nms_model._spec.description.output[0].SerializeToString()) + pipeline.spec.description.output[1].ParseFromString(nms_model._spec.description.output[1].SerializeToString()) + + # Update metadata + pipeline.spec.specificationVersion = spec.specificationVersion + pipeline.spec.description.metadata.CopyFrom(spec.description.metadata) + pipeline.spec.description.metadata.userDefined.update( + {"IoU threshold": str(nms.iouThreshold), "Confidence threshold": str(nms.confidenceThreshold)} + ) + + # Save the model + model = ct.models.MLModel(pipeline.spec, weights_dir=weights_dir, skip_model_load=True) + model.input_description["image"] = "Input image" + model.input_description["iouThreshold"] = f"(optional) IoU threshold override (default: {nms.iouThreshold})" + model.input_description["confidenceThreshold"] = ( + f"(optional) Confidence threshold override (default: {nms.confidenceThreshold})" + ) + model.output_description["confidence"] = 'Boxes × Class confidence (see user-defined metadata "classes")' + model.output_description["coordinates"] = "Boxes × [x, y, width, height] (relative to image size)" + LOGGER.info(f"{prefix} pipeline success") + return model + + +def _coreml_gather(self, x: torch.Tensor, index: torch.Tensor) -> torch.Tensor: + """Select index (batch, k) rows of x along dim 1, keeping the indices int32 through MIL.""" + return x[torch.arange(x.shape[0])[..., None], index] + + +def torch2coreml( + model: nn.Module, + inputs: list, + im: torch.Tensor, + classifier_names: list[str] | None, + output_file: Path | str | None = None, + mlmodel: bool = False, + quantize: int | str | None = None, + metadata: dict | None = None, + prefix: str = "", +) -> Any: + """Export a PyTorch model to CoreML ``.mlpackage`` or ``.mlmodel`` format. + + Args: + model (nn.Module): The PyTorch model to export. + inputs (list): CoreML input descriptions for the model. + im (torch.Tensor): Example input tensor for tracing. + classifier_names (list[str] | None): Class names for classifier config, or None if not a classifier. + output_file (Path | str | None): Output file path, or None to skip saving. + mlmodel (bool): Whether to export as ``.mlmodel`` (neural network) instead of ``.mlpackage`` (ML program). + quantize (int | str | None): Precision scheme, e.g. 16 for FP16 or 8/``"w8a16"`` for INT8 weights. + metadata (dict | None): Metadata to embed in the CoreML model. + prefix (str): Prefix for log messages. + + Returns: + (ct.models.MLModel): The converted CoreML model. + """ + import coremltools as ct + + LOGGER.info(f"\n{prefix} starting export with coremltools {ct.__version__}...") + for m in model.modules(): # MIL types int64 gather indices as fp32 and then rejects them + if isinstance(m, Detect): + m._gather = types.MethodType(_coreml_gather, m) + ts = torch.jit.trace(model.eval(), im, strict=False) # TorchScript model + fp16 = quantize == 16 + weight_int8 = quantize in {8, "w8a16"} + + # Based on apple's documentation it is better to leave out the minimum_deployment target and let that get set + # Internally based on the model conversion and output type. + # Setting minimum_deployment_target >= iOS16 will require setting compute_precision=ct.precision.FLOAT32. + # iOS16 adds in better support for FP16, but none of the CoreML NMS specifications handle FP16 as input. + convert_kwargs = { + "inputs": inputs, + "classifier_config": ct.ClassifierConfig(classifier_names) if classifier_names else None, + "convert_to": "neuralnetwork" if mlmodel else "mlprogram", + "skip_model_load": True, + } + if not mlmodel: + # ML Program conversion defaults to FP16. Pin FP32 unless FP16/INT8 was requested. + from ultralytics.nn.modules.head import RTDETRDecoder + + if not (fp16 or weight_int8): + convert_kwargs["compute_precision"] = ct.precision.FLOAT32 + elif any(isinstance(m, RTDETRDecoder) for m in model.modules()): + # RT-DETR decoder class logits and deformable-sampling indices drift in fp16; pin those op types to fp32. + fp32_ops = {"linear", "gather", "gather_nd", "gather_along_axis"} + convert_kwargs["compute_precision"] = ct.transform.FP16ComputePrecision( + op_selector=lambda op: op.op_type not in fp32_ops + ) + ct_model = ct.convert(ts, **convert_kwargs) + bits, mode = (8, "kmeans") if weight_int8 else (16, "linear") if fp16 else (32, None) + if bits < 32: + if "kmeans" in mode: + check_requirements("scikit-learn") # scikit-learn package required for k-means quantization + if mlmodel: + ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode) + elif bits == 8: # mlprogram already quantized to FP16 + import coremltools.optimize.coreml as cto + + op_config = cto.OpPalettizerConfig(mode="kmeans", nbits=bits, weight_threshold=512) + config = cto.OptimizationConfig(global_config=op_config) + ct_model = cto.palettize_weights(ct_model, config=config) + + m = dict(metadata or {}) # copy to avoid mutating original + ct_model.short_description = m.pop("description", "") + ct_model.author = m.pop("author", "") + ct_model.license = m.pop("license", "") + ct_model.version = m.pop("version", "") + ct_model.user_defined_metadata.update({k: str(v) for k, v in m.items()}) + + if output_file is not None: + try: + ct_model.save(str(output_file)) # save *.mlpackage + except Exception as e: + LOGGER.warning( + f"{prefix} CoreML export to *.mlpackage failed ({e}), reverting to *.mlmodel export. " + f"Known coremltools Python 3.11 and Windows bugs https://github.com/apple/coremltools/issues/1928." + ) + output_file = Path(output_file).with_suffix(".mlmodel") + ct_model.save(str(output_file)) + return ct_model diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/deepx.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/deepx.py new file mode 100644 index 0000000000000000000000000000000000000000..e5e6d24aa2f544fc58be42266d25d1757d4268f2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/deepx.py @@ -0,0 +1,73 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import json +from pathlib import Path + +from ultralytics.utils import LOGGER, YAML +from ultralytics.utils.checks import check_requirements + + +def onnx2deepx( + onnx_file: str | Path, + imgsz: tuple[int, int], + dataset, + metadata: dict | None = None, + optimize: bool = False, + prefix: str = "", +) -> Path: + """Convert an ONNX model to DEEPX format using the DEEPX DX-Compiler. + + Args: + onnx_file (str | Path): Input ONNX model path. + imgsz (tuple[int, int]): Export image size as ``(height, width)``. + dataset (DataLoader): Calibration dataloader used to build the DEEPX config. + metadata (dict | None, optional): Optional metadata to save as YAML. Defaults to None. + optimize (bool, optional): If True, enables higher compiler optimization which reduces inference latency and + increases compilation time. Defaults to False. + prefix (str, optional): Logging prefix. Defaults to "". + + Returns: + (Path): Path to the exported DEEPX model directory. + """ + try: + import dx_com + except ImportError: + check_requirements("dx_com", cmds="-f https://sdk.deepx.ai/release/dxcom/v2.3.0/index.html") + import dx_com + + LOGGER.info(f"\n{prefix} starting export with DEEPX...") + + onnx_file = Path(onnx_file) + export_path = onnx_file.parent / f"{onnx_file.stem}_deepx_model" + export_path.mkdir(exist_ok=True) + config_path = export_path / "config.json" + + config = { + "inputs": {"images": [1, 3, imgsz[0], imgsz[1]]}, + "calibration_num": 100, # number of steps used during calibration + "calibration_method": "ema", # calibration method used during quantization + "default_loader": { + # JSON needs str; ClassificationDataset stores its image directory as 'root' rather than 'img_path' + "dataset_path": str(getattr(dataset.dataset, "img_path", None) or dataset.dataset.root), + "file_extensions": [val for x in ["jpeg", "jpg", "png"] for val in (x.lower(), x.upper())], + "preprocessings": [ + {"resize": {"mode": "pad", "size": imgsz[0], "pad_location": "edge", "pad_value": [114, 114, 114]}}, + {"div": {"x": 255.0}}, + {"convertColor": {"form": "BGR2RGB"}}, + {"transpose": {"axis": [2, 0, 1]}}, + {"expandDim": {"axis": 0}}, + ], + }, + } + + with open(config_path, "w") as file: + json.dump(config, file) + + dx_com.compile(model=str(onnx_file), output_dir=str(export_path), config=str(config_path), opt_level=int(optimize)) + + if metadata is not None: + YAML.save(export_path / "metadata.yaml", metadata) + + return export_path diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/engine.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/engine.py new file mode 100644 index 0000000000000000000000000000000000000000..18908dc2b0127433ce50ffa083ea3803508501d4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/engine.py @@ -0,0 +1,472 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import json +import re +import types +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from ultralytics.utils import ASSETS, IS_JETSON, LOGGER, TORCH_VERSION, ThreadingLocked, imread, is_dgx, is_jetson +from ultralytics.utils.checks import check_requirements, check_tensorrt, check_version +from ultralytics.utils.torch_utils import TORCH_2_4 + + +class _NormalizeCoords(torch.nn.Module): + """Wrap a model with input-relative box and pose coordinates for per-tensor quantization.""" + + def __init__(self, model: torch.nn.Module, h: int, w: int, task: str, nc: int, kpt_shape: tuple | None): + """Initialize with the wrapped model and prediction metadata.""" + super().__init__() + self.model = model + self.h = h + self.w = w + self.task = task + self.nc = nc + self.kpt_shape = kpt_shape + + def forward(self, x: torch.Tensor): + """Run the wrapped model and normalize its coordinate channels by input size.""" + y = self.model(x) + det = y[0] if isinstance(y, (tuple, list)) else y + box_wh = torch.tensor([self.w, self.h, self.w, self.h], dtype=det.dtype, device=det.device).view(1, 4, 1) + parts = [det[:, :4] / box_wh] + if self.task == "pose" and self.kpt_shape: + parts.append(det[:, 4 : 4 + self.nc]) + b, _, a = det.shape + kpts = det[:, 4 + self.nc :].view(b, self.kpt_shape[0], self.kpt_shape[1], a) + kpt_wh = torch.tensor([self.w, self.h], dtype=det.dtype, device=det.device).view(1, 1, 2, 1) + kpts = torch.cat([kpts[:, :, :2] / kpt_wh, kpts[:, :, 2:]], dim=2) + parts.append(kpts.reshape(b, -1, a)) + else: + parts.append(det[:, 4 : 4 + self.nc]) + if det.shape[1] > 4 + self.nc: + parts.append(det[:, 4 + self.nc :]) + det = torch.cat(parts, dim=1) + return (det, *y[1:]) if isinstance(y, (tuple, list)) else det + + +def best_onnx_opset(onnx: types.ModuleType) -> int: + """Return max ONNX opset for this torch version with ONNX fallback.""" + version = ".".join(TORCH_VERSION.split(".")[:2]) + opset = { + "1.8": 12, + "1.9": 12, + "1.10": 13, + "1.11": 14, + "1.12": 15, + "1.13": 17, + "2.0": 17, # reduced from 18 to fix ONNX errors + "2.1": 17, # reduced from 19 + "2.2": 17, # reduced from 19 + "2.3": 17, # reduced from 19 + }.get(version, 18) + # torch>=2.4 supports opset>=19, but ONNX Runtime CUDA has no Resize-19 or ReduceMax-20 kernel, so opset>=19 runs + # those nodes on the CPU and copies their tensors back and forth. Its static INT8 quantization also rejects opset>=21. + return min(opset, onnx.defs.onnx_opset_version()) + + +@ThreadingLocked() +def torch2onnx( + model: torch.nn.Module, + im: torch.Tensor | tuple[torch.Tensor, ...], + output_file: Path | str, + opset: int = 14, + input_names: list[str] | None = None, + output_names: list[str] | None = None, + dynamic: dict | None = None, +) -> str: + """Export a PyTorch model to ONNX format. + + Args: + model (torch.nn.Module): The PyTorch model to export. + im (torch.Tensor | tuple[torch.Tensor, ...]): Example input tensor(s) for tracing. + output_file (Path | str): Path to save the exported ONNX file. + opset (int): ONNX opset version to use for export. + input_names (list[str] | None): List of input tensor names. Defaults to ``["images"]``. + output_names (list[str] | None): List of output tensor names. Defaults to ``["output0"]``. + dynamic (dict | None): Dictionary specifying dynamic axes for inputs and outputs. + + Returns: + (str): Path to the exported ONNX file. + """ + if input_names is None: + input_names = ["images"] + if output_names is None: + output_names = ["output0"] + kwargs = {"dynamo": False} if TORCH_2_4 else {} + torch.onnx.export( + model, + im, + output_file, + opset_version=opset, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic, + **kwargs, + ) + return str(output_file) + + +def modelopt_quantize_onnx( + onnx_file: str, + quantize: int | str | None = None, + dataset=None, + shape: tuple[int, int, int, int] = (1, 3, 640, 640), + dynamic: bool = False, + prefix: str = "", +) -> str: + """Bake reduced precision into an ONNX model for TensorRT 11 strongly-typed builds using NVIDIA ModelOpt. + + TensorRT 11 is strongly-typed only: it removed the FP16/INT8 builder flags and the ``IInt8Calibrator`` interface, so + reduced precision must be expressed in the ONNX graph itself before building. FP16 is applied via ModelOpt AutoCast + mixed-precision conversion and INT8 via explicit Q/DQ quantization with calibration. + + Args: + onnx_file (str): Path to the FP32 ONNX file to convert. + quantize (int | str | None): Precision scheme, 8 for INT8 Q/DQ nodes or 16 for FP16 precision. + dataset (ultralytics.data.build.InfiniteDataLoader | None): Dataloader providing INT8 calibration images. + Required when ``quantize=8``. + shape (tuple[int, int, int, int]): Input shape (batch, channels, height, width) used for dynamic calibration. + dynamic (bool): Whether the ONNX model uses dynamic input shapes. + prefix (str): Prefix for log messages. + + Returns: + (str): Path to the precision-converted ONNX file. + """ + if quantize == 8 and dataset is None: + raise ValueError("INT8 ModelOpt quantization requires a calibration dataset.") + + # Require modelopt >= 0.44: older releases import onnx.mapping which was removed in onnx >= 1.18 and crash + check_requirements("nvidia-modelopt[onnx]>=0.44") + import onnx + + input_name = onnx.load(onnx_file, load_external_data=False).graph.input[0].name + if quantize == 8: + from modelopt.onnx.quantization import quantize as modelopt_quantize + + out_file = str(Path(onnx_file).with_suffix(".int8.onnx")) + # Collect up to ~500 calibration images (TensorRT recommendation); ModelOpt holds them in memory at once, + # so cap the count to bound memory instead of materializing the entire (possibly thousands-image) dataset. + images, n = [], 0 + for batch in dataset: + images.append(batch["img"]) + n += images[-1].shape[0] + if n >= 512: + break + calib = torch.cat(images) + del images, batch + calib = calib.to(torch.float32).div_(255.0) + LOGGER.info(f"{prefix} quantizing ONNX to INT8 with ModelOpt using {calib.shape[0]} calibration images...") + kwargs = {"calibration_shapes": f"{input_name}:{'x'.join(str(d) for d in shape)}"} if dynamic else {} + modelopt_quantize( + onnx_file, + quantize_mode="int8", + calibration_data={input_name: calib.cpu().numpy()}, + calibration_method="max", + # Calibrate on CPU. ModelOpt's CUDA EP session can hit an uncatchable cuDNN-ABI segfault (its pinned + # onnxruntime-gpu's cuDNN vs the installed torch's) and the TensorRT EP aborts on RTX cards (NvTensorRTRTX); + # scales are EP-independent, so the INT8 engine is equivalent and only this one-time step is slower. + calibration_eps=["cpu"], + # The head's output convolutions, the bare `nn.Conv2d` after each pair of `Conv` blocks, and DFL's fixed + # conv cost most of the INT8 accuracy for a small share of the runtime, so they stay in float + nodes_to_exclude=[r".*\.2/Conv$", r".*/dfl/"], + output_path=out_file, + **kwargs, + ) + return out_file + + from modelopt.onnx import autocast + + out_file = str(Path(onnx_file).with_suffix(".fp16.onnx")) + LOGGER.info(f"{prefix} converting ONNX to FP16 mixed precision with ModelOpt AutoCast...") + # AutoCast keeps a node in FP32 when its observed activation range exceeds `data_max`, so calibrate it on a real + # image: unstructured noise inflates the early activations and strands the first convolutions of most models. + im = cv2.resize(imread(ASSETS / "bus.jpg"), shape[:1:-1])[..., ::-1].transpose(2, 0, 1) # BGR HWC to RGB CHW + im = np.resize(im, shape[1:]) # repeat or drop channels for models that are not 3-channel + im = np.broadcast_to(im, shape).astype(np.float32, order="C") / 255 + onnx.save( + autocast.convert_to_mixed_precision( + onnx_file, + low_precision_type="fp16", + keep_io_types=True, + calibration_data={input_name: im}, + ), + out_file, + ) + return out_file + + +def onnx2engine( + onnx_file: str, + output_file: Path | str | None = None, + workspace: int | None = None, + quantize: int | str | None = None, + dynamic: bool = False, + shape: tuple[int, int, int, int] = (1, 3, 640, 640), + dla: int | None = None, + dataset=None, + metadata: dict | None = None, + verbose: bool = False, + prefix: str = "", +) -> str: + """Export a YOLO model to TensorRT engine format. + + Args: + onnx_file (str): Path to the ONNX file to be converted. + output_file (Path | str | None): Path to save the generated TensorRT engine file. + workspace (int | None): Workspace size in GB for TensorRT. + quantize (int | str | None): Precision scheme, 16 for FP16 or 8 for INT8. + dynamic (bool, optional): Enable dynamic input shapes. + shape (tuple[int, int, int, int], optional): Input shape (batch, channels, height, width). + dla (int | None): DLA core to use (Jetson devices only). + dataset (ultralytics.data.build.InfiniteDataLoader, optional): Dataset for INT8 calibration, unused when the + ONNX graph already carries Q/DQ ranges. + metadata (dict | None): Metadata to include in the engine file. + verbose (bool, optional): Enable verbose logging. + prefix (str, optional): Prefix for log messages. + + Returns: + (str): Path to the exported engine file. + + Raises: + ValueError: If DLA is enabled on non-Jetson devices or required precision is not set. + RuntimeError: If the ONNX file cannot be parsed. + + Notes: + TensorRT version compatibility is handled for workspace size and engine building. On TensorRT 7-10, INT8 + calibration uses an ``IInt8Calibrator`` over ``dataset`` and writes a calibration cache, while FP16/INT8 are + enabled with builder flags. On TensorRT 11 these were removed in favor of strongly-typed networks, so reduced + precision is baked into the ONNX with NVIDIA ModelOpt before building (FP16 AutoCast, INT8 explicit Q/DQ) by + `modelopt_quantize_onnx`. The TensorRT 7-10 path keeps the head Sigmoid layers in FP32 to preserve + confidence-score calibration (see #24668) and the head's output convolutions in FP16 for accuracy. Metadata is + serialized and written to the engine file if provided. + """ + import onnx + + # Force re-install TensorRT on CUDA 13 ARM devices to 10.15.x versions for RT-DETR exports + # https://github.com/ultralytics/ultralytics/issues/22873 + if is_jetson(jetpack=7) or is_dgx(): + check_tensorrt("10.15") + + try: + import tensorrt as trt + except ImportError: + check_tensorrt() + import tensorrt as trt + check_version(trt.__version__, ">=7.0.0", hard=True) + check_version(trt.__version__, "!=10.2.0", msg="https://github.com/ultralytics/ultralytics/pull/24367") + + LOGGER.info(f"\n{prefix} starting export with TensorRT {trt.__version__}...") + output_file = output_file or Path(onnx_file).with_suffix(".engine") + + logger = trt.Logger(trt.Logger.INFO) + if verbose: + logger.min_severity = trt.Logger.Severity.VERBOSE + + # Engine builder + builder = trt.Builder(logger) + config = builder.create_builder_config() + workspace_bytes = int((workspace or 0) * (1 << 30)) + trt_major = int(trt.__version__.split(".", 1)[0]) + is_trt10 = trt_major >= 10 + # TensorRT >= 11 is strongly-typed only: precision builder flags and IInt8Calibrator removed + is_trt11 = trt_major >= 11 + if workspace_bytes > 0: + if hasattr(config, "set_memory_pool_limit"): + config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace_bytes) + else: # TensorRT 7 fallback + config.max_workspace_size = workspace_bytes + # EXPLICIT_BATCH flag is removed in TensorRT 10 (explicit batch is the only/default mode); keep it for TRT 7/8 + flag = 0 if is_trt10 else (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) + network = builder.create_network(flag) + # platform_has_fast_fp16/int8 were removed from the Builder in TensorRT 10; default to True when absent + use_fp16 = getattr(builder, "platform_has_fast_fp16", True) and quantize == 16 + use_int8 = getattr(builder, "platform_has_fast_int8", True) and quantize == 8 + qdq = any(n.op_type == "QuantizeLinear" for n in onnx.load(onnx_file, load_external_data=False).graph.node) + calibrate = use_int8 and not qdq # explicit quantization carries its ranges in the graph + if calibrate and dataset is None: + raise ValueError("INT8 TensorRT export requires a calibration dataset.") + + # Optionally switch to DLA if enabled + if dla is not None: + if not IS_JETSON: + raise ValueError("DLA is only available on NVIDIA Jetson devices") + if check_version(trt.__version__, ">=11.0.0,<11.1.0"): + # DLA is unsupported in TensorRT 11.0 and is planned to return in a later release + # https://docs.nvidia.com/deeplearning/tensorrt/latest/api/migration/tensorrt-10x-to-11x-jetson.html + raise ValueError("DLA is not supported in TensorRT 11.0; export with TensorRT 10.x to use DLA.") + LOGGER.info(f"{prefix} enabling DLA on core {dla}...") + if not use_fp16 and not use_int8: + raise ValueError( + "DLA requires either quantize=16 (FP16) or quantize=8 (INT8). Please enable one of them and try again." + ) + config.default_device_type = trt.DeviceType.DLA + config.DLA_core = int(dla) + config.set_flag(trt.BuilderFlag.GPU_FALLBACK) + + # TensorRT 11 is strongly-typed and removed the FP16/INT8 builder flags and INT8 calibrator, so reduced + # precision must be baked into the ONNX graph with NVIDIA ModelOpt before parsing (FP16 AutoCast, INT8 Q/DQ) + if is_trt11 and (use_fp16 or use_int8): + onnx_file = modelopt_quantize_onnx(onnx_file, 16 if qdq else quantize, dataset, shape, dynamic, prefix) + + # Read ONNX file + parser = trt.OnnxParser(network, logger) + if not parser.parse_from_file(onnx_file): + raise RuntimeError(f"failed to load ONNX file: {onnx_file}") + + # Network inputs + inputs = [network.get_input(i) for i in range(network.num_inputs)] + outputs = [network.get_output(i) for i in range(network.num_outputs)] + for inp in inputs: + LOGGER.info(f'{prefix} input "{inp.name}" with shape{inp.shape} {inp.dtype}') + for out in outputs: + LOGGER.info(f'{prefix} output "{out.name}" with shape{out.shape} {out.dtype}') + + if dynamic: + profile = builder.create_optimization_profile() + min_shape = (1, shape[1], 32, 32) # minimum input shape + max_shape = (*shape[:2], *(int(max(2, workspace or 2) * d) for d in shape[2:])) # max input shape + for inp in inputs: + inp_min = tuple(d if d != -1 else lo for d, lo in zip(inp.shape, min_shape)) + inp_max = tuple(d if d != -1 else hi for d, hi in zip(inp.shape, max_shape)) + profile.set_shape(inp.name, min=inp_min, opt=shape, max=inp_max) + config.add_optimization_profile(profile) + if calibrate and not is_trt10: # deprecated in TensorRT 10, causes internal errors + config.set_calibration_profile(profile) + + LOGGER.info( + f"{prefix} building {'INT8' if use_int8 else 'FP' + ('16' if use_fp16 else '32')} engine as {output_file}" + ) + if use_int8 and not is_trt11: + config.set_flag(trt.BuilderFlag.INT8) + config.profiling_verbosity = trt.ProfilingVerbosity.DETAILED + if (use_fp16 or use_int8 or qdq) and not is_trt11: # unquantized layers take the fastest precision allowed + config.set_flag(trt.BuilderFlag.FP16) + + # Explicit Q/DQ graphs need neither calibration nor per-layer Sigmoid constraints. + if calibrate and not is_trt11: + + class EngineCalibrator(trt.IInt8Calibrator): + """Custom INT8 calibrator for TensorRT engine optimization. + + This calibrator provides the necessary interface for TensorRT to perform INT8 quantization calibration using + a dataset. It handles batch generation, caching, and calibration algorithm selection. + + Attributes: + dataset: Dataset for calibration. + data_iter: Iterator over the calibration dataset. + algo (trt.CalibrationAlgoType): Calibration algorithm type. + batch (int): Batch size for calibration. + cache (Path): Path to save the calibration cache. + + Methods: + get_algorithm: Get the calibration algorithm to use. + get_batch_size: Get the batch size to use for calibration. + get_batch: Get the next batch to use for calibration. + read_calibration_cache: Use existing cache instead of calibrating again. + write_calibration_cache: Write calibration cache to disk. + """ + + def __init__( + self, + dataset, # ultralytics.data.build.InfiniteDataLoader + cache: str = "", + ) -> None: + """Initialize the INT8 calibrator with dataset and cache path.""" + trt.IInt8Calibrator.__init__(self) + self.dataset = dataset + self.data_iter = iter(dataset) + self.algo = ( + trt.CalibrationAlgoType.ENTROPY_CALIBRATION_2 # DLA quantization needs ENTROPY_CALIBRATION_2 + if dla is not None + else trt.CalibrationAlgoType.MINMAX_CALIBRATION + ) + self.batch = dataset.batch_size + self.cache = Path(cache) + + def get_algorithm(self) -> trt.CalibrationAlgoType: + """Get the calibration algorithm to use.""" + return self.algo + + def get_batch_size(self) -> int: + """Get the batch size to use for calibration.""" + return self.batch or 1 + + def get_batch(self, names) -> list[int] | None: + """Get the next batch to use for calibration, as a list of device memory pointers.""" + try: + im0s = next(self.data_iter)["img"] / 255.0 + im0s = im0s.to("cuda") if im0s.device.type == "cpu" else im0s + return [int(im0s.data_ptr())] + except StopIteration: + # Return None to signal to TensorRT there is no calibration data remaining + return None + + def read_calibration_cache(self) -> bytes | None: + """Use existing cache instead of calibrating again, otherwise, implicitly return None.""" + if self.cache.exists() and self.cache.suffix == ".cache": + return self.cache.read_bytes() + + def write_calibration_cache(self, cache: bytes) -> None: + """Write calibration cache to disk.""" + _ = self.cache.write_bytes(cache) + + # Load dataset w/ builder (for batching) and calibrate + config.int8_calibrator = EngineCalibrator( + dataset=dataset, + cache=str(Path(onnx_file).with_suffix(".cache")), + ) + + # Implicit quantization cannot exclude op types like ModelOpt on TRT 11, so keep the head Sigmoid (an + # ACTIVATION layer named after its ONNX node) in FP32 via per-layer precision constraints to preserve + # confidence-score calibration, mirroring the OpenVINO IgnoredScope + # https://github.com/ultralytics/ultralytics/issues/24668, and the head's output convolutions and DFL in FP16 + # as `modelopt_quantize_onnx` does. Scope this to the head: every SiLU activation is also a Sigmoid, and + # constraining all of them costs INT8 speed across backbone and neck. + names = [network.get_layer(i).name for i in range(network.num_layers)] + indices = [int(m.group(1)) for n in names if (m := re.match(r"/model\.(\d+)/", n))] + head = f"/model.{max(indices)}/" if indices else "/" + count = 0 + for i in range(network.num_layers): + layer = network.get_layer(i) + if not layer.name.startswith(head): + continue + if layer.type == trt.LayerType.ACTIVATION and "sigmoid" in layer.name.lower(): + dtype = trt.float32 + elif layer.type == trt.LayerType.CONVOLUTION and (layer.name.endswith(".2/Conv") or "/dfl/" in layer.name): + dtype = trt.float16 + else: + continue + layer.precision = dtype + for j in range(layer.num_outputs): + layer.set_output_type(j, dtype) + count += 1 + if count: + flag = ( + trt.BuilderFlag.OBEY_PRECISION_CONSTRAINTS + if hasattr(trt.BuilderFlag, "OBEY_PRECISION_CONSTRAINTS") + else trt.BuilderFlag.STRICT_TYPES + ) + config.set_flag(flag) # OBEY_PRECISION_CONSTRAINTS replaced STRICT_TYPES in TensorRT 8.2 + LOGGER.info(f"{prefix} keeping {count} head layers out of INT8 for accuracy") + + # Write file + if hasattr(builder, "build_serialized_network"): + engine = builder.build_serialized_network(network, config) + else: + engine = builder.build_engine(network, config) + engine = None if engine is None else engine.serialize() + if engine is None: + raise RuntimeError("TensorRT engine build failed, check logs for errors") + with open(output_file, "wb") as t: + if metadata is not None: + meta = json.dumps(metadata) + t.write(len(meta).to_bytes(4, byteorder="little", signed=True)) + t.write(meta.encode()) + t.write(engine) + return str(output_file) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/executorch.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/executorch.py new file mode 100644 index 0000000000000000000000000000000000000000..9360daec10fa1666358aadcf3147c2a2ccf55a30 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/executorch.py @@ -0,0 +1,80 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from functools import partial +from pathlib import Path + +import torch + +from ultralytics.nn.modules import Pose, Pose26 +from ultralytics.utils import LOGGER, YAML +from ultralytics.utils.checks import check_executorch_requirements + + +def executorch_wrapper(model: torch.nn.Module) -> torch.nn.Module: + """Apply ExecuTorch-specific model patches required for export/runtime compatibility.""" + import types + + for m in model.modules(): + if not isinstance(m, Pose): + continue + m.kpts_decode = types.MethodType(partial(_executorch_kpts_decode, is_pose26=type(m) is Pose26), m) + return model + + +def _executorch_kpts_decode(self, kpts: torch.Tensor, is_pose26: bool = False) -> torch.Tensor: + """Decode pose keypoints for ExecuTorch export with XNNPACK-safe broadcasting.""" + ndim = self.kpt_shape[1] + bs = kpts.shape[0] + y = kpts.view(bs, *self.kpt_shape, -1) + + # XNNPACK requires explicit dim matching for broadcasting, expand 2D tensors to 4D. + anchors = self.anchors[None, None] + strides = self.strides[None, None] + a = ((y[:, :, :2] + anchors) if is_pose26 else (y[:, :, :2] * 2.0 + (anchors - 0.5))) * strides + if ndim == 3: + a = torch.cat((a, y[:, :, 2:3].sigmoid()), 2) + return a.view(bs, self.nk, -1) + + +def torch2executorch( + model: torch.nn.Module, + im: torch.Tensor, + output_dir: Path | str, + metadata: dict | None = None, + prefix: str = "", +) -> str: + """Export a PyTorch model to ExecuTorch format. + + Args: + model (torch.nn.Module): The PyTorch model to export. + im (torch.Tensor): Example input tensor for tracing/export. + output_dir (Path | str): Directory to save the exported ExecuTorch model. + metadata (dict | None, optional): Optional metadata to save as YAML. + prefix (str, optional): Prefix for log messages. + + Returns: + (str): Path to the exported ExecuTorch model directory. + """ + check_executorch_requirements() + from executorch import version as executorch_version + from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner + from executorch.exir import to_edge_transform_and_lower + + LOGGER.info(f"\n{prefix} starting export with ExecuTorch {executorch_version.__version__}...") + + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + pte_file = output_dir / "model.pte" + et_program = to_edge_transform_and_lower( + torch.export.export(model, (im,)), + partitioner=[XnnpackPartitioner()], + ).to_executorch() + pte_file.write_bytes(et_program.buffer) + + if metadata is not None: + YAML.save(output_dir / "metadata.yaml", metadata) + + return str(output_dir) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/imx.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/imx.py new file mode 100644 index 0000000000000000000000000000000000000000..83591cd0ee26f0551ceb932b486d5e5016988449 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/imx.py @@ -0,0 +1,370 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import re +import subprocess +import sys +import types +from pathlib import Path +from shutil import which + +import numpy as np +import torch + +from ultralytics.nn.modules import Detect, Pose, Segment +from ultralytics.utils import IS_DEBIAN_BOOKWORM, IS_DEBIAN_TRIXIE, IS_RASPBERRYPI, IS_UBUNTU, LOGGER, WINDOWS +from ultralytics.utils.checks import check_apt_requirements, check_requirements +from ultralytics.utils.patches import onnx_export_patch +from ultralytics.utils.tal import make_anchors +from ultralytics.utils.torch_utils import copy_attr + +# Configuration for Model Compression Toolkit (MCT) quantization +MCT_CONFIG = { + "YOLO11": { + "detect": { + "layer_names": ["sub", "mul_2", "add_14", "cat_19"], + "weights_memory": 2585350.2439, + "n_layers": {238, 239}, + }, + "pose": { + "layer_names": ["sub", "mul_2", "add_14", "cat_21", "cat_22", "mul_4", "add_15"], + "weights_memory": 2437771.67, + "n_layers": {257, 258}, + }, + "classify": {"layer_names": [], "weights_memory": np.inf, "n_layers": {112}}, + "segment": { + "layer_names": ["sub", "mul_2", "add_14", "cat_21"], + "weights_memory": 2466604.8, + "n_layers": {265, 266}, + }, + }, + "YOLOv8": { + "detect": { + "layer_names": ["sub", "mul", "add_6", "cat_15"], + "weights_memory": 2550540.8, + "n_layers": {168, 169}, + }, + "pose": { + "layer_names": ["add_7", "mul_2", "cat_17", "mul", "sub", "add_6", "cat_18"], + "weights_memory": 2482451.85, + "n_layers": {187, 188}, + }, + "classify": {"layer_names": [], "weights_memory": np.inf, "n_layers": {73}}, + "segment": { + "layer_names": ["sub", "mul", "add_6", "cat_17"], + "weights_memory": 2580060.0, + "n_layers": {195, 196}, + }, + }, +} + + +class FXModel(torch.nn.Module): + """A custom model class for torch.fx compatibility. + + This class extends `torch.nn.Module` and is designed to ensure compatibility with torch.fx for tracing and graph + manipulation. It copies attributes from an existing model and explicitly sets the model attribute to ensure proper + copying. + + Attributes: + model (nn.Module): The original model's layers. + imgsz (tuple[int, int]): The input image size (height, width). + """ + + def __init__(self, model, imgsz=(640, 640)): + """Initialize the FXModel. + + Args: + model (nn.Module): The original model to wrap for torch.fx compatibility. + imgsz (tuple[int, int]): The input image size (height, width). Default is (640, 640). + """ + super().__init__() + copy_attr(self, model) + # Explicitly set `model` since `copy_attr` somehow does not copy it. + self.model = model.model + self.imgsz = imgsz + + def forward(self, x): + """Forward pass through the model. + + This method performs the forward pass through the model, handling the dependencies between layers and saving + intermediate outputs. + + Args: + x (torch.Tensor): The input tensor to the model. + + Returns: + (torch.Tensor): The output tensor from the model. + """ + y = [] # outputs + for m in self.model: + if m.f != -1: # if not from previous layer + # from earlier layers + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] + if isinstance(m, Detect): + m._inference = types.MethodType(_inference, m) # bind method to Detect + m.anchors, m.strides = ( + x.transpose(0, 1) + for x in make_anchors( + torch.cat([s / m.stride.unsqueeze(-1) for s in self.imgsz], dim=1), m.stride, 0.5 + ) + ) + if type(m) is Pose: + m.forward = types.MethodType(pose_forward, m) # bind method to Pose + if type(m) is Segment: + m.forward = types.MethodType(segment_forward, m) # bind method to Segment + x = m(x) # run + y.append(x) # save output + return x + + +def _inference(self, x: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]: + """Decode boxes and cls scores for imx object detection.""" + dbox = self.decode_bboxes(self.dfl(x["boxes"]), self.anchors.unsqueeze(0)) * self.strides + return dbox.transpose(1, 2), x["scores"].sigmoid().permute(0, 2, 1) + + +def pose_forward(self, x: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Forward pass for imx pose estimation, including keypoint decoding.""" + bs = x[0].shape[0] # batch size + nk_out = getattr(self, "nk_output", self.nk) + kpt = torch.cat([self.cv4[i](x[i]).view(bs, nk_out, -1) for i in range(self.nl)], -1) + + # If using Pose26 with 5 dims, convert to 3 dims for export + if hasattr(self, "nk_output") and self.nk_output != self.nk: + spatial = kpt.shape[-1] + kpt = kpt.view(bs, self.kpt_shape[0], self.kpt_shape[1] + 2, spatial) + kpt = kpt[:, :, :-2, :] # Remove sigma_x, sigma_y + kpt = kpt.view(bs, self.nk, spatial) + x = Detect.forward(self, x) + pred_kpt = self.kpts_decode(kpt) + return *x, pred_kpt.permute(0, 2, 1) + + +def segment_forward(self, x: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Forward pass for imx segmentation.""" + p = self.proto(x[0]) # mask protos + bs = p.shape[0] # batch size + mc = torch.cat([self.cv4[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) # mask coefficients + x = Detect.forward(self, x) + return *x, mc.transpose(1, 2), p + + +class NMSWrapper(torch.nn.Module): + """Wrap PyTorch Module with multiclass_nms layer from edge-mdt-cl.""" + + def __init__( + self, + model: torch.nn.Module, + score_threshold: float = 0.001, + iou_threshold: float = 0.7, + max_detections: int = 300, + task: str = "detect", + ): + """Initialize NMSWrapper with PyTorch Module and NMS parameters. + + Args: + model (torch.nn.Module): Model instance. + score_threshold (float): Score threshold for non-maximum suppression. + iou_threshold (float): Intersection over union threshold for non-maximum suppression. + max_detections (int): The number of detections to return. + task (str): Task type, one of 'detect', 'pose', or 'segment'. + """ + super().__init__() + self.model = model + self.score_threshold = score_threshold + self.iou_threshold = iou_threshold + self.max_detections = max_detections + self.task = task + + def forward(self, images): + """Forward pass with model inference and NMS post-processing.""" + from edgemdt_cl.pytorch.nms.nms_with_indices import multiclass_nms_with_indices + + # model inference + outputs = self.model(images) + boxes, scores = outputs[0], outputs[1] + nms_outputs = multiclass_nms_with_indices( + boxes=boxes, + scores=scores, + score_threshold=self.score_threshold, + iou_threshold=self.iou_threshold, + max_detections=self.max_detections, + ) + if self.task == "pose": + kpts = outputs[2] # (bs, max_detections, kpts 17*3) + out_kpts = torch.gather(kpts, 1, nms_outputs.indices.unsqueeze(-1).expand(-1, -1, kpts.size(-1))) + return nms_outputs.boxes, nms_outputs.scores, nms_outputs.labels, out_kpts + if self.task == "segment": + mc, proto = outputs[2], outputs[3] + out_mc = torch.gather(mc, 1, nms_outputs.indices.unsqueeze(-1).expand(-1, -1, mc.size(-1))) + return nms_outputs.boxes, nms_outputs.scores, nms_outputs.labels, out_mc, proto + return nms_outputs.boxes, nms_outputs.scores, nms_outputs.labels, nms_outputs.n_valid + + +def torch2imx( + model: torch.nn.Module, + output_dir: Path | str, + conf: float, + iou: float, + max_det: int, + metadata: dict | None = None, + gptq: bool = False, + dataset=None, + prefix: str = "", +) -> str: + """Export YOLO model to IMX format for deployment on Sony IMX500 devices. + + This function quantizes a YOLO model using Model Compression Toolkit (MCT) and exports it to IMX format compatible + with Sony IMX500 edge devices. It supports both YOLOv8n and YOLO11n models for detection, segmentation, pose + estimation, and classification tasks. + + Args: + model (torch.nn.Module): The YOLO model to export. Must be YOLOv8n or YOLO11n. + output_dir (Path | str): Directory to save the exported IMX model. + conf (float): Confidence threshold for NMS post-processing. + iou (float): IoU threshold for NMS post-processing. + max_det (int): Maximum number of detections to return. + metadata (dict | None, optional): Metadata to embed in the ONNX model. Defaults to None. + gptq (bool, optional): Whether to use Gradient-Based Post Training Quantization. If False, uses standard Post + Training Quantization. Defaults to False. + dataset (optional): Representative dataset for quantization calibration. Defaults to None. + prefix (str, optional): Logging prefix string. Defaults to "". + + Returns: + (str): Path to the exported IMX model directory. + + Raises: + ValueError: If the model is not a supported YOLOv8n or YOLO11n variant. + + Examples: + >>> from ultralytics import YOLO + >>> model = YOLO("yolo11n.pt") + >>> path = torch2imx(model, "output_dir/", conf=0.25, iou=0.7, max_det=300) + + Notes: + - Auto-installs Java>=17, model-compression-toolkit, imx500-converter, and related packages if not present + - Only supports YOLOv8n and YOLO11n models (detection, segmentation, pose, and classification tasks) + - Output includes quantized ONNX model, IMX binary, and labels.txt file + """ + # Install Java>=17 + try: + java_output = subprocess.run(["java", "--version"], check=True, capture_output=True).stdout.decode() + version_match = re.search(r"(?:openjdk|java) (\d+)", java_output) + java_version = int(version_match.group(1)) if version_match else 0 + assert java_version >= 17, "Java version too old" + except (FileNotFoundError, subprocess.CalledProcessError, AssertionError): + if IS_UBUNTU or IS_DEBIAN_TRIXIE: + check_apt_requirements(["openjdk-21-jre"]) + elif IS_RASPBERRYPI or IS_DEBIAN_BOOKWORM: + check_apt_requirements(["openjdk-17-jre"]) + + check_requirements( + ( + "model-compression-toolkit>=2.4.1", + "edge-mdt-cl<1.1.0", + "edge-mdt-tpc>=1.2.0", + "pydantic<2.12", + ) + ) + check_requirements("imx500-converter[pt]>=3.17.3") + dataset = dataset() if callable(dataset) else dataset # resolve lazy dataloader + + import model_compression_toolkit as mct + import onnx + from edgemdt_tpc import get_target_platform_capabilities + + LOGGER.info(f"\n{prefix} starting export with model_compression_toolkit {mct.__version__}...") + + def representative_dataset_gen(dataloader=dataset): + for batch in dataloader: + img = batch["img"] + img = img / 255.0 + yield [img] + + # NOTE: need tpc_version to be "4.0" for IMX500 Pose estimation models + tpc = get_target_platform_capabilities(tpc_version="4.0", device_type="imx500") + + bit_cfg = mct.core.BitWidthConfig() + mct_config = MCT_CONFIG["YOLO11" if "C2PSA" in model.__str__() else "YOLOv8"][model.task] + + # Check if the model has the expected number of layers + if len(list(model.modules())) not in mct_config["n_layers"]: + raise ValueError("IMX export only supported for YOLOv8n and YOLO11n models.") + + for layer_name in mct_config["layer_names"]: + bit_cfg.set_manual_activation_bit_width([mct.core.common.network_editors.NodeNameFilter(layer_name)], 16) + + config = mct.core.CoreConfig( + mixed_precision_config=mct.core.MixedPrecisionQuantizationConfig(num_of_images=10), + quantization_config=mct.core.QuantizationConfig(concat_threshold_update=True), + bit_width_config=bit_cfg, + ) + + resource_utilization = mct.core.ResourceUtilization(weights_memory=mct_config["weights_memory"]) + + quant_model = ( + mct.gptq.pytorch_gradient_post_training_quantization( # Perform Gradient-Based Post Training Quantization + model=model, + representative_data_gen=representative_dataset_gen, + target_resource_utilization=resource_utilization, + gptq_config=mct.gptq.get_pytorch_gptq_config( + n_epochs=1000, use_hessian_based_weights=False, use_hessian_sample_attention=False + ), + core_config=config, + target_platform_capabilities=tpc, + )[0] + if gptq + else mct.ptq.pytorch_post_training_quantization( # Perform post training quantization + in_module=model, + representative_data_gen=representative_dataset_gen, + target_resource_utilization=resource_utilization, + core_config=config, + target_platform_capabilities=tpc, + )[0] + ) + + if model.task != "classify": + quant_model = NMSWrapper( + model=quant_model, + score_threshold=0.001 if conf is None else conf, + iou_threshold=iou, + max_detections=max_det, + task=model.task, + ) + + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + onnx_model = output_dir / "model_imx.onnx" + + with onnx_export_patch(): + mct.exporter.pytorch_export_model( + model=quant_model, save_model_path=onnx_model, repr_dataset=representative_dataset_gen + ) + + model_onnx = onnx.load(onnx_model) # load onnx model + for k, v in (metadata or {}).items(): + meta = model_onnx.metadata_props.add() + meta.key, meta.value = k, str(v) + + onnx.save(model_onnx, onnx_model) + + # Find imxconv-pt binary - check venv bin directory first, then PATH + bin_dir = Path(sys.executable).parent + imxconv = bin_dir / ("imxconv-pt.exe" if WINDOWS else "imxconv-pt") + if not imxconv.exists(): + imxconv = which("imxconv-pt") # fallback to PATH + if not imxconv: + raise FileNotFoundError("imxconv-pt not found. Install with: pip install imx500-converter[pt]") + + subprocess.run( + [str(imxconv), "-i", str(onnx_model), "-o", str(output_dir), "--no-input-persistency", "--overwrite-output"], + check=True, + ) + + # Needed for imx models. + with open(output_dir / "labels.txt", "w", encoding="utf-8") as labels_file: + labels_file.writelines([f"{name}\n" for _, name in model.names.items()]) + + return str(output_dir) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/litert.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/litert.py new file mode 100644 index 0000000000000000000000000000000000000000..09a733eb05922fbd02e25903cd5ce5511cd1478a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/litert.py @@ -0,0 +1,134 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import json +import types +import zipfile +from pathlib import Path + +import torch + +from ultralytics.nn.modules import Detect +from ultralytics.utils import LOGGER +from ultralytics.utils.export.engine import _NormalizeCoords + + +def _litert_grouped_topk(x: torch.Tensor, k: int, groups: int) -> tuple[torch.Tensor, torch.Tensor]: + """Select the top k of x along dim 1 with int32 indices, which GPU delegates accept and int64 they do not.""" + values, index = Detect._grouped_topk(x, k, groups) + return values, index.int() + + +def _litert_gather(self, x: torch.Tensor, index: torch.Tensor) -> torch.Tensor: + """Select index (batch, k) rows of x along dim 1 without gather_nd, which GPU delegates do not implement.""" + b, n = x.shape[:2] + offset = torch.arange(b, device=x.device, dtype=index.dtype)[..., None] * n + return x.flatten(0, 1).index_select(0, (index + offset).flatten()).view(b, index.shape[1], *x.shape[2:]) + + +def torch2litert( + model: torch.nn.Module, + im: torch.Tensor, + file: Path, + quantize: int | str | None, + calibration_dataset: torch.utils.data.DataLoader | None, + metadata: dict | None, + prefix: str, +) -> Path: + """Export a PyTorch model to LiteRT format using litert_torch, with optional INT8 quantization. + + Three INT8 schemes are supported via ``quantize``: ``8`` applies static INT8 (int8 weights + int8 activations) and + ``'w8a16'`` applies static INT8 weights with int16 activations, both requiring a ``calibration_dataset``; + ``'w8a32'`` applies dynamic/weight-only INT8 (int8 weights + FP32 activations) and needs no calibration. + ``None``/``32`` exports FP32. FP16 is not exported as a separate model: LiteRT runs an FP32 model in FP16 at runtime + via the GPU delegate (FP16 by default) or the XNNPACK ``FORCE_FP16`` flag on ARM. + + Args: + model (torch.nn.Module): The PyTorch model to export. + im (torch.Tensor): Example input tensor for tracing. + file (Path | str): Source model file path used to derive output directory. + quantize (int | str | None): Quantization scheme: ``8`` (static INT8), ``'w8a16'`` (static int8 weights + int16 + activations), ``'w8a32'`` (dynamic INT8), or ``None``/``32`` (FP32). + calibration_dataset (DataLoader | None): Calibration dataloader for static quantization, as returned by + ``get_int8_calibration_dataloader``. Required when ``quantize`` is ``8`` or ``'w8a16'``. + metadata (dict | None): Optional metadata embedded in the ``.tflite`` as a ``metadata.json`` entry. + prefix (str): Prefix for log messages. + + Returns: + (Path): Path to the exported ``.tflite`` file with metadata embedded as a ``metadata.json`` entry. + """ + from ultralytics.utils.checks import check_requirements + + check_requirements(("litert-torch>=0.9.0", "ai-edge-litert>=2.1.4")) + import litert_torch + + static_int8 = quantize == 8 + static_int16 = quantize == "w8a16" + dynamic_int8 = quantize == "w8a32" + LOGGER.info(f"\n{prefix} starting export with litert_torch {litert_torch.__version__}...") + file = Path(file) + quant_tag = "_int8" if static_int8 else "_w8a16" if static_int16 else "_w8a32" if dynamic_int8 else "" + + # Normalize coordinate channels by input size so INT8 quantization preserves scores (denormalized in LiteRTBackend). + # End-to-end models output post-NMS pixel coordinates in FP32 (no scale collapse), so they are left as-is. + meta = metadata or {} + task = meta.get("task") + if ( + task in {"detect", "segment", "pose", "obb"} + and not meta.get("end2end", False) + and meta.get("head") != "RTDETRDecoder" + ): + model = _NormalizeCoords( + model, int(im.shape[2]), int(im.shape[3]), task, len(meta.get("names", {})), meta.get("kpt_shape") + ) + + for m in model.modules(): # int32 indices and a gather_nd-free gather keep the head on the GPU delegate + if isinstance(m, Detect): + m._grouped_topk = _litert_grouped_topk + m._gather = types.MethodType(_litert_gather, m) + + # Lower index_select to tfl.gather: the default lowering emits GATHER_ND, which GPU delegates do not implement + litert_torch.fx_infra.decomp.add_pre_lower_decomp( + torch.ops.aten.index_select.default, lambda x, dim, index: torch.ops.tfl.gather(x, index.int(), dim) + ) + edge_model = litert_torch.convert(model.eval(), (im,)) # export wrappers default to training mode + tflite_file = file.with_name(f"{file.stem}{quant_tag}.tflite") + edge_model.export(tflite_file) + + if static_int8 or static_int16 or dynamic_int8: + check_requirements("ai-edge-quantizer>=0.6.0") + from ai_edge_quantizer import qtyping, quantizer, recipe + + qt = quantizer.Quantizer(str(tflite_file)) + if static_int8 or static_int16: # static schemes calibrate over representative images + act = "int8" if static_int8 else "int16" + LOGGER.info(f"{prefix} applying static quantization (int8 weights + {act} activations)...") + calib_samples = [] + for batch in calibration_dataset: + imgs = batch["img"].cpu().float() / 255.0 + # litert-torch traces a fixed batch; tile under-sized batches up to im's batch dim (repeats are + # statistics-identical for calibration) + if imgs.shape[0] < im.shape[0]: + imgs = imgs.repeat(-(-im.shape[0] // imgs.shape[0]), 1, 1, 1)[: im.shape[0]] + calib_samples.append({"args_0": imgs.numpy()}) + qt.load_quantization_recipe(recipe.static_wi8_ai8() if static_int8 else recipe.static_wi8_ai16()) + # Keep FP32 graph input/output (weights/activations stay int8/int16 internally): matches the historical + # onnx2tf "fp32 in/out" contract that downstream consumers (LiteRT GPU delegate, on-device runtimes) expect, + # and avoids forcing every consumer to (de)quantize at the boundary. Must run after load_quantization_recipe. + for op in (qtyping.TFLOperationName.INPUT, qtyping.TFLOperationName.OUTPUT): + qt.update_quantization_recipe( + regex=".*", operation_name=op, algorithm_key=recipe.AlgorithmName.NO_QUANTIZE + ) + result = qt.calibrate({"serving_default": calib_samples}) + qt.quantize(calibration_result=result).export_model(str(tflite_file), overwrite=True) + else: # dynamic / weight-only INT8: int8 weights, FP32 activations, no calibration needed + LOGGER.info(f"{prefix} applying dynamic INT8 quantization (int8 weights + FP32 activations)...") + qt.load_quantization_recipe(recipe.dynamic_wi8_afp32()) + qt.quantize().export_model(str(tflite_file), overwrite=True) + + # Embed metadata as a JSON entry appended to the .tflite (zip-tolerant flatbuffer), so the model is a single + # self-contained file that LiteRTBackend reads back at load time. + with zipfile.ZipFile(tflite_file, "a", zipfile.ZIP_DEFLATED) as zf: + zf.writestr("metadata.json", json.dumps(metadata or {})) + return tflite_file diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/mnn.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/mnn.py new file mode 100644 index 0000000000000000000000000000000000000000..5cbce56e871f1add15e9ac405c635c1e36fc542b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/mnn.py @@ -0,0 +1,61 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import json +from pathlib import Path + +from ultralytics.utils import LOGGER + + +def onnx2mnn( + onnx_file: str, + output_file: Path | str, + quantize: int | str | None = None, + metadata: dict | None = None, + prefix: str = "", +) -> str: + """Convert an ONNX model to MNN format. + + Args: + onnx_file (str): Path to the source ONNX file. + output_file (Path | str): Path to save the exported MNN model. + quantize (int | str | None): Precision scheme, e.g. 16 for FP16 or 8 for INT8 weights. + metadata (dict | None): Optional metadata embedded via ``--bizCode``. + prefix (str): Prefix for log messages. + + Returns: + (str): Path to the exported ``.mnn`` file. + """ + from ultralytics.utils.checks import check_requirements + from ultralytics.utils.torch_utils import TORCH_1_10 + + assert TORCH_1_10, "MNN export requires torch>=1.10.0 to avoid segmentation faults" + assert Path(onnx_file).exists(), f"failed to export ONNX file: {onnx_file}" + + check_requirements("MNN>=2.9.6") + import MNN + from MNN.tools import mnnconvert + + LOGGER.info(f"\n{prefix} starting export with MNN {MNN.version()}...") + mnn_args = [ + "", + "-f", + "ONNX", + "--modelFile", + onnx_file, + "--MNNModel", + str(output_file), + "--bizCode", + json.dumps(metadata or {}), + ] + if quantize == 8: + mnn_args.extend(("--weightQuantBits", "8")) + if quantize == 16: + mnn_args.append("--fp16") + mnnconvert.convert(mnn_args) + # Remove scratch file created during model convert optimize + convert_scratch = Path(output_file).parent / ".__convert_external_data.bin" + if convert_scratch.exists(): + convert_scratch.unlink() + return str(output_file) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/ncnn.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/ncnn.py new file mode 100644 index 0000000000000000000000000000000000000000..ebc2bb245e73e8e7a980e78dbf549f8b4f6ab362 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/ncnn.py @@ -0,0 +1,68 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import torch + +from ultralytics.utils import LOGGER, YAML + + +def torch2ncnn( + model: torch.nn.Module, + im: torch.Tensor, + output_dir: Path | str, + quantize: int | str | None = None, + metadata: dict | None = None, + device: torch.device | None = None, + prefix: str = "", +) -> str: + """Export a PyTorch model to NCNN format using PNNX. + + Args: + model (torch.nn.Module): The PyTorch model to export. + im (torch.Tensor): Example input tensor for tracing. + output_dir (Path | str): Directory to save the exported NCNN model. + quantize (int | str | None): Precision scheme, e.g. 16 for FP16. + metadata (dict | None): Optional metadata saved as ``metadata.yaml``. + device (torch.device | None): Device the model lives on. + prefix (str): Prefix for log messages. + + Returns: + (str): Path to the exported ``_ncnn_model`` directory. + """ + from ultralytics.utils.checks import check_requirements + + check_requirements("ncnn", cmds="--no-deps") # no deps to avoid installing opencv-python + # Pin until PNNX 20260704 NCNN inference segfault is fixed: https://github.com/pnnx/pnnx/issues/293 + check_requirements("pnnx==20260526") + import ncnn + import pnnx + + LOGGER.info(f"\n{prefix} starting export with NCNN {ncnn.__version__} and PNNX {pnnx.__version__}...") + output_dir = Path(output_dir) + + ncnn_args = { + "ncnnparam": (output_dir / "model.ncnn.param").as_posix(), + "ncnnbin": (output_dir / "model.ncnn.bin").as_posix(), + "ncnnpy": (output_dir / "model_ncnn.py").as_posix(), + } + pnnx_args = { + "ptpath": (output_dir / "model.pt").as_posix(), + "pnnxparam": (output_dir / "model.pnnx.param").as_posix(), + "pnnxbin": (output_dir / "model.pnnx.bin").as_posix(), + "pnnxpy": (output_dir / "model_pnnx.py").as_posix(), + "pnnxonnx": (output_dir / "model.pnnx.onnx").as_posix(), + } + + output_dir.mkdir(parents=True, exist_ok=True) # make ncnn_model directory + device_type = device.type if device is not None else "cpu" + pnnx.export(model, inputs=im, **ncnn_args, **pnnx_args, fp16=quantize == 16, device=device_type) + + for f_debug in ("debug.bin", "debug.param", "debug2.bin", "debug2.param", *pnnx_args.values()): + Path(f_debug).unlink(missing_ok=True) + + if metadata: + YAML.save(output_dir / "metadata.yaml", metadata) # add metadata.yaml + return str(output_dir) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/onnx.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a0badaffad1ebc3e2cd73cdf4622e7c50b7708 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/onnx.py @@ -0,0 +1,64 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import numpy as np + +from ultralytics.utils import LOGGER + + +def onnx_calibration_reader(dataset, transform_fn, input_name: str = "images", batch: int = 0): + """Create an ONNX Runtime calibration data reader from an Ultralytics calibration dataloader. + + `batch` is the graph's static batch dimension (0 for dynamic-batch models): calibration datasets smaller than the + export batch yield undersized batches that static graphs reject, so samples are tiled up to exactly `batch`. + """ + from onnxruntime.quantization import CalibrationDataReader + + class _CalibrationReader(CalibrationDataReader): + def __init__(self): + """Initialize calibration dataset iteration.""" + self.iterator = iter(dataset) + + def get_next(self): + """Return the next calibration sample, or None when exhausted.""" + if (b := next(self.iterator, None)) is None: + return None + im = transform_fn(b) + if batch and im.shape[0] != batch: # tile up to the static batch dimension + im = np.tile(im, (-(-batch // im.shape[0]), 1, 1, 1))[:batch] + return {input_name: im} + + def rewind(self): + """Reset the iterator for an additional calibration pass.""" + self.iterator = iter(dataset) + + return _CalibrationReader() + + +def onnx_int8_quantize( + onnx_file, + output_file, + dataset, + transform_fn, + input_name: str = "images", + batch: int = 0, + prefix: str = "", +) -> str: + """Quantize an ONNX model to INT8 using ONNX Runtime static quantization.""" + import onnx + from onnxruntime.quantization import quantize_static + + # Quantize only weighted ops so the head decode stays float: one INT8 scale spanning box pixels (~0-640) and class + # probs (0-1) rounds every score to 0. Excluding by node (not op_types) still calibrates all tensors, avoiding an + # ONNX Runtime crash on the uncalibrated attention Softmax. + graph = onnx.load(onnx_file).graph + exclude = [n.name for n in graph.node if n.op_type not in {"Conv", "Gemm", "MatMul"}] + del graph + + LOGGER.info(f"{prefix} quantizing INT8 with ONNX Runtime...") + quantize_static( + onnx_file, + output_file, + onnx_calibration_reader(dataset, transform_fn, input_name, batch), + nodes_to_exclude=exclude, + ) + return str(output_file) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/openvino.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/openvino.py new file mode 100644 index 0000000000000000000000000000000000000000..97c4a21771cdc0fa400730ad8f6215193fe7191c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/openvino.py @@ -0,0 +1,84 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import torch + +from ultralytics.utils import LOGGER + + +def torch2openvino( + model: torch.nn.Module, + im: torch.Tensor | list[torch.Tensor] | tuple[torch.Tensor, ...], + output_dir: Path | str | None = None, + dynamic: bool = False, + quantize: int | str | None = None, + calibration_dataset: Any | None = None, + int8_detect: bool = False, + prefix: str = "", +) -> Any: + """Export a PyTorch model to OpenVINO format with optional INT8 quantization. + + Args: + model (torch.nn.Module): The model to export (may be NMS-wrapped). + im (torch.Tensor | list[torch.Tensor] | tuple[torch.Tensor, ...]): Example input tensor(s) for tracing. + output_dir (Path | str | None): Directory to save the exported OpenVINO model. + dynamic (bool): Whether to use dynamic input shapes. + quantize (int | str | None): Precision scheme, e.g. 16 for FP16 or 8 for INT8. + calibration_dataset (nncf.Dataset | None): Dataset for INT8 calibration (required when ``quantize=8``). + int8_detect (bool): Whether to keep the detection head in floating-point precision during INT8 quantization. + prefix (str): Prefix for log messages. + + Returns: + (ov.Model): The converted OpenVINO model. + """ + import openvino as ov + + LOGGER.info(f"\n{prefix} starting export with openvino {ov.__version__}...") + + input_shape = [i.shape for i in im] if isinstance(im, (list, tuple)) else im.shape + # Hand OpenVINO an already-traced ScriptModule (torchscript/coreml exports trace the same way), not a raw + # nn.Module, so it doesn't re-trace internally with check_trace=True - that re-trace-and-diff sanity check is + # non-deterministic on NMS models and fails with "Graphs differed across invocations!". check_trace=False skips + # the same check on our own trace. + ts = torch.jit.trace(model, im, strict=False, check_trace=False) + ov_model = ov.convert_model(ts, input=None if dynamic else input_shape, example_input=im) + if quantize == 8: + import nncf + + from ultralytics.nn.modules import RTDETRDecoder + + ignored_scope = None + if int8_detect: + operations = ov_model.get_ordered_ops() + sigmoid_names = [op.get_friendly_name() for op in operations if op.get_type_name() == "Sigmoid"] + head_scope = sigmoid_names[-1].split("/", 1)[0] + ignored_scope = nncf.IgnoredScope( + names=[ + op.get_friendly_name() + for op in operations + if op.get_type_name() == "Sigmoid" + or op.get_friendly_name().startswith((f"{head_scope}/", f"{head_scope}.dfl")) + ] + ) + ov_model = nncf.quantize( + model=ov_model, + calibration_dataset=calibration_dataset, + preset=nncf.QuantizationPreset.MIXED, + model_type=nncf.ModelType.TRANSFORMER + if any(isinstance(m, RTDETRDecoder) for m in model.modules()) + else None, + # Calibrate on the full dataset like other INT8 backends, not nncf's 300-batch default + subset_size=calibration_dataset.get_length() or 300, + ignored_scope=ignored_scope, + ) + + if output_dir is not None: + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + output_file = output_dir / "model.xml" + ov.save_model(ov_model, output_file, compress_to_fp16=quantize == 16) + return ov_model diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/paddle.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/paddle.py new file mode 100644 index 0000000000000000000000000000000000000000..1ff336b5e50c782388ac7c79021f460de7169c2c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/paddle.py @@ -0,0 +1,67 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +import torch + +from ultralytics.utils import ARM64, IS_JETSON, LOGGER, YAML + + +def torch2paddle( + model: torch.nn.Module, + im: torch.Tensor, + output_dir: Path | str, + metadata: dict | None = None, + prefix: str = "", +) -> str: + """Export a PyTorch model to PaddlePaddle format using X2Paddle. + + Args: + model (torch.nn.Module): The PyTorch model to export. + im (torch.Tensor): Example input tensor for tracing. + output_dir (Path | str): Directory to save the exported PaddlePaddle model. + metadata (dict | None): Optional metadata saved as ``metadata.yaml``. + prefix (str): Prefix for log messages. + + Returns: + (str): Path to the exported ``_paddle_model`` directory. + """ + assert not IS_JETSON, "Jetson Paddle exports not supported yet" + from ultralytics.utils.checks import check_requirements + + check_requirements( + ( + # Interchangeable candidates so an installed variant is never dual-installed over (both ship 'paddle') + ( + "paddlepaddle-gpu>=3.0.0,<3.3.0" # pin <3.3.0 https://github.com/PaddlePaddle/Paddle/issues/77340 + if im.device.type == "cuda" + else "paddlepaddle==3.0.0" # pin 3.0.0 for ARM64 + if ARM64 + else "paddlepaddle>=3.0.0,<3.3.0", # pin <3.3.0 https://github.com/PaddlePaddle/Paddle/issues/77340 + "paddlepaddle==3.0.0" if ARM64 else "paddlepaddle>=3.0.0,<3.3.0", + "paddlepaddle-gpu>=3.0.0,<3.3.0", + ), + "x2paddle", + ) + ) + + import x2paddle + from x2paddle.convert import pytorch2paddle + from x2paddle.op_mapper.pytorch2paddle import prim2code + + # x2paddle 1.6.0 codegen for pooling asserts reads exec() results from locals(), which PEP 667 broke in Python + # 3.13. The assert only re-checks pooling args that torch already validated during tracing, so skip emitting it. + prim_assert = prim2code.prim_assert + prim2code.prim_assert = lambda layer, **kwargs: None + + LOGGER.info(f"\n{prefix} starting export with X2Paddle {x2paddle.__version__}...") + + try: + pytorch2paddle(module=model, save_dir=output_dir, jit_type="trace", input_examples=[im]) # export + finally: + prim2code.prim_assert = prim_assert + if metadata: + YAML.save(Path(output_dir) / "metadata.yaml", metadata) # add metadata.yaml + return str(output_dir) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/qnn.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/qnn.py new file mode 100644 index 0000000000000000000000000000000000000000..55b3938af63020a5181787f1191b57d74079657b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/qnn.py @@ -0,0 +1,164 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +from ultralytics.utils import LOGGER, QNN_HTP_TARGETS, WINDOWS +from ultralytics.utils.checks import check_requirements + + +def qnn_library_paths() -> tuple[str | None, str]: + """Resolve the QNN Execution Provider and HTP backend library paths for the installed onnxruntime-qnn build. + + onnxruntime-qnn ships two ways: plugin builds expose an `onnxruntime_qnn` helper module, while monolithic builds + expose `QNNExecutionProvider` directly and bundle the QNN backend libraries in `onnxruntime/capi`. + + Returns: + (tuple[str | None, str]): `(ep_library_path, htp_backend_path)`. `ep_library_path` is `None` when QNN is already + built into ONNX Runtime and does not need `register_execution_provider_library`. + """ + try: + import onnxruntime_qnn as qnn_ep + + return qnn_ep.get_library_path(), qnn_ep.get_qnn_htp_path() + except ImportError: + import onnxruntime + + capi = Path(onnxruntime.__file__).parent / "capi" + if "QNNExecutionProvider" in onnxruntime.get_available_providers(): + ep_lib = None + else: + ep_lib = capi / ("onnxruntime_providers_qnn.dll" if WINDOWS else "libonnxruntime_providers_qnn.so") + htp_lib = "QnnHtp.dll" if WINDOWS else "libQnnHtp.so" + return str(ep_lib) if ep_lib else None, str(capi / htp_lib) + + +def onnx2qnn( + onnx_file: str | Path, + output_file: Path | str, + dataset, + transform_fn, + name: str = "73", + metadata: dict | None = None, + batch: int = 0, + prefix: str = "", +) -> str: + """Convert an ONNX model to a Qualcomm QNN context binary using the ONNX Runtime QNN Execution Provider. + + The conversion runs entirely on the host with no Qualcomm account or cloud upload. The model is quantized with ONNX + Runtime's QNN QDQ flow to 16-bit activations and 8-bit weights (the recommended accuracy/performance balance for the + Hexagon NPU), then the `onnxruntime-qnn` Execution Provider — which bundles the Qualcomm AI Runtime (QAIRT) + libraries — compiles the quantized graph into a QNN context binary embedded in `_qnn.onnx`. No inference is + run. + + Args: + onnx_file (str | Path): Path to the source ONNX file (already exported). + output_file (Path | str): Path to save the exported QNN ONNX context-binary model. + dataset (DataLoader): Calibration dataloader (from `Exporter.get_int8_calibration_dataloader`) used for INT8 + quantization. + transform_fn (Callable): Preprocessing transform (`Exporter._transform_fn`) converting a calibration item to a + normalized `float32` NCHW array. + name (str): Target Hexagon Tensor Processor (HTP) architecture version, e.g. `"73"` (Snapdragon 8 Gen 2), `"75"` + (8 Gen 3), `"79"` (8 Elite), or supported SoC name such as `"iq-8275"`. Finalizes the graph for the target + chip when exporting on a host without a Snapdragon NPU. + metadata (dict | None): Ultralytics model metadata ensured present in the context model's `metadata_props` (ONNX + Runtime normally carries the source model's metadata through, but this is not a documented guarantee). + batch (int): Static batch dimension of the ONNX graph used to tile undersized calibration batches, or 0 for + dynamic-batch models. + prefix (str): Prefix for log messages. + + Returns: + (str): Path to the exported `*_qnn.onnx` file. + + Notes: + `onnxruntime-qnn` wheels may expose QNN either as a plugin library or as a built-in ONNX Runtime provider. + """ + check_requirements("onnxruntime-qnn") + import onnxruntime as ort + from onnxruntime.quantization import QuantType, quantize + from onnxruntime.quantization.execution_providers.qnn import get_qnn_qdq_config + from onnxruntime.quantization.shape_inference import quant_pre_process + + from ultralytics.utils.export.onnx import onnx_calibration_reader + + ep_library, htp_backend = qnn_library_paths() + + onnx_file = Path(onnx_file) + ctx_file = Path(output_file) + ctx_file.parent.mkdir(parents=True, exist_ok=True) + pre_file = ctx_file.with_name(f"{onnx_file.stem}_qnn_preprocessed.onnx") + qdq_file = ctx_file.with_name(f"{onnx_file.stem}_qnn_qdq.onnx") + + LOGGER.info(f"\n{prefix} starting W8A16 quantization and export with ONNX Runtime QNN (HTP target {name})...") + import onnx + + dims = [d.dim_value for d in onnx.load(str(onnx_file)).graph.input[0].type.tensor_type.shape.dim] + if len(dims) == 4 and dims[3] in {1, 3} and dims[1] not in {1, 3}: # channel-last graph (QNNModel export) + nchw_transform = transform_fn + + def transform_fn(data_item): + """Transform calibration data from NCHW to NHWC.""" + return nchw_transform(data_item).transpose(0, 2, 3, 1) + + try: + quant_pre_process(str(onnx_file), str(pre_file)) + # 16-bit activations + 8-bit weights is the ORT-recommended accuracy/perf balance for the HTP backend + qdq_config = get_qnn_qdq_config( + str(pre_file), + onnx_calibration_reader(dataset, transform_fn, batch=batch), + activation_type=QuantType.QUInt16, + weight_type=QuantType.QUInt8, + ) + quantize(str(pre_file), str(qdq_file), qdq_config) + + # Register the QNN EP, then compile the quantized graph to a context binary during session init (no inference + # run). The provider target finalizes the graph offline on a host without an NPU, and the shared-memory allocator + # is disabled (no device present). Targets not exposed by ONNX Runtime's htp_arch parser are finalized through + # their QNN SoC model instead. + ep_name = "QNNExecutionProvider" + ep_options = { + "backend_path": htp_backend, + "htp_graph_finalization_optimization_mode": "3", + "enable_htp_shared_memory_allocator": "0", + } + option, value = QNN_HTP_TARGETS[name] + ep_options[option] = value + options = ort.SessionOptions() + options.add_session_config_entry("ep.context_enable", "1") + options.add_session_config_entry("ep.context_file_path", str(ctx_file)) + options.add_session_config_entry("ep.context_embed_mode", "1") + if ep_library: + ort.register_execution_provider_library(ep_name, ep_library) + try: + if ep_library: + devices = [d for d in ort.get_ep_devices() if d.ep_name == ep_name] + if not devices: + raise RuntimeError("QNN EP registered but no QNN devices were found by ONNX Runtime.") + options.add_provider_for_devices(devices, ep_options) + ort.InferenceSession(str(qdq_file), sess_options=options) + else: + ort.InferenceSession( + str(qdq_file), sess_options=options, providers=[ep_name], provider_options=[ep_options] + ) + finally: + if ep_library: + ort.unregister_execution_provider_library(ep_name) + finally: + for f in (pre_file, qdq_file): # remove quantization intermediates; the context binary is self-contained + f.unlink(missing_ok=True) + + if not ctx_file.exists(): + raise RuntimeError(f"QNN context binary was not generated at {ctx_file}. See {prefix} logs for details.") + + if metadata: # ensure Ultralytics metadata is present in the context model (usually preserved by ONNX Runtime) + import onnx + + ctx_model = onnx.load(str(ctx_file)) + existing = {p.key for p in ctx_model.metadata_props} + if missing := {k: v for k, v in metadata.items() if str(k) not in existing}: + for k, v in missing.items(): + entry = ctx_model.metadata_props.add() + entry.key, entry.value = str(k), str(v) + onnx.save(ctx_model, str(ctx_file)) + return str(ctx_file) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/rknn.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/rknn.py new file mode 100644 index 0000000000000000000000000000000000000000..b98df2b864c7e8e2ef4f7d14c7d89ca29d0fcb36 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/rknn.py @@ -0,0 +1,84 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from pathlib import Path + +from ultralytics.utils import IS_COLAB, LOGGER, YAML + + +def _check_rknn_return(ret, name: str): + """Raise a RuntimeError if an RKNN API call failed.""" + if ret not in {0, None}: + raise RuntimeError(f"RKNN {name} failed with return code {ret}.") + + +def onnx2rknn( + onnx_file: str, + output_dir: Path | str, + name: str = "rk3588", + quantize: int | str | None = None, + dataset: Path | str | None = None, + metadata: dict | None = None, + prefix: str = "", + batch: int = 1, +) -> str: + """Export an ONNX model to RKNN format for Rockchip NPUs with optional INT8 quantization. + + Args: + onnx_file (str): Path to the source ONNX file (already exported, opset <=19). + output_dir (Path | str): Directory to save the exported RKNN model. + name (str): Target platform name (e.g. ``"rk3588"``). + quantize (int | str | None): Precision scheme, 8 for INT8 or 16/None for floating-point builds. + dataset (Path | str | None): Path to the generated RKNN Toolkit calibration image-list file, required when + ``quantize=8``. Users should pass YOLO dataset YAMLs to ``export(data=...)``; ``export_rknn()`` converts + them to this internal image-path list. + metadata (dict | None): Metadata saved as ``metadata.yaml``. + prefix (str): Prefix for log messages. + batch (int): Inference batch size applied by RKNN Toolkit after loading the batch-1 ONNX model. + + Returns: + (str): Path to the exported ``_rknn_model`` directory. + """ + use_int8 = quantize == 8 + if name in {"rv1103", "rv1106", "rv1103b", "rv1106b"} and not use_int8: + raise ValueError( + f"Rockchip target '{name}' requires quantize=8. Use a target that supports floating-point builds " + f"(e.g. rk2118, rk3562, rk3566, rk3568, rk3576, rk3588, rv1126b) or export with quantize=8." + ) + if use_int8: + if not dataset: + raise ValueError("RKNN INT8 export requires a generated calibration image-list file.") + dataset = Path(dataset) + if not dataset.is_file(): + raise ValueError(f"Generated RKNN INT8 calibration image-list file not found: {dataset}") + + from ultralytics.utils.checks import check_requirements + + LOGGER.info(f"\n{prefix} starting export with rknn-toolkit2...") + # setuptools<82 retains pkg_resources, which rknn-toolkit2 depends on and setuptools 82 removed + check_requirements(["rknn-toolkit2>=2.3.2", "setuptools<82"]) + + if IS_COLAB: + # Prevent 'exit' from closing the notebook https://github.com/airockchip/rknn-toolkit2/issues/259 + import builtins + + builtins.exit = lambda: None + + from rknn.api import RKNN + + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + rknn = RKNN(verbose=False) + config = {"mean_values": [[0, 0, 0]], "std_values": [[255, 255, 255]], "target_platform": name} + _check_rknn_return(rknn.config(**config), "config") + _check_rknn_return(rknn.load_onnx(model=onnx_file), "load_onnx") + build_kwargs = {"do_quantization": use_int8} + if use_int8: + build_kwargs["dataset"] = str(dataset) + _check_rknn_return(rknn.build(**build_kwargs, rknn_batch_size=batch), "build") + _check_rknn_return(rknn.export_rknn(str(output_dir / f"{Path(onnx_file).stem}-{name}.rknn")), "export_rknn") + if metadata: + YAML.save(output_dir / "metadata.yaml", metadata) + return str(output_dir) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/tensorflow.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/tensorflow.py new file mode 100644 index 0000000000000000000000000000000000000000..637036ac22bb04b16d57902340e0a241355722a3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/tensorflow.py @@ -0,0 +1,303 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import contextlib +from functools import partial +from pathlib import Path + +import numpy as np +import torch + +from ultralytics.nn.modules import Detect, Pose, Pose26 +from ultralytics.utils import AUTOINSTALL, LINUX, LOGGER, MACOS +from ultralytics.utils.checks import ( + IS_PYTHON_MINIMUM_3_13, + check_apt_requirements, + check_requirements, + check_version, + is_sudo_available, +) +from ultralytics.utils.downloads import attempt_download_asset +from ultralytics.utils.tal import make_anchors + + +def tf_wrapper(model: torch.nn.Module) -> torch.nn.Module: + """A wrapper for TensorFlow export compatibility (TF-specific handling is now in head modules).""" + for m in model.modules(): + if not isinstance(m, Detect): + continue + import types + + m._get_decode_boxes = types.MethodType(_tf_decode_boxes, m) + if isinstance(m, Pose): + m.kpts_decode = types.MethodType(partial(_tf_kpts_decode, is_pose26=type(m) is Pose26), m) + return model + + +def _tf_decode_boxes(self, x: dict[str, torch.Tensor]) -> torch.Tensor: + """Decode bounding boxes for TensorFlow export.""" + shape = x["feats"][0].shape # BCHW + boxes = x["boxes"] + if self.format != "imx" and (self.dynamic or self.shape != shape): + self.anchors, self.strides = (a.transpose(0, 1) for a in make_anchors(x["feats"], self.stride, 0.5)) + self.shape = shape + grid_h, grid_w = shape[2:4] + grid_size = torch.tensor([grid_w, grid_h, grid_w, grid_h], device=boxes.device).reshape(1, 4, 1) + norm = self.strides / (self.stride[0] * grid_size) + dbox = self.decode_bboxes(self.dfl(boxes) * norm, self.anchors.unsqueeze(0) * norm[:, :2], x.get("angle")) + return dbox + + +def _tf_kpts_decode(self, kpts: torch.Tensor, is_pose26: bool = False) -> torch.Tensor: + """Decode keypoints for TensorFlow export.""" + ndim = self.kpt_shape[1] + bs = kpts.shape[0] + # Precompute normalization factor to increase numerical stability + y = kpts.view(bs, *self.kpt_shape, -1) + grid_h, grid_w = self.shape[2:4] + grid_size = torch.tensor([grid_w, grid_h], device=y.device).reshape(1, 2, 1) + norm = self.strides / (self.stride[0] * grid_size) + a = ((y[:, :, :2] + self.anchors) if is_pose26 else (y[:, :, :2] * 2.0 + (self.anchors - 0.5))) * norm + if ndim == 3: + a = torch.cat((a, y[:, :, 2:3].sigmoid()), 2) + return a.view(bs, self.nk, -1) + + +def onnx2saved_model( + onnx_file: str, + output_dir: Path | str, + quantize: int | str | None = None, + images: np.ndarray | None = None, + disable_group_convolution: bool = False, + cuda: bool = False, + prefix: str = "", +): + """Convert an ONNX model to TensorFlow SavedModel format using onnx2tf. + + Args: + onnx_file (str): ONNX file path. + output_dir (Path | str): Output directory path for the SavedModel. + quantize (int | str | None): Precision scheme, 8 for INT8. + images (np.ndarray | None, optional): Calibration images for INT8 quantization in BHWC format. + disable_group_convolution (bool, optional): Disable group convolution optimization. Defaults to False. + cuda (bool, optional): True if exporting on a CUDA device; selects GPU onnxruntime and keeps GPUs visible to + TensorFlow, which are otherwise hidden so CPU exports never touch GPU memory. Defaults to False. + prefix (str, optional): Logging prefix. Defaults to "". + + Returns: + (keras.Model): Converted Keras model. + + Notes: + - Auto-installs tensorflow, onnx2tf, and all required dependencies if not present. + - Downloads calibration data if INT8 quantization is enabled. + - Removes temporary files and renames quantized models after conversion. + """ + try: + import tensorflow as tf + except ImportError: + check_requirements("tensorflow>2.19.0" if IS_PYTHON_MINIMUM_3_13 else "tensorflow>=2.0.0,<=2.19.0") + import tensorflow as tf + if not cuda: + with contextlib.suppress(Exception): # fails only if TF GPUs are already initialized by earlier user code + tf.config.set_visible_devices([], "GPU") # hide GPUs so non-CUDA exports never allocate GPU memory + check_requirements( + f"onnx2tf{'>=2.3.0,<2.3.16' if IS_PYTHON_MINIMUM_3_13 else '>=1.26.3,<1.29.0'}", # pin to avoid h5py build issues on aarch64 + cmds="--no-deps", + ) + check_requirements( + ( + f"tf_keras{'>2.19.0' if IS_PYTHON_MINIMUM_3_13 else '<=2.19.0'}", # required by 'onnx2tf' package + "sng4onnx>=1.0.1", # required by 'onnx2tf' package + "onnx_graphsurgeon>=0.3.26", # required by 'onnx2tf' package + "ai-edge-litert>=1.2.0" + (",<1.4.0" if MACOS else ""), # required by 'onnx2tf' package + "onnx>=1.12.0,<2.0.0", + f"onnx2tf{'>=2.3.0,<2.3.16' if IS_PYTHON_MINIMUM_3_13 else '>=1.26.3,<1.29.0'}", + "onnxslim>=0.1.82", + # Interchangeable candidates so an installed variant (e.g. onnxruntime-gpu) is never dual-installed over + ("onnxruntime-gpu" if cuda else "onnxruntime", "onnxruntime", "onnxruntime-gpu", "onnxruntime-qnn"), + "protobuf>=6.31.1,<7.0.0" + if IS_PYTHON_MINIMUM_3_13 + else "protobuf>=5", # TF>2.19 (Python 3.13) needs protobuf>=6.31.1; cap <7 to match TF gencode and avoid PaddlePaddle segfault + ) + ) + + LOGGER.info(f"\n{prefix} starting export with tensorflow {tf.__version__}...") + check_version( + tf.__version__, + ">=2.0.0", + name="tensorflow", + verbose=True, + msg="https://github.com/ultralytics/ultralytics/issues/5161", + ) + + output_dir = Path(output_dir) + use_int8 = quantize == 8 + # Pre-download calibration file to fix https://github.com/PINTO0309/onnx2tf/issues/545 + onnx2tf_file = Path("calibration_image_sample_data_20x128x128x3_float32.npy") + if not onnx2tf_file.exists(): + attempt_download_asset(f"{onnx2tf_file}.zip", unzip=True, delete=True) + np_data = None + if use_int8: + tmp_file = output_dir / "tmp_tflite_int8_calibration_images.npy" # int8 calibration images file + if images is not None: + output_dir.mkdir(parents=True, exist_ok=True) + np.save(str(tmp_file), images) # BHWC + del images + np_data = [["images", tmp_file, [[[[0, 0, 0]]]], [[[[255, 255, 255]]]]]] + + # Patch onnx.helper for onnx_graphsurgeon compatibility with ONNX>=1.17 + # The float32_to_bfloat16 function was removed in ONNX 1.17, but onnx_graphsurgeon still uses it + import onnx.helper + + if not hasattr(onnx.helper, "float32_to_bfloat16"): + import struct + + def float32_to_bfloat16(fval): + """Convert float32 to bfloat16 (truncates lower 16 bits of mantissa).""" + ival = struct.unpack("=I", struct.pack("=f", fval))[0] + return ival >> 16 + + onnx.helper.float32_to_bfloat16 = float32_to_bfloat16 + + import importlib + import inspect + import pathlib + + import onnx2tf.ops.TopK as _t + + _path = pathlib.Path(inspect.getfile(_t)) + _text = _path.read_text() + _patched = _text.replace( + "k_tensor = int(k_tensor)", + "k_tensor = int(k_tensor.squeeze()) if hasattr(k_tensor, 'squeeze') else int(k_tensor)", + ) + if _patched != _text: # write only when unpatched; site-packages may be read-only (pre-patched containers) + try: + _path.write_text(_patched) + importlib.reload(_t) + except OSError as e: # read-only install: continue unpatched, only TopK-containing models are affected + LOGGER.warning(f"{prefix} unable to apply onnx2tf TopK patch: {e}") + import onnx2tf # scoped for after ONNX export for reduced conflict during import + + LOGGER.info(f"{prefix} starting TFLite export with onnx2tf {onnx2tf.__version__}...") + keras_model = onnx2tf.convert( + input_onnx_file_path=onnx_file, + output_folder_path=str(output_dir), + not_use_onnxsim=True, + verbosity="error", # note INT8-FP16 activation bug https://github.com/ultralytics/ultralytics/issues/15873 + output_integer_quantized_tflite=use_int8, + custom_input_op_name_np_data_path=np_data, + enable_batchmatmul_unfold=not use_int8, # fix lower no. of detected objects on GPU delegate + output_signaturedefs=True, # fix error with Attention block group convolution + disable_group_convolution=disable_group_convolution, # fix error with group convolution + ) + + # Remove/rename TFLite models + if use_int8: + tmp_file.unlink(missing_ok=True) + for file in output_dir.rglob("*_dynamic_range_quant.tflite"): + file.rename(file.with_name(file.stem.replace("_dynamic_range_quant", "_int8") + file.suffix)) + for file in output_dir.rglob("*_integer_quant_with_int16_act.tflite"): + file.unlink() # delete extra fp16 activation TFLite files + return keras_model + + +def keras2pb(keras_model, output_file: Path | str, prefix: str = "") -> str: + """Convert a Keras model to TensorFlow GraphDef (.pb) format. + + Args: + keras_model (keras.Model): Keras model to convert to frozen graph format. + output_file (Path | str): Output file path (suffix will be changed to .pb). + prefix (str, optional): Logging prefix. Defaults to "". + + Returns: + (str): Path to the exported ``.pb`` file. + + Notes: + Creates a frozen graph by converting variables to constants for inference optimization. + """ + import tensorflow as tf + from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2 + + LOGGER.info(f"\n{prefix} starting export with tensorflow {tf.__version__}...") + m = tf.function(lambda x: keras_model(x)) # full model + m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)) + frozen_func = convert_variables_to_constants_v2(m) + frozen_func.graph.as_graph_def() + output_file = Path(output_file) + tf.io.write_graph( + graph_or_graph_def=frozen_func.graph, logdir=str(output_file.parent), name=output_file.name, as_text=False + ) + return str(output_file) + + +def tflite2edgetpu(tflite_file: str | Path, output_dir: str | Path, prefix: str = "") -> str: + """Convert a TensorFlow Lite model to Edge TPU format using the Edge TPU compiler. + + Args: + tflite_file (str | Path): Path to the input TensorFlow Lite (.tflite) model file. + output_dir (str | Path): Output directory path for the compiled Edge TPU model. + prefix (str, optional): Logging prefix. Defaults to "". + + Returns: + (str): Path to the exported Edge TPU model file. + + Notes: + Auto-installs the Edge TPU compiler if not found. The function compiles the TFLite model + for optimal performance on Google's Edge TPU hardware accelerator. + """ + import shlex + import subprocess + + # Install Edge TPU compiler if not found + check_cmd = "edgetpu_compiler --version" + help_url = "https://coral.ai/docs/edgetpu/compiler/" + assert LINUX, f"export only supported on Linux. See {help_url}" + if ( + subprocess.run( + check_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True, check=False + ).returncode + != 0 + ): + if not AUTOINSTALL: + raise FileNotFoundError( + f"Edge TPU compiler not found and YOLO_AUTOINSTALL=False. Install it from {help_url}" + ) + LOGGER.info(f"\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}") + sudo = "sudo " if is_sudo_available() else "" + for c in ( + f"{sudo}mkdir -p /etc/apt/keyrings", + f"curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | {sudo}gpg --no-tty --dearmor -o /etc/apt/keyrings/google.gpg", + f'echo "deb [signed-by=/etc/apt/keyrings/google.gpg] https://packages.cloud.google.com/apt coral-edgetpu-stable main" | {sudo}tee /etc/apt/sources.list.d/coral-edgetpu.list', + ): + subprocess.run(c, shell=True, check=True) + check_apt_requirements(["edgetpu-compiler"]) + + ver = subprocess.run(check_cmd, shell=True, capture_output=True, check=True).stdout.decode().rsplit(maxsplit=1)[-1] + LOGGER.info(f"\n{prefix} starting export with Edge TPU compiler {ver}...") + + cmd = [ + "edgetpu_compiler", + "--out_dir", + str(output_dir), + "--show_operations", + "--search_delegate", + "--delegate_search_step", + "30", + "--timeout_sec", + "180", + str(tflite_file), + ] # argv list avoids shell metacharacter issues in output_dir/tflite_file paths + LOGGER.info(f"{prefix} running '{shlex.join(cmd)}'") + subprocess.run(cmd, check=True) + return str(Path(output_dir) / f"{Path(tflite_file).stem}_edgetpu.tflite") + + +def gd_outputs(gd): + """Return TensorFlow GraphDef model output node names.""" + name_list, input_list = [], [] + for node in gd.node: # tensorflow.core.framework.node_def_pb2.NodeDef + name_list.append(node.name) + input_list.extend(node.input) + return sorted(f"{x}:0" for x in list(set(name_list) - set(input_list)) if not x.startswith("NoOp")) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/export/torchscript.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/torchscript.py new file mode 100644 index 0000000000000000000000000000000000000000..237e71ff7f5f7452c9196353cbd634ee6ac9b47d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/export/torchscript.py @@ -0,0 +1,38 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import json +from pathlib import Path + +import torch + +from ultralytics.utils import LOGGER, TORCH_VERSION + + +def torch2torchscript( + model: torch.nn.Module, + im: torch.Tensor, + output_file: Path | str, + metadata: dict | None = None, + prefix: str = "", +) -> str: + """Export a PyTorch model to TorchScript format. + + Args: + model (torch.nn.Module): The PyTorch model to export (may be NMS-wrapped). + im (torch.Tensor): Example input tensor for tracing. + output_file (Path | str): Path to save the exported TorchScript model. + metadata (dict | None): Optional metadata to embed in the TorchScript archive. + prefix (str): Prefix for log messages. + + Returns: + (str): Path to the exported ``.torchscript`` file. + """ + LOGGER.info(f"\n{prefix} starting export with torch {TORCH_VERSION}...") + + output_file = str(output_file) + ts = torch.jit.trace(model, im, strict=False, check_trace=False) + extra_files = {"config.txt": json.dumps(metadata or {})} # torch._C.ExtraFilesMap() + ts.save(output_file, _extra_files=extra_files) + return output_file diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/files.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/files.py new file mode 100644 index 0000000000000000000000000000000000000000..e7a51029561499c724da413b386ff2b13b9b288e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/files.py @@ -0,0 +1,222 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import contextlib +import glob +import os +import shutil +import tempfile +from contextlib import contextmanager +from datetime import datetime +from pathlib import Path + + +class WorkingDirectory(contextlib.ContextDecorator): + """A context manager and decorator for temporarily changing the working directory. + + This class allows for the temporary change of the working directory using a context manager or decorator. It ensures + that the original working directory is restored after the context or decorated function completes. + + Attributes: + dir (Path | str): The new directory to switch to. + cwd (Path): The original current working directory before the switch. + + Methods: + __enter__: Changes the current directory to the specified directory. + __exit__: Restores the original working directory on context exit. + + Examples: + Using as a context manager: + >>> with WorkingDirectory("/path/to/new/dir"): + ... # Perform operations in the new directory + ... pass + + Using as a decorator: + >>> @WorkingDirectory("/path/to/new/dir") + ... def some_function(): + ... # Perform operations in the new directory + ... pass + """ + + def __init__(self, new_dir: str | Path): + """Initialize the WorkingDirectory context manager with the target directory.""" + self.dir = new_dir # new dir + self.cwd = Path.cwd().resolve() # current dir + + def __enter__(self): + """Change the current working directory to the specified directory upon entering the context.""" + os.chdir(self.dir) + + def __exit__(self, exc_type, exc_val, exc_tb): + """Restore the original working directory when exiting the context.""" + os.chdir(self.cwd) + + +@contextmanager +def spaces_in_path(path: str | Path): + """Context manager to handle paths with spaces in their names. + + If a path contains spaces, it replaces them with underscores, copies the file/directory to the new path, executes + the context code block, then copies the file/directory back to its original location. + + Args: + path (str | Path): The original path that may contain spaces. + + Yields: + (Path | str): Temporary path with any spaces replaced by underscores. + + Examples: + >>> with spaces_in_path("/path/with spaces") as new_path: + ... # Your code here + ... pass + """ + # If path has spaces, replace them with underscores + if " " in str(path): + string = isinstance(path, str) # input type + path = Path(path) + + # Create a temporary directory and construct the new path + with tempfile.TemporaryDirectory() as tmp_dir: + tmp_path = Path(tmp_dir) / path.name.replace(" ", "_") + + # Copy file/directory + if path.is_dir(): + shutil.copytree(path, tmp_path) + elif path.is_file(): + tmp_path.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, tmp_path) + + try: + # Yield the temporary path + yield str(tmp_path) if string else tmp_path + + finally: + # Copy file/directory back + if tmp_path.is_dir(): + shutil.copytree(tmp_path, path, dirs_exist_ok=True) + elif tmp_path.is_file(): + shutil.copy2(tmp_path, path) # Copy back the file + + else: + # If there are no spaces, just yield the original path + yield path + + +def increment_path(path: str | Path, exist_ok: bool = False, sep: str = "-", mkdir: bool = False) -> Path: + """Increment a file or directory path, i.e., runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc. + + If the path exists and `exist_ok` is not True, the path will be incremented by appending a number and `sep` to the + end of the path. If the path is a file, the file extension will be preserved. If the path is a directory, the number + will be appended directly to the end of the path. + + Args: + path (str | Path): Path to increment. + exist_ok (bool, optional): If True, the path will not be incremented and returned as-is. + sep (str, optional): Separator to use between the path and the incrementation number. + mkdir (bool, optional): Create a directory if it does not exist. + + Returns: + (Path): Incremented path. + + Examples: + Increment a directory path: + >>> import tempfile + >>> from pathlib import Path + >>> with tempfile.TemporaryDirectory() as tmp: + ... exp = Path(tmp) / "exp" + ... exp.mkdir() + ... increment_path(exp).name + 'exp-2' + + Increment a file path: + >>> with tempfile.TemporaryDirectory() as tmp: + ... results = Path(tmp) / "results.txt" + ... results.touch() + ... increment_path(results).name + 'results-2.txt' + """ + path = Path(path) # os-agnostic + if path.exists() and not exist_ok: + path, suffix = (path.with_suffix(""), path.suffix) if path.is_file() else (path, "") + + # Method 1 + for n in range(2, 9999): + p = f"{path}{sep}{n}{suffix}" # increment path + if not os.path.exists(p): + break + path = Path(p) + + if mkdir: + path.mkdir(parents=True, exist_ok=True) # make directory + + return path + + +def file_age(path: str | Path = __file__) -> int: + """Return days since the last modification of the specified file.""" + dt = datetime.now().astimezone() - datetime.fromtimestamp(Path(path).stat().st_mtime).astimezone() # delta + return dt.days # + dt.seconds / 86400 # fractional days + + +def file_date(path: str | Path = __file__) -> str: + """Return the file modification date in 'YYYY-M-D' format.""" + t = datetime.fromtimestamp(Path(path).stat().st_mtime).astimezone() + return f"{t.year}-{t.month}-{t.day}" + + +def file_size(path: str | Path) -> float: + """Return the size of a file or directory in mebibytes (MiB).""" + if isinstance(path, (str, Path)): + mb = 1 << 20 # bytes to MiB (1024 ** 2) + path = Path(path) + if path.is_file(): + return path.stat().st_size / mb + elif path.is_dir(): + return sum(f.stat().st_size for f in path.glob("**/*") if f.is_file()) / mb + return 0.0 + + +def get_latest_run(search_dir: str = ".") -> str: + """Return the path to the most recent 'last.pt' file in the specified directory for resuming training.""" + last_list = glob.glob(f"{search_dir}/**/last*.pt", recursive=True) + return max(last_list, key=os.path.getctime) if last_list else "" + + +def update_models(model_names: tuple = ("yolo26n.pt",), source_dir: Path = Path("."), update_names: bool = False): + """Update and re-save specified YOLO models in an 'updated_models' subdirectory. + + Args: + model_names (tuple, optional): Model filenames to update. + source_dir (Path, optional): Directory containing models and target subdirectory. + update_names (bool, optional): Update model names from a data YAML. + + Examples: + Update specified YOLO models and save them in 'updated_models' subdirectory: + >>> from ultralytics.utils.files import update_models + >>> model_names = ("yolo26n.pt", "yolo11s.pt") + >>> update_models(model_names, source_dir=Path("/models"), update_names=True) + """ + from ultralytics import YOLO + from ultralytics.nn.autobackend import default_class_names + from ultralytics.utils import LOGGER + + target_dir = source_dir / "updated_models" + target_dir.mkdir(parents=True, exist_ok=True) # Ensure target directory exists + + for model_name in model_names: + model_path = source_dir / model_name + LOGGER.info(f"Loading model from {model_path}") + + # Load model + model = YOLO(model_path) + model.half() + if update_names: # update model names from a dataset YAML + model.model.names = default_class_names("coco8.yaml") + + # Define new save path + save_path = target_dir / model_name + + # Save model using model.save() + LOGGER.info(f"Re-saving {model_name} model to {save_path}") + model.save(save_path) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/git.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/git.py new file mode 100644 index 0000000000000000000000000000000000000000..39a9b4b3970d54d78b1ef3787bbfbd7ad1f9b1a2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/git.py @@ -0,0 +1,169 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import zlib +from functools import cached_property +from pathlib import Path + + +class GitRepo: + """Represent a local Git repository and expose branch, commit, and remote metadata. + + This class discovers the repository root by searching for a .git entry from the given path upward, resolves the + actual .git directory (including worktrees), and reads Git metadata directly from on-disk files. It does not invoke + the git binary and therefore works in restricted environments. All metadata properties are resolved lazily and + cached; construct a new instance to refresh state. + + Attributes: + root (Path | None): Repository root directory containing the .git entry; None if not in a repository. + gitdir (Path | None): Resolved .git directory path; handles worktrees; None if unresolved. + refdir (Path | None): Directory containing shared refs, objects, and config; None if unresolved. + head (str | None): Raw contents of HEAD; a SHA for detached HEAD or "ref: " for branch heads. + is_repo (bool): Whether the provided path resides inside a Git repository. + branch (str | None): Current branch name when HEAD points to a branch; None for detached HEAD or non-repo. + commit (str | None): Current commit SHA for HEAD; None if not determinable. + message (str | None): Current commit subject from a loose object; None if not determinable. + origin (str | None): URL of the "origin" remote as read from gitdir/config; None if unset or unavailable. + + Examples: + Initialize from the current working directory and read metadata + >>> from pathlib import Path + >>> repo = GitRepo(Path.cwd()) + >>> is_repo = repo.is_repo + >>> branch, commit, origin = repo.branch, repo.commit, repo.origin + + Notes: + - Resolves metadata by reading files: HEAD, packed-refs, config, and objects; no subprocess calls are used. + - Caches properties on first access using cached_property; recreate the object to reflect repository changes. + """ + + def __init__(self, path: Path | None = None): + """Initialize a Git repository context by discovering the repository root from a starting path. + + Args: + path (Path, optional): File or directory path used as the starting point to locate the repository root. + """ + self.root = self._find_root(path or Path(__file__).resolve()) + self.gitdir = self._gitdir(self.root) if self.root else None + self.refdir = self._refdir(self.gitdir) + + @staticmethod + def _find_root(p: Path) -> Path | None: + """Return repo root or None.""" + return next((d for d in [p, *list(p.parents)] if (d / ".git").exists()), None) + + @staticmethod + def _gitdir(root: Path) -> Path | None: + """Resolve actual .git directory (handles worktrees).""" + g = root / ".git" + if g.is_dir(): + return g + if g.is_file(): + t = g.read_text(errors="ignore").strip() + if t.startswith("gitdir:"): + return (root / t.split(":", 1)[1].strip()).resolve() + return None + + @staticmethod + def _refdir(gitdir: Path | None) -> Path | None: + """Resolve directory containing refs, objects, and config.""" + p = gitdir / "commondir" if gitdir else None + if s := GitRepo._read(p): + d = Path(s) + return (gitdir / d).resolve() if not d.is_absolute() else d + return gitdir + + @staticmethod + def _read(p: Path | None) -> str | None: + """Read and strip file if exists.""" + return p.read_text(errors="ignore").strip() if p and p.exists() else None + + @cached_property + def head(self) -> str | None: + """HEAD file contents.""" + return self._read(self.gitdir / "HEAD" if self.gitdir else None) + + def _ref_commit(self, ref: str) -> str | None: + """Commit for ref (handles packed-refs).""" + rf = self.refdir / ref + if s := self._read(rf): + return s + pf = self.refdir / "packed-refs" + b = pf.read_bytes().splitlines() if pf.exists() else [] + tgt = ref.encode() + for line in b: + if line[:1] in (b"#", b"^") or b" " not in line: + continue + sha, name = line.split(b" ", 1) + if name.strip() == tgt: + return sha.decode() + return None + + def _commit_subject(self, commit: str) -> str | None: + """Commit subject from loose object or None.""" + obj = self.refdir / "objects" / commit[:2] / commit[2:] + if not obj.exists(): + return None + data = zlib.decompress(obj.read_bytes()) + if b"\0" not in data: + return None + kind, body = data.split(b"\0", 1) + if not kind.startswith(b"commit ") or b"\n\n" not in body: + return None + subject = body.split(b"\n\n", 1)[1].splitlines()[0].decode(errors="replace").strip() + return subject or None + + @property + def is_repo(self) -> bool: + """True if inside a git repo.""" + return self.gitdir is not None + + @cached_property + def branch(self) -> str | None: + """Current branch or None.""" + if not self.is_repo or not self.head or not self.head.startswith("ref: "): + return None + ref = self.head[5:].strip() + return ref[11:] if ref.startswith("refs/heads/") else ref + + @cached_property + def commit(self) -> str | None: + """Current commit SHA or None.""" + if not self.is_repo or not self.head: + return None + return self._ref_commit(self.head[5:].strip()) if self.head.startswith("ref: ") else self.head + + @cached_property + def message(self) -> str | None: + """Current commit subject or None.""" + if not self.is_repo or not self.commit: + return None + return self._commit_subject(self.commit) + + @cached_property + def origin(self) -> str | None: + """Origin URL or None.""" + if not self.is_repo: + return None + cfg = self.refdir / "config" + remote, url = None, None + for s in (self._read(cfg) or "").splitlines(): + t = s.strip() + if t.startswith("[") and t.endswith("]"): + remote = t.lower() + elif t.lower().startswith("url =") and remote == '[remote "origin"]': + url = t.split("=", 1)[1].strip() + break + return url + + +if __name__ == "__main__": + import time + + g = GitRepo() + if g.is_repo: + t0 = time.perf_counter() + print(f"repo={g.root}\nbranch={g.branch}\ncommit={g.commit}\nmessage={g.message}\norigin={g.origin}") + dt = (time.perf_counter() - t0) * 1000 + print(f"\n⏱️ Profiling: total {dt:.3f} ms") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/instance.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/instance.py new file mode 100644 index 0000000000000000000000000000000000000000..18d8094265de283abb54858187bb20990fde8485 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/instance.py @@ -0,0 +1,527 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from collections import abc +from itertools import repeat +from numbers import Number + +import cv2 +import numpy as np + +from .ops import ltwh2xywh, ltwh2xyxy, resample_segments, xywh2ltwh, xywh2xyxy, xyxy2ltwh, xyxy2xywh + + +def _ntuple(n): + """Create a function that converts input to n-tuple by repeating singleton values.""" + + def parse(x): + """Parse input to return n-tuple by repeating singleton values n times.""" + return x if isinstance(x, abc.Iterable) else tuple(repeat(x, n)) + + return parse + + +to_2tuple = _ntuple(2) +to_4tuple = _ntuple(4) + +# `xyxy` means left top and right bottom +# `xywh` means center x, center y and width, height(YOLO format) +# `ltwh` means left top and width, height(COCO format) +_formats = ["xyxy", "xywh", "ltwh"] + +__all__ = ("Bboxes", "Instances") # tuple or list + + +class Bboxes: + """A class for handling bounding boxes in multiple formats. + + The class supports various bounding box formats like 'xyxy', 'xywh', and 'ltwh' and provides methods for format + conversion, scaling, and area calculation. Bounding box data should be provided as numpy arrays. + + Attributes: + bboxes (np.ndarray): The bounding boxes stored in a 2D numpy array with shape (N, 4). + format (str): The format of the bounding boxes ('xyxy', 'xywh', or 'ltwh'). + + Methods: + convert: Convert bounding box format from one type to another. + areas: Calculate the area of bounding boxes. + mul: Multiply bounding box coordinates by scale factor(s). + add: Add offset to bounding box coordinates. + concatenate: Concatenate multiple Bboxes objects. + + Examples: + Create bounding boxes in YOLO format + >>> bboxes = Bboxes(np.array([[100, 50, 150, 100]]), format="xywh") + >>> bboxes.convert("xyxy") + >>> print(bboxes.areas()) + [15000] + + Notes: + This class does not handle normalization or denormalization of bounding boxes. + """ + + def __init__(self, bboxes: np.ndarray, format: str = "xyxy") -> None: + """Initialize the Bboxes class with bounding box data in a specified format. + + Args: + bboxes (np.ndarray): Array of bounding boxes with shape (N, 4) or (4,). + format (str): Format of the bounding boxes, one of 'xyxy', 'xywh', or 'ltwh'. + """ + assert format in _formats, f"Invalid bounding box format: {format}, format must be one of {_formats}" + bboxes = bboxes[None, :] if bboxes.ndim == 1 else bboxes + assert bboxes.ndim == 2 + assert bboxes.shape[1] == 4 + self.bboxes = bboxes + self.format = format + + def convert(self, format: str) -> None: + """Convert bounding box format from one type to another. + + Args: + format (str): Target format for conversion, one of 'xyxy', 'xywh', or 'ltwh'. + """ + assert format in _formats, f"Invalid bounding box format: {format}, format must be one of {_formats}" + if self.format == format: + return + elif self.format == "xyxy": + func = xyxy2xywh if format == "xywh" else xyxy2ltwh + elif self.format == "xywh": + func = xywh2xyxy if format == "xyxy" else xywh2ltwh + else: + func = ltwh2xyxy if format == "xyxy" else ltwh2xywh + self.bboxes = func(self.bboxes) + self.format = format + + def areas(self) -> np.ndarray: + """Calculate the area of bounding boxes.""" + return ( + (self.bboxes[:, 2] - self.bboxes[:, 0]) * (self.bboxes[:, 3] - self.bboxes[:, 1]) # format xyxy + if self.format == "xyxy" + else self.bboxes[:, 3] * self.bboxes[:, 2] # format xywh or ltwh + ) + + def mul(self, scale: int | tuple | list) -> None: + """Multiply bounding box coordinates by scale factor(s). + + Args: + scale (int | tuple | list): Scale factor(s) for four coordinates. If int, the same scale is applied to all + coordinates. + """ + if isinstance(scale, Number): + scale = to_4tuple(scale) + assert isinstance(scale, (tuple, list)) + assert len(scale) == 4 + self.bboxes[:, 0] *= scale[0] + self.bboxes[:, 1] *= scale[1] + self.bboxes[:, 2] *= scale[2] + self.bboxes[:, 3] *= scale[3] + + def add(self, offset: int | tuple | list) -> None: + """Add offset to bounding box coordinates. + + Args: + offset (int | tuple | list): Offset(s) for four coordinates. If int, the same offset is applied to all + coordinates. + """ + if isinstance(offset, Number): + offset = to_4tuple(offset) + assert isinstance(offset, (tuple, list)) + assert len(offset) == 4 + self.bboxes[:, 0] += offset[0] + self.bboxes[:, 1] += offset[1] + self.bboxes[:, 2] += offset[2] + self.bboxes[:, 3] += offset[3] + + def __len__(self) -> int: + """Return the number of bounding boxes.""" + return len(self.bboxes) + + @classmethod + def concatenate(cls, boxes_list: list[Bboxes], axis: int = 0) -> Bboxes: + """Concatenate a list of Bboxes objects into a single Bboxes object. + + Args: + boxes_list (list[Bboxes]): A list of Bboxes objects to concatenate. + axis (int, optional): The axis along which to concatenate the bounding boxes. + + Returns: + (Bboxes): A new Bboxes object containing the concatenated bounding boxes. + + Notes: + The input should be a list or tuple of Bboxes objects. + """ + assert isinstance(boxes_list, (list, tuple)) + if not boxes_list: + return cls(np.empty(0)) + assert all(isinstance(box, Bboxes) for box in boxes_list) + + if len(boxes_list) == 1: + return boxes_list[0] + return cls(np.concatenate([b.bboxes for b in boxes_list], axis=axis)) + + def __getitem__(self, index: int | np.ndarray | slice) -> Bboxes: + """Retrieve a specific bounding box or a set of bounding boxes using indexing. + + Args: + index (int | slice | np.ndarray): The index, slice, or boolean array to select the desired bounding boxes. + + Returns: + (Bboxes): A new Bboxes object containing the selected bounding boxes. + + Notes: + When using boolean indexing, make sure to provide a boolean array with the same length as the number of + bounding boxes. + """ + b = self.bboxes[index] + if b.ndim == 1: + b = b.reshape(1, -1) + assert b.ndim == 2, f"Indexing on Bboxes with {index} failed to return a matrix!" + return Bboxes(b, format=self.format) + + +class Instances: + """Container for bounding boxes, segments, and keypoints of detected objects in an image. + + This class provides a unified interface for handling different types of object annotations including bounding boxes, + segmentation masks, and keypoints. It supports various operations like scaling, normalization, clipping, and format + conversion. + + Attributes: + _bboxes (Bboxes): Internal object for handling bounding box operations. + keypoints (np.ndarray): Keypoints with shape (N, 17, 3) in format (x, y, visible). + normalized (bool): Flag indicating whether the bounding box coordinates are normalized. + segments (np.ndarray): Segments array with shape (N, M, 2) after resampling. + + Methods: + convert_bbox: Convert bounding box format. + scale: Scale coordinates by given factors. + denormalize: Convert normalized coordinates to absolute coordinates. + normalize: Convert absolute coordinates to normalized coordinates. + add_padding: Add padding to coordinates. + flipud: Flip coordinates vertically. + fliplr: Flip coordinates horizontally. + clip: Clip coordinates to stay within image boundaries. + remove_zero_area_boxes: Remove boxes with zero area. + update: Update instance variables. + concatenate: Concatenate multiple Instances objects. + + Examples: + Create instances with bounding boxes and segments + >>> instances = Instances( + ... bboxes=np.array([[10, 10, 30, 30], [20, 20, 40, 40]]), + ... segments=[np.array([[5, 5], [10, 10]]), np.array([[15, 15], [20, 20]])], + ... keypoints=np.array([[[5, 5, 1], [10, 10, 1]], [[15, 15, 1], [20, 20, 1]]]), + ... ) + """ + + def __init__( + self, + bboxes: np.ndarray, + segments: np.ndarray = None, + keypoints: np.ndarray = None, + bbox_format: str = "xywh", + normalized: bool = True, + ) -> None: + """Initialize the Instances object with bounding boxes, segments, and keypoints. + + Args: + bboxes (np.ndarray): Bounding boxes with shape (N, 4). + segments (np.ndarray, optional): Segmentation masks. + keypoints (np.ndarray, optional): Keypoints with shape (N, 17, 3) in format (x, y, visible). + bbox_format (str): Format of bboxes. + normalized (bool): Whether the coordinates are normalized. + """ + self._bboxes = Bboxes(bboxes=bboxes, format=bbox_format) + self.keypoints = keypoints + self.normalized = normalized + self.segments = segments if segments is not None else np.zeros((0, 0, 2), dtype=np.float32) + + def convert_bbox(self, format: str) -> None: + """Convert bounding box format. + + Args: + format (str): Target format for conversion, one of 'xyxy', 'xywh', or 'ltwh'. + """ + self._bboxes.convert(format=format) + + @property + def bbox_areas(self) -> np.ndarray: + """Calculate the area of bounding boxes.""" + return self._bboxes.areas() + + def scale(self, scale_w: float, scale_h: float, bbox_only: bool = False): + """Scale coordinates by given factors. + + Args: + scale_w (float): Scale factor for width. + scale_h (float): Scale factor for height. + bbox_only (bool, optional): Whether to scale only bounding boxes. + """ + self._bboxes.mul(scale=(scale_w, scale_h, scale_w, scale_h)) + if bbox_only: + return + self.segments[..., 0] *= scale_w + self.segments[..., 1] *= scale_h + if self.keypoints is not None: + self.keypoints[..., 0] *= scale_w + self.keypoints[..., 1] *= scale_h + + def denormalize(self, w: int, h: int) -> None: + """Convert normalized coordinates to absolute coordinates. + + Args: + w (int): Image width. + h (int): Image height. + """ + if not self.normalized: + return + self._bboxes.mul(scale=(w, h, w, h)) + self.segments[..., 0] *= w + self.segments[..., 1] *= h + if self.keypoints is not None: + self.keypoints[..., 0] *= w + self.keypoints[..., 1] *= h + self.normalized = False + + def normalize(self, w: int, h: int) -> None: + """Convert absolute coordinates to normalized coordinates. + + Args: + w (int): Image width. + h (int): Image height. + """ + if self.normalized: + return + self._bboxes.mul(scale=(1 / w, 1 / h, 1 / w, 1 / h)) + self.segments[..., 0] /= w + self.segments[..., 1] /= h + if self.keypoints is not None: + self.keypoints[..., 0] /= w + self.keypoints[..., 1] /= h + self.normalized = True + + def add_padding(self, padw: int, padh: int) -> None: + """Add padding to coordinates. + + Args: + padw (int): Padding width. + padh (int): Padding height. + """ + assert not self.normalized, "you should add padding with absolute coordinates." + self._bboxes.add(offset=(padw, padh, padw, padh)) + self.segments[..., 0] += padw + self.segments[..., 1] += padh + if self.keypoints is not None: + self.keypoints[..., 0] += padw + self.keypoints[..., 1] += padh + + def __getitem__(self, index: int | np.ndarray | slice) -> Instances: + """Retrieve a specific instance or a set of instances using indexing. + + Args: + index (int | slice | np.ndarray): The index, slice, or boolean array to select the desired instances. + + Returns: + (Instances): A new Instances object containing the selected boxes, segments, and keypoints if present. + """ + index = [index] if isinstance(index, (int, np.integer)) else index + segments = self.segments[index] if len(self.segments) else self.segments + keypoints = self.keypoints[index] if self.keypoints is not None else None + bboxes = self.bboxes[index] + bbox_format = self._bboxes.format + return Instances( + bboxes=bboxes, + segments=segments, + keypoints=keypoints, + bbox_format=bbox_format, + normalized=self.normalized, + ) + + def flipud(self, h: int) -> None: + """Flip coordinates vertically. + + Args: + h (int): Image height. + """ + if self._bboxes.format == "xyxy": + y1 = self.bboxes[:, 1].copy() + y2 = self.bboxes[:, 3].copy() + self.bboxes[:, 1] = h - y2 + self.bboxes[:, 3] = h - y1 + else: + self.bboxes[:, 1] = h - self.bboxes[:, 1] + self.segments[..., 1] = h - self.segments[..., 1] + if self.keypoints is not None: + self.keypoints[..., 1] = h - self.keypoints[..., 1] + + def fliplr(self, w: int) -> None: + """Flip coordinates horizontally. + + Args: + w (int): Image width. + """ + if self._bboxes.format == "xyxy": + x1 = self.bboxes[:, 0].copy() + x2 = self.bboxes[:, 2].copy() + self.bboxes[:, 0] = w - x2 + self.bboxes[:, 2] = w - x1 + else: + self.bboxes[:, 0] = w - self.bboxes[:, 0] + self.segments[..., 0] = w - self.segments[..., 0] + if self.keypoints is not None: + self.keypoints[..., 0] = w - self.keypoints[..., 0] + + def clip(self, w: int, h: int, preserve_obb: bool = False) -> None: + """Clip coordinates to stay within image boundaries. + + Args: + w (int): Image width. + h (int): Image height. + preserve_obb (bool): Preserve oriented-box direction while clipping segments. + """ + ori_format = self._bboxes.format + self.convert_bbox(format="xyxy") + if preserve_obb and len(self.segments): + segment_mins, segment_maxs = self.segments.min(1), self.segments.max(1) + inside = ((segment_mins >= 0) & (segment_maxs <= (w, h))).all(1) + if not inside.all(): + canvas = np.array(((0, 0), (w, 0), (w, h), (0, h)), dtype=np.float32) + bboxes, segments = self.bboxes.copy(), self.segments.copy() + for i in np.flatnonzero(~inside): + segment = self.segments[i] + visible_area, visible = cv2.intersectConvexConvex( + cv2.convexHull(segment.astype(np.float32)), canvas + ) + if visible is None or visible_area <= 0: + bboxes[i], segments[i] = 0, 0 + continue + visible = visible.reshape(-1, 2) + bboxes[i] = np.array((*visible.min(0), *visible.max(0)), dtype=segment.dtype) + + # Fit the visible polygon in the full box's coordinates so edge crops cannot change its angle. + (_, _), (box_w, box_h), angle = cv2.minAreaRect(segment.astype(np.float32)) + if box_w < box_h: + angle += 90 + angle = np.deg2rad(angle) + cos, sin = np.cos(angle), np.sin(angle) + basis = np.array(((cos, -sin), (sin, cos)), dtype=np.float32) + aligned = visible @ basis + (u1, v1), (u2, v2) = aligned.min(0), aligned.max(0) + corners = np.array(((u2, v2), (u2, v1), (u1, v1), (u1, v2)), dtype=np.float32) + segments[i] = resample_segments([corners @ basis.T], n=len(segment))[0] + self.update(bboxes, segments) + else: + self.bboxes[:, [0, 2]] = self.bboxes[:, [0, 2]].clip(0, w) + self.bboxes[:, [1, 3]] = self.bboxes[:, [1, 3]].clip(0, h) + self.segments[..., 0] = self.segments[..., 0].clip(0, w) + self.segments[..., 1] = self.segments[..., 1].clip(0, h) + if ori_format != "xyxy": + self.convert_bbox(format=ori_format) + if self.keypoints is not None: + # Set out of bounds visibility to zero + self.keypoints[..., 2][ + (self.keypoints[..., 0] < 0) + | (self.keypoints[..., 0] > w) + | (self.keypoints[..., 1] < 0) + | (self.keypoints[..., 1] > h) + ] = 0.0 + self.keypoints[..., 0] = self.keypoints[..., 0].clip(0, w) + self.keypoints[..., 1] = self.keypoints[..., 1].clip(0, h) + + def remove_zero_area_boxes(self) -> np.ndarray: + """Remove zero-area boxes, i.e. after clipping some boxes may have zero width or height. + + Returns: + (np.ndarray): Boolean array indicating which boxes were kept. + """ + good = self.bbox_areas > 0 + if not all(good): + self._bboxes = self._bboxes[good] + if self.segments is not None and len(self.segments): + self.segments = self.segments[good] + if self.keypoints is not None: + self.keypoints = self.keypoints[good] + return good + + def update(self, bboxes: np.ndarray, segments: np.ndarray = None, keypoints: np.ndarray = None): + """Update instance variables. + + Args: + bboxes (np.ndarray): New bounding boxes. + segments (np.ndarray, optional): New segments. + keypoints (np.ndarray, optional): New keypoints. + """ + self._bboxes = Bboxes(bboxes, format=self._bboxes.format) + if segments is not None: + self.segments = segments + if keypoints is not None: + self.keypoints = keypoints + + def __len__(self) -> int: + """Return the number of instances.""" + return len(self.bboxes) + + @classmethod + def concatenate(cls, instances_list: list[Instances], axis=0) -> Instances: + """Concatenate a list of Instances objects into a single Instances object. + + Args: + instances_list (list[Instances]): A list of Instances objects to concatenate. + axis (int, optional): The axis along which the arrays will be concatenated. + + Returns: + (Instances): A new Instances object containing the concatenated bounding boxes, segments, and keypoints if + present. + + Notes: + The `Instances` objects in the list should have the same properties, such as the format of the bounding + boxes, whether keypoints are present, and if the coordinates are normalized. + """ + assert isinstance(instances_list, (list, tuple)) + if not instances_list: + return cls(np.empty(0)) + assert all(isinstance(instance, Instances) for instance in instances_list) + + if len(instances_list) == 1: + return instances_list[0] + + use_keypoint = instances_list[0].keypoints is not None + bbox_format = instances_list[0]._bboxes.format + normalized = instances_list[0].normalized + + cat_boxes = np.concatenate([ins.bboxes for ins in instances_list], axis=axis) + seg_len = [b.segments.shape[1] for b in instances_list] + if len(frozenset(seg_len)) > 1: # resample segments if there's different length + max_len = max(seg_len) + cat_segments = np.concatenate( + [ + resample_segments(list(b.segments), max_len) + if len(b.segments) + else np.zeros((0, max_len, 2), dtype=np.float32) # re-generating empty segments + for b in instances_list + ], + axis=axis, + ) + else: + cat_segments = np.concatenate([b.segments for b in instances_list], axis=axis) + cat_keypoints = np.concatenate([b.keypoints for b in instances_list], axis=axis) if use_keypoint else None + return cls(cat_boxes, cat_segments, cat_keypoints, bbox_format, normalized) + + @property + def bboxes(self) -> np.ndarray: + """Return bounding boxes.""" + return self._bboxes.bboxes + + def __repr__(self) -> str: + """Return a string representation of the Instances object.""" + # Map private to public names and include direct attributes + attr_map = {"_bboxes": "bboxes"} + parts = [] + for key, value in self.__dict__.items(): + name = attr_map.get(key, key) + if name == "bboxes": + value = self.bboxes # Use the property + if value is not None: + parts.append(f"{name}={value!r}") + return "Instances({})".format("\n".join(parts)) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/logger.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..55132ac7701fc667a0af980c19717f66f5280704 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/logger.py @@ -0,0 +1,670 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import json +import logging +import plistlib +import shutil +import subprocess +import sys +import threading +import time +from datetime import datetime +from pathlib import Path + +from ultralytics.utils import LINUX, LOGGER, MACOS, RANK, WINDOWS + + +class ConsoleLogger: + """Console output capture with batched streaming to file, API, or custom callback. + + Captures stdout/stderr output and streams it with intelligent deduplication and configurable batching. + + Attributes: + destination (str | Path | None): Target destination for streaming (URL, Path, or None for callback-only). + batch_size (int): Number of lines to batch before flushing (default: 1 for immediate). + flush_interval (float): Seconds between automatic flushes (default: 5.0). + on_flush (callable | None): Optional callback function called with batched content on flush. + active (bool): Whether console capture is currently active. + + Examples: + File logging (immediate): + >>> logger = ConsoleLogger("training.log") + >>> logger.start_capture() + >>> print("This will be logged") + >>> logger.stop_capture() + + API streaming with batching: + >>> logger = ConsoleLogger("https://api.example.com/logs", batch_size=10) + >>> logger.start_capture() + + Custom callback with batching: + >>> def my_handler(content, line_count, chunk_id): + ... print(f"Received {line_count} lines") + >>> logger = ConsoleLogger(on_flush=my_handler, batch_size=5) + >>> logger.start_capture() + """ + + def __init__(self, destination=None, batch_size=1, flush_interval=5.0, on_flush=None): + """Initialize console logger with optional batching. + + Args: + destination (str | Path | None): API endpoint URL (http/https), local file path, or None. + batch_size (int): Lines to accumulate before flush (1 = immediate, higher = batched). + flush_interval (float): Max seconds between flushes when batching. + on_flush (callable | None): Callback(content: str, line_count: int, chunk_id: int) for custom handling. + """ + if isinstance(destination, str) and destination.startswith("http://"): + LOGGER.warning("ConsoleLogger destination uses plaintext HTTP; captured logs are sent unencrypted.") + self.destination = destination + self.is_api = isinstance(destination, str) and destination.startswith(("http://", "https://")) + if destination is not None and not self.is_api: + self.destination = Path(destination) + + # Batching configuration + self.batch_size = max(1, batch_size) + self.flush_interval = flush_interval + self.on_flush = on_flush + + # Console capture state + self.original_stdout = sys.stdout + self.original_stderr = sys.stderr + self.active = False + self._log_handler = None # Track handler for cleanup + + # Buffer for batching + self.buffer = [] + self.buffer_lock = threading.Lock() + self.flush_thread = None + self.chunk_id = 0 + + # Deduplication state + self.last_line = "" + self.last_time = 0.0 + self.progress = {} # live progress bar frames by bar id, held as state instead of buffered as log lines + self.progress_sent = {} + + def start_capture(self): + """Start capturing console output and redirect stdout/stderr. + + Notes: + In DDP training, only activates on rank 0/-1 to prevent duplicate logging. + """ + if self.active or RANK not in {-1, 0}: + return + + self.active = True + self.stdout_capture = sys.stdout = self._ConsoleCapture(self.original_stdout, self._queue_log) + self.stderr_capture = sys.stderr = self._ConsoleCapture(self.original_stderr, self._queue_log) + + # Hook Ultralytics logger + try: + self._log_handler = self._LogHandler(self._queue_log) + logging.getLogger("ultralytics").addHandler(self._log_handler) + except Exception: + pass + + # Background flush thread: carries live progress frames in every mode, batched lines when batching + if not (self.flush_thread and self.flush_thread.is_alive()): # a worker still sleeping resumes on its own + self.flush_thread = threading.Thread(target=self._flush_worker, daemon=True) + self.flush_thread.start() + + def stop_capture(self): + """Stop capturing console output and flush remaining buffer.""" + if not self.active: + return + + self.stdout_capture.callback = self.stderr_capture.callback = None + self.active = False + sys.stdout = self.original_stdout + sys.stderr = self.original_stderr + + # Remove logging handler to prevent memory leak + if self._log_handler: + try: + logging.getLogger("ultralytics").removeHandler(self._log_handler) + except Exception: + pass + self._log_handler = None + + # Final flush, without the frames of any bar that outlived the capture + self.progress.clear() + self._flush_buffer() + + def _queue_log(self, text, bar_id): + """Queue console text with deduplication and timestamp processing, holding bar frames as state.""" + if not self.active: + return + + current_time = time.time() + + # Handle carriage returns and strip ANSI clear-line codes (TQDM writes "\r\033[K" interactively) + if "\r" in text: + text = text.split("\r")[-1] + text = text.replace("\x1b[K", "") + + if bar_id is not None: # a redraw is bar state, so only the frame a bar closed with becomes a log line + with self.buffer_lock: + if text: + self.progress[str(bar_id)] = text.rstrip() + return + text = self.progress.pop(str(bar_id), "") + + lines = text.split("\n") + if lines and lines[-1] == "": + lines.pop() + + for line in lines: + if not (line := line.rstrip()): + continue # a bare newline carries nothing once timestamped + + # General deduplication + if line == self.last_line and current_time - self.last_time < 0.1: + continue + + self.last_line = line + self.last_time = current_time + + # Add timestamp if needed + if not line.startswith("[20"): + timestamp = datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S") + line = f"[{timestamp}] {line}" + + # Add to buffer and check if flush needed + should_flush = False + with self.buffer_lock: + self.buffer.append(line) + if len(self.buffer) >= self.batch_size: + should_flush = True + + # Flush outside lock to avoid deadlock + if should_flush: + self._flush_buffer() + + def _flush_worker(self): + """Background worker that flushes buffer periodically.""" + while self.active: + time.sleep(self.flush_interval) + if self.active: + self._flush_buffer() + + def _flush_buffer(self): + """Flush buffered lines and current progress bar frames to destination and/or callback.""" + with self.buffer_lock: + if not self.buffer and self.progress == self.progress_sent: + return # nothing new: an idle bar must not flush a chunk of its own + lines = self.buffer.copy() + self.buffer.clear() + self.progress_sent = dict(self.progress) + self.chunk_id += 1 + chunk_id = self.chunk_id # Capture under lock to avoid race + + content = "\n".join(lines) + line_count = len(lines) + + # Call custom callback if provided + if self.on_flush: + try: + self.on_flush(content, line_count, chunk_id) + except Exception: + pass # Silently ignore callback errors to avoid flooding stderr + + # Write to destination (file or API) + if self.destination is not None and lines: + self._write_destination(content) + + def _write_destination(self, content): + """Write content to file or API destination.""" + try: + if self.is_api: + import requests + + payload = {"timestamp": datetime.now().astimezone().isoformat(), "message": content} + requests.post(str(self.destination), json=payload, timeout=5) + else: + self.destination.parent.mkdir(parents=True, exist_ok=True) + with self.destination.open("a", encoding="utf-8") as f: + f.write(content + "\n") + except Exception as e: + print(f"Console logger write error: {e}", file=self.original_stderr) + + class _ConsoleCapture: + """Lightweight stdout/stderr capture.""" + + __slots__ = ("callback", "original") + + def __init__(self, original, callback): + """Initialize a stream wrapper that redirects writes to a callback while preserving the original.""" + self.original = original + self.callback = callback + + def write(self, text): + """Write text to the original stream and forward it to the capture callback.""" + self.original.write(text) + if self.callback: + self.callback(text, None) + + def progress(self, bar_id, frame): + """Write a TQDM frame to the original stream and report it as bar state instead of a log line.""" + self.original.write(frame) + if self.callback: + self.callback(frame, bar_id) + + def flush(self): + """Flush the wrapped stream to propagate buffered output promptly during console capture.""" + self.original.flush() + + def isatty(self): + """Delegate isatty check to the original stream.""" + return self.original.isatty() + + class _LogHandler(logging.Handler): + """Lightweight logging handler.""" + + __slots__ = ("callback",) + + def __init__(self, callback): + """Initialize a lightweight logging.Handler that forwards log records to the provided callback.""" + super().__init__() + self.callback = callback + + def emit(self, record): + """Format and forward LogRecord messages to the capture callback for unified log streaming.""" + self.callback(self.format(record) + "\n", None) + + +class _DriveInfo: + """Resolve mounted storage paths backed by local drives. + + This helper keeps platform-specific drive discovery isolated from SystemLogger metric collection. It uses fast + psutil mount discovery first and falls back to native OS commands only when multiple visible mounts need + disambiguation. + + Examples: + >>> logger = SystemLogger(all_drives=True) + >>> logger.mounts + ['/'] + """ + + @staticmethod + def mounts(psutil, all_drives=False): + """Get mounted paths to monitor.""" + partitions = [p for p in psutil.disk_partitions(all=False) if p.mountpoint] + if not all_drives: + return [_DriveInfo._current_mount(partitions)] + + mounts = [ + p.mountpoint for p in partitions if Path(p.mountpoint).is_dir() and "dontbrowse" not in p.opts.split(",") + ] + if len(mounts) <= 1: + return _DriveInfo._sort(mounts) or [_DriveInfo._current_mount(partitions)] + + for getter in ( + _DriveInfo._macos_mounts if MACOS else None, + _DriveInfo._linux_mounts if LINUX else None, + _DriveInfo._windows_mounts if WINDOWS else None, + ): + if getter: + try: + if platform_mounts := getter(partitions): + return _DriveInfo._sort(platform_mounts) + except (json.JSONDecodeError, OSError, plistlib.InvalidFileException, subprocess.SubprocessError): + pass + return _DriveInfo._sort(mounts) + + @staticmethod + def _sort(mounts): + """Sort mounted paths with root first, excluding boot/firmware partitions like /boot and /boot/efi.""" + mounts = {m for m in mounts if not (m + "/").startswith(("/boot/", "/efi/"))} + return sorted(mounts, key=lambda mount: (mount != "/", mount)) + + @staticmethod + def _current_mount(partitions): + """Get the mounted filesystem backing the current working directory.""" + try: + cwd = Path.cwd().resolve() + except OSError: + return "C:\\" if WINDOWS else "/" + matches = [] + for partition in partitions: + try: + mount = Path(partition.mountpoint).resolve() + except OSError: + continue + if cwd == mount or cwd.is_relative_to(mount): + matches.append(partition.mountpoint) + return max(matches, key=len, default=Path.cwd().anchor or "/") + + @staticmethod + def _macos_mounts(partitions): + """Get user-visible macOS mounts backed by physical disks.""" + disk_info = plistlib.loads(subprocess.check_output(["diskutil", "list", "-plist", "physical"], timeout=5)) + physical_devices = set(disk_info.get("WholeDisks", [])) + for disk in disk_info.get("AllDisksAndPartitions", []): + physical_devices.add(disk.get("DeviceIdentifier", "")) + physical_devices.update(p.get("DeviceIdentifier", "") for p in disk.get("Partitions", [])) + + mounts, volume_groups = [], set() + for partition in partitions: + if partition.mountpoint != "/" and "dontbrowse" in partition.opts.split(","): + continue + info = plistlib.loads( + subprocess.check_output( + ["diskutil", "info", "-plist", partition.mountpoint], + stderr=subprocess.DEVNULL, + timeout=5, + ) + ) + devices = {info.get("DeviceIdentifier", "")} + devices.update(s.get("APFSPhysicalStore", "") for s in info.get("APFSPhysicalStores", [])) + if not devices & physical_devices: + continue + group = info.get("APFSVolumeGroupID") or info.get("APFSContainerReference") or partition.mountpoint + if group in volume_groups: + continue + volume_groups.add(group) + mounts.append(partition.mountpoint) + return mounts + + @staticmethod + def _linux_mounts(_partitions): + """Get Linux mounts backed by physical block devices.""" + block_info = json.loads( + subprocess.check_output( + ["lsblk", "--json", "--output", "NAME,TYPE,MOUNTPOINT,MOUNTPOINTS"], text=True, timeout=5 + ) + ) + mounts = [] + + def visit(block, physical=False): + physical = physical or block.get("type") == "disk" + if physical: + values = block.get("mountpoints") or [block.get("mountpoint")] + if isinstance(values, str): + values = [values] + mounts.extend(m for m in values if isinstance(m, str) and m.startswith("/") and Path(m).is_dir()) + for child in block.get("children", []): + visit(child, physical) + + for block in block_info.get("blockdevices", []): + visit(block) + return mounts + + @staticmethod + def _windows_mounts(_partitions): + """Get Windows fixed local drive mounts.""" + output = subprocess.check_output( + [ + "powershell", + "-NoProfile", + "-Command", + "Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' | Select-Object -ExpandProperty DeviceID", + ], + text=True, + timeout=5, + ) + return [f"{drive}\\" for drive in (line.strip() for line in output.splitlines()) if drive] + + +class SystemLogger: + """Log dynamic system metrics for training monitoring. + + Captures real-time system metrics including CPU, RAM, disk I/O, network I/O, and NVIDIA GPU statistics for training + performance monitoring and analysis. + + Attributes: + pynvml: NVIDIA pynvml module instance if successfully imported, None otherwise. + nvidia_initialized (bool): Whether NVIDIA GPU monitoring is available and initialized. + net_start: Initial network I/O counters for calculating cumulative usage. + disk_start: Initial disk I/O counters for calculating cumulative usage. + + Examples: + Basic usage (single drive): + >>> logger = SystemLogger() + >>> metrics = logger.get_metrics() + >>> print(f"CPU: {metrics['cpu']}%, RAM: {metrics['ram']}%") + >>> for disk in metrics["disk"]: + ... print(f"{disk['mount']}: {disk['used_gb']}/{disk['total_gb']} GB") + + Monitor all drives: + >>> logger = SystemLogger(all_drives=True) + >>> metrics = logger.get_metrics() + >>> for disk in metrics["disk"]: + ... print(f"{disk['mount']}: {disk['used_gb']}/{disk['total_gb']} GB") + + Training loop integration: + >>> system_logger = SystemLogger() + >>> for epoch in range(epochs): + ... # Training code here + ... metrics = system_logger.get_metrics() + ... # Log to database/file + """ + + def __init__(self, all_drives=False): + """Initialize the system logger. + + Args: + all_drives (bool): If True, monitor all mounted drives. If False, monitor the current drive. + """ + import psutil # scoped as slow import + + self.pynvml = None + self.nvidia_initialized = self._init_nvidia() + self.nvidia_versions = {} + if self.nvidia_initialized: + try: + self.nvidia_versions["driver_version"] = self.pynvml.nvmlSystemGetDriverVersion() + cuda = self.pynvml.nvmlSystemGetCudaDriverVersion_v2() + self.nvidia_versions["cuda_version"] = f"{cuda // 1000}.{cuda % 1000 // 10}" + except self.pynvml.NVMLError: + pass + self.net_start = psutil.net_io_counters() + self.disk_start = psutil.disk_io_counters() + self.mounts = _DriveInfo.mounts(psutil, all_drives) + + # For rate calculation + self._prev_net = self.net_start + self._prev_disk = self.disk_start + self._prev_time = time.time() + + def _init_nvidia(self): + """Initialize NVIDIA GPU monitoring with pynvml.""" + if MACOS: + return False + + try: + import pynvml # scoped as slow import + + self.pynvml = pynvml + pynvml.nvmlInit() + return True + except Exception as e: + import torch + + if torch.cuda.is_available(): + LOGGER.warning(f"SystemLogger NVML init failed: {e}") + return False + + def get_metrics(self, rates=False): + """Get current system metrics including CPU, RAM, disk, network, and GPU usage. + + Collects comprehensive system metrics including CPU usage, RAM usage, disk usage, disk I/O statistics, network + I/O statistics, and GPU metrics (if available). + + On NVIDIA systems, also reports `driver_version` and `cuda_version` cached from NVML at initialization. CUDA is the + driver-supported version shown by nvidia-smi, not the installed toolkit or PyTorch build version. + + Example output (rates=False, default): + ```python + { + "cpu": 45.2, + "ram": 78.9, + "disk": [{"mount": "/", "used_gb": 256.8, "total_gb": 512.0}], + "disk_io": {"read_mb": 156.7, "write_mb": 89.3}, + "network": {"recv_mb": 157.2, "sent_mb": 89.1}, + "gpus": { + "0": {"usage": 95.6, "memory": 85.4, "temp": 72, "power": 285}, + "1": {"usage": 94.1, "memory": 82.7, "temp": 70, "power": 278}, + }, + } + ``` + + Example output (rates=True): + ```python + { + "cpu": 45.2, + "ram": 78.9, + "disk": [{"mount": "/", "used_gb": 256.8, "total_gb": 512.0}], + "disk_io": {"read_mbs": 12.5, "write_mbs": 8.3}, + "network": {"recv_mbs": 5.2, "sent_mbs": 1.1}, + "gpus": { + "0": {"usage": 95.6, "memory": 85.4, "temp": 72, "power": 285}, + }, + } + ``` + + Args: + rates (bool): If True, return disk/network as MB/s rates instead of cumulative MB. + + Returns: + (dict): Metrics dictionary with cpu, ram, disk, network, and gpus keys. + + Examples: + >>> logger = SystemLogger() + >>> logger.get_metrics()["cpu"] # CPU percentage + >>> logger.get_metrics(rates=True)["network"]["recv_mbs"] # MB/s download rate + """ + import psutil # scoped as slow import + + net = psutil.net_io_counters() + disk_io = psutil.disk_io_counters() + memory = psutil.virtual_memory() + now = time.time() + + # Calculate elapsed time since last call + elapsed = max(0.1, now - self._prev_time) # Avoid division by zero + + if rates: + disk_io_metrics = { + "read_mbs": round(max(0, (disk_io.read_bytes - self._prev_disk.read_bytes) / 1e6 / elapsed), 3), + "write_mbs": round(max(0, (disk_io.write_bytes - self._prev_disk.write_bytes) / 1e6 / elapsed), 3), + } + else: + disk_io_metrics = { + "read_mb": round((disk_io.read_bytes - self.disk_start.read_bytes) / 1e6, 3), + "write_mb": round((disk_io.write_bytes - self.disk_start.write_bytes) / 1e6, 3), + } + + disks = [] + for mounts in (self.mounts, ["C:\\" if WINDOWS else "/"]): + for mount in mounts: + try: + usage = shutil.disk_usage(mount) + disks.append( + { + "mount": mount, + "used_gb": round(usage.used / 1e9, 3), + "total_gb": round(usage.total / 1e9, 3), + } + ) + except (PermissionError, OSError): + continue # Skip inaccessible drives + if disks: + break + + metrics = { + **self.nvidia_versions, + "cpu": round(psutil.cpu_percent(), 3), + "ram": round(memory.percent, 3), + "disk": disks, + "disk_io": disk_io_metrics, + "gpus": {}, + } + + if rates: + metrics["network"] = { + "recv_mbs": round(max(0, (net.bytes_recv - self._prev_net.bytes_recv) / 1e6 / elapsed), 3), + "sent_mbs": round(max(0, (net.bytes_sent - self._prev_net.bytes_sent) / 1e6 / elapsed), 3), + } + else: + metrics["network"] = { + "recv_mb": round((net.bytes_recv - self.net_start.bytes_recv) / 1e6, 3), + "sent_mb": round((net.bytes_sent - self.net_start.bytes_sent) / 1e6, 3), + } + + # Always update previous values for accurate rate calculation on next call + self._prev_net = net + self._prev_disk = disk_io + self._prev_time = now + + # Add GPU metrics (NVIDIA only) + if self.nvidia_initialized: + metrics["gpus"].update(self._get_nvidia_metrics()) + + return metrics + + def _get_nvidia_metrics(self): + """Get NVIDIA GPU metrics including utilization, memory, temperature, and power.""" + gpus = {} + if not self.nvidia_initialized or not self.pynvml: + return gpus + try: + device_count = self.pynvml.nvmlDeviceGetCount() + for i in range(device_count): + handle = self.pynvml.nvmlDeviceGetHandleByIndex(i) + util = self.pynvml.nvmlDeviceGetUtilizationRates(handle) + memory = self.pynvml.nvmlDeviceGetMemoryInfo(handle) + temp = self.pynvml.nvmlDeviceGetTemperature(handle, self.pynvml.NVML_TEMPERATURE_GPU) + power = self.pynvml.nvmlDeviceGetPowerUsage(handle) // 1000 + + gpus[str(i)] = { + "usage": round(util.gpu, 3), + "memory": round((memory.used / memory.total) * 100, 3), + "temp": temp, + "power": power, + } + except Exception: + pass + return gpus + + +if __name__ == "__main__": + print("SystemLogger Real-time Metrics Monitor") + print("Press Ctrl+C to stop\n") + + logger = SystemLogger(all_drives=True) + + try: + while True: + metrics = logger.get_metrics() + + # Clear screen (works on most terminals) + print("\033[H\033[J", end="", flush=True) + + # Display system metrics + print(f"CPU: {metrics['cpu']:5.1f}%") + print(f"RAM: {metrics['ram']:5.1f}%") + print(f"Net Recv: {metrics['network']['recv_mb']:9.1f} MB") + print(f"Net Sent: {metrics['network']['sent_mb']:9.1f} MB") + + # Display disk metrics + print("\nDisk Metrics:") + for disk in metrics["disk"]: + print(f" {disk['mount']}: {disk['used_gb']:.1f}/{disk['total_gb']:.1f} GB") + + # Display GPU metrics if available + if metrics["gpus"]: + print("\nGPU Metrics:") + for gpu_id, gpu_data in metrics["gpus"].items(): + print( + f" GPU {gpu_id}: {gpu_data['usage']:3}% | " + f"Mem: {gpu_data['memory']:5.1f}% | " + f"Temp: {gpu_data['temp']:2}°C | " + f"Power: {gpu_data['power']:3}W" + ) + else: + print("\nGPU: No NVIDIA GPUs detected") + + time.sleep(1) + + except KeyboardInterrupt: + print("\n\nStopped monitoring.") diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/loss.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..262667a7814020e9fa633212cf489e3655074698 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/loss.py @@ -0,0 +1,1529 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import math +from pathlib import Path +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn + +from ultralytics.utils.metrics import CITYSCAPES_WEIGHT, OKS_SIGMA, RLE_WEIGHT +from ultralytics.utils.ops import crop_mask, xywh2xyxy, xyxy2xywh +from ultralytics.utils.tal import RotatedTaskAlignedAssigner, TaskAlignedAssigner, dist2bbox, dist2rbox, make_anchors +from ultralytics.utils.torch_utils import autocast + +from .metrics import bbox_iou, probiou +from .tal import bbox2dist, rbox2dist + + +class VarifocalLoss(nn.Module): + """Varifocal loss by Zhang et al. + + Implements the Varifocal Loss function for addressing class imbalance in object detection by focusing on + hard-to-classify examples and balancing positive/negative samples. + + Attributes: + gamma (float): The focusing parameter that controls how much the loss focuses on hard-to-classify examples. + alpha (float): The balancing factor used to address class imbalance. + + References: + https://arxiv.org/abs/2008.13367 + """ + + def __init__(self, gamma: float = 2.0, alpha: float = 0.75): + """Initialize the VarifocalLoss class with focusing and balancing parameters.""" + super().__init__() + self.gamma = gamma + self.alpha = alpha + + def forward(self, pred_score: torch.Tensor, gt_score: torch.Tensor, label: torch.Tensor) -> torch.Tensor: + """Compute varifocal loss between predictions and ground truth.""" + weight = self.alpha * pred_score.sigmoid().pow(self.gamma) * (1 - label) + gt_score * label + with autocast(enabled=False, device=pred_score.device.type): + loss = ( + (F.binary_cross_entropy_with_logits(pred_score.float(), gt_score.float(), reduction="none") * weight) + .mean(1) + .sum() + ) + return loss + + +class FocalLoss(nn.Module): + """Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5). + + Implements the Focal Loss function for addressing class imbalance by down-weighting easy examples and focusing on + hard negatives during training. + + Attributes: + gamma (float): The focusing parameter that controls how much the loss focuses on hard-to-classify examples. + alpha (torch.Tensor): The balancing factor used to address class imbalance. + """ + + def __init__(self, gamma: float = 1.5, alpha: float = 0.25): + """Initialize FocalLoss class with focusing and balancing parameters.""" + super().__init__() + self.gamma = gamma + self.alpha = torch.tensor(alpha) + + def forward(self, pred: torch.Tensor, label: torch.Tensor) -> torch.Tensor: + """Calculate focal loss with modulating factors for class imbalance.""" + loss = F.binary_cross_entropy_with_logits(pred, label, reduction="none") + # p_t = torch.exp(-loss) + # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability + + # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py + pred_prob = pred.sigmoid() # prob from logits + p_t = label * pred_prob + (1 - label) * (1 - pred_prob) + modulating_factor = (1.0 - p_t) ** self.gamma + loss *= modulating_factor + if (self.alpha > 0).any(): + self.alpha = self.alpha.to(device=pred.device, dtype=pred.dtype) + alpha_factor = label * self.alpha + (1 - label) * (1 - self.alpha) + loss *= alpha_factor + return loss.mean(1).sum() + + +class DFLoss(nn.Module): + """Criterion class for computing Distribution Focal Loss (DFL).""" + + def __init__(self, reg_max: int = 16) -> None: + """Initialize the DFL module with regularization maximum.""" + super().__init__() + self.reg_max = reg_max + + def __call__(self, pred_dist: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """Return sum of left and right DFL losses from https://arxiv.org/abs/2006.04388.""" + target = target.clamp_(0, self.reg_max - 1 - 0.01) + tl = target.long() # target left + tr = tl + 1 # target right + wl = tr - target # weight left + wr = 1 - wl # weight right + # Compute log_softmax once, then two gathers; cross_entropy(x, t) = -log_softmax(x).gather(t) + logp = F.log_softmax(pred_dist, dim=1) + return -( + logp.gather(1, tl.view(-1, 1)).view(tl.shape) * wl + logp.gather(1, tr.view(-1, 1)).view(tl.shape) * wr + ).mean(-1, keepdim=True) + + +class BboxLoss(nn.Module): + """Criterion class for computing training losses for bounding boxes.""" + + def __init__(self, reg_max: int = 16): + """Initialize the BboxLoss module with regularization maximum and DFL settings.""" + super().__init__() + self.dfl_loss = DFLoss(reg_max) if reg_max > 1 else None + + def forward( + self, + pred_dist: torch.Tensor, + pred_bboxes: torch.Tensor, + anchor_points: torch.Tensor, + target_bboxes: torch.Tensor, + target_scores: torch.Tensor, + target_scores_sum: torch.Tensor, + fg_mask: torch.Tensor, + imgsz: torch.Tensor, + stride: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Compute IoU and DFL losses for bounding boxes.""" + fg_mask = fg_mask.nonzero(as_tuple=True) # index once; long-index gathers and their backward do not sync + weight = target_scores[fg_mask].sum(-1, keepdim=True) + iou = bbox_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask], xywh=False, CIoU=True) + loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum + + # DFL loss + if self.dfl_loss: + target_ltrb = bbox2dist(anchor_points, target_bboxes, self.dfl_loss.reg_max - 1) + loss_dfl = self.dfl_loss(pred_dist[fg_mask].view(-1, self.dfl_loss.reg_max), target_ltrb[fg_mask]) * weight + loss_dfl = loss_dfl.sum() / target_scores_sum + else: + target_ltrb = bbox2dist(anchor_points, target_bboxes) + # normalize ltrb by image size + target_ltrb = target_ltrb * stride + target_ltrb[..., 0::2] /= imgsz[1] + target_ltrb[..., 1::2] /= imgsz[0] + pred_dist = pred_dist * stride + pred_dist[..., 0::2] /= imgsz[1] + pred_dist[..., 1::2] /= imgsz[0] + loss_dfl = ( + F.l1_loss(pred_dist[fg_mask], target_ltrb[fg_mask], reduction="none").mean(-1, keepdim=True) * weight + ) + loss_dfl = loss_dfl.sum() / target_scores_sum + + return loss_iou, loss_dfl + + +class RLELoss(nn.Module): + """Residual Log-Likelihood Estimation Loss. + + Attributes: + size_average (bool): Option to average the loss by the batch_size. + use_target_weight (bool): Option to use weighted loss. + residual (bool): Option to add L1 loss and let the flow learn the residual error distribution. + + References: + https://arxiv.org/abs/2107.11291 + https://github.com/open-mmlab/mmpose/blob/main/mmpose/models/losses/regression_loss.py + """ + + def __init__(self, use_target_weight: bool = True, size_average: bool = True, residual: bool = True): + """Initialize RLELoss with target weight and residual options. + + Args: + use_target_weight (bool): Whether to use target weights for loss calculation. + size_average (bool): Whether to average the loss over elements. + residual (bool): Whether to include residual log-likelihood term. + """ + super().__init__() + self.size_average = size_average + self.use_target_weight = use_target_weight + self.residual = residual + + def forward( + self, sigma: torch.Tensor, log_phi: torch.Tensor, error: torch.Tensor, target_weight: torch.Tensor = None + ) -> torch.Tensor: + """ + Args: + sigma (torch.Tensor): Output sigma, shape (N, D). + log_phi (torch.Tensor): Output log_phi, shape (N). + error (torch.Tensor): Error, shape (N, D). + target_weight (torch.Tensor): Weights across different joint types, shape (N). + """ + log_sigma = torch.log(sigma) + loss = log_sigma - log_phi.unsqueeze(1) + + if self.residual: + loss += torch.log(sigma * 2) + torch.abs(error) + + if self.use_target_weight: + assert target_weight is not None, "'target_weight' should not be None when 'use_target_weight' is True." + if target_weight.dim() == 1: + target_weight = target_weight.unsqueeze(1) + loss *= target_weight + + if self.size_average: + loss /= len(loss) + + return loss.sum() + + +class RotatedBboxLoss(BboxLoss): + """Criterion class for computing training losses for rotated bounding boxes.""" + + floor = 0.01 + + def __init__(self, reg_max: int): + """Initialize the RotatedBboxLoss module with regularization maximum and DFL settings.""" + super().__init__(reg_max) + + def forward( + self, + pred_dist: torch.Tensor, + pred_bboxes: torch.Tensor, + anchor_points: torch.Tensor, + target_bboxes: torch.Tensor, + target_scores: torch.Tensor, + target_scores_sum: torch.Tensor, + fg_mask: torch.Tensor, + imgsz: torch.Tensor, + stride: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Compute IoU and DFL losses for rotated bounding boxes.""" + weight = target_scores[fg_mask].sum(-1, keepdim=True) + iou = probiou(pred_bboxes[fg_mask], target_bboxes[fg_mask], floor=self.floor) + loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum + + # DFL loss + if self.dfl_loss: + target_ltrb = rbox2dist( + target_bboxes[..., :4], anchor_points, target_bboxes[..., 4:5], reg_max=self.dfl_loss.reg_max - 1 + ) + loss_dfl = self.dfl_loss(pred_dist[fg_mask].view(-1, self.dfl_loss.reg_max), target_ltrb[fg_mask]) * weight + loss_dfl = loss_dfl.sum() / target_scores_sum + else: + target_ltrb = rbox2dist(target_bboxes[..., :4], anchor_points, target_bboxes[..., 4:5]) + target_ltrb = target_ltrb * stride + target_ltrb[..., 0::2] /= imgsz[1] + target_ltrb[..., 1::2] /= imgsz[0] + pred_dist = pred_dist * stride + pred_dist[..., 0::2] /= imgsz[1] + pred_dist[..., 1::2] /= imgsz[0] + loss_dfl = ( + F.l1_loss(pred_dist[fg_mask], target_ltrb[fg_mask], reduction="none").mean(-1, keepdim=True) * weight + ) + loss_dfl = loss_dfl.sum() / target_scores_sum + + return loss_iou, loss_dfl + + +class MultiChannelDiceLoss(nn.Module): + """Criterion class for computing multi-channel Dice losses.""" + + def __init__(self, smooth: float = 1e-6, reduction: str = "mean"): + """Initialize MultiChannelDiceLoss with smoothing and reduction options. + + Args: + smooth (float): Smoothing factor to avoid division by zero. + reduction (str): Reduction method ('mean', 'sum', or 'none'). + """ + super().__init__() + self.smooth = smooth + self.reduction = reduction + + def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """Calculate multi-channel Dice loss between predictions and targets.""" + assert pred.size() == target.size(), "the size of predict and target must be equal." + + pred = pred.sigmoid() + intersection = (pred * target).sum(dim=(2, 3)) + union = pred.sum(dim=(2, 3)) + target.sum(dim=(2, 3)) + dice = (2.0 * intersection + self.smooth) / (union + self.smooth) + dice_loss = 1.0 - dice + dice_loss = dice_loss.mean(dim=1) + + if self.reduction == "mean": + return dice_loss.mean() + elif self.reduction == "sum": + return dice_loss.sum() + else: + return dice_loss + + +class BCEDiceLoss(nn.Module): + """Criterion class for computing combined BCE and Dice losses.""" + + def __init__(self, weight_bce: float = 0.5, weight_dice: float = 0.5): + """Initialize BCEDiceLoss with BCE and Dice weight factors. + + Args: + weight_bce (float): Weight factor for BCE loss component. + weight_dice (float): Weight factor for Dice loss component. + """ + super().__init__() + self.weight_bce = weight_bce + self.weight_dice = weight_dice + self.bce = nn.BCEWithLogitsLoss() + self.dice = MultiChannelDiceLoss(smooth=1) + + def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """Calculate combined BCE and Dice loss between predictions and targets.""" + _, _, mask_h, mask_w = pred.shape + if tuple(target.shape[-2:]) != (mask_h, mask_w): # downsample to the same size as pred + target = F.interpolate(target, (mask_h, mask_w), mode="nearest") + return self.weight_bce * self.bce(pred, target) + self.weight_dice * self.dice(pred, target) + + +class KeypointLoss(nn.Module): + """Criterion class for computing keypoint losses.""" + + def __init__(self, sigmas: torch.Tensor) -> None: + """Initialize the KeypointLoss class with keypoint sigmas.""" + super().__init__() + self.sigmas = sigmas + + def forward( + self, pred_kpts: torch.Tensor, gt_kpts: torch.Tensor, kpt_mask: torch.Tensor, area: torch.Tensor + ) -> torch.Tensor: + """Calculate keypoint loss factor and Euclidean distance loss for keypoints.""" + d = (pred_kpts[..., 0] - gt_kpts[..., 0]).pow(2) + (pred_kpts[..., 1] - gt_kpts[..., 1]).pow(2) + kpt_loss_factor = kpt_mask.shape[1] / (torch.sum(kpt_mask != 0, dim=1) + 1e-9) + # e = d / (2 * (area * self.sigmas) ** 2 + 1e-9) # from formula + e = d / ((2 * self.sigmas).pow(2) * (area + 1e-9) * 2) # from cocoeval + return (kpt_loss_factor.view(-1, 1) * ((1 - torch.exp(-e)) * kpt_mask)).mean() + + +class v8DetectionLoss: + """Criterion class for computing training losses for YOLOv8 object detection.""" + + def __init__( + self, model: torch.nn.Module, tal_topk: int = 10, tal_topk2: int | None = None + ): # model must be de-paralleled + """Initialize v8DetectionLoss with model parameters and task-aligned assignment settings.""" + device = next(model.parameters()).device # get model device + h = model.args # hyperparameters + + m = model.model[-1] # Detect() module + self.bce = nn.BCEWithLogitsLoss(reduction="none") + self.hyp = h + self.stride = m.stride # model strides + self.nc = m.nc # number of classes + self.no = m.nc + m.reg_max * 4 + self.reg_max = m.reg_max + self.device = device + + self.use_dfl = m.reg_max > 1 + self.loss_names = "box_loss", "cls_loss", "dfl_loss" if self.use_dfl else "l1_loss" + + # Class weights for handling imbalanced datasets + self.class_weights = getattr(model, "class_weights", None) + if self.class_weights is not None: + self.class_weights = self.class_weights.to(device).view(1, 1, -1) + + self.assigner = TaskAlignedAssigner( + topk=tal_topk, + num_classes=self.nc, + alpha=0.5, + beta=6.0, + stride=self.stride.tolist(), + topk2=tal_topk2, + ) + self.bbox_loss = BboxLoss(m.reg_max).to(device) + self.proj = torch.arange(m.reg_max, dtype=torch.float, device=device) + + def preprocess(self, targets: torch.Tensor, batch_size: int, scale_tensor: torch.Tensor) -> torch.Tensor: + """Preprocess targets by converting to tensor format and scaling coordinates.""" + nl, ne = targets.shape + if nl == 0: + out = torch.zeros(batch_size, 0, ne - 1, device=self.device) + else: + batch_idx = targets[:, 0].long() # image index + _, counts = batch_idx.unique(return_counts=True) + counts = counts.to(dtype=torch.int32) + out = torch.zeros(batch_size, counts.max(), ne - 1, device=self.device) + offsets = torch.zeros(batch_size + 1, dtype=torch.long, device=self.device) + offsets.scatter_add_(0, batch_idx + 1, torch.ones_like(batch_idx)) + offsets = offsets.cumsum(0) + within_idx = torch.arange(nl, device=self.device) - offsets[batch_idx] + out[batch_idx, within_idx] = targets[:, 1:] + out[..., 1:5] = xywh2xyxy(out[..., 1:5].mul_(scale_tensor)) + return out + + def bbox_decode(self, anchor_points: torch.Tensor, pred_dist: torch.Tensor) -> torch.Tensor: + """Decode predicted object bounding box coordinates from anchor points and distribution.""" + if self.use_dfl: + b, a, c = pred_dist.shape # batch, anchors, channels + pred_dist = pred_dist.view(b, a, 4, c // 4).softmax(3).matmul(self.proj.type(pred_dist.dtype)) + # pred_dist = pred_dist.view(b, a, c // 4, 4).transpose(2,3).softmax(3).matmul(self.proj.type(pred_dist.dtype)) + # pred_dist = (pred_dist.view(b, a, c // 4, 4).softmax(2) * self.proj.type(pred_dist.dtype).view(1, 1, -1, 1)).sum(2) + return dist2bbox(pred_dist, anchor_points, xywh=False) + + def get_assigned_targets_and_loss(self, preds: dict[str, torch.Tensor], batch: dict[str, Any]) -> tuple: + """Calculate the sum of the loss for box, cls and dfl multiplied by batch size and return foreground mask and + target indices. + """ + loss = torch.zeros(3, device=self.device) # box, cls, dfl + pred_distri, pred_scores = ( + preds["boxes"].permute(0, 2, 1).contiguous(), + preds["scores"].permute(0, 2, 1).contiguous(), + ) + anchor_points, stride_tensor = make_anchors(preds["feats"], self.stride, 0.5) + + dtype = pred_scores.dtype + batch_size = pred_scores.shape[0] + imgsz = torch.tensor(preds["feats"][0].shape[2:], device=self.device, dtype=dtype) * self.stride[0] + + # Targets + targets = torch.cat((batch["batch_idx"].view(-1, 1), batch["cls"].view(-1, 1), batch["bboxes"]), 1) + targets = self.preprocess(targets.to(self.device), batch_size, scale_tensor=imgsz[[1, 0, 1, 0]]) + gt_labels, gt_bboxes = targets.split((1, 4), 2) # cls, xyxy + mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0.0) + + # Pboxes + pred_bboxes = self.bbox_decode(anchor_points, pred_distri) # xyxy, (b, h*w, 4) + + _, target_bboxes, target_scores, fg_mask, target_gt_idx = self.assigner( + pred_scores.detach().sigmoid(), + (pred_bboxes.detach() * stride_tensor).type(gt_bboxes.dtype), + anchor_points * stride_tensor, + gt_labels, + gt_bboxes, + mask_gt, + ) + + target_scores_sum = target_scores.sum().clamp_(min=1) # on the device: no host sync + + # Cls loss with optional class weighting + bce_loss = self.bce(pred_scores, target_scores.to(dtype)) # (bs, num_anchors, nc) + if self.class_weights is not None: + bce_loss *= self.class_weights + loss[1] = bce_loss.sum() / target_scores_sum # BCE + + # Bbox loss: zero on an empty foreground, and pred_distri stays in the graph either way + loss[0], loss[2] = self.bbox_loss( + pred_distri, + pred_bboxes, + anchor_points, + target_bboxes / stride_tensor, + target_scores, + target_scores_sum, + fg_mask, + imgsz, + stride_tensor, + ) + + loss[0] *= self.hyp.box # box gain + loss[1] *= self.hyp.cls # cls gain + loss[2] *= self.hyp.dfl # dfl gain + return ( + (fg_mask, target_gt_idx, target_bboxes, anchor_points, stride_tensor), + loss, + dict(zip(self.loss_names, loss.detach())), + ) # loss(box, cls, dfl) + + def parse_output( + self, preds: dict[str, torch.Tensor] | tuple[torch.Tensor, dict[str, torch.Tensor]] + ) -> torch.Tensor: + """Parse model predictions to extract features.""" + return preds[1] if isinstance(preds, tuple) else preds + + def __call__( + self, + preds: dict[str, torch.Tensor] | tuple[torch.Tensor, dict[str, torch.Tensor]], + batch: dict[str, torch.Tensor], + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Calculate the sum of the loss for box, cls and dfl multiplied by batch size.""" + return self.loss(self.parse_output(preds), batch) + + def loss( + self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor] + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Calculate detection loss using assigned targets.""" + batch_size = preds["boxes"].shape[0] + loss, loss_detach = self.get_assigned_targets_and_loss(preds, batch)[1:] + return loss * batch_size, loss_detach + + +class v8SegmentationLoss(v8DetectionLoss): + """Criterion class for computing training losses for YOLOv8 segmentation.""" + + def __init__( + self, model: torch.nn.Module, tal_topk: int = 10, tal_topk2: int | None = None + ): # model must be de-paralleled + """Initialize the v8SegmentationLoss class with model parameters and mask overlap setting.""" + super().__init__(model, tal_topk, tal_topk2) + self.loss_names = ("box_loss", "seg_loss", *self.loss_names[1:], "sem_loss") + self.overlap = model.args.overlap_mask + self.bcedice_loss = BCEDiceLoss(weight_bce=0.5, weight_dice=0.5) + + def loss( + self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor] + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Calculate and return the combined loss for detection and segmentation.""" + pred_masks, proto = preds["mask_coefficient"].permute(0, 2, 1).contiguous(), preds["proto"] + loss = torch.zeros(5, device=self.device) # box, seg, cls, dfl, semantic + if isinstance(proto, tuple) and len(proto) == 2: + proto, pred_semantic = proto + else: + pred_semantic = None + (fg_mask, target_gt_idx, target_bboxes, _, _), det_loss, _ = self.get_assigned_targets_and_loss(preds, batch) + # NOTE: re-assign index for consistency for now. Need to be removed in the future. + loss[0], loss[2], loss[3] = det_loss[0], det_loss[1], det_loss[2] + + batch_size, _, mask_h, mask_w = proto.shape # batch size, number of masks, mask height, mask width + if fg_mask.sum(): + # Masks loss + masks = batch["masks"].to(self.device).float() + if tuple(masks.shape[-2:]) != (mask_h, mask_w): # downsample + # masks = F.interpolate(masks[None], (mask_h, mask_w), mode="nearest")[0] + proto = F.interpolate(proto, masks.shape[-2:], mode="bilinear", align_corners=False) + + imgsz = ( + torch.tensor(preds["feats"][0].shape[2:], device=self.device, dtype=pred_masks.dtype) * self.stride[0] + ) + loss[1] = self.calculate_segmentation_loss( + fg_mask, + masks, + target_gt_idx, + target_bboxes, + batch["batch_idx"].view(-1, 1), + proto, + pred_masks, + imgsz, + ) + if pred_semantic is not None: + sem_idx = batch["sem_masks"].to(self.device).long().unsqueeze(1) # Nx1xHxW + if self.overlap: + present = masks != 0 # NxHxW + else: + batch_idx = batch["batch_idx"].view(-1) # [total_instances] + present = torch.zeros(batch_size, *masks.shape[-2:], dtype=torch.bool, device=self.device) + for i in range(batch_size): + instance_mask_i = masks[batch_idx == i] # [num_instances_i, H, W] + if len(instance_mask_i): + present[i] = instance_mask_i.sum(dim=0) != 0 + # One-hot targets zeroed at uncovered pixels, without F.one_hot's int64 NxHxWxC intermediate + sem_masks = torch.zeros(sem_idx.shape[0], self.nc, *sem_idx.shape[2:], device=self.device) + sem_masks.scatter_(1, sem_idx, present.unsqueeze(1).float()) # NxCxHxW + + loss[4] = self.bcedice_loss(pred_semantic, sem_masks) + loss[4] *= self.hyp.box # seg gain + + # WARNING: lines below prevent Multi-GPU DDP 'unused gradient' PyTorch errors, do not remove + else: + loss[1] += (proto * 0).sum() + (pred_masks * 0).sum() # inf sums may lead to nan loss + if pred_semantic is not None: + loss[4] += (pred_semantic * 0).sum() + + loss[1] *= self.hyp.box # seg gain + return loss * batch_size, dict(zip(self.loss_names, loss.detach())) # loss(box, seg, cls, dfl, semantic) + + @staticmethod + def single_mask_loss( + gt_mask: torch.Tensor, pred: torch.Tensor, proto: torch.Tensor, xyxy: torch.Tensor, area: torch.Tensor + ) -> torch.Tensor: + """Compute the instance segmentation loss for a single image. + + Args: + gt_mask (torch.Tensor): Ground truth mask of shape (N, H, W), where N is the number of objects. + pred (torch.Tensor): Predicted mask coefficients of shape (N, 32). + proto (torch.Tensor): Prototype masks of shape (32, H, W). + xyxy (torch.Tensor): Ground truth bounding boxes in xyxy format, normalized to [0, 1], of shape (N, 4). + area (torch.Tensor): Area of each ground truth bounding box of shape (N,). + + Returns: + (torch.Tensor): The calculated mask loss for a single image. + + Notes: + The function uses the equation pred_mask = torch.einsum('in,nhw->ihw', pred, proto) to produce the + predicted masks from the prototype masks and predicted mask coefficients. + """ + pred_mask = torch.einsum("in,nhw->ihw", pred, proto) # (n, 32) @ (32, 80, 80) -> (n, 80, 80) + loss = F.binary_cross_entropy_with_logits(pred_mask, gt_mask, reduction="none") + return (crop_mask(loss, xyxy).mean(dim=(1, 2)) / area).sum() + + def calculate_segmentation_loss( + self, + fg_mask: torch.Tensor, + masks: torch.Tensor, + target_gt_idx: torch.Tensor, + target_bboxes: torch.Tensor, + batch_idx: torch.Tensor, + proto: torch.Tensor, + pred_masks: torch.Tensor, + imgsz: torch.Tensor, + ) -> torch.Tensor: + """Calculate the loss for instance segmentation. + + Args: + fg_mask (torch.Tensor): A binary tensor of shape (BS, N_anchors) indicating which anchors are positive. + masks (torch.Tensor): Ground truth masks, shape (BS, H, W) if `overlap` else (N_instances_in_batch, H, W). + target_gt_idx (torch.Tensor): Indexes of ground truth objects for each anchor of shape (BS, N_anchors). + target_bboxes (torch.Tensor): Ground truth bounding boxes for each anchor of shape (BS, N_anchors, 4). + batch_idx (torch.Tensor): Batch indices of shape (N_labels_in_batch, 1). + proto (torch.Tensor): Prototype masks of shape (BS, 32, H, W). + pred_masks (torch.Tensor): Predicted masks for each anchor of shape (BS, N_anchors, 32). + imgsz (torch.Tensor): Size of the input image as a tensor of shape (2), i.e., (H, W). + + Returns: + (torch.Tensor): The calculated loss for instance segmentation. + + Notes: + The batch loss can be computed for improved speed at higher memory usage. + For example, pred_mask can be computed as follows: + pred_mask = torch.einsum('in,nhw->ihw', pred, proto) # (i, 32) @ (32, 160, 160) -> (i, 160, 160) + """ + _, _, mask_h, mask_w = proto.shape + loss = 0 + + # Normalize to 0-1 + target_bboxes_normalized = target_bboxes / imgsz[[1, 0, 1, 0]] + + # Areas of target bboxes + marea = xyxy2xywh(target_bboxes_normalized)[..., 2:].prod(2) + + # Normalize to mask size + mxyxy = target_bboxes_normalized * torch.tensor([mask_w, mask_h, mask_w, mask_h], device=proto.device) + + for i, single_i in enumerate(zip(fg_mask, target_gt_idx, pred_masks, proto, mxyxy, marea)): + fg_mask_i, target_gt_idx_i, pred_masks_i, proto_i, mxyxy_i, marea_i = single_i + if fg_mask_i.any(): + mask_idx = target_gt_idx_i[fg_mask_i] + if self.overlap: + gt_mask = masks[i] == (mask_idx + 1).view(-1, 1, 1) + gt_mask = gt_mask.float() + else: + gt_mask = masks[batch_idx.view(-1) == i][mask_idx] + + loss += self.single_mask_loss( + gt_mask, pred_masks_i[fg_mask_i], proto_i, mxyxy_i[fg_mask_i], marea_i[fg_mask_i] + ) + + # WARNING: lines below prevents Multi-GPU DDP 'unused gradient' PyTorch errors, do not remove + else: + loss += (proto * 0).sum() + (pred_masks * 0).sum() # inf sums may lead to nan loss + + return loss / fg_mask.sum() + + +class v8PoseLoss(v8DetectionLoss): + """Criterion class for computing training losses for YOLOv8 pose estimation.""" + + def __init__(self, model: torch.nn.Module, tal_topk: int = 10, tal_topk2: int = 10): # model must be de-paralleled + """Initialize v8PoseLoss with model parameters and keypoint-specific loss functions.""" + super().__init__(model, tal_topk, tal_topk2) + self.loss_names = ("box_loss", "pose_loss", "kobj_loss", *self.loss_names[1:]) + self.kpt_shape = model.model[-1].kpt_shape + self.bce_pose = nn.BCEWithLogitsLoss() + is_pose = self.kpt_shape == [17, 3] + nkpt = self.kpt_shape[0] # number of keypoints + + sigmas = getattr(model, "kpt_oks_sigmas", None) + if sigmas is None: + sigmas = ( + torch.from_numpy(OKS_SIGMA).to(self.device) if is_pose else torch.ones(nkpt, device=self.device) / nkpt + ) + else: + sigmas = torch.as_tensor(sigmas, device=self.device, dtype=torch.float32).flatten() + if len(sigmas) != nkpt or not torch.all(sigmas > 0): + raise ValueError(f"'kpt_oks_sigmas' must be {nkpt} positive values, got {sigmas.tolist()}") + + self.keypoint_loss = KeypointLoss(sigmas=sigmas) + + def loss( + self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor] + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Calculate the total loss and detach it for pose estimation.""" + pred_kpts = preds["kpts"].permute(0, 2, 1).contiguous() + loss = torch.zeros(5, device=self.device) # box, kpt_location, kpt_visibility, cls, dfl + (fg_mask, target_gt_idx, target_bboxes, anchor_points, stride_tensor), det_loss, _ = ( + self.get_assigned_targets_and_loss(preds, batch) + ) + # NOTE: re-assign index for consistency for now. Need to be removed in the future. + loss[0], loss[3], loss[4] = det_loss[0], det_loss[1], det_loss[2] + + batch_size = pred_kpts.shape[0] + imgsz = torch.tensor(preds["feats"][0].shape[2:], device=self.device, dtype=pred_kpts.dtype) * self.stride[0] + + # Pboxes + pred_kpts = self.kpts_decode(anchor_points, pred_kpts.view(batch_size, -1, *self.kpt_shape)) # (b, h*w, 17, 3) + + # Keypoint loss + if fg_mask.sum(): + keypoints = batch["keypoints"].to(self.device).float().clone() + keypoints[..., 0] *= imgsz[1] + keypoints[..., 1] *= imgsz[0] + + loss[1], loss[2] = self.calculate_keypoints_loss( + fg_mask, + target_gt_idx, + keypoints, + batch["batch_idx"].view(-1, 1), + stride_tensor, + target_bboxes, + pred_kpts, + ) + # WARNING: line below prevents Multi-GPU DDP 'unused gradient' PyTorch errors, do not remove + else: + loss[1] += pred_kpts[..., :0].sum() + + loss[1] *= self.hyp.pose # pose gain + loss[2] *= self.hyp.kobj # kobj gain + + return loss * batch_size, dict(zip(self.loss_names, loss.detach())) # loss(box, pose, kobj, cls, dfl) + + @staticmethod + def kpts_decode(anchor_points: torch.Tensor, pred_kpts: torch.Tensor) -> torch.Tensor: + """Decode predicted keypoints to image coordinates.""" + y = pred_kpts.clone() + y[..., :2] *= 2.0 + y[..., 0] += anchor_points[:, [0]] - 0.5 + y[..., 1] += anchor_points[:, [1]] - 0.5 + return y + + def _select_target_keypoints( + self, + keypoints: torch.Tensor, + batch_idx: torch.Tensor, + target_gt_idx: torch.Tensor, + masks: torch.Tensor, + ) -> torch.Tensor: + """Select target keypoints for each anchor based on batch index and target ground truth index. + + Args: + keypoints (torch.Tensor): Ground truth keypoints, shape (N_kpts_in_batch, N_kpts_per_object, kpts_dim). + batch_idx (torch.Tensor): Batch index tensor for keypoints, shape (N_kpts_in_batch, 1). + target_gt_idx (torch.Tensor): Index tensor mapping anchors to ground truth objects, shape (BS, N_anchors). + masks (torch.Tensor): Binary mask tensor indicating object presence, shape (BS, N_anchors). + + Returns: + (torch.Tensor): Selected keypoints tensor, shape (BS, N_anchors, N_kpts_per_object, kpts_dim). + """ + batch_idx = batch_idx.flatten() + batch_size = len(masks) + + # Find the maximum number of keypoints in a single image + max_kpts = torch.unique(batch_idx, return_counts=True)[1].max() + + # Create a tensor to hold batched keypoints + batched_keypoints = torch.zeros( + (batch_size, max_kpts, keypoints.shape[1], keypoints.shape[2]), device=keypoints.device + ) + + # Vectorized fill: compute within-batch position for each keypoint using cumulative offsets + batch_idx_long = batch_idx.long() + offsets = torch.zeros(batch_size + 1, dtype=torch.long, device=keypoints.device) + offsets.scatter_add_(0, batch_idx_long + 1, torch.ones_like(batch_idx_long)) + offsets = offsets.cumsum(0) + within_idx = torch.arange(len(batch_idx), device=keypoints.device) - offsets[batch_idx_long] + batched_keypoints[batch_idx_long, within_idx] = keypoints + + # Expand dimensions of target_gt_idx to match the shape of batched_keypoints + target_gt_idx_expanded = target_gt_idx.unsqueeze(-1).unsqueeze(-1) + + # Use target_gt_idx_expanded to select keypoints from batched_keypoints + selected_keypoints = batched_keypoints.gather( + 1, target_gt_idx_expanded.expand(-1, -1, keypoints.shape[1], keypoints.shape[2]) + ) + + return selected_keypoints + + def calculate_keypoints_loss( + self, + masks: torch.Tensor, + target_gt_idx: torch.Tensor, + keypoints: torch.Tensor, + batch_idx: torch.Tensor, + stride_tensor: torch.Tensor, + target_bboxes: torch.Tensor, + pred_kpts: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Calculate the keypoints loss for the model. + + This function calculates the keypoints loss and keypoints object loss for a given batch. The keypoints loss is + based on the difference between the predicted keypoints and ground truth keypoints. The keypoints object loss is + a binary classification loss that classifies whether a keypoint is present or not. + + Args: + masks (torch.Tensor): Binary mask tensor indicating object presence, shape (BS, N_anchors). + target_gt_idx (torch.Tensor): Index tensor mapping anchors to ground truth objects, shape (BS, N_anchors). + keypoints (torch.Tensor): Ground truth keypoints, shape (N_kpts_in_batch, N_kpts_per_object, kpts_dim). + batch_idx (torch.Tensor): Batch index tensor for keypoints, shape (N_kpts_in_batch, 1). + stride_tensor (torch.Tensor): Stride tensor for anchors, shape (N_anchors, 1). + target_bboxes (torch.Tensor): Ground truth boxes in (x1, y1, x2, y2) format, shape (BS, N_anchors, 4). + pred_kpts (torch.Tensor): Predicted keypoints, shape (BS, N_anchors, N_kpts_per_object, kpts_dim). + + Returns: + kpts_loss (torch.Tensor): The keypoints loss. + kpts_obj_loss (torch.Tensor): The keypoints object loss. + """ + # Select target keypoints using helper method + selected_keypoints = self._select_target_keypoints(keypoints, batch_idx, target_gt_idx, masks) + + kpts_loss = 0 + kpts_obj_loss = 0 + + if masks.any(): + target_bboxes /= stride_tensor + gt_kpt = selected_keypoints[masks] + gt_kpt[..., :2] /= stride_tensor.view(1, -1).expand(masks.shape[0], -1)[masks][:, None, None] + area = xyxy2xywh(target_bboxes[masks])[:, 2:].prod(1, keepdim=True) + pred_kpt = pred_kpts[masks] + kpt_mask = gt_kpt[..., 2] != 0 if gt_kpt.shape[-1] == 3 else torch.full_like(gt_kpt[..., 0], True) + kpts_loss = self.keypoint_loss(pred_kpt, gt_kpt, kpt_mask, area) # pose loss + + if pred_kpt.shape[-1] == 3: + kpts_obj_loss = self.bce_pose(pred_kpt[..., 2], kpt_mask.float()) # keypoint obj loss + + return kpts_loss, kpts_obj_loss + + +class PoseLoss26(v8PoseLoss): + """Criterion class for computing training losses for YOLO26 pose estimation with RLE loss support.""" + + def __init__( + self, model: torch.nn.Module, tal_topk: int = 10, tal_topk2: int | None = None + ): # model must be de-paralleled + """Initialize PoseLoss26 with model parameters and keypoint-specific loss functions including RLE loss.""" + super().__init__(model, tal_topk, tal_topk2) + is_pose = self.kpt_shape == [17, 3] + nkpt = self.kpt_shape[0] # number of keypoints + self.rle_loss = None + self.flow_model = model.model[-1].flow_model if hasattr(model.model[-1], "flow_model") else None + if self.flow_model is not None: + self.rle_loss = RLELoss(use_target_weight=True).to(self.device) + self.loss_names += ("rle_loss",) + self.target_weights = ( + torch.from_numpy(RLE_WEIGHT).to(self.device) if is_pose else torch.ones(nkpt, device=self.device) + ) + + def loss( + self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor] + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Calculate the total loss and detach it for pose estimation.""" + pred_kpts = preds["kpts"].permute(0, 2, 1).contiguous() + loss = torch.zeros( + 6 if self.rle_loss else 5, device=self.device + ) # box, kpt_location, kpt_visibility, cls, dfl[, rle] + (fg_mask, target_gt_idx, target_bboxes, anchor_points, stride_tensor), det_loss, _ = ( + self.get_assigned_targets_and_loss(preds, batch) + ) + # NOTE: re-assign index for consistency for now. Need to be removed in the future. + loss[0], loss[3], loss[4] = det_loss[0], det_loss[1], det_loss[2] + + batch_size = pred_kpts.shape[0] + imgsz = torch.tensor(preds["feats"][0].shape[2:], device=self.device, dtype=pred_kpts.dtype) * self.stride[0] + + pred_kpts = pred_kpts.view(batch_size, -1, *self.kpt_shape) # (b, h*w, 17, 3) + + if self.rle_loss and preds.get("kpts_sigma", None) is not None: + pred_sigma = preds["kpts_sigma"].permute(0, 2, 1).contiguous() + pred_sigma = pred_sigma.view(batch_size, -1, self.kpt_shape[0], 2) # (b, h*w, 17, 2) + pred_kpts = torch.cat([pred_kpts, pred_sigma], dim=-1) # (b, h*w, 17, 5) + + pred_kpts = self.kpts_decode(anchor_points, pred_kpts) + + # Keypoint loss + if fg_mask.sum(): + keypoints = batch["keypoints"].to(self.device).float().clone() + keypoints[..., 0] *= imgsz[1] + keypoints[..., 1] *= imgsz[0] + + keypoints_loss = self.calculate_keypoints_loss( + fg_mask, + target_gt_idx, + keypoints, + batch["batch_idx"].view(-1, 1), + stride_tensor, + target_bboxes, + pred_kpts, + ) + loss[1] = keypoints_loss[0] + loss[2] = keypoints_loss[1] + if self.rle_loss is not None: + loss[5] = keypoints_loss[2] + # WARNING: lines below prevent Multi-GPU DDP 'unused gradient' PyTorch errors, do not remove + else: + loss[1] += pred_kpts[..., :0].sum() + if self.rle_loss is not None: + loss[5] += self._rle_zero(pred_kpts) + + loss[1] *= self.hyp.pose # pose gain + loss[2] *= self.hyp.kobj # kobj gain + if self.rle_loss is not None: + loss[5] *= self.hyp.rle # rle gain + + # loss(box, kpt_location, kpt_visibility, cls, dfl[, rle]) + return loss * batch_size, dict(zip(self.loss_names, loss.detach())) + + @staticmethod + def kpts_decode(anchor_points: torch.Tensor, pred_kpts: torch.Tensor) -> torch.Tensor: + """Decode predicted keypoints to image coordinates.""" + y = pred_kpts.clone() + y[..., 0] += anchor_points[:, [0]] + y[..., 1] += anchor_points[:, [1]] + return y + + def _rle_zero(self, pred_kpt: torch.Tensor) -> torch.Tensor: + """Return a zero RLE loss keeping `pred_kpt` and the flow model in the graph, for Multi-GPU DDP.""" + return pred_kpt[..., :0].sum() + sum(p[..., :0].sum() for p in self.flow_model.parameters()) + + def calculate_rle_loss(self, pred_kpt: torch.Tensor, gt_kpt: torch.Tensor, kpt_mask: torch.Tensor) -> torch.Tensor: + """Calculate the RLE (Residual Log-likelihood Estimation) loss for keypoints. + + Args: + pred_kpt (torch.Tensor): Predicted kpts with sigma, shape (N, num_keypoints, kpts_dim) where kpts_dim >= 4. + gt_kpt (torch.Tensor): Ground truth keypoints, shape (N, num_keypoints, kpts_dim). + kpt_mask (torch.Tensor): Mask for valid keypoints, shape (N, num_keypoints). + + Returns: + (torch.Tensor): The RLE loss. + """ + if not kpt_mask.any(): + return self._rle_zero(pred_kpt) + + pred_kpt_visible = pred_kpt[kpt_mask] + gt_kpt_visible = gt_kpt[kpt_mask] + pred_coords = pred_kpt_visible[:, 0:2] + pred_sigma = pred_kpt_visible[:, -2:] + gt_coords = gt_kpt_visible[:, 0:2] + + target_weights = self.target_weights.unsqueeze(0).repeat(kpt_mask.shape[0], 1) + target_weights = target_weights[kpt_mask] + + pred_sigma = pred_sigma.sigmoid() + error = (pred_coords - gt_coords) / (pred_sigma + 1e-9) + if not error.numel(): + return self._rle_zero(pred_kpt) + + # Filter out NaN and Inf values that would propagate into the loss + valid_mask = ~(torch.isnan(error) | torch.isinf(error)).any(dim=-1) + if not valid_mask.any(): + return self._rle_zero(pred_kpt) + + error = error[valid_mask] + error = error.clamp(-100, 100) # Prevent numerical instability + pred_sigma = pred_sigma[valid_mask] + target_weights = target_weights[valid_mask] + + log_phi = self.flow_model.log_prob(error) + + return self.rle_loss(pred_sigma, log_phi, error, target_weights) + + def calculate_keypoints_loss( + self, + masks: torch.Tensor, + target_gt_idx: torch.Tensor, + keypoints: torch.Tensor, + batch_idx: torch.Tensor, + stride_tensor: torch.Tensor, + target_bboxes: torch.Tensor, + pred_kpts: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Calculate the keypoints loss for the model. + + This function calculates the keypoints loss and keypoints object loss for a given batch. The keypoints loss is + based on the difference between the predicted keypoints and ground truth keypoints. The keypoints object loss is + a binary classification loss that classifies whether a keypoint is present or not. + + Args: + masks (torch.Tensor): Binary mask tensor indicating object presence, shape (BS, N_anchors). + target_gt_idx (torch.Tensor): Index tensor mapping anchors to ground truth objects, shape (BS, N_anchors). + keypoints (torch.Tensor): Ground truth keypoints, shape (N_kpts_in_batch, N_kpts_per_object, kpts_dim). + batch_idx (torch.Tensor): Batch index tensor for keypoints, shape (N_kpts_in_batch, 1). + stride_tensor (torch.Tensor): Stride tensor for anchors, shape (N_anchors, 1). + target_bboxes (torch.Tensor): Ground truth boxes in (x1, y1, x2, y2) format, shape (BS, N_anchors, 4). + pred_kpts (torch.Tensor): Predicted keypoints, shape (BS, N_anchors, N_kpts_per_object, kpts_dim). + + Returns: + kpts_loss (torch.Tensor): The keypoints loss. + kpts_obj_loss (torch.Tensor): The keypoints object loss. + rle_loss (torch.Tensor): The RLE loss. + """ + # Select target keypoints using inherited helper method + selected_keypoints = self._select_target_keypoints(keypoints, batch_idx, target_gt_idx, masks) + + kpts_loss = 0 + kpts_obj_loss = 0 + rle_loss = 0 + + if masks.any(): + target_bboxes /= stride_tensor + gt_kpt = selected_keypoints[masks] + gt_kpt[..., :2] /= stride_tensor.view(1, -1).expand(masks.shape[0], -1)[masks][:, None, None] + area = xyxy2xywh(target_bboxes[masks])[:, 2:].prod(1, keepdim=True) + pred_kpt = pred_kpts[masks] + kpt_mask = gt_kpt[..., 2] != 0 if gt_kpt.shape[-1] == 3 else torch.full_like(gt_kpt[..., 0], True) + kpts_loss = self.keypoint_loss(pred_kpt, gt_kpt, kpt_mask, area) # pose loss + + if self.rle_loss is not None and (pred_kpt.shape[-1] == 4 or pred_kpt.shape[-1] == 5): + rle_loss = self.calculate_rle_loss(pred_kpt, gt_kpt, kpt_mask) + rle_loss = rle_loss.clamp(min=0) + if pred_kpt.shape[-1] == 3 or pred_kpt.shape[-1] == 5: + kpts_obj_loss = self.bce_pose(pred_kpt[..., 2], kpt_mask.float()) # keypoint obj loss + + return kpts_loss, kpts_obj_loss, rle_loss + + +class v8ClassificationLoss: + """Criterion class for computing training losses for classification.""" + + def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Compute the classification loss between predictions and true labels.""" + preds = preds[1] if isinstance(preds, (list, tuple)) else preds + loss = F.cross_entropy(preds, batch["cls"], reduction="mean") + return loss, {"loss": loss.detach()} + + +class v8OBBLoss(v8DetectionLoss): + """Calculates losses for object detection, classification, and box distribution in rotated YOLO models.""" + + def __init__(self, model: torch.nn.Module, tal_topk=10, tal_topk2: int | None = None): + """Initialize v8OBBLoss with model, assigner, and rotated bbox loss; model must be de-paralleled.""" + super().__init__(model, tal_topk=tal_topk) + self.loss_names = (*self.loss_names, "angle_loss") + self.assigner = RotatedTaskAlignedAssigner( + topk=tal_topk, + num_classes=self.nc, + alpha=0.5, + beta=6.0, + stride=self.stride.tolist(), + topk2=tal_topk2, + ) + self.bbox_loss = RotatedBboxLoss(self.reg_max).to(self.device) + + def preprocess(self, targets: torch.Tensor, batch_size: int, scale_tensor: torch.Tensor) -> torch.Tensor: + """Preprocess targets for oriented bounding box detection.""" + if targets.shape[0] == 0: + out = torch.zeros(batch_size, 0, 6, device=self.device) + else: + batch_idx = targets[:, 0].long() # image index + _, counts = batch_idx.unique(return_counts=True) + counts = counts.to(dtype=torch.int32) + out = torch.zeros(batch_size, counts.max(), 6, device=self.device) + packed_targets = targets[:, 1:].clone() + packed_targets[:, 1:5].mul_(scale_tensor) + offsets = torch.zeros(batch_size + 1, dtype=torch.long, device=self.device) + offsets.scatter_add_(0, batch_idx + 1, torch.ones_like(batch_idx)) + offsets = offsets.cumsum(0) + within_idx = torch.arange(len(targets), device=self.device) - offsets[batch_idx] + out[batch_idx, within_idx] = packed_targets + return out + + def loss( + self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor] + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Calculate and return the loss for oriented bounding box detection.""" + loss = torch.zeros(4, device=self.device) # box, cls, dfl, angle + pred_distri, pred_scores, pred_angle = ( + preds["boxes"].permute(0, 2, 1).contiguous(), + preds["scores"].permute(0, 2, 1).contiguous(), + preds["angle"].permute(0, 2, 1).contiguous(), + ) + anchor_points, stride_tensor = make_anchors(preds["feats"], self.stride, 0.5) + batch_size = pred_angle.shape[0] # batch size + + dtype = pred_scores.dtype + imgsz = torch.tensor(preds["feats"][0].shape[2:], device=self.device, dtype=dtype) * self.stride[0] + + # targets + try: + batch_idx = batch["batch_idx"].view(-1, 1) + targets = torch.cat((batch_idx, batch["cls"].view(-1, 1), batch["bboxes"].view(-1, 5)), 1) + rw, rh = targets[:, 4] * float(imgsz[1]), targets[:, 5] * float(imgsz[0]) + targets = targets[(rw >= 2) & (rh >= 2)] # filter rboxes of tiny size to stabilize training + targets = self.preprocess(targets.to(self.device), batch_size, scale_tensor=imgsz[[1, 0, 1, 0]]) + gt_labels, gt_bboxes = targets.split((1, 5), 2) # cls, xywhr + mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0.0) + except RuntimeError as e: + raise TypeError( + "ERROR ❌ OBB dataset incorrectly formatted or not a OBB dataset.\n" + "This error can occur when incorrectly training a 'OBB' model on a 'detect' dataset, " + "i.e. 'yolo train model=yolo26n-obb.pt data=dota8.yaml'.\nVerify your dataset is a " + "correctly formatted 'OBB' dataset using 'data=dota8.yaml' " + "as an example.\nSee https://docs.ultralytics.com/datasets/obb for help." + ) from e + + # Pboxes + pred_bboxes = self.bbox_decode(anchor_points, pred_distri, pred_angle) # xywhr, (b, h*w, 5) + + bboxes_for_assigner = pred_bboxes.clone().detach() + # Only the first four elements need to be scaled + bboxes_for_assigner[..., :4] *= stride_tensor + _, target_bboxes, target_scores, fg_mask, _ = self.assigner( + pred_scores.detach().sigmoid(), + bboxes_for_assigner.type(gt_bboxes.dtype), + anchor_points * stride_tensor, + gt_labels, + gt_bboxes, + mask_gt, + ) + + target_scores_sum = max(target_scores.sum(), 1) + + # Cls loss + # loss[1] = self.varifocal_loss(pred_scores, target_scores, target_labels) / target_scores_sum # VFL way + bce_loss = self.bce(pred_scores, target_scores.to(dtype)) # BCE + if self.class_weights is not None: + bce_loss *= self.class_weights + loss[1] = bce_loss.sum() / target_scores_sum + + # Bbox loss + if fg_mask.sum(): + target_bboxes[..., :4] /= stride_tensor + loss[0], loss[2] = self.bbox_loss( + pred_distri, + pred_bboxes, + anchor_points, + target_bboxes, + target_scores, + target_scores_sum, + fg_mask, + imgsz, + stride_tensor, + ) + weight = target_scores[fg_mask].sum(-1) + loss[3] = self.calculate_angle_loss( + pred_bboxes, target_bboxes, fg_mask, weight, target_scores_sum + ) # angle loss + else: + loss[0] += (pred_angle * 0).sum() + pred_distri[..., :0].sum() + + loss[0] *= self.hyp.box # box gain + loss[1] *= self.hyp.cls # cls gain + loss[2] *= self.hyp.dfl # dfl gain + loss[3] *= self.hyp.angle # angle gain + + return loss * batch_size, dict(zip(self.loss_names, loss.detach())) # loss(box, cls, dfl, angle) + + def bbox_decode( + self, anchor_points: torch.Tensor, pred_dist: torch.Tensor, pred_angle: torch.Tensor + ) -> torch.Tensor: + """Decode predicted object bounding box coordinates from anchor points and distribution. + + Args: + anchor_points (torch.Tensor): Anchor points, (h*w, 2). + pred_dist (torch.Tensor): Predicted rotated distance, (bs, h*w, 4). + pred_angle (torch.Tensor): Predicted angle, (bs, h*w, 1). + + Returns: + (torch.Tensor): Predicted rotated bounding boxes with angles, (bs, h*w, 5). + """ + if self.use_dfl: + b, a, c = pred_dist.shape # batch, anchors, channels + pred_dist = pred_dist.view(b, a, 4, c // 4).softmax(3).matmul(self.proj.type(pred_dist.dtype)) + return torch.cat((dist2rbox(pred_dist, pred_angle, anchor_points), pred_angle), dim=-1) + + def calculate_angle_loss(self, pred_bboxes, target_bboxes, fg_mask, weight, target_scores_sum, lambda_val=3): + """Calculate oriented angle loss. + + Args: + pred_bboxes (torch.Tensor): Predicted bounding boxes with shape [N, 5] (x, y, w, h, theta). + target_bboxes (torch.Tensor): Target bounding boxes with shape [N, 5] (x, y, w, h, theta). + fg_mask (torch.Tensor): Foreground mask indicating valid predictions. + weight (torch.Tensor): Loss weights for each prediction. + target_scores_sum (torch.Tensor): Sum of target scores for normalization. + lambda_val (int): Controls the sensitivity to aspect ratio. + + Returns: + (torch.Tensor): The calculated angle loss. + """ + w_gt = target_bboxes[..., 2] + h_gt = target_bboxes[..., 3] + pred_theta = pred_bboxes[..., 4] + target_theta = target_bboxes[..., 4] + + log_ar = torch.log((w_gt + 1e-9) / (h_gt + 1e-9)) + scale_weight = torch.exp(-(log_ar**2) / (lambda_val**2)) + + delta_theta = pred_theta - target_theta + delta_theta_wrapped = delta_theta - torch.round(delta_theta / math.pi) * math.pi + ang_loss = torch.sin(2 * delta_theta_wrapped[fg_mask]) ** 2 + + ang_loss = scale_weight[fg_mask] * ang_loss + ang_loss = ang_loss * weight + + return ang_loss.sum() / target_scores_sum + + +class DepthLoss26: + """Criterion class for computing training losses for YOLO depth estimation. + + Uses scale-invariant log loss (SILog) + gradient-matching loss, following the Depth Anything approach. SILog handles + scale ambiguity while gradient loss preserves edges. + """ + + def __init__(self, model: torch.nn.Module): + """Initialize DepthLoss26.""" + device = next(model.parameters()).device + self.device = device + h = model.args # hyperparameters + self.silog_weight = h.dlog + self.grad_weight = h.dgrad + self.silog_lambda = h.dlam # 1.0 = scale-invariant, 0.0 = log-RMSE + self.grad_scales = 4 + self.loss_names = "dlog_loss", "dgrad_loss" + + @staticmethod + def _grad_l1(pred_log: torch.Tensor, gt_log: torch.Tensor, valid_f: torch.Tensor) -> torch.Tensor: + """L1 between predicted and GT log-depth spatial gradients (dx, dy), gated by the valid mask. + + Each gradient is zeroed unless both contributing pixels are valid, so edges are only + matched where GT is defined. + """ + pred_dx = (pred_log[:, :, :, 1:] - pred_log[:, :, :, :-1]) * valid_f[:, :, :, 1:] * valid_f[:, :, :, :-1] + gt_dx = (gt_log[:, :, :, 1:] - gt_log[:, :, :, :-1]) * valid_f[:, :, :, 1:] * valid_f[:, :, :, :-1] + pred_dy = (pred_log[:, :, 1:, :] - pred_log[:, :, :-1, :]) * valid_f[:, :, 1:, :] * valid_f[:, :, :-1, :] + gt_dy = (gt_log[:, :, 1:, :] - gt_log[:, :, :-1, :]) * valid_f[:, :, 1:, :] * valid_f[:, :, :-1, :] + return F.l1_loss(pred_dx, gt_dx) + F.l1_loss(pred_dy, gt_dy) + + def __call__( + self, preds: dict[str, torch.Tensor] | torch.Tensor, batch: dict[str, torch.Tensor] + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Calculate depth estimation loss. + + Args: + preds (dict | torch.Tensor): Dict with "depth" key or raw tensor of (B, 1, H, W) predicted depth. + batch (dict): Dict with "depth" key holding (B, H, W) ground truth depth in meters. + + Returns: + loss_sum (torch.Tensor): Total loss scaled by batch size. + loss_items (dict[str, torch.Tensor]): Detached silog/gradient losses keyed by loss_names. + """ + loss = torch.zeros(2, device=self.device) + pred_depth = preds["depth"] if isinstance(preds, dict) else preds + gt_depth = batch["depth"].to(self.device) + + if gt_depth.ndim == 3: + gt_depth = gt_depth.unsqueeze(1) + + if gt_depth.shape[-2:] != pred_depth.shape[-2:]: + pred_depth = F.interpolate(pred_depth, size=gt_depth.shape[-2:], mode="bilinear", align_corners=True) + + valid = gt_depth > 0.001 + if valid.sum() < 10: + # Keep the result attached so BaseTrainer's unconditional backward() works. + return pred_depth.sum() * 0.0, dict(zip(self.loss_names, loss.detach())) + + pred_valid = pred_depth[valid] + gt_valid = gt_depth[valid] + + pred_valid = pred_valid.clamp(min=0.001) + + log_diff = torch.log(pred_valid) - torch.log(gt_valid) + # Centered variance form: non-negative by construction and fp16-stable near convergence. + m = log_diff.mean() + silog = torch.sqrt(((log_diff - m) ** 2).mean() + (1.0 - self.silog_lambda) * m**2 + 1e-6) + loss[0] = silog * self.silog_weight + + # Multi-scale gradient-matching loss. + pred_log = torch.log(pred_depth.clamp(min=0.001)) + gt_log = torch.log(gt_depth.clamp(min=0.001)) + valid_f = valid.float() + grad_loss = self._grad_l1(pred_log, gt_log, valid_f) + for _ in range(1, max(self.grad_scales, 1)): + if pred_log.shape[-1] < 4 or pred_log.shape[-2] < 4: + break + vp = F.avg_pool2d(valid_f, 2) + occupied = vp > 0 + # Continue per image while its occupied cells are mostly full: contiguous padding is, LiDAR scatter is not + keep = (vp.sum(dim=(1, 2, 3)) > 0.7 * occupied.sum(dim=(1, 2, 3))).view(-1, 1, 1, 1) + if not keep.any(): + break + denom = vp.clamp(min=1e-6) + pred_log = F.avg_pool2d(pred_log * valid_f, 2) / denom + gt_log = F.avg_pool2d(gt_log * valid_f, 2) / denom + valid_f = occupied.float() * keep # zeroed images cannot re-enter deeper levels + grad_loss = grad_loss + self._grad_l1(pred_log, gt_log, valid_f) + loss[1] = grad_loss * self.grad_weight + + return loss * pred_depth.shape[0], dict(zip(self.loss_names, loss.detach())) + + +class E2EDetectLoss: + """Criterion class for computing training losses for end-to-end detection.""" + + def __init__(self, model: torch.nn.Module): + """Initialize E2EDetectLoss with one-to-many and one-to-one detection losses using the provided model.""" + self.one2many = v8DetectionLoss(model, tal_topk=10) + self.one2one = v8DetectionLoss(model, tal_topk=1) + + def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Calculate the sum of the loss for box, cls and dfl multiplied by batch size.""" + preds = preds[1] if isinstance(preds, tuple) else preds + one2many = preds["one2many"] + loss_one2many = self.one2many(one2many, batch) + one2one = preds["one2one"] + loss_one2one = self.one2one(one2one, batch) + return loss_one2many[0] + loss_one2one[0], { + k: loss_one2many[1][k] + loss_one2one[1][k] for k in loss_one2many[1] + } + + +class E2ELoss: + """Criterion class for computing training losses for end-to-end detection.""" + + def __init__(self, model: torch.nn.Module, loss_fn=v8DetectionLoss): + """Initialize E2ELoss with one-to-many and one-to-one detection losses using the provided model.""" + self.one2many = loss_fn(model, tal_topk=10) + self.one2one = loss_fn(model, tal_topk=7, tal_topk2=1) + self.updates = 0 + self.total = 1.0 + # init gain + self.o2m = 0.8 + self.o2o = self.total - self.o2m + self.o2m_copy = self.o2m + # final gain + self.final_o2m = 0.1 + + def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Calculate the sum of the loss for box, cls and dfl multiplied by batch size.""" + preds = self.one2many.parse_output(preds) + one2many, one2one = preds["one2many"], preds["one2one"] + loss_one2many = self.one2many.loss(one2many, batch) + loss_one2one = self.one2one.loss(one2one, batch) + return loss_one2many[0] * self.o2m + loss_one2one[0] * self.o2o, loss_one2one[1] + + def update(self) -> None: + """Update the weights for one-to-many and one-to-one losses based on the decay schedule.""" + self.updates += 1 + self.o2m = self.decay(self.updates) + self.o2o = max(self.total - self.o2m, 0) + + def decay(self, x) -> float: + """Calculate the decayed weight for one-to-many loss based on the current update step.""" + return max(1 - x / max(self.one2one.hyp.epochs - 1, 1), 0) * (self.o2m_copy - self.final_o2m) + self.final_o2m + + +class TVPDetectLoss: + """Criterion class for computing training losses for text-visual prompt detection.""" + + def __init__(self, model: torch.nn.Module, tal_topk=10, tal_topk2: int | None = None): + """Initialize TVPDetectLoss with task-prompt and visual-prompt criteria using the provided model.""" + self.vp_criterion = v8DetectionLoss(model, tal_topk, tal_topk2) + self.loss_names = tuple(k[:-5] for k in self.vp_criterion.loss_names) # strip "_loss" suffix + # NOTE: store following info as it's changeable in __call__ + self.hyp = self.vp_criterion.hyp + self.ori_nc = self.vp_criterion.nc + self.ori_no = self.vp_criterion.no + self.ori_reg_max = self.vp_criterion.reg_max + + def parse_output(self, preds) -> dict[str, torch.Tensor]: + """Parse model predictions to extract features.""" + return self.vp_criterion.parse_output(preds) + + def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Calculate the loss for text-visual prompt detection.""" + return self.loss(self.parse_output(preds), batch) + + def loss( + self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor] + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Calculate the loss for text-visual prompt detection.""" + if self.ori_nc == preds["scores"].shape[1]: + loss = torch.zeros(3, device=self.vp_criterion.device, requires_grad=True) + return loss, dict(zip(self.loss_names, loss.detach())) + + preds["scores"] = self._get_vp_features(preds) + vp_loss = self.vp_criterion(preds, batch) + return vp_loss[0][1], dict(zip(self.loss_names, vp_loss[1].values())) + + def _get_vp_features(self, preds: dict[str, torch.Tensor]) -> list[torch.Tensor]: + """Extract visual-prompt features from the model output.""" + scores = preds["scores"] + vnc = scores.shape[1] + + self.vp_criterion.nc = vnc + self.vp_criterion.no = vnc + self.vp_criterion.reg_max * 4 + self.vp_criterion.assigner.num_classes = vnc + return scores + + +class TVPSegmentLoss(TVPDetectLoss): + """Criterion class for computing training losses for text-visual prompt segmentation.""" + + def __init__(self, model: torch.nn.Module, tal_topk=10, tal_topk2: int | None = None): + """Initialize TVPSegmentLoss with task-prompt and visual-prompt criteria using the provided model.""" + super().__init__(model) + self.vp_criterion = v8SegmentationLoss(model, tal_topk, tal_topk2) + self.loss_names = tuple(k[:-5] for k in self.vp_criterion.loss_names if k != "sem_loss") # strip "_loss" + self.hyp = self.vp_criterion.hyp + + def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Calculate the loss for text-visual prompt segmentation.""" + return self.loss(self.parse_output(preds), batch) + + def loss(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Calculate the loss for text-visual prompt segmentation.""" + if self.ori_nc == preds["scores"].shape[1]: + loss = torch.zeros(4, device=self.vp_criterion.device, requires_grad=True) + return loss, dict(zip(self.loss_names, loss.detach())) + + preds["scores"] = self._get_vp_features(preds) + vp_loss = self.vp_criterion(preds, batch) + cls_loss = vp_loss[0][2] + # zip drops the trailing "sem_loss" item to match the logged columns + return cls_loss, dict(zip(self.loss_names, vp_loss[1].values())) + + +class SemanticSegmentationLoss(nn.Module): + """Loss function for semantic segmentation using cross-entropy and Dice terms. + + Attributes: + nc (int): Number of semantic classes. + ce (nn.CrossEntropyLoss): Cross-entropy loss with ignore_index=255. + """ + + def __init__(self, model: torch.nn.Module): + """Initialize semantic segmentation loss. + + Args: + model (torch.nn.Module): Model containing the SemanticSegment head. + """ + super().__init__() + m = model.model[-1] + self.nc = m.nc + self.device = next(model.parameters()).device + self.dtype = next(model.parameters()).dtype + data_name = Path(str(getattr(model.args, "data", "") or "")).stem.lower() + self.use_cityscapes_weight = data_name in {"cityscapes", "cityscapes8"} and self.nc == len(CITYSCAPES_WEIGHT) + weight = getattr(model, "class_weights", None) # cls_pw frequency weights, else hardcoded Cityscapes + if weight is None and self.use_cityscapes_weight: + weight = torch.from_numpy(CITYSCAPES_WEIGHT) + weight = None if weight is None else weight.to(device=self.device, dtype=self.dtype) + if self.nc == 1: + self.ce = nn.BCEWithLogitsLoss(reduction="sum") # binary: class weighting intentionally unsupported + else: + self.ce = nn.CrossEntropyLoss(ignore_index=255, reduction="sum").to(device=self.device, dtype=self.dtype) + if weight is not None: + # Non-persistent: weight is a deterministic constant, no need to serialize into ckpt state_dict. + self.ce.register_buffer("weight", weight, persistent=False) + + def _resize_masks(self, masks, target_shape): + """Resize masks to match prediction spatial dimensions.""" + if masks.shape[1:] != target_shape: + return ( + F.interpolate(masks.float().unsqueeze(1), size=target_shape, mode="nearest").squeeze(1).to(torch.int32) + ) + return masks + + def _ce_loss(self, preds, masks, valid): + """Compute cross-entropy on flattened pixels to avoid the CUDA nll_loss2d path.""" + flat = masks.reshape(-1) + if self.nc == 1: + logits = preds.reshape(-1)[valid] + target = flat[valid].float() + denominator = valid.sum() + else: + logits = preds.permute(0, 2, 3, 1).reshape(-1, self.nc) + target = flat.long() + denominator = valid.sum() if self.ce.weight is None else self.ce.weight[target[valid]].sum() + return self.ce(logits, target) / denominator.clamp_min(1) + + def _dice_loss(self, preds, masks, valid): + """Compute Dice loss excluding ignore pixels.""" + if self.nc == 1: + return self._binary_dice_loss(preds, masks, valid) + flat_target = masks.reshape(-1) + pred_soft = F.softmax(preds, dim=1) + target = flat_target[valid].long() + flat_pred = pred_soft.float().permute(0, 2, 3, 1).reshape(-1, self.nc)[valid] + intersection = torch.zeros(self.nc, device=preds.device, dtype=torch.float32) + intersection.scatter_add_(0, target, flat_pred.gather(1, target[:, None]).squeeze(1)) + pred_sum = flat_pred.sum(dim=0) + target_sum = torch.zeros_like(intersection).scatter_add_( + 0, target, torch.ones_like(target, dtype=torch.float32) + ) + cardinality = pred_sum + target_sum + return (1.0 - (2.0 * intersection + 1.0) / (cardinality + 1.0)).mean() + + def _binary_dice_loss(self, preds, masks, valid): + """Compute Dice loss for single-class (binary) segmentation. + + Pixels with value 255 are excluded from Dice terms to match BCE valid-pixel filtering. + """ + valid = valid.reshape_as(masks).float() + pred_soft = preds.squeeze(1).sigmoid() + target = (masks == 1).float() + intersection = (pred_soft * target * valid).sum() + cardinality = ((pred_soft + target) * valid).sum() + return 1.0 - (2.0 * intersection + 1.0) / (cardinality + 1.0) + + def forward(self, preds, batch): + """Compute semantic segmentation loss with optional auxiliary loss. + + Args: + preds (torch.Tensor | tuple): Main logits [B, nc, H', W'], or (main, aux) tuple. + batch (dict): Batch dict with 'semantic_mask' [B, H, W] containing class IDs (255=ignore). + + Returns: + (tuple[torch.Tensor, dict[str, torch.Tensor]]): Total loss * batch_size and a dict of detached loss items + (ce_loss, dice_loss, aux_loss). + """ + # Unpack auxiliary logits when present. + aux_logits = None + if isinstance(preds, tuple): + preds, aux_logits = preds + + masks = batch["semantic_mask"].to(preds.device) + valid = masks.reshape(-1) != 255 + if preds.shape[2:] != masks.shape[1:]: + preds = F.interpolate(preds, size=masks.shape[1:], mode="bilinear", align_corners=False) + + # Main cross-entropy and Dice loss. + ce_loss = self._ce_loss(preds, masks, valid) + dice_loss = self._dice_loss(preds, masks, valid) + total = ce_loss + dice_loss + + # Auxiliary cross-entropy loss. Match ce_loss dtype so adding to total succeeds under AMP. + aux_loss = torch.tensor(0.0, device=preds.device, dtype=ce_loss.dtype) + if aux_logits is not None: + if aux_logits.shape[2:] != masks.shape[1:]: + aux_logits = F.interpolate(aux_logits, size=masks.shape[1:], mode="bilinear", align_corners=False) + aux_loss = self._ce_loss(aux_logits, masks, valid) * 0.4 + total += aux_loss + + loss_items = {"ce_loss": ce_loss.detach(), "dice_loss": dice_loss.detach(), "aux_loss": aux_loss.detach()} + return total * preds.shape[0], loss_items diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/metrics.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..6b6ec78664efb1995d6f45de4a1a3840e7aee868 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/metrics.py @@ -0,0 +1,2069 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Model validation metrics.""" + +from __future__ import annotations + +import math +import warnings +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from ultralytics.utils import LOGGER, DataExportMixin, SimpleClass, TryExcept, checks, plt_settings +from ultralytics.utils.plotting import colors + +OKS_SIGMA = ( + np.array( + [0.26, 0.25, 0.25, 0.35, 0.35, 0.79, 0.79, 0.72, 0.72, 0.62, 0.62, 1.07, 1.07, 0.87, 0.87, 0.89, 0.89], + dtype=np.float32, + ) + / 10.0 +) +RLE_WEIGHT = np.array( + [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.2, 1.2, 1.5, 1.5, 1.0, 1.0, 1.2, 1.2, 1.5, 1.5], dtype=np.float32 +) +CITYSCAPES_WEIGHT = np.array( + [ + 0.8373, + 0.918, + 0.866, + 1.0345, + 1.0166, + 0.9969, + 0.9754, + 1.0489, + 0.8786, + 1.0023, + 0.9539, + 0.9843, + 1.1116, + 0.9037, + 1.0865, + 1.0955, + 1.0865, + 1.1529, + 1.0507, + ] +) + + +def bbox_ioa(box1: np.ndarray, box2: np.ndarray, iou: bool = False, eps: float = 1e-7) -> np.ndarray: + """Calculate the intersection over box2 area given box1 and box2. + + Args: + box1 (np.ndarray): A numpy array of shape (N, 4) representing N bounding boxes in x1y1x2y2 format. + box2 (np.ndarray): A numpy array of shape (M, 4) representing M bounding boxes in x1y1x2y2 format. + iou (bool, optional): Calculate the standard IoU if True else return inter_area/box2_area. + eps (float, optional): A small value to avoid division by zero. + + Returns: + (np.ndarray): A numpy array of shape (N, M) representing the intersection over box2 area. + """ + # Get the coordinates of bounding boxes + b1_x1, b1_y1, b1_x2, b1_y2 = box1.T + b2_x1, b2_y1, b2_x2, b2_y2 = box2.T + + # Intersection area + inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * ( + np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1) + ).clip(0) + + # Box2 area + area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + if iou: + box1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1) + area = area + box1_area[:, None] - inter_area + + # Intersection over box2 area + return inter_area / (area + eps) + + +def box_iou(box1: torch.Tensor, box2: torch.Tensor, eps: float = 1e-7) -> torch.Tensor: + """Calculate intersection-over-union (IoU) of boxes. + + Args: + box1 (torch.Tensor): A tensor of shape (N, 4) representing N bounding boxes in (x1, y1, x2, y2) format. + box2 (torch.Tensor): A tensor of shape (M, 4) representing M bounding boxes in (x1, y1, x2, y2) format. + eps (float, optional): A small value to avoid division by zero. + + Returns: + (torch.Tensor): An NxM tensor containing the pairwise IoU values for every element in box1 and box2. + + References: + https://github.com/pytorch/vision/blob/main/torchvision/ops/boxes.py + """ + # NOTE: Need .float() to get accurate iou values + (a1, a2), (b1, b2) = box1.float().unsqueeze(1).chunk(2, 2), box2.float().unsqueeze(0).chunk(2, 2) + wh, wh1, wh2 = (torch.min(a2, b2) - torch.max(a1, b1)).clamp_(0), a2 - a1, b2 - b1 + inter = wh[..., 0] * wh[..., 1] # slice products, not prod(2): MPS compiles a reduction graph per input shape + + # IoU = inter / (area1 + area2 - inter) + return inter / (wh1[..., 0] * wh1[..., 1] + wh2[..., 0] * wh2[..., 1] - inter + eps) + + +def bbox_iou( + box1: torch.Tensor, + box2: torch.Tensor, + xywh: bool = True, + GIoU: bool = False, + DIoU: bool = False, + CIoU: bool = False, + eps: float = 1e-7, +) -> torch.Tensor: + """Calculate the Intersection over Union (IoU) between bounding boxes. + + This function supports various shapes for `box1` and `box2` as long as the last dimension is 4. For instance, you + may pass tensors shaped like (4,), (N, 4), (B, N, 4), or (B, N, 1, 4). Internally, the code will split the last + dimension into (x, y, w, h) if `xywh=True`, or (x1, y1, x2, y2) if `xywh=False`. + + Args: + box1 (torch.Tensor): A tensor representing one or more bounding boxes, with the last dimension being 4. + box2 (torch.Tensor): A tensor representing one or more bounding boxes, with the last dimension being 4. + xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in (x1, y1, + x2, y2) format. + GIoU (bool, optional): If True, calculate Generalized IoU. + DIoU (bool, optional): If True, calculate Distance IoU. + CIoU (bool, optional): If True, calculate Complete IoU. + eps (float, optional): A small value to avoid division by zero. + + Returns: + (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags. + """ + # Get the coordinates of bounding boxes + if xywh: # transform from xywh to xyxy + (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1) + w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2 + b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_ + b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_ + else: # x1, y1, x2, y2 = box1 + b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1) + b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1) + w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps + w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps + + # Intersection area + inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * ( + b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1) + ).clamp_(0) + + # Union Area + union = w1 * h1 + w2 * h2 - inter + eps + + # IoU + iou = inter / union + if CIoU or DIoU or GIoU: + cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width + ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height + if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 + c2 = cw.pow(2) + ch.pow(2) + eps # convex diagonal squared + rho2 = ( + (b2_x1 + b2_x2 - b1_x1 - b1_x2).pow(2) + (b2_y1 + b2_y2 - b1_y1 - b1_y2).pow(2) + ) / 4 # center dist**2 + if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 + v = (4 / math.pi**2) * ((w2 / h2).atan() - (w1 / h1).atan()).pow(2) + with torch.no_grad(): + alpha = v / (1 - iou + v + eps) + return iou - (rho2 / c2 + v * alpha) # CIoU + return iou - rho2 / c2 # DIoU + c_area = cw * ch + eps # convex area + return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf + return iou # IoU + + +def mask_iou(mask1: torch.Tensor, mask2: torch.Tensor, eps: float = 1e-7) -> torch.Tensor: + """Calculate masks IoU. + + Args: + mask1 (torch.Tensor): A tensor of shape (N, n) where N is the number of ground truth objects and n is the + product of image width and height. + mask2 (torch.Tensor): A tensor of shape (M, n) where M is the number of predicted objects and n is the product + of image width and height. + eps (float, optional): A small value to avoid division by zero. + + Returns: + (torch.Tensor): A tensor of shape (N, M) representing masks IoU. + """ + intersection = torch.matmul(mask1, mask2.T).clamp_(0) + union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection # (area1 + area2) - intersection + return intersection / (union + eps) + + +def kpt_iou( + kpt1: torch.Tensor, kpt2: torch.Tensor, area: torch.Tensor, sigma: list[float], eps: float = 1e-7 +) -> torch.Tensor: + """Calculate Object Keypoint Similarity (OKS). + + Args: + kpt1 (torch.Tensor): A tensor of shape (N, 17, 3) representing ground truth keypoints. + kpt2 (torch.Tensor): A tensor of shape (M, 17, 3) representing predicted keypoints. + area (torch.Tensor): A tensor of shape (N,) representing areas from ground truth. + sigma (list[float]): A list containing 17 values representing keypoint scales. + eps (float, optional): A small value to avoid division by zero. + + Returns: + (torch.Tensor): A tensor of shape (N, M) representing keypoint similarities. + """ + d = (kpt1[:, None, :, 0] - kpt2[..., 0]).pow(2) + (kpt1[:, None, :, 1] - kpt2[..., 1]).pow(2) # (N, M, 17) + sigma = torch.tensor(sigma, device=kpt1.device, dtype=kpt1.dtype) # (17, ) + kpt_mask = kpt1[..., 2] != 0 # (N, 17) + e = d / ((2 * sigma).pow(2) * (area[:, None, None] + eps) * 2) # from cocoeval + # e = d / ((area[None, :, None] + eps) * sigma) ** 2 / 2 # from formula + return ((-e).exp() * kpt_mask[:, None]).sum(-1) / (kpt_mask.sum(-1)[:, None] + eps) + + +def _get_covariance_matrix(boxes: torch.Tensor, floor: float = 0.0) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Generate covariance matrix from oriented bounding boxes. + + Args: + boxes (torch.Tensor): A tensor of shape (N, 5) representing rotated bounding boxes, with xywhr format. + floor (float, optional): Small value added to width/height to bound gradients for sub-stride boxes. + + Returns: + (tuple[torch.Tensor, torch.Tensor, torch.Tensor]): Covariance matrix components (a, b, c) where the covariance + matrix is [[a, c], [c, b]], each of shape (N, 1). + """ + # Gaussian bounding boxes, ignore the center points (the first two columns) because they are not needed here. + gbbs = torch.cat((boxes[:, 2:4].pow(2) / 12 + floor, boxes[:, 4:]), dim=-1) + a, b, c = gbbs.split(1, dim=-1) + cos = c.cos() + sin = c.sin() + cos2 = cos.pow(2) + sin2 = sin.pow(2) + return a * cos2 + b * sin2, a * sin2 + b * cos2, (a - b) * cos * sin + + +def probiou( + obb1: torch.Tensor, obb2: torch.Tensor, CIoU: bool = False, eps: float = 1e-7, floor: float = 0.0 +) -> torch.Tensor: + """Calculate probabilistic IoU between oriented bounding boxes. + + Args: + obb1 (torch.Tensor): Ground truth OBBs, shape (N, 5), format xywhr. + obb2 (torch.Tensor): Predicted OBBs, shape (N, 5), format xywhr. + CIoU (bool, optional): If True, calculate CIoU. + eps (float, optional): Small value to avoid division by zero. + floor (float, optional): Small value passed to `_get_covariance_matrix` to bound gradients for sub-stride boxes. + + Returns: + (torch.Tensor): OBB similarities, shape (N,). + + Notes: + OBB format: [center_x, center_y, width, height, rotation_angle]. + + References: + https://arxiv.org/pdf/2106.06072v1.pdf + """ + x1, y1 = obb1[..., :2].split(1, dim=-1) + x2, y2 = obb2[..., :2].split(1, dim=-1) + a1, b1, c1 = _get_covariance_matrix(obb1, floor) + a2, b2, c2 = _get_covariance_matrix(obb2, floor) + + t1 = ( + ((a1 + a2) * (y1 - y2).pow(2) + (b1 + b2) * (x1 - x2).pow(2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps) + ) * 0.25 + t2 = (((c1 + c2) * (x2 - x1) * (y1 - y2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)) * 0.5 + t3 = ( + ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2)) + / (4 * ((a1 * b1 - c1.pow(2)).clamp_(0) * (a2 * b2 - c2.pow(2)).clamp_(0)).sqrt() + eps) + + eps + ).log() * 0.5 + bd = (t1 + t2 + t3).clamp(eps, 100.0) + hd = (1.0 - (-bd).exp() + eps).sqrt() + iou = 1 - hd + if CIoU: # only include the wh aspect ratio part + w1, h1 = obb1[..., 2:4].split(1, dim=-1) + w2, h2 = obb2[..., 2:4].split(1, dim=-1) + v = (4 / math.pi**2) * ((w2 / h2).atan() - (w1 / h1).atan()).pow(2) + with torch.no_grad(): + alpha = v / (v - iou + (1 + eps)) + return iou - v * alpha # CIoU + return iou + + +def batch_probiou(obb1: torch.Tensor | np.ndarray, obb2: torch.Tensor | np.ndarray, eps: float = 1e-7) -> torch.Tensor: + """Calculate the probabilistic IoU between oriented bounding boxes. + + Args: + obb1 (torch.Tensor | np.ndarray): A tensor of shape (N, 5) representing ground truth obbs, with xywhr format. + obb2 (torch.Tensor | np.ndarray): A tensor of shape (M, 5) representing predicted obbs, with xywhr format. + eps (float, optional): A small value to avoid division by zero. + + Returns: + (torch.Tensor): A tensor of shape (N, M) representing obb similarities. + + References: + https://arxiv.org/pdf/2106.06072v1.pdf + """ + obb1 = torch.from_numpy(obb1) if isinstance(obb1, np.ndarray) else obb1 + obb2 = torch.from_numpy(obb2) if isinstance(obb2, np.ndarray) else obb2 + + x1, y1 = obb1[..., :2].split(1, dim=-1) + x2, y2 = (x.squeeze(-1)[None] for x in obb2[..., :2].split(1, dim=-1)) + a1, b1, c1 = _get_covariance_matrix(obb1) + a2, b2, c2 = (x.squeeze(-1)[None] for x in _get_covariance_matrix(obb2)) + + t1 = ( + ((a1 + a2) * (y1 - y2).pow(2) + (b1 + b2) * (x1 - x2).pow(2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps) + ) * 0.25 + t2 = (((c1 + c2) * (x2 - x1) * (y1 - y2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)) * 0.5 + t3 = ( + ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2)) + / (4 * ((a1 * b1 - c1.pow(2)).clamp_(0) * (a2 * b2 - c2.pow(2)).clamp_(0)).sqrt() + eps) + + eps + ).log() * 0.5 + bd = (t1 + t2 + t3).clamp(eps, 100.0) + hd = (1.0 - (-bd).exp() + eps).sqrt() + return 1 - hd + + +def smooth_bce(eps: float = 0.1) -> tuple[float, float]: + """Compute smoothed positive and negative Binary Cross-Entropy targets. + + Args: + eps (float, optional): The epsilon value for label smoothing. + + Returns: + pos (float): Positive label smoothing BCE target. + neg (float): Negative label smoothing BCE target. + + References: + https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441 + """ + return 1.0 - 0.5 * eps, 0.5 * eps + + +class ConfusionMatrix(DataExportMixin): + """A class for calculating and updating a confusion matrix for object detection and classification tasks. + + Attributes: + task (str): The type of task, one of 'detect', 'classify', 'semantic', or 'obb'. + matrix (np.ndarray): The confusion matrix, with dimensions depending on the task. + nc (int): The number of classes. + names (dict[int, str]): The names of the classes, used as labels on the plot. + matches (dict | None): Contains the indices of ground truths and predictions categorized into TP, FP and FN. + """ + + def __init__(self, names: dict[int, str] | None = None, task: str = "detect", save_matches: bool = False): + """Initialize a ConfusionMatrix instance. + + Args: + names (dict[int, str], optional): Names of classes, used as labels on the plot. + task (str, optional): Type of task, one of 'detect', 'classify', 'semantic', or 'obb'. + save_matches (bool, optional): Save the indices of GTs, TPs, FPs, FNs for visualization. + """ + names = names if names is not None else {} + self.task = task + self.nc = len(names) # number of classes + self.matrix = ( + np.zeros((self.nc, self.nc)) + if self.task in {"classify", "semantic"} + else np.zeros((self.nc + 1, self.nc + 1)) + ) + self.names = names # name of classes + self.matches = {} if save_matches else None + + def _append_matches(self, mtype: str, batch: dict[str, Any], idx: int) -> None: + """Append the matches to TP, FP, FN or GT list for the last batch. + + This method updates the matches dictionary by appending specific batch data to the appropriate match type (True + Positive, False Positive, or False Negative). + + Args: + mtype (str): Match type identifier ('TP', 'FP', 'FN' or 'GT'). + batch (dict[str, Any]): Batch data containing detection results with keys like 'bboxes', 'cls', 'conf', + 'keypoints', 'masks'. + idx (int): Index of the specific detection to append from the batch. + + Notes: + For masks, handles both overlap and non-overlap cases. When masks.max() > 1.0, it indicates + overlap_mask=True with shape (1, H, W), otherwise uses direct indexing. + """ + if self.matches is None: + return + for k, v in batch.items(): + if k in {"bboxes", "cls", "conf", "keypoints"}: + self.matches[mtype][k] += v[[idx]] + elif k == "masks": + # NOTE: masks.max() > 1.0 means overlap_mask=True with (1, H, W) shape + self.matches[mtype][k] += [v[0] == idx + 1] if v.max() > 1.0 else [v[idx]] + + def process_cls_preds(self, preds: list[torch.Tensor], targets: list[torch.Tensor]) -> None: + """Update confusion matrix for classification task. + + Args: + preds (list[torch.Tensor]): Predicted class labels. + targets (list[torch.Tensor]): Ground truth class labels. + """ + preds, targets = torch.cat(preds)[:, 0], torch.cat(targets) + for p, t in zip(preds.cpu().numpy(), targets.cpu().numpy()): + self.matrix[p][t] += 1 + + def process_batch( + self, + detections: dict[str, torch.Tensor], + batch: dict[str, Any], + conf: float = 0.25, + iou_thres: float = 0.45, + ) -> None: + """Update confusion matrix for object detection task. + + Args: + detections (dict[str, torch.Tensor]): Dictionary containing detected bounding boxes and their associated + information. Should contain 'cls', 'conf', and 'bboxes' keys, where 'bboxes' can be Array[N, 4] for + regular boxes or Array[N, 5] for OBB with angle. + batch (dict[str, Any]): Batch dictionary containing ground truth data with 'bboxes' (Array[M, 4]| Array[M, + 5]) and 'cls' (Array[M]) keys, where M is the number of ground truth objects. + conf (float, optional): Confidence threshold for detections. + iou_thres (float, optional): IoU threshold for matching detections to ground truth. + """ + gt_cls, gt_bboxes = batch["cls"], batch["bboxes"] + if self.matches is not None: # only if visualization is enabled + self.matches = {k: defaultdict(list) for k in ("TP", "FP", "FN", "GT")} + for i in range(gt_cls.shape[0]): + self._append_matches("GT", batch, i) # store GT + is_obb = gt_bboxes.shape[1] == 5 # check if boxes contains angle for OBB + no_pred = detections["cls"].shape[0] == 0 + if gt_cls.shape[0] == 0: # Check if labels is empty + if not no_pred: + detections = {k: detections[k][detections["conf"] > conf] for k in detections} + detection_classes = detections["cls"].int().tolist() + for i, dc in enumerate(detection_classes): + self.matrix[dc, self.nc] += 1 # FP + self._append_matches("FP", detections, i) + return + if no_pred: + gt_classes = gt_cls.int().tolist() + for i, gc in enumerate(gt_classes): + self.matrix[self.nc, gc] += 1 # FN + self._append_matches("FN", batch, i) + return + + detections = {k: detections[k][detections["conf"] > conf] for k in detections} + gt_classes = gt_cls.int().tolist() + detection_classes = detections["cls"].int().tolist() + bboxes = detections["bboxes"] + iou = batch_probiou(gt_bboxes, bboxes) if is_obb else box_iou(gt_bboxes, bboxes) + + x = torch.where(iou > iou_thres) + if x[0].shape[0]: + matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() + if x[0].shape[0] > 1: + matches = matches[matches[:, 2].argsort()[::-1]] + matches = matches[np.unique(matches[:, 1], return_index=True)[1]] + matches = matches[matches[:, 2].argsort()[::-1]] + matches = matches[np.unique(matches[:, 0], return_index=True)[1]] + else: + matches = np.zeros((0, 3)) + + m0, m1, _ = matches.transpose().astype(int) + # matches is deduplicated on both columns, so each gt and each detection appears at most once + gt_match = np.full(len(gt_classes), -1) + gt_match[m0] = m1 + matched_det = set(m1.tolist()) + for i, gc in enumerate(gt_classes): + if (di := gt_match[i].item()) >= 0: + dc = detection_classes[di] + self.matrix[dc, gc] += 1 # TP if class is correct else both an FP and an FN + if dc == gc: + self._append_matches("TP", detections, di) + else: + self._append_matches("FP", detections, di) + self._append_matches("FN", batch, i) + else: + self.matrix[self.nc, gc] += 1 # FN + self._append_matches("FN", batch, i) + + for i, dc in enumerate(detection_classes): + if i not in matched_det: + self.matrix[dc, self.nc] += 1 # FP + self._append_matches("FP", detections, i) + + def tp_fp(self) -> tuple[np.ndarray, np.ndarray]: + """Return true positives and false positives. + + Returns: + tp (np.ndarray): True positives. + fp (np.ndarray): False positives. + """ + tp = self.matrix.diagonal() # true positives + fp = self.matrix.sum(1) - tp # false positives + # fn = self.matrix.sum(0) - tp # false negatives (missed detections) + return (tp, fp) if self.task in {"classify", "semantic"} else (tp[:-1], fp[:-1]) # remove background row/col + + def plot_matches( + self, img: torch.Tensor, im_file: str, save_dir: Path, show_labels: bool = True, show_conf: bool = True + ) -> None: + """Plot grid of GT, TP, FP, FN for each image. + + Args: + img (torch.Tensor): Image to plot onto. + im_file (str): Image filename to save visualizations. + save_dir (Path): Location to save the visualizations to. + show_labels (bool): Whether to display class labels in the visualization. + show_conf (bool): Whether to display confidence values in the visualization. + """ + if not self.matches: + return + from .ops import xyxy2xywh + from .plotting import plot_images + + # Create batch of 4 (GT, TP, FP, FN) + labels = defaultdict(list) + for i, mtype in enumerate(["GT", "FP", "TP", "FN"]): + mbatch = self.matches[mtype] + if "conf" not in mbatch: + mbatch["conf"] = torch.tensor([1.0] * len(mbatch["bboxes"]), device=img.device) + mbatch["batch_idx"] = torch.ones(len(mbatch["bboxes"]), device=img.device) * i + for k in mbatch: + labels[k] += mbatch[k] + + labels = {k: torch.stack(v, 0) if len(v) else torch.empty(0) for k, v in labels.items()} + if self.task != "obb" and labels["bboxes"].shape[0]: + labels["bboxes"] = xyxy2xywh(labels["bboxes"]) + (save_dir / "visualizations").mkdir(parents=True, exist_ok=True) + plot_images( + labels, + img.repeat(4, 1, 1, 1), + paths=["Ground Truth", "False Positives", "True Positives", "False Negatives"], + fname=save_dir / "visualizations" / Path(im_file).name, + names=self.names, + max_subplots=4, + conf_thres=0.001, + show_labels=show_labels, + show_conf=show_conf, + ) + + @TryExcept(msg="ConfusionMatrix plot failure") + @plt_settings() + def plot(self, normalize: bool = True, save_dir: str = "", on_plot=None): + """Plot the confusion matrix using matplotlib and save it to a file. + + Args: + normalize (bool, optional): Whether to normalize the confusion matrix. + save_dir (str, optional): Directory where the plot will be saved. + on_plot (callable, optional): An optional callback to pass plots path and data when they are rendered. + """ + import matplotlib.pyplot as plt # scope for faster 'import ultralytics' + + array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1e-9) if normalize else 1) # normalize columns + array[array < 0.005] = np.nan # don't annotate (would appear as 0.00) + + fig, ax = plt.subplots(1, 1, figsize=(12, 9)) + names, n = list(self.names.values()), self.nc + if self.nc >= 100: # downsample for large class count + k = max(2, self.nc // 60) # step size for downsampling, always > 1 + keep_idx = slice(None, None, k) # create slice instead of array + names = names[keep_idx] # slice class names + array = array[keep_idx, :][:, keep_idx] # slice matrix rows and cols + n = (self.nc + k - 1) // k # number of retained classes + nc = n if self.task in {"classify", "semantic"} else n + 1 # adjust for background if needed + ticklabels = "auto" + if 0 < nc < 99: + ticklabels = names if self.task in {"classify", "semantic"} else [*names, "background"] + xy_ticks = np.arange(len(ticklabels)) if ticklabels != "auto" else np.arange(nc) + tick_fontsize = max(6, 15 - 0.1 * nc) # Minimum size is 6 + label_fontsize = max(6, 12 - 0.1 * nc) + title_fontsize = max(6, 12 - 0.1 * nc) + btm = max(0.1, 0.25 - 0.001 * nc) # Minimum value is 0.1 + with warnings.catch_warnings(): + warnings.simplefilter("ignore") # suppress empty matrix RuntimeWarning: All-NaN slice encountered + im = ax.imshow(array, cmap="Blues", vmin=0.0, interpolation="none") + ax.xaxis.set_label_position("bottom") + if nc < 30: # Add score for each cell of confusion matrix + color_threshold = 0.45 * (1 if normalize else np.nanmax(array)) # text color threshold + for i, row in enumerate(array[:nc]): + for j, val in enumerate(row[:nc]): + val = array[i, j] + if np.isnan(val): + continue + ax.text( + j, + i, + f"{val:.2f}" if normalize else f"{int(val)}", + ha="center", + va="center", + fontsize=10, + color="white" if val > color_threshold else "black", + ) + cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.05) + title = "Confusion Matrix" + " Normalized" * normalize + ax.set_xlabel("True", fontsize=label_fontsize, labelpad=10) + ax.set_ylabel("Predicted", fontsize=label_fontsize, labelpad=10) + ax.set_title(title, fontsize=title_fontsize, pad=20) + ax.set_xticks(xy_ticks) + ax.set_yticks(xy_ticks) + ax.tick_params(axis="x", bottom=True, top=False, labelbottom=True, labeltop=False) + ax.tick_params(axis="y", left=True, right=False, labelleft=True, labelright=False) + if ticklabels != "auto": + ax.set_xticklabels(ticklabels, fontsize=tick_fontsize, rotation=90, ha="center") + ax.set_yticklabels(ticklabels, fontsize=tick_fontsize) + for s in ("left", "right", "bottom", "top", "outline"): + if s != "outline": + ax.spines[s].set_visible(False) # Confusion matrix plot don't have outline + cbar.ax.spines[s].set_visible(False) + fig.subplots_adjust(left=0, right=0.84, top=0.94, bottom=btm) # Adjust layout to ensure equal margins + plot_fname = Path(save_dir) / f"{title.lower().replace(' ', '_')}.png" + fig.savefig(plot_fname, dpi=250) + plt.close(fig) + if on_plot: + on_plot(plot_fname, {"type": "confusion_matrix", "matrix": self.matrix.tolist()}) + + def print(self): + """Print the confusion matrix to the console.""" + for i in range(self.matrix.shape[0]): + LOGGER.info(" ".join(map(str, self.matrix[i]))) + + def summary(self, normalize: bool = False, decimals: int = 5) -> list[dict[str, float]]: + """Generate a summarized representation of the confusion matrix as a list of dictionaries, with optional + normalization. This is useful for exporting the matrix to various formats such as CSV, XML, HTML, JSON, + or SQL. + + Args: + normalize (bool): Whether to normalize the confusion matrix values. + decimals (int): Number of decimal places to round the output values to. + + Returns: + (list[dict[str, float]]): A list of dictionaries, each representing one predicted class with corresponding + values for all actual classes. + + Examples: + >>> results = model.val(data="coco8.yaml", plots=True) + >>> cm_dict = results.confusion_matrix.summary(normalize=True, decimals=5) + >>> print(cm_dict) + """ + import re + + names = ( + list(self.names.values()) + if self.task in {"classify", "semantic"} + else [*list(self.names.values()), "background"] + ) + clean_names, seen = [], set() + for name in names: + clean_name = re.sub(r"[^a-zA-Z0-9_]", "_", name) + original_clean = clean_name + counter = 1 + while clean_name.lower() in seen: + clean_name = f"{original_clean}_{counter}" + counter += 1 + seen.add(clean_name.lower()) + clean_names.append(clean_name) + array = (self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1e-9) if normalize else 1)).round(decimals) + return [ + dict({"Predicted": clean_names[i]}, **{clean_names[j]: array[i, j] for j in range(len(clean_names))}) + for i in range(len(clean_names)) + ] + + +def smooth(y: np.ndarray, f: float = 0.05) -> np.ndarray: + """Box filter of fraction f.""" + nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd) + p = np.ones(nf // 2) # ones padding + yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded + return np.convolve(yp, np.ones(nf) / nf, mode="valid") # y-smoothed + + +@plt_settings() +def plot_pr_curve( + px: np.ndarray, + py: np.ndarray, + ap: np.ndarray, + save_dir: Path = Path("pr_curve.png"), + names: dict[int, str] | None = None, + on_plot=None, +): + """Plot precision-recall curve. + + Args: + px (np.ndarray): X values for the PR curve. + py (np.ndarray): Y values for the PR curve. + ap (np.ndarray): Average precision values. + save_dir (Path, optional): Path to save the plot. + names (dict[int, str], optional): Dictionary mapping class indices to class names. + on_plot (callable, optional): Function to call after plot is saved. + """ + import matplotlib.pyplot as plt # scope for faster 'import ultralytics' + + names = names if names is not None else {} + fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) + py = np.stack(py, axis=1) + + if 0 < len(names) < 21: # display per-class legend if < 21 classes + for i, y in enumerate(py.T): + ax.plot(px, y, linewidth=1, label=f"{names[i]} {ap[i, 0]:.3f}") # plot(recall, precision) + else: + ax.plot(px, py, linewidth=1, color="gray") # plot(recall, precision) + + ax.plot(px, py.mean(1), linewidth=3, color="blue", label=f"all classes {ap[:, 0].mean():.3f} mAP@0.5") + ax.set_xlabel("Recall") + ax.set_ylabel("Precision") + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) + ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left") + ax.set_title("Precision-Recall Curve") + fig.savefig(save_dir, dpi=250) + plt.close(fig) + if on_plot: + # Pass PR curve data for interactive plotting (class names stored at model level) + # Transpose py to match other curves: y[class][point] format + on_plot(save_dir, {"type": "pr_curve", "x": px.tolist(), "y": py.T.tolist(), "ap": ap.tolist()}) + + +@plt_settings() +def plot_mc_curve( + px: np.ndarray, + py: np.ndarray, + save_dir: Path = Path("mc_curve.png"), + names: dict[int, str] | None = None, + xlabel: str = "Confidence", + ylabel: str = "Metric", + on_plot=None, +): + """Plot metric-confidence curve. + + Args: + px (np.ndarray): X values for the metric-confidence curve. + py (np.ndarray): Y values for the metric-confidence curve. + save_dir (Path, optional): Path to save the plot. + names (dict[int, str], optional): Dictionary mapping class indices to class names. + xlabel (str, optional): X-axis label. + ylabel (str, optional): Y-axis label. + on_plot (callable, optional): Function to call after plot is saved. + """ + import matplotlib.pyplot as plt # scope for faster 'import ultralytics' + + names = names if names is not None else {} + fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) + + if 0 < len(names) < 21: # display per-class legend if < 21 classes + for i, y in enumerate(py): + ax.plot(px, y, linewidth=1, label=f"{names[i]}") # plot(confidence, metric) + else: + ax.plot(px, py.T, linewidth=1, color="gray") # plot(confidence, metric) + + y = smooth(py.mean(0), 0.1) + ax.plot(px, y, linewidth=3, color="blue", label=f"all classes {y.max():.2f} at {px[y.argmax()]:.3f}") + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) + ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left") + ax.set_title(f"{ylabel}-Confidence Curve") + fig.savefig(save_dir, dpi=250) + plt.close(fig) + if on_plot: + # Pass metric-confidence curve data for interactive plotting (class names stored at model level) + on_plot(save_dir, {"type": f"{ylabel.lower()}_curve", "x": px.tolist(), "y": py.tolist()}) + + +def compute_ap(recall: list[float], precision: list[float]) -> tuple[float, np.ndarray, np.ndarray]: + """Compute the average precision (AP) given the recall and precision curves. + + Args: + recall (list[float]): The recall curve. + precision (list[float]): The precision curve. + + Returns: + ap (float): Average precision. + mpre (np.ndarray): Precision envelope curve. + mrec (np.ndarray): Modified recall curve with sentinel values added at the beginning and end. + """ + # Append sentinel values to beginning and end + mrec = np.concatenate(([0.0], recall, [recall[-1] if len(recall) else 1.0], [1.0])) + mpre = np.concatenate(([1.0], precision, [0.0], [0.0])) + + # Compute the precision envelope + mpre = np.flip(np.maximum.accumulate(np.flip(mpre))) + + # Integrate area under curve + method = "interp" # methods: 'continuous', 'interp' + if method == "interp": + x = np.linspace(0, 1, 101) # 101-point interp (COCO) + func = np.trapezoid if checks.check_version(np.__version__, ">=2.0") else np.trapz # np.trapz deprecated + ap = func(np.interp(x, mrec, mpre), x) # integrate + else: # 'continuous' + i = np.where(mrec[1:] != mrec[:-1])[0] # points where x-axis (recall) changes + ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve + + return ap, mpre, mrec + + +def ap_per_class( + tp: np.ndarray, + conf: np.ndarray, + pred_cls: np.ndarray, + target_cls: np.ndarray, + plot: bool = False, + on_plot=None, + save_dir: Path = Path(), + names: dict[int, str] | None = None, + eps: float = 1e-16, + prefix: str = "", +) -> tuple: + """Compute the average precision per class for object detection evaluation. + + Args: + tp (np.ndarray): Binary array indicating whether the detection is correct (True) or not (False). + conf (np.ndarray): Array of confidence scores of the detections. + pred_cls (np.ndarray): Array of predicted classes of the detections. + target_cls (np.ndarray): Array of true classes of the targets. + plot (bool, optional): Whether to plot PR curves or not. + on_plot (callable, optional): A callback to pass plots path and data when they are rendered. + save_dir (Path, optional): Directory to save the PR curves. + names (dict[int, str], optional): Dictionary of class names to plot PR curves. + eps (float, optional): A small value to avoid division by zero. + prefix (str, optional): A prefix string for saving the plot files. + + Returns: + tp (np.ndarray): True positive counts at threshold given by max F1 metric for each class. + fp (np.ndarray): False positive counts at threshold given by max F1 metric for each class. + p (np.ndarray): Precision values at threshold given by max F1 metric for each class. + r (np.ndarray): Recall values at threshold given by max F1 metric for each class. + f1 (np.ndarray): F1-score values at threshold given by max F1 metric for each class. + ap (np.ndarray): Average precision for each class at different IoU thresholds. + unique_classes (np.ndarray): An array of unique classes that have data. + p_curve (np.ndarray): Precision curves for each class. + r_curve (np.ndarray): Recall curves for each class. + f1_curve (np.ndarray): F1-score curves for each class. + x (np.ndarray): X-axis values for the curves. + prec_values (np.ndarray): Precision values at mAP@0.5 for each class. + """ + names = names if names is not None else {} + # Sort by objectness + i = np.argsort(-conf) + tp, conf, pred_cls = tp[i], conf[i], pred_cls[i] + + # Find unique classes + unique_classes, nt = np.unique(target_cls, return_counts=True) + nc = unique_classes.shape[0] # number of classes, number of detections + + # Create Precision-Recall curve and compute AP for each class + x, prec_values = np.linspace(0, 1, 1000), [] + + # Average precision, precision and recall curves + ap, p_curve, r_curve = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000)) + for ci, c in enumerate(unique_classes): + i = pred_cls == c + n_l = nt[ci] # number of labels + n_p = i.sum() # number of predictions + if n_p == 0 or n_l == 0: + prec_values.append(np.zeros_like(x)) # keep one row per class, aligned with `ap` and `names` + continue + + # Accumulate FPs and TPs + fpc = (1 - tp[i]).cumsum(0) + tpc = tp[i].cumsum(0) + + # Recall + recall = tpc / (n_l + eps) # recall curve + r_curve[ci] = np.interp(-x, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases + + # Precision + precision = tpc / (tpc + fpc) # precision curve + p_curve[ci] = np.interp(-x, -conf[i], precision[:, 0], left=1) # p at pr_score + + # AP from recall-precision curve + for j in range(tp.shape[1]): + ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j]) + if j == 0: + prec_values.append(np.interp(x, mrec, mpre)) # precision at mAP@0.5 + + prec_values = np.array(prec_values) if prec_values else np.zeros((1, 1000)) # (nc, 1000) + + # Compute F1 (harmonic mean of precision and recall) + f1_curve = 2 * p_curve * r_curve / (p_curve + r_curve + eps) + names = {i: names[k] for i, k in enumerate(unique_classes) if k in names} # dict: only classes that have data + if plot: + plot_pr_curve(x, prec_values, ap, save_dir / f"{prefix}PR_curve.png", names, on_plot=on_plot) + plot_mc_curve(x, f1_curve, save_dir / f"{prefix}F1_curve.png", names, ylabel="F1", on_plot=on_plot) + plot_mc_curve(x, p_curve, save_dir / f"{prefix}P_curve.png", names, ylabel="Precision", on_plot=on_plot) + plot_mc_curve(x, r_curve, save_dir / f"{prefix}R_curve.png", names, ylabel="Recall", on_plot=on_plot) + + i = smooth(f1_curve.mean(0), 0.1).argmax() # max F1 index + p, r, f1 = p_curve[:, i], r_curve[:, i], f1_curve[:, i] # max-F1 precision, recall, F1 values + tp = (r * nt).round() # true positives + fp = (tp / (p + eps) - tp).round() # false positives + return tp, fp, p, r, f1, ap, unique_classes.astype(int), p_curve, r_curve, f1_curve, x, prec_values + + +class Metric(SimpleClass): + """Class for computing evaluation metrics for Ultralytics YOLO models. + + Attributes: + p (list): Precision for each class. Shape: (nc,). + r (list): Recall for each class. Shape: (nc,). + f1 (list): F1 score for each class. Shape: (nc,). + all_ap (list): AP scores for all classes and all IoU thresholds. Shape: (nc, 10). + ap_class_index (list): Index of class for each AP score. Shape: (nc,). + nc (int): Number of classes. + + Methods: + ap50: AP at IoU threshold of 0.5 for all classes. + ap: AP at IoU thresholds from 0.5 to 0.95 for all classes. + mp: Mean precision of all classes. + mr: Mean recall of all classes. + map50: Mean AP at IoU threshold of 0.5 for all classes. + map75: Mean AP at IoU threshold of 0.75 for all classes. + map: Mean AP at IoU thresholds from 0.5 to 0.95 for all classes. + mean_results: Mean of results, returns mp, mr, map50, map. + class_result: Class-aware result, returns p[i], r[i], ap50[i], ap[i]. + maps: mAP of each class. + fitness: Model fitness as a weighted combination of metrics. + update: Update metric attributes with new evaluation results. + curves: Provides a list of curves for accessing specific metrics like precision, recall, F1, etc. + curves_results: Provide a list of results for accessing specific metrics like precision, recall, F1, etc. + """ + + def __init__(self) -> None: + """Initialize a Metric instance for computing evaluation metrics for the YOLO model.""" + self.p = [] # (nc, ) + self.r = [] # (nc, ) + self.f1 = [] # (nc, ) + self.all_ap = [] # (nc, 10) + self.ap_class_index = [] # (nc, ) + self.nc = 0 + self.image_metrics = {} + + @property + def ap50(self) -> np.ndarray | list: + """Return the Average Precision (AP) at an IoU threshold of 0.5 for all classes. + + Returns: + (np.ndarray | list): Array of shape (nc,) with AP50 values per class, or an empty list if not available. + """ + return self.all_ap[:, 0] if len(self.all_ap) else [] + + @property + def ap(self) -> np.ndarray | list: + """Return the Average Precision (AP) at an IoU threshold of 0.5-0.95 for all classes. + + Returns: + (np.ndarray | list): Array of shape (nc,) with AP50-95 values per class, or an empty list if not available. + """ + return self.all_ap.mean(1) if len(self.all_ap) else [] + + @property + def mp(self) -> float: + """Return the Mean Precision of all classes. + + Returns: + (float): The mean precision of all classes. + """ + return self.p.mean() if len(self.p) else 0.0 + + @property + def mr(self) -> float: + """Return the Mean Recall of all classes. + + Returns: + (float): The mean recall of all classes. + """ + return self.r.mean() if len(self.r) else 0.0 + + @property + def map50(self) -> float: + """Return the mean Average Precision (mAP) at an IoU threshold of 0.5. + + Returns: + (float): The mAP at an IoU threshold of 0.5. + """ + return self.all_ap[:, 0].mean() if len(self.all_ap) else 0.0 + + @property + def map75(self) -> float: + """Return the mean Average Precision (mAP) at an IoU threshold of 0.75. + + Returns: + (float): The mAP at an IoU threshold of 0.75. + """ + return self.all_ap[:, 5].mean() if len(self.all_ap) else 0.0 + + @property + def map(self) -> float: + """Return the mean Average Precision (mAP) over IoU thresholds of 0.5 - 0.95 in steps of 0.05. + + Returns: + (float): The mAP over IoU thresholds of 0.5 - 0.95 in steps of 0.05. + """ + return self.all_ap.mean() if len(self.all_ap) else 0.0 + + def mean_results(self) -> list[float]: + """Return mean of results, mp, mr, map50, map.""" + return [self.mp, self.mr, self.map50, self.map] + + def class_result(self, i: int) -> tuple[float, float, float, float]: + """Return class-aware result, p[i], r[i], ap50[i], ap[i].""" + return self.p[i], self.r[i], self.ap50[i], self.ap[i] + + @property + def maps(self) -> np.ndarray: + """Return mAP of each class.""" + maps = np.zeros(self.nc) + self.map + for i, c in enumerate(self.ap_class_index): + maps[c] = self.ap[i] + return maps + + def fitness(self) -> float: + """Return model fitness as a weighted combination of metrics.""" + w = [0.0, 0.0, 0.0, 1.0] # weights for [P, R, mAP@0.5, mAP@0.5:0.95] + return float((np.nan_to_num(np.array(self.mean_results())) * w).sum()) + + def update(self, results: tuple): + """Update the evaluation metrics with a new set of results. + + Args: + results (tuple): A tuple containing evaluation metrics: + - p (list): Precision for each class. + - r (list): Recall for each class. + - f1 (list): F1 score for each class. + - all_ap (list): AP scores for all classes and all IoU thresholds. + - ap_class_index (list): Index of class for each AP score. + - p_curve (list): Precision curve for each class. + - r_curve (list): Recall curve for each class. + - f1_curve (list): F1 curve for each class. + - px (list): X values for the curves. + - prec_values (list): Precision values for each class. + """ + ( + self.p, + self.r, + self.f1, + self.all_ap, + self.ap_class_index, + self.p_curve, + self.r_curve, + self.f1_curve, + self.px, + self.prec_values, + ) = results + + def clear_image_metrics(self) -> None: + """Clear stored per-image metrics from the current validation run.""" + self.image_metrics.clear() + + @property + def curves(self) -> list: + """Return a list of curves for accessing specific metrics curves.""" + return [] + + @property + def curves_results(self) -> list[list]: + """Return a list of curves results for accessing specific metrics curves.""" + return [ + [self.px, self.prec_values, "Recall", "Precision"], + [self.px, self.f1_curve, "Confidence", "F1"], + [self.px, self.p_curve, "Confidence", "Precision"], + [self.px, self.r_curve, "Confidence", "Recall"], + ] + + def update_image_metrics(self, tp: np.ndarray, target_cls: np.ndarray, pred_cls: np.ndarray, im_name: str) -> None: + """Update per-image precision, recall, F1, TP, FP, and FN at IoU threshold 0.5. + + Args: + tp (np.ndarray): True positive array of shape (num_preds, num_iou_thresholds), where the first column (IoU + >= 0.5) is used. + target_cls (np.ndarray): Ground truth class labels for the image. + pred_cls (np.ndarray): Predicted class labels for the image. + im_name (str): The image filename used as the per-image key. + """ + # Use the default IoU=0.5 column to match the validator's image-level matching policy. + tp = int(tp[:, 0].sum()) + num_preds = pred_cls.shape[0] + num_targets = target_cls.shape[0] + fp = num_preds - tp + fn = num_targets - tp + if num_preds == 0 and num_targets == 0: + # Empty-GT image with no predictions is a trivially correct call, so report a perfect score rather than + # zeroing out P/R/F1 by the standard 0/0 fallback below. + precision = recall = f1 = 1.0 + else: + precision = tp / num_preds if num_preds else 0.0 + recall = tp / num_targets if num_targets else 0.0 + denom = precision + recall + f1 = 2 * precision * recall / denom if denom else 0.0 + self.image_metrics[im_name] = { + "precision": float(precision), + "recall": float(recall), + "f1": float(f1), + "tp": int(tp), + "fp": int(fp), + "fn": int(fn), + } + + +class DetMetrics(SimpleClass, DataExportMixin): + """Utility class for computing detection metrics such as precision, recall, and mean average precision (mAP). + + Attributes: + names (dict[int, str]): A dictionary of class names. + box (Metric): An instance of the Metric class for storing detection results. + speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process. + stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes, + target classes, and target images. + nt_per_class: Number of targets per class. + nt_per_image: Number of targets per image. + + Methods: + update_stats: Update statistics by appending new values to existing stat collections. + process: Process predicted results for object detection and update metrics. + clear_stats: Clear the stored statistics. + keys: Return a list of keys for accessing specific metrics. + mean_results: Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95. + class_result: Return the result of evaluating the performance of an object detection model on a specific class. + maps: Return mean Average Precision (mAP) scores per class. + fitness: Return the fitness of box object. + ap_class_index: Return the average precision index per class. + results_dict: Return dictionary of computed performance metrics and statistics. + curves: Return a list of curves for accessing specific metrics curves. + curves_results: Return a list of computed performance metrics and statistics. + summary: Generate a summarized representation of per-class detection metrics as a list of dictionaries. + """ + + def __init__(self, names: dict[int, str] | None = None) -> None: + """Initialize a DetMetrics instance with class names. + + Args: + names (dict[int, str], optional): Dictionary of class names. + """ + self.names = names if names is not None else {} + self.box = Metric() + self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0} + self.stats = {"tp": [], "conf": [], "pred_cls": [], "target_cls": [], "target_img": []} + self.nt_per_class = None + self.nt_per_image = None + + def update_stats(self, stat: dict[str, Any]) -> None: + """Update statistics by appending new values to existing stat collections. + + Args: + stat (dict[str, Any]): Dictionary containing new statistical values to append. Keys should match existing + keys in self.stats. + """ + for k in self.stats: + self.stats[k].append(stat[k]) + self.box.update_image_metrics(stat["tp"], stat["target_cls"], stat["pred_cls"], stat["im_name"]) + + def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]: + """Process predicted results for object detection and update metrics. + + Args: + save_dir (Path): Directory to save plots. Defaults to Path("."). + plot (bool): Whether to plot precision-recall curves. Defaults to False. + on_plot (callable, optional): Function to call after plots are generated. Defaults to None. + + Returns: + (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays. + """ + stats = {k: np.concatenate(v, 0) for k, v in self.stats.items()} # to numpy + if not stats: + return stats + results = ap_per_class( + stats["tp"], + stats["conf"], + stats["pred_cls"], + stats["target_cls"], + plot=plot, + save_dir=save_dir, + names=self.names, + on_plot=on_plot, + prefix="Box", + )[2:] + self.box.nc = len(self.names) + self.box.update(results) + self.nt_per_class = np.bincount(stats["target_cls"].astype(int), minlength=len(self.names)) + self.nt_per_image = np.bincount(stats["target_img"].astype(int), minlength=len(self.names)) + return stats + + def clear_stats(self): + """Clear the stored statistics.""" + for v in self.stats.values(): + v.clear() + + def clear_image_metrics(self) -> None: + """Clear stored per-image metrics.""" + self.box.clear_image_metrics() + + @property + def keys(self) -> list[str]: + """Return a list of keys for accessing specific metrics.""" + return ["metrics/precision(B)", "metrics/recall(B)", "metrics/mAP50(B)", "metrics/mAP50-95(B)"] + + def mean_results(self) -> list[float]: + """Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.""" + return self.box.mean_results() + + def class_result(self, i: int) -> tuple[float, float, float, float]: + """Return the result of evaluating the performance of an object detection model on a specific class.""" + return self.box.class_result(i) + + @property + def maps(self) -> np.ndarray: + """Return mean Average Precision (mAP) scores per class.""" + return self.box.maps + + @property + def fitness(self) -> float: + """Return the fitness of box object.""" + return self.box.fitness() + + @property + def ap_class_index(self) -> list: + """Return the average precision index per class.""" + return self.box.ap_class_index + + @property + def results_dict(self) -> dict[str, float]: + """Return dictionary of computed performance metrics and statistics.""" + keys = [*self.keys, "fitness"] + values = ((float(x) if hasattr(x, "item") else x) for x in ([*self.mean_results(), self.fitness])) + return dict(zip(keys, values)) + + @property + def curves(self) -> list[str]: + """Return a list of curves for accessing specific metrics curves.""" + return ["Precision-Recall(B)", "F1-Confidence(B)", "Precision-Confidence(B)", "Recall-Confidence(B)"] + + @property + def curves_results(self) -> list[list]: + """Return a list of computed performance metrics and statistics.""" + return self.box.curves_results + + def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]: + """Generate a summarized representation of per-class detection metrics as a list of dictionaries. Includes + shared scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for each class. + + Args: + normalize (bool): For Detect metrics, everything is normalized by default [0-1]. + decimals (int): Number of decimal places to round the metrics values to. + + Returns: + (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric + values. + + Examples: + >>> results = model.val(data="coco8.yaml") + >>> detection_summary = results.summary() + >>> print(detection_summary) + """ + per_class = { + "Box-P": self.box.p, + "Box-R": self.box.r, + "Box-F1": self.box.f1, + } + return [ + { + "Class": self.names[self.ap_class_index[i]], + "Images": self.nt_per_image[self.ap_class_index[i]], + "Instances": self.nt_per_class[self.ap_class_index[i]], + **{k: round(v[i], decimals) for k, v in per_class.items()}, + "mAP50": round(self.class_result(i)[2], decimals), + "mAP75": round(self.box.all_ap[i, 5], decimals), + "mAP50-95": round(self.class_result(i)[3], decimals), + } + for i in range(len(per_class["Box-P"])) + ] + + +class SegmentMetrics(DetMetrics): + """Calculate and aggregate detection and segmentation metrics over a given set of classes. + + Attributes: + names (dict[int, str]): Dictionary of class names. + box (Metric): An instance of the Metric class for storing detection results. + seg (Metric): An instance of the Metric class to calculate mask segmentation metrics. + speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process. + stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes, + target classes, and target images. + nt_per_class: Number of targets per class. + nt_per_image: Number of targets per image. + + Methods: + process: Process the detection and segmentation metrics over the given set of predictions. + keys: Return a list of keys for accessing metrics. + mean_results: Return the mean metrics for bounding box and segmentation results. + class_result: Return classification results for a specified class index. + maps: Return mAP scores for object detection and segmentation models. + fitness: Return the fitness score for both segmentation and bounding box models. + curves: Return a list of curves for accessing specific metrics curves. + curves_results: Provide a list of computed performance metrics and statistics. + summary: Generate a summarized representation of per-class segmentation metrics as a list of dictionaries. + """ + + def __init__(self, names: dict[int, str] | None = None) -> None: + """Initialize a SegmentMetrics instance with class names. + + Args: + names (dict[int, str], optional): Dictionary of class names. + """ + DetMetrics.__init__(self, names) + self.seg = Metric() + self.stats["tp_m"] = [] # add additional stats for masks + + def update_stats(self, stat: dict[str, Any]) -> None: + """Update statistics by appending new values to existing stat collections. + + Args: + stat (dict[str, Any]): Dictionary containing new statistical values to append. Keys should match existing + keys in self.stats. + """ + super().update_stats(stat) # update box stats + self.seg.update_image_metrics(stat["tp_m"], stat["target_cls"], stat["pred_cls"], stat["im_name"]) + + def clear_image_metrics(self) -> None: + """Clear stored per-image metrics.""" + super().clear_image_metrics() + self.seg.clear_image_metrics() + + def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]: + """Process the detection and segmentation metrics over the given set of predictions. + + Args: + save_dir (Path): Directory to save plots. Defaults to Path("."). + plot (bool): Whether to plot precision-recall curves. Defaults to False. + on_plot (callable, optional): Function to call after plots are generated. Defaults to None. + + Returns: + (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays. + """ + stats = DetMetrics.process(self, save_dir, plot, on_plot=on_plot) # process box stats + results_mask = ap_per_class( + stats["tp_m"], + stats["conf"], + stats["pred_cls"], + stats["target_cls"], + plot=plot, + on_plot=on_plot, + save_dir=save_dir, + names=self.names, + prefix="Mask", + )[2:] + self.seg.nc = len(self.names) + self.seg.update(results_mask) + return stats + + @property + def keys(self) -> list[str]: + """Return a list of keys for accessing metrics.""" + return [ + *DetMetrics.keys.fget(self), + "metrics/precision(M)", + "metrics/recall(M)", + "metrics/mAP50(M)", + "metrics/mAP50-95(M)", + ] + + def mean_results(self) -> list[float]: + """Return the mean metrics for bounding box and segmentation results.""" + return DetMetrics.mean_results(self) + self.seg.mean_results() + + def class_result(self, i: int) -> list[float]: + """Return classification results for a specified class index.""" + return DetMetrics.class_result(self, i) + self.seg.class_result(i) + + @property + def maps(self) -> np.ndarray: + """Return mAP scores for object detection and segmentation models.""" + return DetMetrics.maps.fget(self) + self.seg.maps + + @property + def fitness(self) -> float: + """Return the fitness score for both segmentation and bounding box models.""" + return self.seg.fitness() + DetMetrics.fitness.fget(self) + + @property + def curves(self) -> list[str]: + """Return a list of curves for accessing specific metrics curves.""" + return [ + *DetMetrics.curves.fget(self), + "Precision-Recall(M)", + "F1-Confidence(M)", + "Precision-Confidence(M)", + "Recall-Confidence(M)", + ] + + @property + def curves_results(self) -> list[list]: + """Return a list of computed performance metrics and statistics.""" + return DetMetrics.curves_results.fget(self) + self.seg.curves_results + + def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]: + """Generate a summarized representation of per-class segmentation metrics as a list of dictionaries. Includes + both box and mask scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for + each class. + + Args: + normalize (bool): For Segment metrics, everything is normalized by default [0-1]. + decimals (int): Number of decimal places to round the metrics values to. + + Returns: + (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric + values. + + Examples: + >>> results = model.val(data="coco8-seg.yaml") + >>> seg_summary = results.summary(decimals=4) + >>> print(seg_summary) + """ + per_class = { + "Mask-P": self.seg.p, + "Mask-R": self.seg.r, + "Mask-F1": self.seg.f1, + } + summary = DetMetrics.summary(self, normalize, decimals) # get box summary + for i, s in enumerate(summary): + s.update({**{k: round(v[i], decimals) for k, v in per_class.items()}}) + return summary + + +class PoseMetrics(DetMetrics): + """Calculate and aggregate detection and pose metrics over a given set of classes. + + Attributes: + names (dict[int, str]): Dictionary of class names. + pose (Metric): An instance of the Metric class to calculate pose metrics. + box (Metric): An instance of the Metric class for storing detection results. + speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process. + stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes, + target classes, and target images. + nt_per_class: Number of targets per class. + nt_per_image: Number of targets per image. + + Methods: + process: Process the detection and pose metrics over the given set of predictions. + keys: Return a list of keys for accessing metrics. + mean_results: Return the mean results of box and pose. + class_result: Return the class-wise detection results for a specific class i. + maps: Return the mean average precision (mAP) per class for both box and pose detections. + fitness: Return combined fitness score for pose and box detection. + curves: Return a list of curves for accessing specific metrics curves. + curves_results: Provide a list of computed performance metrics and statistics. + summary: Generate a summarized representation of per-class pose metrics as a list of dictionaries. + """ + + def __init__(self, names: dict[int, str] | None = None) -> None: + """Initialize the PoseMetrics class with class names. + + Args: + names (dict[int, str], optional): Dictionary of class names. + """ + super().__init__(names) + self.pose = Metric() + self.stats["tp_p"] = [] # add additional stats for pose + + def update_stats(self, stat: dict[str, Any]) -> None: + """Update statistics by appending new values to existing stat collections. + + Args: + stat (dict[str, Any]): Dictionary containing new statistical values to append. Keys should match existing + keys in self.stats. + """ + super().update_stats(stat) # update box stats + self.pose.update_image_metrics(stat["tp_p"], stat["target_cls"], stat["pred_cls"], stat["im_name"]) + + def clear_image_metrics(self) -> None: + """Clear stored per-image metrics.""" + super().clear_image_metrics() + self.pose.clear_image_metrics() + + def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]: + """Process the detection and pose metrics over the given set of predictions. + + Args: + save_dir (Path): Directory to save plots. Defaults to Path("."). + plot (bool): Whether to plot precision-recall curves. Defaults to False. + on_plot (callable, optional): Function to call after plots are generated. + + Returns: + (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays. + """ + stats = DetMetrics.process(self, save_dir, plot, on_plot=on_plot) # process box stats + results_pose = ap_per_class( + stats["tp_p"], + stats["conf"], + stats["pred_cls"], + stats["target_cls"], + plot=plot, + on_plot=on_plot, + save_dir=save_dir, + names=self.names, + prefix="Pose", + )[2:] + self.pose.nc = len(self.names) + self.pose.update(results_pose) + return stats + + @property + def keys(self) -> list[str]: + """Return a list of evaluation metric keys.""" + return [ + *DetMetrics.keys.fget(self), + "metrics/precision(P)", + "metrics/recall(P)", + "metrics/mAP50(P)", + "metrics/mAP50-95(P)", + ] + + def mean_results(self) -> list[float]: + """Return the mean results of box and pose.""" + return DetMetrics.mean_results(self) + self.pose.mean_results() + + def class_result(self, i: int) -> list[float]: + """Return the class-wise detection results for a specific class i.""" + return DetMetrics.class_result(self, i) + self.pose.class_result(i) + + @property + def maps(self) -> np.ndarray: + """Return the mean average precision (mAP) per class for both box and pose detections.""" + return DetMetrics.maps.fget(self) + self.pose.maps + + @property + def fitness(self) -> float: + """Return combined fitness score for pose and box detection.""" + return self.pose.fitness() + DetMetrics.fitness.fget(self) + + @property + def curves(self) -> list[str]: + """Return a list of curves for accessing specific metrics curves.""" + return [ + *DetMetrics.curves.fget(self), + "Precision-Recall(P)", + "F1-Confidence(P)", + "Precision-Confidence(P)", + "Recall-Confidence(P)", + ] + + @property + def curves_results(self) -> list[list]: + """Return a list of computed performance metrics and statistics.""" + return DetMetrics.curves_results.fget(self) + self.pose.curves_results + + def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]: + """Generate a summarized representation of per-class pose metrics as a list of dictionaries. Includes both box + and pose scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for each class. + + Args: + normalize (bool): For Pose metrics, everything is normalized by default [0-1]. + decimals (int): Number of decimal places to round the metrics values to. + + Returns: + (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric + values. + + Examples: + >>> results = model.val(data="coco8-pose.yaml") + >>> pose_summary = results.summary(decimals=4) + >>> print(pose_summary) + """ + per_class = { + "Pose-P": self.pose.p, + "Pose-R": self.pose.r, + "Pose-F1": self.pose.f1, + } + summary = DetMetrics.summary(self, normalize, decimals) # get box summary + for i, s in enumerate(summary): + s.update({**{k: round(v[i], decimals) for k, v in per_class.items()}}) + return summary + + +class ClassifyMetrics(SimpleClass, DataExportMixin): + """Class for computing classification metrics including top-1 and top-5 accuracy. + + Attributes: + top1 (float): The top-1 accuracy. + top5 (float): The top-5 accuracy. + speed (dict[str, float]): A dictionary containing the time taken for each step in the pipeline. + + Methods: + process: Process target classes and predicted classes to compute metrics. + fitness: Return mean of top-1 and top-5 accuracies as fitness score. + results_dict: Return a dictionary with model's performance metrics and fitness score. + keys: Return a list of keys for the results_dict property. + curves: Return a list of curves for accessing specific metrics curves. + curves_results: Provide a list of computed performance metrics and statistics. + summary: Generate a single-row summary of classification metrics (Top-1 and Top-5 accuracy). + """ + + def __init__(self) -> None: + """Initialize a ClassifyMetrics instance.""" + self.top1 = 0 + self.top5 = 0 + self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0} + + def process(self, targets: torch.Tensor, pred: torch.Tensor): + """Process target classes and predicted classes to compute metrics. + + Args: + targets (torch.Tensor): Target classes. + pred (torch.Tensor): Predicted classes. + """ + pred, targets = torch.cat(pred), torch.cat(targets) + correct = (targets[:, None] == pred).float() + acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1) # (top1, top5) accuracy + self.top1, self.top5 = acc.mean(0).tolist() + + @property + def fitness(self) -> float: + """Return mean of top-1 and top-5 accuracies as fitness score.""" + return (self.top1 + self.top5) / 2 + + @property + def results_dict(self) -> dict[str, float]: + """Return a dictionary with model's performance metrics and fitness score.""" + return dict(zip([*self.keys, "fitness"], [self.top1, self.top5, self.fitness])) + + @property + def keys(self) -> list[str]: + """Return a list of keys for the results_dict property.""" + return ["metrics/accuracy_top1", "metrics/accuracy_top5"] + + @property + def curves(self) -> list: + """Return a list of curves for accessing specific metrics curves.""" + return [] + + @property + def curves_results(self) -> list: + """Return a list of curves results for accessing specific metrics curves.""" + return [] + + def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, float]]: + """Generate a single-row summary of classification metrics (Top-1 and Top-5 accuracy). + + Args: + normalize (bool): For Classify metrics, everything is normalized by default [0-1]. + decimals (int): Number of decimal places to round the metrics values to. + + Returns: + (list[dict[str, float]]): A list with one dictionary containing Top-1 and Top-5 classification accuracy. + + Examples: + >>> results = model.val(data="imagenet10") + >>> classify_summary = results.summary(decimals=4) + >>> print(classify_summary) + """ + return [{"top1_acc": round(self.top1, decimals), "top5_acc": round(self.top5, decimals)}] + + +class OBBMetrics(DetMetrics): + """Metrics for evaluating oriented bounding box (OBB) detection. + + Attributes: + names (dict[int, str]): Dictionary of class names. + box (Metric): An instance of the Metric class for storing detection results. + speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process. + stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes, + target classes, and target images. + nt_per_class: Number of targets per class. + nt_per_image: Number of targets per image. + + References: + https://arxiv.org/pdf/2106.06072.pdf + """ + + def __init__(self, names: dict[int, str] | None = None) -> None: + """Initialize an OBBMetrics instance with class names. + + Args: + names (dict[int, str], optional): Dictionary of class names. + """ + DetMetrics.__init__(self, names) + + +class SemanticMetrics(SimpleClass, DataExportMixin): + """Metrics for semantic segmentation, including mIoU, pixel accuracy, and per-class IoU. + + Attributes: + names (dict): Class names mapping. + nc (int): Number of classes. + cm_nc (int): Confusion matrix side length (2 for binary segmentation, else nc). + device (torch.device | None): Device used for confusion matrix accumulation. + matrix (torch.Tensor | None): Accumulated confusion matrix of shape (cm_nc, cm_nc). + speed (dict): Processing speed statistics. + nt_per_image (np.ndarray): Number of images containing each class. + nt_per_class (np.ndarray): Number of pixels per class. + _miou (float): Cached mean IoU. + _pixel_accuracy (float): Cached pixel accuracy. + _per_class_iou (np.ndarray): Cached per-class IoU values. + _per_class_pixel_acc (np.ndarray): Cached per-class pixel accuracy. + """ + + def __init__(self, names: dict[int, str] | None = None) -> None: + """Initialize semantic segmentation metrics. + + Args: + names (dict, optional): Dictionary mapping class indices to names. + """ + self.names = names or {} + self.nc = len(self.names) + self.cm_nc = 2 if self.nc == 1 else self.nc + self.matrix = None + self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0} + self.nt_per_image = np.zeros(self.nc, dtype=np.int32) + self._miou = 0.0 + self._pixel_accuracy = 0.0 + self._per_class_iou = np.zeros(self.nc, dtype=np.float32) + self._per_class_pixel_acc = np.zeros(self.nc, dtype=np.float32) + self.nt_per_class = np.zeros(self.nc, dtype=np.int32) + + def update_stats(self, preds: torch.Tensor, targets: torch.Tensor) -> None: + """Accumulate confusion matrix from predictions and targets. + + Args: + preds (torch.Tensor): Predicted class IDs [B, H, W]. + targets (torch.Tensor): Ground truth class IDs [B, H, W]. + """ + if self.matrix is None: + self.matrix = torch.zeros((self.cm_nc, self.cm_nc), device=preds.device, dtype=torch.float32) + + valid = (targets != 255) & (preds >= 0) & (preds < self.cm_nc) & (targets >= 0) & (targets < self.cm_nc) + idx = (self.cm_nc * targets[valid] + preds[valid]).long() + for i in idx.split(1 << 24): # float32 counts are exact up to 2**24 per chunk; bincount is very slow on MPS + hist = torch.zeros(self.cm_nc**2, device=i.device, dtype=self.matrix.dtype) + self.matrix += hist.scatter_add_(0, i, torch.ones_like(i, dtype=hist.dtype)).view_as(self.matrix) + + present = torch.zeros((targets.shape[0], self.cm_nc), dtype=torch.bool, device=targets.device) + batch_idx = torch.arange(targets.shape[0], device=targets.device).view(-1, 1, 1).expand_as(targets) + present[batch_idx[valid], targets[valid].long()] = True + if self.nc == 1: + self.nt_per_image[0] += int(present[:, 1].sum()) + else: + self.nt_per_image += present[:, : self.nc].sum(0).cpu().numpy() + + def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot: callable | None = None) -> None: + """Compute final metrics from accumulated confusion matrix. + + Args: + save_dir (Path): Directory to save plots. Defaults to Path('.'). + plot (bool): Whether to plot IoU bars and confusion matrix. Defaults to False. + on_plot (callable, optional): Function to call after plots are generated. Defaults to None. + """ + if self.matrix is None: + return + + intersection = torch.diagonal(self.matrix) + union = self.matrix.sum(1) + self.matrix.sum(0) - intersection + iou = torch.where(union > 0, intersection / union, torch.zeros_like(intersection, dtype=torch.float32)) + row_sum = self.matrix.sum(1) + pa = intersection / (row_sum + 1e-10) + + if self.nc == 1: + self._miou = float(iou[1].item()) + self._per_class_iou = iou[1:].cpu().numpy() + self._per_class_pixel_acc = pa[1:].cpu().numpy() + self.nt_per_class = np.array([row_sum[1].item()], dtype=np.int32) + else: + # Average IoU only over classes present in the ground truth; classes with no GT pixels (absent + # from the val set or removed by the `classes` filter) are excluded. + present = row_sum > 0 + self._miou = float(iou[present].mean().item()) if present.any() else 0.0 + self._per_class_iou = iou.cpu().numpy() + self._per_class_pixel_acc = pa.cpu().numpy() + self.nt_per_class = row_sum[: self.nc].cpu().numpy().astype(np.int32) + + self._pixel_accuracy = float((intersection.sum() / (self.matrix.sum() + 1e-10)).item()) + + if plot: + self._plot_iou_bars(save_dir, on_plot) + + def clear_stats(self): + """Clear accumulated statistics.""" + self.matrix = None + self.nt_per_image.fill(0) + + @plt_settings() + def _plot_iou_bars(self, save_dir, on_plot): + """Plot per-class IoU bar chart. + + Args: + save_dir (Path | str): Directory to save the plot. + on_plot (callable, optional): Function to call after plot is saved. + """ + import matplotlib.pyplot as plt + + fig, ax = plt.subplots(1, 1, figsize=(10, 6), tight_layout=True) + names = list(self.names.values()) if self.names else [str(i) for i in range(self.nc)] + x = np.arange(self.nc) + bars = ax.bar(x, self._per_class_iou, color=[[c / 255.0 for c in colors(i, False)] for i in range(self.nc)]) + ax.set_xlabel("Class") + ax.set_ylabel("IoU") + ax.set_title("Per-Class IoU") + ax.set_ylim(0, 1) + if 0 < len(names) < 30: + ax.set_xticks(x) + ax.set_xticklabels(names, rotation=90, fontsize=10) + for bar in bars: + height = bar.get_height() + ax.text(bar.get_x() + bar.get_width() / 2.0, height, f"{height:.3f}", ha="center", va="bottom", fontsize=8) + fname = Path(save_dir) / "iou_bar_chart.png" + plt.savefig(fname, dpi=250) + plt.close(fig) + if on_plot: + on_plot(fname) + + @property + def miou(self): + """Return mean IoU (foreground IoU only for binary segmentation).""" + return self._miou + + @property + def pixel_accuracy(self): + """Return overall pixel accuracy.""" + return self._pixel_accuracy + + @property + def per_class_iou(self): + """Return per-class IoU values (foreground IoU only for binary segmentation).""" + return self._per_class_iou + + @property + def per_class_pixel_accuracy(self): + """Return per-class pixel accuracy (diagonal / row sum for each class).""" + return self._per_class_pixel_acc + + @property + def fitness(self): + """Return model fitness as mean IoU.""" + return self.miou + + @property + def keys(self): + """Return metric keys for logging.""" + return ["metrics/mIoU", "metrics/pixel_acc"] + + def mean_results(self): + """Return mean results for logging.""" + return [self.miou, self.pixel_accuracy] + + def class_result(self, i: int) -> list[float]: + """Return the result of evaluating the performance on a specific class.""" + if self._per_class_iou is None or len(self._per_class_iou) == 0: + return [0.0, 0.0] + c = self.ap_class_index[i] + return [float(self._per_class_iou[c]), float(self._per_class_pixel_acc[c])] + + @property + def ap_class_index(self): + """Return the indices of classes present in the ground truth for per-class reporting.""" + return [i for i in range(self.nc) if self.nt_per_class[i] > 0] + + @property + def results_dict(self): + """Return results dictionary.""" + return dict(zip([*self.keys, "fitness"], [*self.mean_results(), self.fitness])) + + @property + def curves(self): + """Return an empty list because semantic segmentation has no PR curves.""" + return [] + + @property + def curves_results(self): + """Return empty list (no PR curve results).""" + return [] + + def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict]: + """Generate a per-class summary of semantic segmentation metrics, with global mIoU and pixel accuracy on each + row. + + Args: + normalize (bool): For semantic metrics, values are already in [0, 1]. + decimals (int): Number of decimal places to round the metric values to. + + Returns: + (list[dict]): A list of dictionaries, one per class, with per-class IoU and shared scalars. + """ + miou = round(self.miou, decimals) + pixel_acc = round(self.pixel_accuracy, decimals) + per_class = self.per_class_iou + names = self.names or {i: str(i) for i in range(len(per_class))} + return [ + { + "Class": names.get(c, str(c)), + "Images": int(self.nt_per_image[c]), + "Pixels": int(self.nt_per_class[c]), + "IoU": round(float(per_class[c]), decimals), + "mIoU": miou, + "pixel_acc": pixel_acc, + } + for c in self.ap_class_index + ] + + +class DepthMetrics(SimpleClass, DataExportMixin): + """Monocular depth estimation metrics: delta1-3, abs_rel, rmse, silog. + + Metrics are finalized per image, then averaged across the val set so every image weighs equally regardless of its + valid-pixel count, matching the per-sample averaging used by Depth Anything V2 and Monodepth2. Images with fewer + than 10 valid ground-truth pixels are skipped entirely, the same floor Depth Anything V2 applies to its own valid + mask. Non-finite predictions are scored at a depth bound rather than hiding the image from the average. Per-image + results are accumulated in float64 on CPU, so DDP reduction is still a plain sum-then-all_reduce. Following the + standard Eigen evaluation protocol, pixels with gt outside (min_depth, max_depth) are excluded and predictions are + clamped into that range. + + Attributes: + min_depth (float): Minimum valid depth in meters. + max_depth (float): Maximum valid depth in meters. + """ + + def __init__( + self, + min_depth: float = 0.001, + max_depth: float = 100.0, + align: str = "median", + ) -> None: + """Initialize depth metric accumulators. + + Args: + min_depth (float): Minimum valid depth in meters; pixels with gt <= min_depth are ignored. + max_depth (float): Maximum valid depth in meters; pixels with gt >= max_depth are ignored and predictions + are clamped to it. + align (str): Per-image scale alignment before scoring, following the Depth Anything eval protocol. "median" + rescales each prediction by median(gt)/median(pred) so affine-invariant (scale-ambiguous) outputs are + comparable to metric GT; "none" disables alignment and scores predictions in their raw output scale. + """ + self.min_depth = min_depth + self.max_depth = max_depth + self.align = align + self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0} + self._totals = None + self._count = 0.0 + self._results = {} + + def update_stats(self, preds: torch.Tensor, targets: torch.Tensor) -> None: + """Accumulate per-image metrics, with per-image scale alignment. + + Args: + preds (torch.Tensor): Predicted depth (B,1,H,W) or (B,H,W). + targets (torch.Tensor): Ground-truth depth in meters, same shape. + """ + p = preds.squeeze(1) if preds.ndim == 4 else preds + g = targets.squeeze(1) if targets.ndim == 4 else targets + if p.ndim == 2: # single image (H,W) -> (1,H,W) so alignment is always per-image + p, g = p[None], g[None] + for pi, gi in zip(p, g): + # Eigen protocol: score only pixels with gt inside (min_depth, max_depth) + mask = (gi > self.min_depth) & (gi < self.max_depth) + if int(mask.sum()) < 10: # Depth Anything V2 floor: aligning the median of a few pixels is meaningless + continue + pv = pi[mask].float() + gv = gi[mask].float() + if self.align == "median": + finite = torch.isfinite(pv) + if finite.any(): + scale = torch.median(gv[finite]) / torch.median(pv[finite].clamp_min(self.min_depth)) + pv = pv * scale + pv = torch.nan_to_num(pv, nan=self.max_depth, posinf=self.max_depth, neginf=self.min_depth).clamp( + self.min_depth, self.max_depth + ) + thresh = torch.maximum(pv / gv, gv / pv) + log_diff = torch.log(pv) - torch.log(gv) + # λ=1 variance form (ZoeDepth/KITTI), finalized per image so silog also averages per-sample + silog = (log_diff.pow(2).mean() - log_diff.mean().pow(2)).clamp_min(0.0).sqrt() * 100 + image_metrics = torch.stack( + [ + (thresh < 1.25).float().mean(), + (thresh < 1.25**2).float().mean(), + (thresh < 1.25**3).float().mean(), + (torch.abs(pv - gv) / gv).mean(), + ((pv - gv) ** 2).mean().sqrt(), + silog, + ] + ) + if self._totals is None: + self._totals = torch.zeros(6, dtype=torch.float64) + self._totals += image_metrics.cpu().double() # float64 on CPU; MPS tensors cannot be float64 + self._count += 1.0 + + def process(self, *args, **kwargs) -> None: + """Finalize metrics by averaging the accumulated per-image results.""" + if self._totals is None or self._count == 0: + self._results = dict.fromkeys(self.keys, 0.0) + return + d1, d2, d3, abs_rel, rmse, silog = (float(x) for x in self._totals / self._count) + self._results = { + "metrics/delta1": d1, + "metrics/delta2": d2, + "metrics/delta3": d3, + "metrics/abs_rel": abs_rel, + "metrics/rmse": rmse, + "metrics/silog": silog, + } + + def clear_stats(self) -> None: + """Reset accumulators.""" + self._totals = None + self._count = 0.0 + self._results = {} + + @property + def keys(self) -> list[str]: + """Metric keys for logging.""" + return [ + "metrics/delta1", + "metrics/delta2", + "metrics/delta3", + "metrics/abs_rel", + "metrics/rmse", + "metrics/silog", + ] + + def mean_results(self) -> list[float]: + """Return metric values in `keys` order.""" + return [self._results.get(k, 0.0) for k in self.keys] + + @property + def delta1(self) -> float: + """Mean per-image fraction of pixels with max(p/g, g/p) < 1.25.""" + return self._results.get("metrics/delta1", 0.0) + + @property + def delta2(self) -> float: + """Mean per-image fraction of pixels with max(p/g, g/p) < 1.25**2.""" + return self._results.get("metrics/delta2", 0.0) + + @property + def delta3(self) -> float: + """Mean per-image fraction of pixels with max(p/g, g/p) < 1.25**3.""" + return self._results.get("metrics/delta3", 0.0) + + @property + def abs_rel(self) -> float: + """Mean per-image absolute relative error.""" + return self._results.get("metrics/abs_rel", 0.0) + + @property + def rmse(self) -> float: + """Mean per-image root mean squared error (meters).""" + return self._results.get("metrics/rmse", 0.0) + + @property + def silog(self) -> float: + """Mean per-image scale-invariant logarithmic error (x100).""" + return self._results.get("metrics/silog", 0.0) + + @property + def fitness(self) -> float: + """Fitness = delta1 (higher is better).""" + return self._results.get("metrics/delta1", 0.0) + + @property + def results_dict(self) -> dict[str, float]: + """Results dict including fitness.""" + return dict(zip([*self.keys, "fitness"], [*self.mean_results(), self.fitness])) + + @property + def curves(self) -> list: + """No PR curves for depth.""" + return [] + + @property + def curves_results(self) -> list: + """No PR curve results for depth.""" + return [] + + def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict]: + """Single-row summary of global depth metrics.""" + return [{k.split("/")[-1]: round(v, decimals) for k, v in self._results.items()}] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/nms.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/nms.py new file mode 100644 index 0000000000000000000000000000000000000000..885cda106ff6000988d4047cb7c96d0e446825e9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/nms.py @@ -0,0 +1,302 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import sys +import time + +import torch + +from ultralytics.utils import LOGGER +from ultralytics.utils.metrics import batch_probiou, box_iou +from ultralytics.utils.ops import xywh2xyxy + + +def non_max_suppression( + prediction, + conf_thres: float = 0.25, + iou_thres: float = 0.45, + classes=None, + agnostic: bool = False, + multi_label: bool = False, + labels=(), + max_det: int = 300, + nc: int = 0, # number of classes (optional) + max_time_img: float = 0.05, + max_nms: int = 30000, + max_wh: int = 7680, + rotated: bool = False, + end2end: bool = False, + return_idxs: bool = False, +): + """Perform non-maximum suppression (NMS) on prediction results. + + Applies NMS to filter overlapping bounding boxes based on confidence and IoU thresholds. Supports multiple detection + formats including standard boxes, rotated boxes, and masks. + + Args: + prediction (torch.Tensor): Predictions with shape (batch_size, num_classes + 4 + num_masks, num_boxes) + containing boxes, classes, and optional masks. + conf_thres (float): Confidence threshold for filtering detections. Valid values are between 0.0 and 1.0. + iou_thres (float): IoU threshold for NMS filtering. Valid values are between 0.0 and 1.0. + classes (list[int], optional): List of class indices to consider. If None, all classes are considered. + agnostic (bool): Whether to perform class-agnostic NMS. + multi_label (bool): Whether each box can have multiple labels. + labels (list[torch.Tensor]): A priori labels for each image. + max_det (int): Maximum number of detections to keep per image. + nc (int): Number of classes. Indices after this are considered masks. + max_time_img (float): Maximum time in seconds for processing one image. + max_nms (int): Maximum number of boxes for NMS. + max_wh (int): Maximum box width and height in pixels. + rotated (bool): Whether to handle Oriented Bounding Boxes (OBB). + end2end (bool): Whether the model is end-to-end and doesn't require NMS. + return_idxs (bool): Whether to return the indices of kept detections. + + Returns: + (list[torch.Tensor] | tuple[list[torch.Tensor], list[torch.Tensor]]): List of detections per image with shape + (num_boxes, 6 + num_masks) containing (x1, y1, x2, y2, confidence, class, mask1, mask2, ...). If + return_idxs=True, returns a tuple of (output, keepi) where keepi contains indices of kept detections. + """ + # Checks + assert 0 <= conf_thres <= 1, f"Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0" + assert 0 <= iou_thres <= 1, f"Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0" + if isinstance(prediction, (list, tuple)): # YOLOv8 model in validation mode, output = (inference_out, loss_out) + prediction = prediction[0] # select only inference output + if classes is not None: + classes = torch.tensor(classes, device=prediction.device) + + if prediction.shape[-1] == 6 or end2end: # end-to-end model (BNC, i.e. 1,300,6) + output, keepi = [], [] + for pred in prediction: + mask = pred[:, 4] > conf_thres + if classes is not None: + mask &= (pred[:, 5:6] == classes).any(1) + idx = mask.nonzero(as_tuple=False).view(-1)[:max_det] + output.append(pred[idx].float()) # half backend outputs: match the float32 rows the NMS branch returns + keepi.append(idx) + return (output, keepi) if return_idxs else output + + bs = prediction.shape[0] # batch size (BCN, i.e. 1,84,6300) + nc = nc or (prediction.shape[1] - 4) # number of classes + extra = prediction.shape[1] - nc - 4 # number of extra info + mi = 4 + nc # mask start index + xc = prediction[:, 4:mi].amax(1) > conf_thres # candidates + xinds = torch.arange(prediction.shape[-1], device=prediction.device).expand(bs, -1)[..., None] # to track idxs + + # Settings + # min_wh = 2 # (pixels) minimum box width and height + time_limit = 2.0 + max_time_img * bs # seconds to quit after + multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img) + + prediction = prediction.transpose(-1, -2) # shape(1,84,6300) to shape(1,6300,84) + + t = time.time() + output = [torch.zeros((0, 6 + extra), device=prediction.device)] * bs + keepi = [torch.zeros((0, 1), device=prediction.device)] * bs # to store the kept idxs + use_torchvision = prediction.device.type != "xpu" and "torchvision" in sys.modules + for xi, (x, xk) in enumerate(zip(prediction, xinds)): # image index, (preds, preds indices) + # Apply constraints + # x[((x[:, 2:4] < min_wh) | (x[:, 2:4] > max_wh)).any(1), 4] = 0 # width-height + filt = xc[xi] # confidence + x = x[filt] + if not rotated: + x[:, :4] = xywh2xyxy(x[:, :4]) + if return_idxs: + xk = xk[filt] + + # Cat apriori labels if autolabelling + if labels and len(labels[xi]) and not rotated: + lb = labels[xi] + v = torch.zeros((len(lb), nc + extra + 4), device=x.device) + v[:, :4] = xywh2xyxy(lb[:, 1:5]) # box + v[range(len(lb)), lb[:, 0].long() + 4] = 1.0 # cls + x = torch.cat((x, v), 0) + + # If none remain process next image + if not x.shape[0]: + continue + + # Detections matrix nx6 (xyxy, conf, cls) + box, cls, mask = x.split((4, nc, extra), 1) + + if multi_label: + i, j = torch.where(cls > conf_thres) + x = torch.cat((box[i], x[i, 4 + j, None], j[:, None].float(), mask[i]), 1) + if return_idxs: + xk = xk[i] + else: # best class only + conf, j = cls.max(1, keepdim=True) + filt = conf.view(-1) > conf_thres + x = torch.cat((box, conf, j.float(), mask), 1)[filt] + if return_idxs: + xk = xk[filt] + + # Filter by class + if classes is not None: + filt = (x[:, 5:6] == classes).any(1) + x = x[filt] + if return_idxs: + xk = xk[filt] + + # Check shape + n = x.shape[0] # number of boxes + if not n: # no boxes + continue + if n > max_nms: # excess boxes + filt = x[:, 4].argsort(descending=True)[:max_nms] # sort by confidence and remove excess boxes + x = x[filt] + if return_idxs: + xk = xk[filt] + + c = x[:, 5:6] * (0 if agnostic else max_wh) # classes + scores = x[:, 4] # scores + if rotated: + boxes = torch.cat((x[:, :2] + c, x[:, 2:4], x[:, -1:]), dim=-1) # xywhr + i = TorchNMS.fast_nms(boxes, scores, iou_thres, iou_func=batch_probiou) + else: + boxes = x[:, :4] + c # boxes (offset by class) + # Use torchvision if already imported; it has no XPU NMS kernel, but torch_npu CPU-falls back on NPU. + if use_torchvision: + import torchvision # scope as slow import + + i = torchvision.ops.nms(boxes, scores, iou_thres) + else: + i = TorchNMS.nms(boxes, scores, iou_thres) + i = i[:max_det] # limit detections + + output[xi] = x[i] + if return_idxs: + keepi[xi] = xk[i].view(-1) + if (time.time() - t) > time_limit: + LOGGER.warning(f"NMS time limit {time_limit:.3f}s exceeded") + break # time limit exceeded + + return (output, keepi) if return_idxs else output + + +class TorchNMS: + """Ultralytics custom NMS implementation optimized for YOLO. + + This class provides static methods for performing non-maximum suppression (NMS) operations on bounding boxes, + including standard NMS and fast NMS. + + Methods: + fast_nms: Fast-NMS using upper triangular matrix operations. + nms: Optimized NMS with early termination that matches torchvision behavior exactly. + + Examples: + Perform standard NMS on boxes and scores + >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]]) + >>> scores = torch.tensor([0.9, 0.8]) + >>> keep = TorchNMS.nms(boxes, scores, 0.5) + """ + + @staticmethod + def fast_nms( + boxes: torch.Tensor, + scores: torch.Tensor, + iou_threshold: float, + use_triu: bool = True, + iou_func=box_iou, + exit_early: bool = True, + ) -> torch.Tensor: + """Fast-NMS implementation from https://arxiv.org/pdf/1904.02689 using upper triangular matrix operations. + + Args: + boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format. + scores (torch.Tensor): Confidence scores with shape (N,). + iou_threshold (float): IoU threshold for suppression. + use_triu (bool): Whether to use torch.triu operator for upper triangular matrix operations. + iou_func (callable): Function to compute IoU between boxes. + exit_early (bool): Whether to exit early if there are no boxes. + + Returns: + (torch.Tensor): Indices of boxes to keep after NMS. + + Examples: + Apply NMS to a set of boxes + >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]]) + >>> scores = torch.tensor([0.9, 0.8]) + >>> keep = TorchNMS.fast_nms(boxes, scores, 0.5) + """ + if boxes.numel() == 0 and exit_early: + return torch.empty((0,), dtype=torch.int64, device=boxes.device) + + sorted_idx = torch.argsort(scores, descending=True) + boxes = boxes[sorted_idx] + ious = iou_func(boxes, boxes) + if use_triu: + ious = ious.triu_(diagonal=1) + # NOTE: handle the case when len(boxes) hence exportable by eliminating if-else condition + pick = torch.nonzero((ious >= iou_threshold).sum(0) <= 0).squeeze_(-1) + else: + n = boxes.shape[0] + row_idx = torch.arange(n, device=boxes.device).view(-1, 1).expand(-1, n) + col_idx = torch.arange(n, device=boxes.device).view(1, -1).expand(n, -1) + upper_mask = row_idx < col_idx + ious = ious * upper_mask + # Zeroing these scores ensures the additional indices would not affect the final results + scores_ = scores[sorted_idx] + scores_[~((ious >= iou_threshold).sum(0) <= 0)] = 0 + scores[sorted_idx] = scores_ # update original tensor for NMSModel + # NOTE: return indices with fixed length to avoid TFLite reshape error + pick = torch.topk(scores_, scores_.shape[0]).indices + return sorted_idx[pick] + + @staticmethod + def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torch.Tensor: + """Optimized NMS with early termination that matches torchvision behavior exactly. + + Args: + boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format. + scores (torch.Tensor): Confidence scores with shape (N,). + iou_threshold (float): IoU threshold for suppression. + + Returns: + (torch.Tensor): Indices of boxes to keep after NMS. + + Examples: + Apply NMS to a set of boxes + >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]]) + >>> scores = torch.tensor([0.9, 0.8]) + >>> keep = TorchNMS.nms(boxes, scores, 0.5) + """ + if boxes.numel() == 0: + return torch.empty((0,), dtype=torch.int64, device=boxes.device) + + # Pre-allocate and extract coordinates once + x1, y1, x2, y2 = boxes.unbind(1) + areas = (x2 - x1) * (y2 - y1) + + # Sort by scores descending + order = scores.argsort(0, descending=True) + + # Pre-allocate keep list with maximum possible size + keep = torch.zeros(order.numel(), dtype=torch.int64, device=boxes.device) + keep_idx = 0 + while order.numel() > 0: + i = order[0] + keep[keep_idx] = i + keep_idx += 1 + + if order.numel() == 1: + break + # Vectorized IoU calculation for remaining boxes + rest = order[1:] + xx1 = torch.maximum(x1[i], x1[rest]) + yy1 = torch.maximum(y1[i], y1[rest]) + xx2 = torch.minimum(x2[i], x2[rest]) + yy2 = torch.minimum(y2[i], y2[rest]) + + # Fast intersection and IoU + w = (xx2 - xx1).clamp_(min=0) + h = (yy2 - yy1).clamp_(min=0) + inter = w * h + # Early exit: skip IoU calculation if no intersection + if inter.sum() == 0: + # No overlaps with current box, keep all remaining boxes + order = rest + continue + iou = inter / (areas[i] + areas[rest] - inter) + # Keep boxes with IoU <= threshold + order = rest[iou <= iou_threshold] + + return keep[:keep_idx] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/ops.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..fc88e86875ff5130017d8feb949547950a84f0ba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/ops.py @@ -0,0 +1,821 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import contextlib +import math +import re +import time + +import cv2 +import numpy as np +import torch +import torch.nn.functional as F + +from ultralytics.utils import NOT_MACOS14, TORCH_VERSION +from ultralytics.utils.checks import check_version +from ultralytics.utils.torch_utils import get_torch_device_backend + + +class Profile(contextlib.ContextDecorator): + """Ultralytics Profile class for timing code execution. + + Use as a decorator with @Profile() or as a context manager with 'with Profile():'. Provides accurate timing + measurements with accelerator synchronization support. + + Attributes: + t (float): Accumulated time in seconds. + device (torch.device): Device used for model inference. + accelerator (module): PyTorch device module used for timing synchronization. + + Examples: + Use as a context manager to time code execution + >>> with Profile() as dt: + ... pass # slow operation here + >>> str(dt).startswith("Elapsed time is ") + True + + Use as a decorator to time function execution + >>> @Profile() + ... def slow_function(): + ... time.sleep(0.1) + """ + + def __init__(self, t: float = 0.0, device: torch.device | None = None): + """Initialize the Profile class. + + Args: + t (float): Initial accumulated time in seconds. + device (torch.device, optional): Device used for model inference to enable accelerator synchronization. + """ + self.t = t + self.device = device + device_type = getattr(device, "type", str(device).split(":")[0] if device else None) + self.accelerator = get_torch_device_backend(device_type) if device_type in {"cuda", "npu", "xpu"} else None + + def __enter__(self): + """Start timing.""" + self.start = self.time() + return self + + def __exit__(self, type, value, traceback): + """Stop timing.""" + self.dt = self.time() - self.start # delta-time + self.t += self.dt # accumulate dt + + def __str__(self): + """Return a human-readable string representing the accumulated elapsed time.""" + return f"Elapsed time is {self.t} s" + + def time(self): + """Get current time with accelerator synchronization if applicable.""" + if self.accelerator is not None: + self.accelerator.synchronize(self.device) + return time.perf_counter() + + +def segment2box(segment: np.ndarray, width: int = 640, height: int = 640) -> np.ndarray: + """Convert segment coordinates to bounding box coordinates. + + Converts a single segment label to a box label by finding the minimum and maximum x and y coordinates of the polygon + clipped to the image, so segments crossing the image boundary keep their visible extent. Segments already inside the + image return immediately without clipping. + + Args: + segment (np.ndarray): Segment coordinates in format (N, 2) where N is number of points. + width (int): Width of the image in pixels. + height (int): Height of the image in pixels. + + Returns: + (np.ndarray): Bounding box coordinates in xyxy format [x1, y1, x2, y2]. + """ + if not len(segment): + return np.zeros(4, dtype=segment.dtype) + x, y = segment[:, 0], segment[:, 1] + xmin, ymin, xmax, ymax = x.min(), y.min(), x.max(), y.max() + if xmin >= 0 and ymin >= 0 and xmax <= width and ymax <= height: # fully inside image + return np.array([xmin, ymin, xmax, ymax], dtype=segment.dtype) + axes = np.array((0, 0, 1, 1)) + bounds = np.array((0, width, 0, height), dtype=segment.dtype) + lims = np.array((height, height, width, width), dtype=segment.dtype) # (height, width)[axis] per boundary + start, delta = segment, np.roll(segment, -1, axis=0) - segment + with np.errstate(divide="ignore", invalid="ignore"): + t = (bounds - start[:, axes]) / delta[:, axes] + inter = start[:, None, :] + t[:, :, None] * delta[:, None, :] + other = inter[:, np.arange(4), 1 - axes] + corners = np.array(((0, 0), (width, 0), (0, height), (width, height)), dtype=segment.dtype) + contour = segment.astype(np.float32) + points = np.concatenate( + ( + segment[(x >= 0) & (y >= 0) & (x <= width) & (y <= height)], + inter[(t >= 0) & (t <= 1) & (other >= 0) & (other <= lims)], + corners[[cv2.pointPolygonTest(contour, tuple(map(float, p)), False) >= 0 for p in corners]], + ) + ) + return ( + np.array([*points.min(0), *points.max(0)], dtype=segment.dtype) + if len(points) + else np.zeros(4, dtype=segment.dtype) + ) + + +def scale_boxes( + img1_shape: tuple[int, int], + boxes: torch.Tensor | np.ndarray, + img0_shape: tuple[int, int], + ratio_pad: tuple | None = None, + padding: bool = True, + xywh: bool = False, +) -> torch.Tensor | np.ndarray: + """Rescale bounding boxes from one image shape to another. + + Rescales bounding boxes from img1_shape to img0_shape, accounting for padding and aspect ratio changes. Supports + both xyxy and xywh box formats. + + Args: + img1_shape (tuple[int, int]): Shape of the source image (height, width). + boxes (torch.Tensor | np.ndarray): Bounding boxes to rescale in format (N, 4). + img0_shape (tuple[int, int]): Shape of the target image (height, width). + ratio_pad (tuple, optional): Ratio and padding as ((ratio_h, ratio_w), (pad_w, pad_h)). + padding (bool): Whether boxes are based on YOLO-style augmented images with padding. + xywh (bool): Whether box format is xywh (True) or xyxy (False). + + Returns: + (torch.Tensor | np.ndarray): Rescaled bounding boxes in the same format as input. + """ + if ratio_pad is None: # calculate from img0_shape + gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new + gain_y = gain_x = gain + pad_x = round((img1_shape[1] - round(img0_shape[1] * gain)) / 2 - 0.1) + pad_y = round((img1_shape[0] - round(img0_shape[0] * gain)) / 2 - 0.1) + else: + gain_y, gain_x = ratio_pad[0] + pad_x, pad_y = ratio_pad[1] + + if padding: + boxes[..., 0] -= pad_x # x padding + boxes[..., 1] -= pad_y # y padding + if not xywh: + boxes[..., 2] -= pad_x # x padding + boxes[..., 3] -= pad_y # y padding + boxes[..., 0] /= gain_x + boxes[..., 1] /= gain_y + boxes[..., 2] /= gain_x + boxes[..., 3] /= gain_y + return boxes if xywh else clip_boxes(boxes, img0_shape) + + +def make_divisible(x: int, divisor): + """Return the smallest number >= x that is divisible by the given divisor. + + Args: + x (int): The number to make divisible. + divisor (int | torch.Tensor): The divisor. + + Returns: + (int): The smallest number >= x divisible by the divisor. + """ + if isinstance(divisor, torch.Tensor): + divisor = int(divisor.max()) # to int + return math.ceil(x / divisor) * divisor + + +def clip_boxes(boxes, shape): + """Clip bounding boxes to image boundaries. + + Args: + boxes (torch.Tensor | np.ndarray): Bounding boxes to clip. + shape (tuple): Image shape as HWC or HW (supports both). + + Returns: + (torch.Tensor | np.ndarray): Clipped bounding boxes. + """ + h, w = shape[:2] # supports both HWC or HW shapes + if isinstance(boxes, torch.Tensor): # faster individually + if NOT_MACOS14 and not (boxes.device.type == "mps" and check_version(TORCH_VERSION, "<2.5.0")): + boxes[..., 0].clamp_(0, w) # x1 + boxes[..., 1].clamp_(0, h) # y1 + boxes[..., 2].clamp_(0, w) # x2 + boxes[..., 3].clamp_(0, h) # y2 + else: # MPS strided in-place bug on macOS 14 or torch<2.5 + boxes[..., 0] = boxes[..., 0].clamp(0, w) + boxes[..., 1] = boxes[..., 1].clamp(0, h) + boxes[..., 2] = boxes[..., 2].clamp(0, w) + boxes[..., 3] = boxes[..., 3].clamp(0, h) + else: # np.array (faster grouped) + boxes[..., [0, 2]] = boxes[..., [0, 2]].clip(0, w) # x1, x2 + boxes[..., [1, 3]] = boxes[..., [1, 3]].clip(0, h) # y1, y2 + return boxes + + +def clip_coords(coords, shape): + """Clip line coordinates to image boundaries. + + Args: + coords (torch.Tensor | np.ndarray): Line coordinates to clip. + shape (tuple): Image shape as HWC or HW (supports both). + + Returns: + (torch.Tensor | np.ndarray): Clipped coordinates. + """ + h, w = shape[:2] # supports both HWC or HW shapes + if isinstance(coords, torch.Tensor): + if NOT_MACOS14 and not (coords.device.type == "mps" and check_version(TORCH_VERSION, "<2.5.0")): + coords[..., 0].clamp_(0, w) # x + coords[..., 1].clamp_(0, h) # y + else: # MPS strided in-place bug on macOS 14 or torch<2.5 + coords[..., 0] = coords[..., 0].clamp(0, w) + coords[..., 1] = coords[..., 1].clamp(0, h) + else: # np.array + coords[..., 0] = coords[..., 0].clip(0, w) # x + coords[..., 1] = coords[..., 1].clip(0, h) # y + return coords + + +def xyxy2xywh(x): + """Convert bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height) format where (x1, y1) is + the top-left corner and (x2, y2) is the bottom-right corner. + + Args: + x (np.ndarray | torch.Tensor): Input bounding box coordinates in (x1, y1, x2, y2) format. + + Returns: + (np.ndarray | torch.Tensor): Bounding box coordinates in (x, y, width, height) format. + """ + assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}" + y = empty_like(x) # faster than clone/copy + x1, y1, x2, y2 = x[..., 0], x[..., 1], x[..., 2], x[..., 3] + y[..., 0] = (x1 + x2) / 2 # x center + y[..., 1] = (y1 + y2) / 2 # y center + y[..., 2] = x2 - x1 # width + y[..., 3] = y2 - y1 # height + return y + + +def xywh2xyxy(x): + """Convert bounding box coordinates from (x, y, width, height) format to (x1, y1, x2, y2) format where (x1, y1) is + the top-left corner and (x2, y2) is the bottom-right corner. Note: ops per 2 channels faster than per channel. + + Args: + x (np.ndarray | torch.Tensor): Input bounding box coordinates in (x, y, width, height) format. + + Returns: + (np.ndarray | torch.Tensor): Bounding box coordinates in (x1, y1, x2, y2) format. + """ + assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}" + y = empty_like(x) # faster than clone/copy + xy = x[..., :2] # centers + wh = x[..., 2:] / 2 # half width-height + y[..., :2] = xy - wh # top left xy + y[..., 2:] = xy + wh # bottom right xy + return y + + +def xywhn2xyxy(x, w: int = 640, h: int = 640, padw: int = 0, padh: int = 0): + """Convert normalized bounding box coordinates to pixel coordinates. + + Args: + x (np.ndarray | torch.Tensor): Normalized bounding box coordinates in (x, y, w, h) format. + w (int): Image width in pixels. + h (int): Image height in pixels. + padw (int): Padding width in pixels. + padh (int): Padding height in pixels. + + Returns: + (np.ndarray | torch.Tensor): Bounding box coordinates in (x1, y1, x2, y2) format. + """ + assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}" + y = empty_like(x) # faster than clone/copy + xc, yc, xw, xh = x[..., 0], x[..., 1], x[..., 2], x[..., 3] + half_w, half_h = xw / 2, xh / 2 + y[..., 0] = w * (xc - half_w) + padw # top left x + y[..., 1] = h * (yc - half_h) + padh # top left y + y[..., 2] = w * (xc + half_w) + padw # bottom right x + y[..., 3] = h * (yc + half_h) + padh # bottom right y + return y + + +def xyxy2xywhn(x, w: int = 640, h: int = 640, clip: bool = False, eps: float = 0.0): + """Convert bounding box coordinates from (x1, y1, x2, y2) format to normalized (x, y, width, height) format. x, y, + width and height are normalized to image dimensions. + + Args: + x (np.ndarray | torch.Tensor): Input bounding box coordinates in (x1, y1, x2, y2) format. + w (int): Image width in pixels. + h (int): Image height in pixels. + clip (bool): Whether to clip boxes to image boundaries. + eps (float): Minimum value for box width and height. + + Returns: + (np.ndarray | torch.Tensor): Normalized bounding box coordinates in (x, y, width, height) format. + """ + if clip: + x = clip_boxes(x, (h - eps, w - eps)) + assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}" + y = empty_like(x) # faster than clone/copy + x1, y1, x2, y2 = x[..., 0], x[..., 1], x[..., 2], x[..., 3] + y[..., 0] = ((x1 + x2) / 2) / w # x center + y[..., 1] = ((y1 + y2) / 2) / h # y center + y[..., 2] = (x2 - x1) / w # width + y[..., 3] = (y2 - y1) / h # height + return y + + +def xywh2ltwh(x): + """Convert bounding box format from [x, y, w, h] to [x1, y1, w, h] where x1, y1 are top-left coordinates. + + Args: + x (np.ndarray | torch.Tensor): Input bounding box coordinates in xywh format. + + Returns: + (np.ndarray | torch.Tensor): Bounding box coordinates in ltwh format. + """ + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[..., 0] = x[..., 0] - x[..., 2] / 2 # top left x + y[..., 1] = x[..., 1] - x[..., 3] / 2 # top left y + return y + + +def xyxy2ltwh(x): + """Convert bounding boxes from [x1, y1, x2, y2] to [x1, y1, w, h] format. + + Args: + x (np.ndarray | torch.Tensor): Input bounding box coordinates in xyxy format. + + Returns: + (np.ndarray | torch.Tensor): Bounding box coordinates in ltwh format. + """ + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[..., 2] = x[..., 2] - x[..., 0] # width + y[..., 3] = x[..., 3] - x[..., 1] # height + return y + + +def ltwh2xywh(x): + """Convert bounding boxes from [x1, y1, w, h] to [x, y, w, h] where xy1=top-left, xy=center. + + Args: + x (np.ndarray | torch.Tensor): Input bounding box coordinates. + + Returns: + (np.ndarray | torch.Tensor): Bounding box coordinates in xywh format. + """ + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[..., 0] = x[..., 0] + x[..., 2] / 2 # center x + y[..., 1] = x[..., 1] + x[..., 3] / 2 # center y + return y + + +def xyxyxyxy2xywhr(x): + """Convert batched Oriented Bounding Boxes (OBB) from [xy1, xy2, xy3, xy4] to [xywh, rotation] format. + + Args: + x (np.ndarray | torch.Tensor): Input box corners with shape (N, 8) or (N, 4, 2) in [xy1, xy2, xy3, xy4] format. + Polygons with more than four points are accepted in the same two layouts, (N, 2P) or (N, P, 2), and are + reduced to their minimum-area rectangle. + + Returns: + (np.ndarray | torch.Tensor): Converted data in [cx, cy, w, h, rotation] format with shape (N, 5). The + parameterization is canonical rather than the caller's: w is the longer side and rotation is in radians + from [-pi/4, 3pi/4), so a box given with w < h comes back with w and h swapped and its angle shifted by + pi/2 modulo pi. + """ + is_torch = isinstance(x, torch.Tensor) + points = x.cpu().numpy() if is_torch else x + rboxes = [] + for pts in points: + # NOTE: Use cv2.minAreaRect to get accurate xywhr, + # especially some objects are cut off by augmentations in dataloader. + (cx, cy), (w, h), angle = cv2.minAreaRect(pts.reshape(-1, 2)) + # convert angle to radian and normalize to [-pi/4, 3pi/4) + theta = angle / 180 * np.pi + if w < h: + w, h = h, w + theta += np.pi / 2 + while theta >= 3 * np.pi / 4: + theta -= np.pi + while theta < -np.pi / 4: + theta += np.pi + rboxes.append([cx, cy, w, h, theta]) + rboxes = np.asarray(rboxes).reshape(-1, 5) # reshape keeps the (0, 5) shape on an empty input + return torch.tensor(rboxes, device=x.device, dtype=x.dtype) if is_torch else rboxes + + +def xywhr2xyxyxyxy(x): + """Convert batched Oriented Bounding Boxes (OBB) from [xywh, rotation] to [xy1, xy2, xy3, xy4] format. + + Args: + x (np.ndarray | torch.Tensor): Boxes in [cx, cy, w, h, rotation] format with shape (N, 5) or (B, N, 5). Rotation + is in radians and is neither range-checked nor normalized; the box is not canonicalized, so converting the + (N, 4, 2) corners back with xyxyxyxy2xywhr returns the canonical form of the same rectangle rather than + these values. + + Returns: + (np.ndarray | torch.Tensor): Converted corner points with shape (N, 4, 2) or (B, N, 4, 2). + """ + cos, sin, cat, stack = ( + (torch.cos, torch.sin, torch.cat, torch.stack) + if isinstance(x, torch.Tensor) + else (np.cos, np.sin, np.concatenate, np.stack) + ) + + ctr = x[..., :2] + w, h, angle = (x[..., i : i + 1] for i in range(2, 5)) + cos_value, sin_value = cos(angle), sin(angle) + vec1 = [w / 2 * cos_value, w / 2 * sin_value] + vec2 = [-h / 2 * sin_value, h / 2 * cos_value] + vec1 = cat(vec1, -1) + vec2 = cat(vec2, -1) + pt1 = ctr + vec1 + vec2 + pt2 = ctr + vec1 - vec2 + pt3 = ctr - vec1 - vec2 + pt4 = ctr - vec1 + vec2 + return stack([pt1, pt2, pt3, pt4], -2) + + +def ltwh2xyxy(x): + """Convert bounding box from [x1, y1, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right. + + Args: + x (np.ndarray | torch.Tensor): Input bounding box coordinates. + + Returns: + (np.ndarray | torch.Tensor): Bounding box coordinates in xyxy format. + """ + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[..., 2] = x[..., 2] + x[..., 0] # x2 + y[..., 3] = x[..., 3] + x[..., 1] # y2 + return y + + +def segments2boxes(segments): + """Convert segment coordinates to bounding box labels in xywh format. + + Args: + segments (list): List of segments where each segment is a list of points, each point is [x, y] coordinates. + + Returns: + (np.ndarray): Bounding box coordinates in xywh format. + """ + boxes = [] + for s in segments: + x, y = s.T # segment xy + boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy + return xyxy2xywh(np.array(boxes).reshape(-1, 4)) # cls, xywh + + +def resample_segments(segments, n: int = 1000): + """Resample segments to n points each using linear interpolation. + + Args: + segments (list): List of (N, 2) arrays where N is the number of points in each segment. + n (int): Number of points to resample each segment to. + + Returns: + (list): Resampled segments with n points each. + """ + for i, s in enumerate(segments): + if len(s) == n: + continue + s = np.concatenate((s, s[0:1, :]), axis=0) + x = np.linspace(0, len(s) - 1, n - len(s) if len(s) < n else n) + xp = np.arange(len(s)) + x = np.insert(x, np.searchsorted(x, xp), xp) if len(s) < n else x + segments[i] = ( + np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)], dtype=np.float32).reshape(2, -1).T + ) # segment xy + return segments + + +def crop_mask(masks: torch.Tensor, boxes: torch.Tensor) -> torch.Tensor: + """Crop masks to bounding box regions. + + Args: + masks (torch.Tensor): Masks with shape (N, H, W). + boxes (torch.Tensor): Bounding box coordinates with shape (N, 4) in xyxy pixel format. + + Returns: + (torch.Tensor): Cropped masks. + """ + if boxes.device != masks.device: + boxes = boxes.to(masks.device) + _, h, w = masks.shape + x1, y1, x2, y2 = torch.chunk(boxes[:, :, None], 4, 1) # each shape (n,1,1) + r = torch.arange(w, device=masks.device, dtype=x1.dtype)[None, None, :] # columns (1,1,w) + c = torch.arange(h, device=masks.device, dtype=x1.dtype)[None, :, None] # rows (1,h,1) + # Apply the column and row masks separately and in place: the box region is separable, so this avoids ever + # materializing the full (n, h, w) boolean grid the combined product would build, and has no per-mask Python loop. + masks *= (r >= x1) * (r < x2) # zero columns outside the box + masks *= (c >= y1) * (c < y2) # zero rows outside the box + return masks + + +def process_mask(protos, masks_in, bboxes, shape, upsample: bool = False): + """Apply masks to bounding boxes using mask head output. + + Args: + protos (torch.Tensor): Mask prototypes with shape (mask_dim, mask_h, mask_w). + masks_in (torch.Tensor): Mask coefficients with shape (N, mask_dim) where N is number of masks after NMS. + bboxes (torch.Tensor): Bounding boxes with shape (N, 4) where N is number of masks after NMS. + shape (tuple): Input image size as (height, width). + upsample (bool): Whether to upsample masks to original image size. + + Returns: + (torch.Tensor): A binary mask tensor of shape [n, h, w], where n is the number of masks after NMS. When + upsample=True h and w match the input image size; otherwise they are the prototype mask resolution. + """ + c, mh, mw = protos.shape # CHW + if masks_in.shape[0] == 0: # no detections: F.interpolate below rejects an empty (N=0) batch + return torch.zeros((0, *(shape if upsample else (mh, mw))), dtype=torch.uint8, device=masks_in.device) + masks = (masks_in @ protos.float().view(c, -1)).view(-1, mh, mw) # NHW + + if upsample: + # Upsample then crop at image resolution; cropping first smears the bilinear edge outside the bbox (#24272) + masks = F.interpolate(masks[None], shape, mode="bilinear")[0] # NHW + else: + width_ratio = mw / shape[1] + height_ratio = mh / shape[0] + ratios = torch.tensor([[width_ratio, height_ratio, width_ratio, height_ratio]], device=bboxes.device) + bboxes = bboxes * ratios # scale boxes to prototype resolution + # Binarize before cropping so crop_mask runs on uint8 instead of float32, as in process_mask_native + return crop_mask(masks.gt_(0.0).byte(), bboxes) + + +def process_mask_native(protos, masks_in, bboxes, shape): + """Apply masks to bounding boxes using mask head output with native upsampling. + + Args: + protos (torch.Tensor): Mask prototypes with shape (mask_dim, mask_h, mask_w). + masks_in (torch.Tensor): Mask coefficients with shape (N, mask_dim) where N is number of masks after NMS. + bboxes (torch.Tensor): Bounding boxes with shape (N, 4) where N is number of masks after NMS. + shape (tuple): Input image size as (height, width). + + Returns: + (torch.Tensor): Binary mask tensor with shape (N, H, W). + """ + c, mh, mw = protos.shape # CHW + h, w = shape + if masks_in.shape[0] == 0: # no detections: return a well-formed empty mask stack + return torch.zeros((0, h, w), dtype=torch.uint8, device=masks_in.device) + coeffs = masks_in @ protos.float().view(c, -1) # (N, mh*mw) prototype-resolution mask logits + # Upsampling all N masks at once allocates an N*H*W float intermediate (~9 GB on a large image with many + # detections), which OOMs the worker. Upsample in chunks bounded by a pixel budget, thresholding each chunk to + # uint8 immediately so the float intermediate stays small, then crop the assembled uint8 stack. + step = max(1, 32_000_000 // (h * w)) + masks = [ + scale_masks(coeffs[i : i + step].view(-1, mh, mw)[None], shape)[0].gt_(0.0).byte() + for i in range(0, coeffs.shape[0], step) + ] + return crop_mask(torch.cat(masks), bboxes) + + +def scale_masks( + masks: torch.Tensor, + shape: tuple[int, int], + ratio_pad: tuple[tuple[int, int], tuple[int, int]] | None = None, + padding: bool = True, + mode: str = "bilinear", +) -> torch.Tensor: + """Rescale segment masks to target shape. + + Args: + masks (torch.Tensor): Masks with shape (N, C, H, W). + shape (tuple[int, int]): Target height and width as (height, width). + ratio_pad (tuple, optional): Ratio and padding values as ((ratio_h, ratio_w), (pad_w, pad_h)). + padding (bool): Whether masks are based on YOLO-style augmented images with padding. + mode (str): Interpolation mode, e.g. 'bilinear' for logits or 'nearest' for integer class maps. + + Returns: + (torch.Tensor): Rescaled masks. + """ + im1_h, im1_w = masks.shape[2:] + im0_h, im0_w = shape[:2] + if im1_h == im0_h and im1_w == im0_w: + return masks + if masks.shape[1] == 0: # empty mask stack: F.interpolate rejects a 0-length channel dim + return masks.new_zeros((*masks.shape[:2], im0_h, im0_w), dtype=torch.float32) + + if ratio_pad is None: # calculate from im0_shape + gain = min(im1_h / im0_h, im1_w / im0_w) # gain = old / new + pad_w, pad_h = (im1_w - round(im0_w * gain)), (im1_h - round(im0_h * gain)) # wh padding + if padding: + pad_w /= 2 + pad_h /= 2 + else: + pad_w, pad_h = ratio_pad[1] + top, left = (round(pad_h - 0.1), round(pad_w - 0.1)) if padding else (0, 0) + bottom = im1_h - round(pad_h + 0.1) + right = im1_w - round(pad_w + 0.1) + return F.interpolate(masks[..., top:bottom, left:right].float(), shape, mode=mode) # NCHW masks + + +def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None, normalize: bool = False, padding: bool = True): + """Rescale segment coordinates from img1_shape to img0_shape. + + Args: + img1_shape (tuple): Source image shape as HWC or HW (supports both). + coords (torch.Tensor): Coordinates to scale with shape (N, 2). + img0_shape (tuple): Image 0 shape as HWC or HW (supports both). + ratio_pad (tuple, optional): Ratio and padding values as ((ratio_h, ratio_w), (pad_w, pad_h)). + normalize (bool): Whether to normalize coordinates to range [0, 1]. + padding (bool): Whether coordinates are based on YOLO-style augmented images with padding. + + Returns: + (torch.Tensor): Scaled coordinates. + """ + img0_h, img0_w = img0_shape[:2] # supports both HWC or HW shapes + if ratio_pad is None: # calculate from img0_shape + img1_h, img1_w = img1_shape[:2] # supports both HWC or HW shapes + gain = min(img1_h / img0_h, img1_w / img0_w) # gain = old / new + gain_y = gain_x = gain + pad = round((img1_w - round(img0_w * gain)) / 2 - 0.1), round((img1_h - round(img0_h * gain)) / 2 - 0.1) + else: + gain_y, gain_x = ratio_pad[0] + pad = ratio_pad[1] + + if padding: + coords[..., 0] -= pad[0] # x padding + coords[..., 1] -= pad[1] # y padding + coords[..., 0] /= gain_x + coords[..., 1] /= gain_y + coords = clip_coords(coords, img0_shape) + if normalize: + coords[..., 0] /= img0_w # width + coords[..., 1] /= img0_h # height + return coords + + +def regularize_rboxes(rboxes): + """Regularize rotated bounding boxes to range [0, pi/2). + + Args: + rboxes (torch.Tensor): Input rotated boxes with shape (N, 5) in xywhr format. + + Returns: + (torch.Tensor): Regularized rotated boxes. + """ + x, y, w, h, t = rboxes.unbind(dim=-1) + # Swap edge if t >= pi/2 while not being symmetrically opposite + swap = t % math.pi >= math.pi / 2 + w_ = torch.where(swap, h, w) + h_ = torch.where(swap, w, h) + t = t % (math.pi / 2) + return torch.stack([x, y, w_, h_, t], dim=-1) # regularized boxes + + +def masks2segments(masks: np.ndarray | torch.Tensor, strategy: str = "all") -> list[np.ndarray]: + """Convert masks to segments using contour detection. + + Args: + masks (np.ndarray | torch.Tensor): Binary masks with shape (N, H, W). + strategy (str): Segmentation strategy, either 'all' or 'largest'. + + Returns: + (list): List of segment masks as float32 arrays. + """ + from ultralytics.data.converter import merge_multi_segment + + masks = masks.astype("uint8") if isinstance(masks, np.ndarray) else masks.byte().cpu().numpy() + segments = [] + for x in np.ascontiguousarray(masks): + c = cv2.findContours(x, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0] + if c: + if strategy == "all": # merge and concatenate all segments + c = ( + np.concatenate(merge_multi_segment([x.reshape(-1, 2) for x in c])) + if len(c) > 1 + else c[0].reshape(-1, 2) + ) + elif strategy == "largest": # select largest segment + c = np.array(c[np.array([len(x) for x in c]).argmax()]).reshape(-1, 2) + else: + c = np.zeros((0, 2)) # no segments found + segments.append(c.astype("float32")) + return segments + + +def convert_torch2numpy_batch(batch: torch.Tensor) -> np.ndarray: + """Convert a batch of FP32 torch tensors to NumPy uint8 arrays, changing from BCHW to BHWC layout. + + Args: + batch (torch.Tensor): Input tensor batch with shape (Batch, Channels, Height, Width) and dtype torch.float32. + + Returns: + (np.ndarray): Output NumPy array batch with shape (Batch, Height, Width, Channels) and dtype uint8. + """ + return (batch.permute(0, 2, 3, 1).contiguous() * 255).clamp(0, 255).byte().cpu().numpy() + + +def clean_str(s): + """Clean a string by replacing special characters with '_' character. + + Args: + s (str): A string needing special characters replaced. + + Returns: + (str): A string with special characters replaced by an underscore _. + """ + return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨`><+]", repl="_", string=s) + + +def empty_like(x): + """Create empty torch.Tensor or np.ndarray with same shape and dtype as input.""" + return torch.empty_like(x, dtype=x.dtype) if isinstance(x, torch.Tensor) else np.empty_like(x, dtype=x.dtype) + + +_assignment_solver = None # resolved once on first call: SciPy's solver if installed, else the NumPy fallback + + +def linear_sum_assignment(cost_matrix): + """Solve the rectangular linear sum assignment problem (minimum-cost one-to-one matching). + + Uses `scipy.optimize.linear_sum_assignment` when SciPy is installed (faster compiled C++ solver), and otherwise + falls back to an equivalent pure-NumPy implementation of the same modified Jonker-Volgenant shortest augmenting path + algorithm (Crouse 2016). This keeps SciPy out of Ultralytics' required dependencies while preserving its speed when + present. SciPy is imported lazily so it never slows `import ultralytics`. For a rectangular matrix only min(rows, + columns) entries are matched. + + The NumPy fallback supports `+inf` as a forbidden assignment and raises `ValueError("cost matrix is infeasible")` + when no assignment exists; callers must sanitize `NaN` and `-inf`. The two backends may return a different + equal-cost assignment under exact ties, but the total cost is identical. + + The NumPy fallback is validated against SciPy with exact optimal-cost parity across ~6.9k randomized cases (every + shape including empty/tall/wide, ties, negatives, IoU- and RT-DETR-style matrices, `maximize` via negation, + torch-tensor input) plus ~2k independent brute-force global-optimum checks. SciPy's compiled inner loop is faster, + but at the call-site sizes (smaller dimension = object count) the fallback runs in well under a millisecond: + + cost matrix NumPy SciPy + 300 x 20 0.2ms 0.02ms + 300 x 80 0.6ms 0.1ms + 300 x 300 28ms 1.5ms + + Args: + cost_matrix (np.ndarray | torch.Tensor): Cost matrix with shape (N, M); `+inf` forbids assignments. + + Returns: + row_ind (np.ndarray): Row indices of the optimal assignment, sorted ascending, with length min(N, M). + col_ind (np.ndarray): Column indices matched to each row in row_ind. + + Examples: + >>> cost = np.array([[4, 1, 3], [2, 0, 5], [3, 2, 2]], dtype=float) + >>> row_ind, col_ind = linear_sum_assignment(cost) + >>> float(cost[row_ind, col_ind].sum()) + 5.0 + """ + global _assignment_solver + if _assignment_solver is None: # resolve the backend once, then reuse it on every later call + try: + from scipy.optimize import linear_sum_assignment as solver # faster compiled C++ solver when installed + + _assignment_solver = solver + except ImportError: + _assignment_solver = _linear_sum_assignment_numpy + return _assignment_solver(np.asarray(cost_matrix, dtype=np.float64)) + + +def _linear_sum_assignment_numpy(a): + """Solve the rectangular linear sum assignment problem with NumPy (Jonker-Volgenant SciPy-free fallback). + + Args: + a (np.ndarray): Float64 cost matrix of shape (N, M); `+inf` forbids assignments. + + Returns: + row_ind (np.ndarray): Row indices of the optimal assignment, sorted ascending, with length min(N, M). + col_ind (np.ndarray): Column indices matched to each row in row_ind. + """ + n, m = a.shape + if n == 0 or m == 0: + return np.empty(0, dtype=np.intp), np.empty(0, dtype=np.intp) + transposed = n > m + if transposed: + a, n, m = a.T, m, n # ensure rows <= columns + u, v = np.zeros(n + 1), np.zeros(m + 1) # row and column dual potentials + p, way = np.zeros(m + 1, np.intp), np.zeros(m + 1, np.intp) # column->row matches and path pointers + for i in range(1, n + 1): + p[0], j0 = i, 0 + minv, used = np.full(m + 1, np.inf), np.zeros(m + 1, bool) + while True: # grow a shortest augmenting path from row i + used[j0] = True + i0 = p[j0] + cur = a[i0 - 1] - u[i0] - v[1:] + improve = (~used[1:]) & (cur < minv[1:]) + minv[1:][improve], way[1:][improve] = cur[improve], j0 + candidates = np.where(used[1:], np.inf, minv[1:]) + j1 = int(np.argmin(candidates)) + 1 + delta = candidates[j1 - 1] + if delta == np.inf: + raise ValueError("cost matrix is infeasible") + u[p[used]] += delta + v[used] -= delta + minv[~used] -= delta + j0 = j1 + if p[j0] == 0: + break + while j0: # augment along the path + p[j0] = p[way[j0]] + j0 = way[j0] + cols = np.nonzero(p[1:])[0] + rows = p[1:][cols] - 1 + row_ind, col_ind = (cols, rows) if transposed else (rows, cols) + order = np.argsort(row_ind, kind="stable") # match scipy's row-sorted output + return row_ind[order].astype(np.intp), col_ind[order].astype(np.intp) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/patches.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/patches.py new file mode 100644 index 0000000000000000000000000000000000000000..a20cca76a858c271aebc97be768018c9d797d983 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/patches.py @@ -0,0 +1,286 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Monkey patches to update/extend functionality of existing functions.""" + +from __future__ import annotations + +import time +from contextlib import contextmanager +from copy import copy +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from PIL import Image + +# OpenCV Multilanguage-friendly functions ------------------------------------------------------------------------------ +_imshow = cv2.imshow # copy to avoid recursion errors +PIL_FALLBACK_SUFFIXES = (".avif", ".heic", ".heif") # formats needing the lazy-PIL decode fallback + + +def imread(filename: str | Path, flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None: + """Read an image from a file with multilanguage filename support. + + Args: + filename (str | Path): Path to the file to read. + flags (int, optional): Flag that can take values of cv2.IMREAD_*. Controls how the image is read. + + Returns: + (np.ndarray | None): The read image array, or None if reading fails. + + Examples: + >>> img = imread("path/to/image.jpg") + >>> img = imread("path/to/image.jpg", cv2.IMREAD_GRAYSCALE) + """ + filename = str(filename) + try: + file_bytes = np.fromfile(filename, np.uint8) + except (FileNotFoundError, OSError): + return None + if flags != cv2.IMREAD_GRAYSCALE and filename.lower().endswith((".tiff", ".tif")): + success, frames = cv2.imdecodemulti(file_bytes, cv2.IMREAD_UNCHANGED) + if not success: + return None + if len(frames) > 1 or frames[0].ndim == 3: + return frames[0] if len(frames) == 1 else np.stack(frames, axis=2) + im = cv2.imdecode(file_bytes, flags) + # Fallback for formats OpenCV imdecode may not support (AVIF, HEIC, HEIF) + if im is None and filename.lower().endswith(PIL_FALLBACK_SUFFIXES): + im = _imread_pil(filename, flags) + return im[..., None] if im is not None and im.ndim == 2 else im # Always ensure 3 dimensions + + +# PIL patches --------------------------------------------------------------------------------------------------------- +_image_open = Image.open # copy to avoid recursion errors +_pil_plugins_registered = False + + +def image_open(filename, *args, **kwargs): + """Open an image with PIL, lazily registering the HEIF plugin on first failure. + + This monkey-patches PIL.Image.open to add HEIC/HEIF support via pi-heif (lightweight, decode-only), avoiding the + ~800ms startup cost of importing the package unless actually needed. AVIF is supported natively by Pillow 12+ and + does not require a plugin. + + Args: + filename (str): Path to the image file. + *args (Any): Additional positional arguments passed to PIL.Image.open. + **kwargs (Any): Additional keyword arguments passed to PIL.Image.open. + + Returns: + (PIL.Image.Image): The opened PIL image. + """ + global _pil_plugins_registered + if _pil_plugins_registered: + return _image_open(filename, *args, **kwargs) + try: + return _image_open(filename, *args, **kwargs) + except Exception: + from ultralytics.utils.checks import check_requirements + + check_requirements("pi-heif") + from pi_heif import register_heif_opener + + register_heif_opener() + _pil_plugins_registered = True + return _image_open(filename, *args, **kwargs) + + +Image.open = image_open # apply patch + + +def _imread_pil(filename: str, flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None: + """Read an image using PIL as fallback for formats not supported by OpenCV. + + Args: + filename (str): Path to the file to read. + flags (int, optional): OpenCV imread flags (used to determine grayscale conversion). + + Returns: + (np.ndarray | None): The read image array in BGR format, or None if reading fails. + """ + try: + with Image.open(filename) as img: + if flags == cv2.IMREAD_GRAYSCALE: + return np.asarray(img.convert("L")) + return cv2.cvtColor(np.asarray(img.convert("RGB")), cv2.COLOR_RGB2BGR) + except Exception: + return None + + +def imread_unicode(filename: str | Path, flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None: + """Read an image with multilanguage filename support, preserving native cv2.imread behavior. + + This is intended as a Windows monkey-patch for cv2.imread. Unlike `imread`, it does not expand grayscale dimensions + or handle TIFF/AVIF/HEIC fallback. + + Args: + filename (str | Path): Path to the file to read. + flags (int, optional): Flag that can take values of cv2.IMREAD_*. + + Returns: + (np.ndarray | None): The read image array, or None if reading fails. + """ + try: + return cv2.imdecode(np.fromfile(filename, np.uint8), flags) + except (FileNotFoundError, OSError): + return None + + +def imwrite(filename: str, img: np.ndarray, params: list[int] | None = None) -> bool: + """Write an image to a file with multilanguage filename support. + + Args: + filename (str): Path to the file to write. + img (np.ndarray): Image to write. + params (list[int], optional): Additional parameters for image encoding. + + Returns: + (bool): True if the file was written successfully, False otherwise. + + Examples: + >>> import numpy as np + >>> img = np.zeros((100, 100, 3), dtype=np.uint8) # Create a black image + >>> success = imwrite("output.jpg", img) # Write image to file + >>> print(success) + True + """ + try: + cv2.imencode(Path(filename).suffix, img, params)[1].tofile(filename) + return True + except Exception: + return False + + +def imshow(winname: str, mat: np.ndarray) -> None: + """Display an image in the specified window with multilanguage window name support. + + This function is a wrapper around OpenCV's imshow function that displays an image in a named window. It handles + multilanguage window names by encoding them properly for OpenCV compatibility. + + Args: + winname (str): Name of the window where the image will be displayed. If a window with this name already exists, + the image will be displayed in that window. + mat (np.ndarray): Image to be shown. Should be a valid numpy array representing an image. + + Examples: + >>> import numpy as np + >>> img = np.zeros((300, 300, 3), dtype=np.uint8) # Create a black image + >>> img[:100, :100] = [255, 0, 0] # Add a blue square + >>> imshow("Example Window", img) # Display the image + """ + _imshow(winname.encode("unicode_escape").decode(), mat) + + +# PyTorch functions ---------------------------------------------------------------------------------------------------- +_torch_save = torch.save + + +def torch_load(*args, **kwargs): + """Load a PyTorch model with updated arguments to avoid warnings. + + This function wraps torch.load and adds the 'weights_only' argument for PyTorch 1.13.0+ to prevent warnings. + + Args: + *args (Any): Variable length argument list to pass to torch.load. + **kwargs (Any): Arbitrary keyword arguments to pass to torch.load. + + Returns: + (Any): The loaded PyTorch object. + + Notes: + For PyTorch versions 1.13 and above, this function automatically sets `weights_only=False` if the argument is + not provided, to avoid deprecation warnings. + """ + from ultralytics.utils.torch_utils import TORCH_1_13 + + if TORCH_1_13 and "weights_only" not in kwargs: + kwargs["weights_only"] = False + + return torch.load(*args, **kwargs) + + +def torch_save(*args, **kwargs): + """Save PyTorch objects with retry mechanism for robustness. + + This function wraps torch.save with 3 retries and exponential backoff in case of save failures, which can occur due + to device flushing delays or antivirus scanning. + + Args: + *args (Any): Positional arguments to pass to torch.save. + **kwargs (Any): Keyword arguments to pass to torch.save. + + Examples: + >>> model = torch.nn.Linear(10, 1) + >>> torch_save(model.state_dict(), "model.pt") + """ + for i in range(4): # 3 retries + try: + return _torch_save(*args, **kwargs) + except RuntimeError: # Unable to save, possibly waiting for device to flush or antivirus scan + if i == 3: + raise + time.sleep((2**i) / 2) # Exponential backoff: 0.5s, 1.0s, 2.0s + + +@contextmanager +def arange_patch(dynamic: bool = False, quantize: int | str | None = None, fmt: str = ""): + """Workaround for ONNX torch.arange incompatibility with FP16. + + https://github.com/pytorch/pytorch/issues/148041. + """ + if dynamic and quantize == 16 and fmt == "onnx": + func = torch.arange + + def arange(*args, dtype=None, **kwargs): + """Wrap torch.arange to cast dtype after creation instead of passing it directly.""" + return func(*args, **kwargs).to(dtype) # cast to dtype instead of passing dtype + + torch.arange = arange # patch + yield + torch.arange = func # unpatch + else: + yield + + +@contextmanager +def onnx_export_patch(): + """Workaround for ONNX export issues in PyTorch 2.9+ with Dynamo enabled.""" + from ultralytics.utils.torch_utils import TORCH_2_9 + + if TORCH_2_9: + func = torch.onnx.export + + def torch_export(*args, **kwargs): + """Export model to ONNX format with Dynamo disabled for compatibility.""" + return func(*args, **kwargs, dynamo=False) + + torch.onnx.export = torch_export # patch + yield + torch.onnx.export = func # unpatch + else: + yield + + +@contextmanager +def override_configs(args, overrides: dict[str, Any] | None = None): + """Context manager to temporarily override configurations in args. + + Args: + args (IterableSimpleNamespace): Original configuration arguments. + overrides (dict[str, Any] | None): Dictionary of overrides to apply. + + Yields: + (IterableSimpleNamespace): Configuration arguments with overrides applied. + """ + if overrides: + original_args = copy(args) + for key, value in overrides.items(): + setattr(args, key, value) + try: + yield args + finally: + args.__dict__.update(original_args.__dict__) + else: + yield args diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/plotting.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/plotting.py new file mode 100644 index 0000000000000000000000000000000000000000..911a4cef5f47f9cfdedf0c617970165555386f24 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/plotting.py @@ -0,0 +1,1440 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import contextlib +import math +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from PIL import Image, ImageDraw, ImageFont +from PIL import __version__ as pil_version + +from ultralytics.utils import IS_COLAB, IS_KAGGLE, LOGGER, TryExcept, ops, plt_settings, threaded +from ultralytics.utils.checks import check_font, check_version, is_ascii +from ultralytics.utils.files import increment_path +from ultralytics.utils.torch_utils import TORCH_1_10 + + +def _gaussian_filter1d(y, sigma: int = 3, truncate: float = 4.0) -> np.ndarray: + """Smooth a 1D array with a Gaussian kernel (NumPy replacement for scipy.ndimage.gaussian_filter1d). + + Args: + y (np.ndarray): Input 1D array to smooth. + sigma (int): Standard deviation of the Gaussian kernel. + truncate (float): Truncate the kernel at this many standard deviations. + + Returns: + (np.ndarray): Smoothed 1D array with the same length as the input. + """ + y = np.asarray(y, dtype=float) + radius = int(truncate * sigma + 0.5) + kernel = np.exp(-0.5 * (np.arange(-radius, radius + 1) / sigma) ** 2) + kernel /= kernel.sum() + # scipy 'reflect' boundary mode is equivalent to NumPy 'symmetric' + return np.convolve(np.pad(y, radius, mode="symmetric"), kernel, mode="valid") + + +class Colors: + """Ultralytics color palette for visualization and plotting. + + This class provides methods to work with the Ultralytics color palette, including converting hex color codes to RGB + values and accessing predefined color schemes for object detection and pose estimation. + + ## Ultralytics Color Palette + + | Index | Color | HEX | RGB | + |-------|-------------------------------------------------------------------|-----------|-------------------| + | 0 | | `#042aff` | (4, 42, 255) | + | 1 | | `#0bdbeb` | (11, 219, 235) | + | 2 | | `#f3f3f3` | (243, 243, 243) | + | 3 | | `#00dfb7` | (0, 223, 183) | + | 4 | | `#111f68` | (17, 31, 104) | + | 5 | | `#ff6fdd` | (255, 111, 221) | + | 6 | | `#ff444f` | (255, 68, 79) | + | 7 | | `#cced00` | (204, 237, 0) | + | 8 | | `#00f344` | (0, 243, 68) | + | 9 | | `#bd00ff` | (189, 0, 255) | + | 10 | | `#00b4ff` | (0, 180, 255) | + | 11 | | `#dd00ba` | (221, 0, 186) | + | 12 | | `#00ffff` | (0, 255, 255) | + | 13 | | `#26c000` | (38, 192, 0) | + | 14 | | `#01ffb3` | (1, 255, 179) | + | 15 | | `#7d24ff` | (125, 36, 255) | + | 16 | | `#7b0068` | (123, 0, 104) | + | 17 | | `#ff1b6c` | (255, 27, 108) | + | 18 | | `#fc6d2f` | (252, 109, 47) | + | 19 | | `#a2ff0b` | (162, 255, 11) | + + ## Pose Color Palette + + | Index | Color | HEX | RGB | + |-------|-------------------------------------------------------------------|-----------|-------------------| + | 0 | | `#ff8000` | (255, 128, 0) | + | 1 | | `#ff9933` | (255, 153, 51) | + | 2 | | `#ffb266` | (255, 178, 102) | + | 3 | | `#e6e600` | (230, 230, 0) | + | 4 | | `#ff99ff` | (255, 153, 255) | + | 5 | | `#99ccff` | (153, 204, 255) | + | 6 | | `#ff66ff` | (255, 102, 255) | + | 7 | | `#ff33ff` | (255, 51, 255) | + | 8 | | `#66b2ff` | (102, 178, 255) | + | 9 | | `#3399ff` | (51, 153, 255) | + | 10 | | `#ff9999` | (255, 153, 153) | + | 11 | | `#ff6666` | (255, 102, 102) | + | 12 | | `#ff3333` | (255, 51, 51) | + | 13 | | `#99ff99` | (153, 255, 153) | + | 14 | | `#66ff66` | (102, 255, 102) | + | 15 | | `#33ff33` | (51, 255, 51) | + | 16 | | `#00ff00` | (0, 255, 0) | + | 17 | | `#0000ff` | (0, 0, 255) | + | 18 | | `#ff0000` | (255, 0, 0) | + | 19 | | `#ffffff` | (255, 255, 255) | + + !!! note "Ultralytics Brand Colors" + + For Ultralytics brand colors see [https://www.ultralytics.com/brand](https://www.ultralytics.com/brand). + Please use the official Ultralytics colors for all marketing materials. + + Attributes: + palette (list[tuple]): List of RGB color tuples for general use. + n (int): The number of colors in the palette. + pose_palette (np.ndarray): A specific color palette array for pose estimation with dtype np.uint8. + + Examples: + >>> from ultralytics.utils.plotting import Colors + >>> colors = Colors() + >>> colors(5, True) # Returns BGR format: (221, 111, 255) + >>> colors(5, False) # Returns RGB format: (255, 111, 221) + """ + + def __init__(self): + """Initialize the Ultralytics color palette from a fixed list of hex color codes.""" + hexs = ( + "042AFF", + "0BDBEB", + "F3F3F3", + "00DFB7", + "111F68", + "FF6FDD", + "FF444F", + "CCED00", + "00F344", + "BD00FF", + "00B4FF", + "DD00BA", + "00FFFF", + "26C000", + "01FFB3", + "7D24FF", + "7B0068", + "FF1B6C", + "FC6D2F", + "A2FF0B", + ) + self.palette = [self.hex2rgb(f"#{c}") for c in hexs] + self.n = len(self.palette) + self.pose_palette = np.array( + [ + [255, 128, 0], + [255, 153, 51], + [255, 178, 102], + [230, 230, 0], + [255, 153, 255], + [153, 204, 255], + [255, 102, 255], + [255, 51, 255], + [102, 178, 255], + [51, 153, 255], + [255, 153, 153], + [255, 102, 102], + [255, 51, 51], + [153, 255, 153], + [102, 255, 102], + [51, 255, 51], + [0, 255, 0], + [0, 0, 255], + [255, 0, 0], + [255, 255, 255], + ], + dtype=np.uint8, + ) + + def __call__(self, i: int | torch.Tensor, bgr: bool = False) -> tuple: + """Return a color from the palette by index. + + Args: + i (int | torch.Tensor): Color index. + bgr (bool, optional): Whether to return BGR format instead of RGB. + + Returns: + (tuple): RGB or BGR color tuple. + """ + c = self.palette[int(i) % self.n] + return (c[2], c[1], c[0]) if bgr else c + + @staticmethod + def hex2rgb(h: str) -> tuple: + """Convert hex color codes to RGB values (i.e. default PIL order).""" + return tuple(int(h[1 + i : 1 + i + 2], 16) for i in (0, 2, 4)) + + +colors = Colors() # create instance for 'from utils.plots import colors' + + +# Spectral_r anchors (RGB, far→near) baked into a LUT so colorize_depth needs no matplotlib import. +_SPECTRAL_R_ANCHORS = np.array( + [ + [94, 79, 162], + [51, 135, 188], + [102, 194, 165], + [170, 220, 164], + [230, 245, 152], + [255, 254, 190], + [254, 224, 139], + [253, 173, 96], + [244, 109, 67], + [212, 61, 79], + [158, 1, 66], + ], + dtype=np.float32, +) + + +def _spectral_lut() -> np.ndarray: + """Build the 256x1x3 BGR uint8 Spectral_r LUT for cv2.applyColorMap by linearly interpolating the anchors.""" + xs = np.linspace(0.0, 10.0, 256) + i = np.clip(xs.astype(int), 0, 9) + f = (xs - i)[:, None] + rgb = _SPECTRAL_R_ANCHORS[i] * (1.0 - f) + _SPECTRAL_R_ANCHORS[i + 1] * f + return rgb.round().astype(np.uint8)[:, ::-1].reshape(256, 1, 3) # RGB→BGR for cv2 convention + + +_SPECTRAL_LUT = _spectral_lut() +_DEPTH_CMAPS = {"inferno": cv2.COLORMAP_INFERNO, "jet": cv2.COLORMAP_JET, "spectral": None} + + +def colorize_depth( + depth: np.ndarray, + vmin: float | None = None, + vmax: float | None = None, + cmap: str = "jet", + mode: str = "disparity", +) -> np.ndarray: + """Map a (H, W) metric-depth array to a BGR uint8 colorized image, invalid (<= 0) pixels black. + + Args: + depth (np.ndarray): (H, W) depth in meters. + vmin (float, optional): Lower bound of the color range; defaults to the valid-pixel minimum (metric mode) or the + 2nd disparity percentile (disparity mode). + vmax (float, optional): Upper bound of the color range; defaults to the valid-pixel maximum (metric mode) or the + 98th disparity percentile (disparity mode). + cmap (str): Colormap, one of "inferno", "jet", "spectral" (matplotlib Spectral_r, near = warm). + mode (str): "metric" normalizes depth linearly; "disparity" normalizes inverse depth (1/d) between the 2nd and + 98th percentiles for the DepthAnything look (near objects warm, robust to far outliers). + + Returns: + (np.ndarray): (H, W, 3) BGR uint8 colorized depth. + """ + d = np.asarray(depth, dtype=np.float32) + valid = d > 0 + v = np.where(valid, 1.0 / np.where(valid, d, 1.0), 0.0) if mode == "disparity" else d + if vmin is None or vmax is None: + pool = v[valid] + if mode == "disparity": + lo, hi = np.percentile(pool, (2, 98)) if pool.size else (0.0, 1.0) + else: + lo, hi = (float(pool.min()), float(pool.max())) if pool.size else (0.0, 1.0) + vmin = lo if vmin is None else vmin + vmax = hi if vmax is None else vmax + if vmax <= vmin: + vmax = vmin + 1e-6 + dn = np.clip((v - vmin) / (vmax - vmin), 0.0, 1.0) + idx = (dn * 255).astype(np.uint8) + lut = _SPECTRAL_LUT if cmap == "spectral" else None + color = cv2.applyColorMap(idx, lut) if lut is not None else cv2.applyColorMap(idx, _DEPTH_CMAPS[cmap]) # BGR + color[~valid] = 0 + return color + + +class Annotator: + """Ultralytics Annotator for train/val mosaics and JPGs and predictions annotations. + + Tensor images must be contiguous HWC BGR uint8. + + Attributes: + im (Image.Image | np.ndarray | torch.Tensor): The image to annotate. + pil (bool): Whether to use PIL or cv2 for drawing annotations. + font (ImageFont.truetype | ImageFont.load_default): Font used for text annotations. + lw (int): Line width for drawing. + skeleton (list[list[int]]): Skeleton structure for keypoints. + limb_color (np.ndarray): Color palette for limbs. + kpt_color (np.ndarray): Color palette for keypoints. + dark_colors (set): Set of colors considered dark for text contrast. + light_colors (set): Set of colors considered light for text contrast. + + Examples: + >>> from ultralytics.utils.plotting import Annotator + >>> im0 = cv2.imread("test.png") + >>> annotator = Annotator(im0, line_width=10) + >>> annotator.box_label([10, 10, 100, 100], "person", (255, 0, 0)) + """ + + def __init__( + self, + im, + line_width: int | None = None, + font_size: int | None = None, + font: str = "Arial.ttf", + pil: bool = False, + example: str = "abc", + ): + """Initialize the Annotator class with image and line width along with color palette for keypoints and limbs.""" + non_ascii = not is_ascii(example) # non-latin labels, i.e. asian, arabic, cyrillic + input_is_pil = isinstance(im, Image.Image) + input_is_tensor = isinstance(im, torch.Tensor) + self.pil = pil or non_ascii or input_is_pil + self.lw = line_width or max(round(sum(im.size if input_is_pil else im.shape) / 2 * 0.003), 2) + if input_is_tensor: + assert im.ndim == 3 and im.shape[2] == 3 and im.dtype == torch.uint8, ( + f"Expected HWC uint8 tensor image with 3 channels, but got shape {tuple(im.shape)} and dtype {im.dtype}." + ) + if self.pil or im.device.type == "cpu": + im, input_is_tensor = im.cpu().numpy(), False + if not input_is_pil: + if im.shape[2] == 1: # handle grayscale + im = cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) + elif im.shape[2] == 2: # handle 2-channel images + im = np.ascontiguousarray(np.dstack((im, np.zeros_like(im[..., :1])))) + elif im.shape[2] > 3: # multispectral + im = np.ascontiguousarray(im[..., :3]) + if self.pil: # use PIL + self.im = im if input_is_pil else Image.fromarray(im) # stay in BGR since color palette is in BGR + if self.im.mode not in {"RGB", "RGBA"}: # multispectral + self.im = self.im.convert("RGB") + self.draw = ImageDraw.Draw(self.im, "RGBA") + try: + font = check_font("Arial.Unicode.ttf" if non_ascii else font) + size = font_size or max(round(sum(self.im.size) / 2 * 0.035), 12) + self.font = ImageFont.truetype(str(font), size) + except Exception: + self.font = ImageFont.load_default() + # Deprecation fix for w, h = getsize(string) -> _, _, w, h = getbox(string) + if check_version(pil_version, "9.2.0"): + self.font.getsize = lambda x: self.font.getbbox(x)[2:4] # text width, height + else: # use cv2 + assert im.is_contiguous() if input_is_tensor else im.data.contiguous, ( + "Image not contiguous. Apply contiguous() or np.ascontiguousarray(im) to Annotator input images." + ) + self.im = im if input_is_tensor or im.flags.writeable else im.copy() + self.tf = max(self.lw - 1, 1) # font thickness + self.sf = self.lw / 3 # font scale + # Pose + self.skeleton = [ + [16, 14], + [14, 12], + [17, 15], + [15, 13], + [12, 13], + [6, 12], + [7, 13], + [6, 7], + [6, 8], + [7, 9], + [8, 10], + [9, 11], + [2, 3], + [1, 2], + [1, 3], + [2, 4], + [3, 5], + [4, 6], + [5, 7], + ] + + self.limb_color = colors.pose_palette[[9, 9, 9, 9, 7, 7, 7, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16]] + self.kpt_color = colors.pose_palette[[16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9]] + self.dark_colors = { + (235, 219, 11), + (243, 243, 243), + (183, 223, 0), + (221, 111, 255), + (0, 237, 204), + (68, 243, 0), + (255, 255, 0), + (179, 255, 1), + (11, 255, 162), + } + self.light_colors = { + (255, 42, 4), + (79, 68, 255), + (255, 0, 189), + (255, 180, 0), + (186, 0, 221), + (0, 192, 38), + (255, 36, 125), + (104, 0, 123), + (108, 27, 255), + (47, 109, 252), + (104, 31, 17), + } + + def get_txt_color(self, color: tuple = (128, 128, 128), txt_color: tuple = (255, 255, 255)) -> tuple: + """Assign text color based on background color. + + Args: + color (tuple, optional): The background color of the rectangle for text. + txt_color (tuple, optional): The fallback color of the text. + + Returns: + (tuple): Text color for label. + + Examples: + >>> from ultralytics.utils.plotting import Annotator + >>> im0 = cv2.imread("test.png") + >>> annotator = Annotator(im0, line_width=10) + >>> annotator.get_txt_color(color=(104, 31, 17)) # return (255, 255, 255) + """ + if color in self.dark_colors: + return 104, 31, 17 + elif color in self.light_colors: + return 255, 255, 255 + else: + return txt_color + + def box_label(self, box, label: str = "", color: tuple = (128, 128, 128), txt_color: tuple = (255, 255, 255)): + """Draw a bounding box on an image with a given label. + + Args: + box (tuple): The bounding box coordinates (x1, y1, x2, y2). + label (str, optional): The text label to be displayed. + color (tuple, optional): The background color of the rectangle. + txt_color (tuple, optional): The color of the text. + + Examples: + >>> from ultralytics.utils.plotting import Annotator + >>> im0 = cv2.imread("test.png") + >>> annotator = Annotator(im0, line_width=10) + >>> annotator.box_label(box=[10, 20, 30, 40], label="person") + """ + self._to_numpy() + txt_color = self.get_txt_color(color, txt_color) + if isinstance(box, (torch.Tensor, np.ndarray)): + box = box.tolist() + + multi_points = isinstance(box[0], list) # multiple points with shape (n, 2) + p1 = [int(b) for b in box[0]] if multi_points else (int(box[0]), int(box[1])) + if self.pil: + self.draw.polygon( + [tuple(b) for b in box], width=self.lw, outline=color + ) if multi_points else self.draw.rectangle(box, width=self.lw, outline=color) + if label: + w, h = self.font.getsize(label) # text width, height + outside = p1[1] >= h # label fits outside box + if p1[0] > self.im.size[0] - w: # size is (w, h), check if label extend beyond right side of image + p1 = self.im.size[0] - w, p1[1] + self.draw.rectangle( + (p1[0], p1[1] - h if outside else p1[1], p1[0] + w + 1, p1[1] + 1 if outside else p1[1] + h + 1), + fill=color, + ) + # self.draw.text([box[0], box[1]], label, fill=txt_color, font=self.font, anchor='ls') # for PIL>8.0 + self.draw.text((p1[0], p1[1] - h if outside else p1[1]), label, fill=txt_color, font=self.font) + else: # cv2 + cv2.polylines( + self.im, [np.asarray(box, dtype=int)], True, color, self.lw + ) if multi_points else cv2.rectangle( + self.im, p1, (int(box[2]), int(box[3])), color, thickness=self.lw, lineType=cv2.LINE_AA + ) + if label: + w, h = cv2.getTextSize(label, 0, fontScale=self.sf, thickness=self.tf)[0] # text width, height + h += 3 # add pixels to pad text + outside = p1[1] >= h # label fits outside box + if p1[0] > self.im.shape[1] - w: # shape is (h, w), check if label extend beyond right side of image + p1 = self.im.shape[1] - w, p1[1] + p2 = p1[0] + w, p1[1] - h if outside else p1[1] + h + cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled + cv2.putText( + self.im, + label, + (p1[0], p1[1] - 2 if outside else p1[1] + h - 1), + 0, + self.sf, + txt_color, + thickness=self.tf, + lineType=cv2.LINE_AA, + ) + + def masks(self, masks, colors, alpha: float = 0.5): + """Plot masks on image. + + Args: + masks (torch.Tensor | np.ndarray): Predicted masks with shape [n, h, w]. + colors (list[list[int]]): BGR colors for predicted masks, [[b, g, r] * n], matching `self.im`. + alpha (float, optional): Mask transparency: 0.0 fully transparent, 1.0 opaque. + """ + if self.pil: + # Convert to numpy first + self.im = np.asarray(self.im).copy() + if isinstance(masks, np.ndarray): + self._to_numpy() + overlay = self.im.copy() + for i, mask in enumerate(masks): + overlay[mask.astype(bool)] = colors[i] + self.im = cv2.addWeighted(self.im, 1 - alpha, overlay, alpha, 0) + elif len(masks): + # Use scale_masks to properly remove padding and upsample, convert bool to float first + tensor_image = isinstance(self.im, torch.Tensor) + device = self.im.device if tensor_image else masks.device + masks = ops.scale_masks(masks[None].to(device).float(), self.im.shape[:2])[0] > 0.5 + colors = torch.tensor(colors, device=device, dtype=torch.float32) / 255.0 # shape(n,3) + colors = colors[:, None, None] * alpha # shape(n,1,1,3), premultiplied by alpha + masks = masks.unsqueeze(3) # shape(n,h,w,1) + mcs = torch.empty((*masks.shape[1:3], 3), device=device, dtype=torch.float32) # shape(h,w,3) + inv_alpha_masks = torch.empty((*masks.shape[1:3], 1), device=device, dtype=torch.float32) # shape(h,w,1) + # Reduce in row bands so the (n,h,w,*) intermediates never span the full height + bands = max(1, masks.numel() * 12 // 2**23) # 12 bytes per mask element downstream, 8 MB per band + for m, mcs_band, inv_band in zip(masks.chunk(bands, 1), mcs.chunk(bands), inv_alpha_masks.chunk(bands)): + torch.amax(m * colors, 0, out=mcs_band) + torch.prod(1 - m * alpha, 0, out=inv_band) + im = (self.im if tensor_image else torch.from_numpy(self.im)).to(device).float() / 255.0 + im = ((im * inv_alpha_masks + mcs) * 255).byte() + self.im[:] = im if tensor_image else im.cpu().numpy() + if self.pil: + # Convert im back to PIL and update draw + self.fromarray(self.im) + + def semantic_mask(self, mask, alpha: float = 0.5, ignore_index: int = 255): + """Plot a semantic segmentation mask on the image. + + Args: + mask (np.ndarray): Semantic mask with shape [h, w] containing integer class indices. + alpha (float, optional): Mask transparency: 0.0 fully transparent, 1.0 opaque. + ignore_index (int, optional): Class index to ignore (e.g., 255 for void/ignore). + """ + self._to_numpy() + if self.pil: + # Convert to numpy first + self.im = np.asarray(self.im).copy() + ids = np.unique(mask) # class IDs present, ascending + palette = np.array([(0, 0, 0) if i == ignore_index else colors(int(i), True) for i in ids], self.im.dtype) + overlay = palette[np.searchsorted(ids, mask)] if len(ids) else np.zeros_like(self.im) + self.im = cv2.addWeighted(self.im, 1 - alpha, overlay, alpha, 0) + if self.pil: + # Convert im back to PIL and update draw + self.fromarray(self.im) + + def depth_map( + self, + depth: np.ndarray, + alpha: float = 0.6, + cmap: str = "jet", + mode: str = "disparity", + ) -> None: + """Render a colorized depth map blended over the image. + + Args: + depth (np.ndarray): (H, W) depth in meters. + alpha (float): Blend factor for the heatmap overlay. + cmap (str): Colormap, one of "inferno", "jet", "spectral". See `colorize_depth`. + mode (str): "metric" or "disparity" normalization. See `colorize_depth`. + """ + self._to_numpy() + if self.pil: + self.im = np.asarray(self.im).copy() + heat = colorize_depth(depth, cmap=cmap, mode=mode) # BGR, matching the Annotator buffer convention + if heat.shape[:2] != self.im.shape[:2]: + heat = cv2.resize(heat, (self.im.shape[1], self.im.shape[0])) + self.im = cv2.addWeighted(self.im, 1 - alpha, heat, alpha, 0) + if self.pil: + self.fromarray(self.im) + + def kpts( + self, + kpts, + shape: tuple = (640, 640), + radius: int | None = None, + kpt_line: bool = True, + conf_thres: float = 0.25, + kpt_color: tuple | None = None, + ): + """Plot keypoints on the image. + + Args: + kpts (torch.Tensor): Keypoints, shape [17, 3] (x, y, confidence). + shape (tuple, optional): Image shape (h, w). + radius (int, optional): Keypoint radius. + kpt_line (bool, optional): Draw lines between keypoints. + conf_thres (float, optional): Confidence threshold. + kpt_color (tuple, optional): Keypoint color. + + Notes: + - `kpt_line=True` currently only supports human pose plotting. + - Modifies self.im in-place. + - If self.pil is True, converts image to numpy array and back to PIL. + """ + radius = radius if radius is not None else self.lw + self._to_numpy() + if self.pil: + # Convert to numpy first + self.im = np.asarray(self.im).copy() + nkpt, ndim = kpts.shape + is_pose = nkpt == 17 and ndim in {2, 3} + kpt_line &= is_pose # `kpt_line=True` for now only supports human pose plotting + for i, k in enumerate(kpts): + color_k = kpt_color or (self.kpt_color[i].tolist() if is_pose else colors(i)) + x_coord, y_coord = k[0], k[1] + if len(k) == 3: + if k[2] < conf_thres: + continue + elif x_coord == 0 and y_coord == 0: # (0, 0) marks a missing keypoint when there is no confidence channel + continue + cv2.circle(self.im, (int(x_coord), int(y_coord)), radius, color_k, -1, lineType=cv2.LINE_AA) + + if kpt_line: + ndim = kpts.shape[-1] + for i, sk in enumerate(self.skeleton): + pos1 = (int(kpts[(sk[0] - 1), 0]), int(kpts[(sk[0] - 1), 1])) + pos2 = (int(kpts[(sk[1] - 1), 0]), int(kpts[(sk[1] - 1), 1])) + if ndim == 3: + conf1 = kpts[(sk[0] - 1), 2] + conf2 = kpts[(sk[1] - 1), 2] + if conf1 < conf_thres or conf2 < conf_thres: + continue + elif not (kpts[sk[0] - 1, :2].any() and kpts[sk[1] - 1, :2].any()): # (0, 0) marks a missing keypoint + continue + if min(pos1 + pos2) < 0: + continue + cv2.line( + self.im, + pos1, + pos2, + kpt_color or self.limb_color[i].tolist(), + thickness=int(np.ceil(self.lw / 2)), + lineType=cv2.LINE_AA, + ) + if self.pil: + # Convert im back to PIL and update draw + self.fromarray(self.im) + + def rectangle(self, xy, fill=None, outline=None, width: int = 1): + """Add rectangle to image (PIL-only).""" + self.draw.rectangle(xy, fill, outline, width) + + def text(self, xy, text: str, txt_color: tuple = (255, 255, 255), anchor: str = "top", box_color: tuple = ()): + """Add text to an image using PIL or cv2. + + Args: + xy (list[int]): Top-left coordinates for text placement. + text (str): Text to be drawn. + txt_color (tuple, optional): Text color. + anchor (str, optional): Text anchor position ('top' or 'bottom'). + box_color (tuple, optional): Box background color with optional alpha. + """ + self._to_numpy() + if self.pil: + w, h = self.font.getsize(text) + if anchor == "bottom": # start y from font bottom + xy[1] += 1 - h + for line in text.split("\n"): + if box_color: + # Draw rectangle for each line + w, h = self.font.getsize(line) + self.draw.rectangle((xy[0], xy[1], xy[0] + w + 1, xy[1] + h + 1), fill=box_color) + self.draw.text(xy, line, fill=txt_color, font=self.font) + xy[1] += h + else: + if box_color: + w, h = cv2.getTextSize(text, 0, fontScale=self.sf, thickness=self.tf)[0] + h += 3 # add pixels to pad text + outside = xy[1] >= h # label fits outside box + p2 = xy[0] + w, xy[1] - h if outside else xy[1] + h + cv2.rectangle(self.im, xy, p2, box_color, -1, cv2.LINE_AA) # filled + cv2.putText(self.im, text, xy, 0, self.sf, txt_color, thickness=self.tf, lineType=cv2.LINE_AA) + + def fromarray(self, im): + """Update `self.im` from a NumPy array or PIL image.""" + self.im = im if isinstance(im, Image.Image) else Image.fromarray(im) + self.draw = ImageDraw.Draw(self.im) + + def _to_numpy(self): + """Move a tensor image to CPU only when a CPU drawing operation requires it.""" + if isinstance(self.im, torch.Tensor): + self.im = self.im.cpu().numpy() + + def result(self, pil=False): + """Return annotated image as array or PIL image.""" + self._to_numpy() + im = np.asarray(self.im) # self.im is in BGR + return Image.fromarray(im[..., ::-1]) if pil else im + + def show(self, title: str | None = None): + """Show the annotated image.""" + im = Image.fromarray(self.result()[..., ::-1]) # Convert BGR NumPy array to RGB PIL Image + if IS_COLAB or IS_KAGGLE: # cannot use IS_JUPYTER as it runs for all IPython environments + try: + display(im) # noqa - display() function only available in ipython environments + except ImportError as e: + LOGGER.warning(f"Unable to display image in Jupyter notebooks: {e}") + else: + im.show(title=title) + + def save(self, filename: str = "image.jpg"): + """Save the annotated image to 'filename'.""" + cv2.imwrite(filename, self.result()) + + @staticmethod + def get_bbox_dimension(bbox: tuple | list): + """Calculate the dimensions and area of a bounding box. + + Args: + bbox (tuple | list): Bounding box coordinates in the format (x_min, y_min, x_max, y_max). + + Returns: + width (float): Width of the bounding box. + height (float): Height of the bounding box. + area (float): Area enclosed by the bounding box. + + Examples: + >>> from ultralytics.utils.plotting import Annotator + >>> im0 = cv2.imread("test.png") + >>> annotator = Annotator(im0, line_width=10) + >>> annotator.get_bbox_dimension(bbox=[10, 20, 30, 40]) + """ + x_min, y_min, x_max, y_max = bbox + width = x_max - x_min + height = y_max - y_min + return width, height, width * height + + +@TryExcept() +@plt_settings() +def plot_labels(boxes, cls, names=(), save_dir=Path(""), on_plot=None): + """Plot training labels including class histograms and box statistics. + + Args: + boxes (np.ndarray): Bounding box coordinates in format [x, y, width, height]. + cls (np.ndarray): Class indices. + names (dict, optional): Dictionary mapping class indices to class names. + save_dir (Path, optional): Directory to save the plot. + on_plot (Callable, optional): Function to call after plot is saved. + """ + import matplotlib.pyplot as plt # scope for faster 'import ultralytics' + import polars + from matplotlib.colors import LinearSegmentedColormap + + # Plot dataset labels + LOGGER.info(f"Plotting labels to {save_dir / 'labels.jpg'}... ") + nc = int(cls.max() + 1) # number of classes + boxes = boxes[:1000000] # limit to 1M boxes + x = polars.DataFrame(boxes, schema=["x", "y", "width", "height"]) + + # Matplotlib labels + subplot_3_4_color = LinearSegmentedColormap.from_list("white_blue", ["white", "blue"]) + ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel() + y = ax[0].hist(cls, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8) + for i in range(nc): + y[2].patches[i].set_color([x / 255 for x in colors(i)]) + ax[0].set_ylabel("instances") + if 0 < len(names) < 30: + ax[0].set_xticks(range(len(names))) + ax[0].set_xticklabels(list(names.values()), rotation=90, fontsize=10) + ax[0].bar_label(y[2]) + else: + ax[0].set_xlabel("classes") + boxes = np.column_stack([0.5 - boxes[:, 2:4] / 2, 0.5 + boxes[:, 2:4] / 2]) * 1000 + img = Image.fromarray(np.ones((1000, 1000, 3), dtype=np.uint8) * 255) + for class_id, box in zip(cls[:500], boxes[:500]): + ImageDraw.Draw(img).rectangle(box.tolist(), width=1, outline=colors(class_id)) # plot + ax[1].imshow(img) + ax[1].axis("off") + + ax[2].hist2d(x["x"], x["y"], bins=50, cmap=subplot_3_4_color) + ax[2].set_xlabel("x") + ax[2].set_ylabel("y") + ax[3].hist2d(x["width"], x["height"], bins=50, cmap=subplot_3_4_color) + ax[3].set_xlabel("width") + ax[3].set_ylabel("height") + for a in (0, 1, 2, 3): + for s in ("top", "right", "left", "bottom"): + ax[a].spines[s].set_visible(False) + + fname = save_dir / "labels.jpg" + plt.savefig(fname, dpi=200) + plt.close() + if on_plot: + on_plot(fname) + + +def save_one_box( + xyxy, + im, + file: Path = Path("im.jpg"), + gain: float = 1.02, + pad: int = 10, + square: bool = False, + BGR: bool = False, + save: bool = True, +): + """Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop. + + This function takes a bounding box and an image, and then saves a cropped portion of the image according to the + bounding box. Optionally, the crop can be squared, and the function allows for gain and padding adjustments to the + bounding box. + + Args: + xyxy (torch.Tensor | list): A tensor or list representing the bounding box in xyxy format. + im (np.ndarray): The input image. + file (Path, optional): The path where the cropped image will be saved. + gain (float, optional): A multiplicative factor to increase the size of the bounding box. + pad (int, optional): The number of pixels to add to the width and height of the bounding box. + square (bool, optional): If True, the bounding box will be transformed into a square. + BGR (bool, optional): If True, the image will be returned in BGR format, otherwise in RGB. + save (bool, optional): If True, the cropped image will be saved to disk. + + Returns: + (np.ndarray): The cropped image. + + Examples: + >>> from ultralytics.utils.plotting import save_one_box + >>> xyxy = [50, 50, 150, 150] + >>> im = cv2.imread("image.jpg") + >>> cropped_im = save_one_box(xyxy, im, file="cropped.jpg", square=True) + """ + if not isinstance(xyxy, torch.Tensor): + xyxy = torch.as_tensor(xyxy) # list, tuple, or ndarray + b = ops.xyxy2xywh(xyxy.view(-1, 4)) # boxes + if square: + b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # attempt rectangle to square + b[:, 2:] = b[:, 2:] * gain + pad # box wh * gain + pad + xyxy = ops.xywh2xyxy(b).long() + xyxy = ops.clip_boxes(xyxy, im.shape) + grayscale = im.shape[2] == 1 # grayscale image + crop = im[int(xyxy[0, 1]) : int(xyxy[0, 3]), int(xyxy[0, 0]) : int(xyxy[0, 2]), :: (1 if BGR or grayscale else -1)] + if save: + file.parent.mkdir(parents=True, exist_ok=True) # make directory + f = str(increment_path(file).with_suffix(".jpg")) + # cv2.imwrite(f, crop) # save BGR, https://github.com/ultralytics/yolov5/issues/7007 chroma subsampling issue + im_save = crop.squeeze(-1) if grayscale else crop[..., ::-1] if BGR else crop + Image.fromarray(im_save).save(f, quality=95, subsampling=0) # save RGB + return crop + + +@threaded +def plot_images( + labels: dict[str, Any], + images: torch.Tensor | np.ndarray | None = None, + paths: list[str] | None = None, + fname: str = "images.jpg", + names: dict[int, str] | None = None, + on_plot: Callable | None = None, + max_size: int = 1920, + max_subplots: int = 16, + save: bool = True, + conf_thres: float = 0.25, + show_labels: bool = True, + show_conf: bool = True, +) -> np.ndarray | None: + """Plot image grid with labels, bounding boxes, masks, and keypoints. + + Args: + labels (dict[str, Any]): Dictionary containing detection data with keys like 'cls', 'bboxes', 'conf', 'masks', + 'keypoints', 'batch_idx', 'img'. + images (torch.Tensor | np.ndarray): Batch of images to plot. Shape: (batch_size, channels, height, width). + paths (list[str] | None): List of file paths for each image in the batch. + fname (str): Output filename for the plotted image grid. + names (dict[int, str] | None): Dictionary mapping class indices to class names. + on_plot (Callable | None): Callback function to be called after saving the plot. + max_size (int): Maximum size of the output image grid. + max_subplots (int): Maximum number of subplots in the image grid. + save (bool): Whether to save the plotted image grid to a file. + conf_thres (float): Confidence threshold for displaying detections. + show_labels (bool): Whether to display class labels. + show_conf (bool): Whether to display confidence values. + + Returns: + (np.ndarray | None): Plotted image grid as a numpy array if save is False, None otherwise. + + Notes: + This function supports both tensor and numpy array inputs. It will automatically + convert tensor inputs to numpy arrays for processing. + + Channel Support: + - 1 channel: Grayscale + - 2 channels: Third channel added as zeros + - 3 channels: Used as-is (standard RGB) + - 4+ channels: Cropped to first 3 channels + """ + images = np.zeros((0, 3, 640, 640), dtype=np.float32) if images is None else images + for k in ("cls", "bboxes", "conf", "masks", "keypoints", "batch_idx", "images", "semantic_mask", "depth"): + if k not in labels: + continue + if k == "cls" and labels[k].ndim == 2: + labels[k] = labels[k].squeeze(1) # squeeze if shape is (n, 1) + if isinstance(labels[k], torch.Tensor): + labels[k] = labels[k].cpu().numpy() + + cls = labels.get("cls", np.zeros(0, dtype=np.int64)) + batch_idx = labels.get("batch_idx", np.zeros(cls.shape, dtype=np.int64)) + bboxes = labels.get("bboxes", np.zeros(0, dtype=np.float32)) + confs = labels.get("conf", None) + masks = labels.get("masks", np.zeros(0, dtype=np.uint8)) + kpts = labels.get("keypoints", np.zeros(0, dtype=np.float32)) + semantic_masks = labels.get("semantic_mask", np.zeros(0, dtype=np.int64)) + depth_maps = labels.get("depth", np.zeros(0, dtype=np.float32)) + images = labels.get("img", images) # default to input images + + if len(images) and isinstance(images, torch.Tensor): + images = images.cpu().float().numpy() + + # Handle 2-ch and n-ch images + c = images.shape[1] + if c == 2: + zero = np.zeros_like(images[:, :1]) + images = np.concatenate((images, zero), axis=1) # pad 2-ch with a black channel + elif c > 3: + images = images[:, :3] # crop multispectral images to first 3 channels + + bs, _, h, w = images.shape # batch size, _, height, width + bs = min(bs, max_subplots) # limit plot images + ns = np.ceil(bs**0.5) # number of subplots (square) + if np.max(images[0]) <= 1: + images *= 255 # de-normalise (optional) + + # Build Image + mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init + for i in range(bs): + x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin + mosaic[y : y + h, x : x + w, :] = images[i].transpose(1, 2, 0) + + # Resize (optional) + scale = max_size / ns / max(h, w) + if scale < 1: + h = math.ceil(scale * h) + w = math.ceil(scale * w) + mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h))) + + # Annotate + fs = int((h + w) * ns * 0.01) # font size + fs = max(fs, 18) # ensure that the font size is large enough to be easily readable. + annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=str(names)) + for i in range(bs): + x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin + annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders + if paths: + annotator.text([x + 5, y + 5], text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames + if len(cls) > 0: + idx = batch_idx == i + classes = cls[idx].astype("int") + labels = confs is None + conf = confs[idx] if confs is not None else None # check for confidence presence (label vs pred) + + if len(bboxes): + boxes = bboxes[idx] + if len(boxes): + if boxes[:, :4].max() <= 1.1: # if normalized with tolerance 0.1 + boxes[..., [0, 2]] *= w # scale to pixels + boxes[..., [1, 3]] *= h + elif scale < 1: # absolute coords need scale if image scales + boxes[..., :4] *= scale + boxes[..., 0] += x + boxes[..., 1] += y + is_obb = boxes.shape[-1] == 5 # xywhr + boxes = ops.xywhr2xyxyxyxy(boxes) if is_obb else ops.xywh2xyxy(boxes) + for j, box in enumerate(boxes.astype(np.int64).tolist()): + c = classes[j] + color = colors(c) + c = names.get(c, c) if names else c + if labels or conf[j] > conf_thres: + conf_text = f"{conf[j]:.1f}" if conf is not None else "" + label = f"{c}" if show_labels else "" + label += f" {conf_text}".strip() if show_conf else "" + annotator.box_label(box, label, color=color) + + elif len(classes): + for c in classes: + color = colors(c) + c = names.get(c, c) if names else c + label = f"{c}" if labels else f"{c} {conf[0]:.1f}" + annotator.text([x, y], label, txt_color=color, box_color=(64, 64, 64, 128)) + + # Plot keypoints + if len(kpts): + kpts_ = kpts[idx].copy() + if len(kpts_): + if kpts_[..., 0].max() <= 1.01 or kpts_[..., 1].max() <= 1.01: # if normalized with tolerance .01 + kpts_[..., 0] *= w # scale to pixels + kpts_[..., 1] *= h + elif scale < 1: # absolute coords need scale if image scales + kpts_[..., :2] *= scale + kpts_[..., 0] += x + kpts_[..., 1] += y + for j in range(len(kpts_)): + if labels or conf[j] > conf_thres: + annotator.kpts(kpts_[j], conf_thres=conf_thres) + + # Plot masks + if len(masks): + if idx.shape[0] == masks.shape[0] and masks.max() <= 1: # overlap_mask=False + image_masks = masks[idx] + else: # overlap_mask=True + image_masks = masks[[i]] # (1, 640, 640) + nl = idx.sum() + index = np.arange(1, nl + 1).reshape((nl, 1, 1)) + image_masks = (image_masks == index).astype(np.float32) + + im = np.asarray(annotator.im).copy() + for j in range(len(image_masks)): + if labels or conf[j] > conf_thres: + color = colors(classes[j]) + mh, mw = image_masks[j].shape + if mh != h or mw != w: + mask = image_masks[j].astype(np.uint8) + mask = cv2.resize(mask, (w, h)) + mask = mask.astype(bool) + else: + mask = image_masks[j].astype(bool) + try: + im[y : y + h, x : x + w, :][mask] = ( + im[y : y + h, x : x + w, :][mask] * 0.4 + np.array(color) * 0.6 + ) + except Exception: + pass + annotator.fromarray(im) + + # Plot semantic masks + if len(semantic_masks) and i < len(semantic_masks): + mask = semantic_masks[i] + mh, mw = mask.shape + if mh != h or mw != w: + mask = cv2.resize(mask.astype(np.uint8), (w, h), interpolation=cv2.INTER_NEAREST) + im = np.asarray(annotator.im).copy() + sub_annotator = Annotator(np.ascontiguousarray(im[y : y + h, x : x + w]), line_width=1, pil=False) + sub_annotator.semantic_mask(mask, alpha=0.4) + im[y : y + h, x : x + w] = sub_annotator.im + annotator.fromarray(im) + + # Plot depth maps + if len(depth_maps) and i < len(depth_maps): + d = depth_maps[i] + if d.ndim == 3: + d = d.squeeze(0) + dh, dw = d.shape + if dh != h or dw != w: + d = cv2.resize(d.astype(np.float32), (w, h), interpolation=cv2.INTER_NEAREST) + im = np.asarray(annotator.im).copy() + # The mosaic deviates from the Annotator BGR-buffer convention (it holds RGB), so convert the patch + # to BGR for the overlay, then back to RGB for the mosaic. + sub_bgr = cv2.cvtColor(np.ascontiguousarray(im[y : y + h, x : x + w]), cv2.COLOR_RGB2BGR) + sub_annotator = Annotator(sub_bgr, line_width=1, pil=False) + sub_annotator.depth_map(d, alpha=0.6) + im[y : y + h, x : x + w] = cv2.cvtColor(sub_annotator.im, cv2.COLOR_BGR2RGB) + annotator.fromarray(im) + + if not save: + return np.asarray(annotator.im) + annotator.im.save(fname) # save + if on_plot: + on_plot(fname) + + +@plt_settings() +def plot_results(file: str = "path/to/results.csv", dir: str = "", on_plot: Callable | None = None): + """Plot training results from a results CSV file. The function supports various types of data including detection, + instance segmentation, semantic segmentation, depth estimation, classification, and pose estimation. Plots are + saved as 'results.png' in the directory where the CSV is located. + + Args: + file (str, optional): Path to the CSV file containing the training results. + dir (str, optional): Directory where the CSV file is located if 'file' is not provided. + on_plot (Callable, optional): Callback function to be executed after plotting. Takes filename as an argument. + + Examples: + >>> from ultralytics.utils.plotting import plot_results + >>> plot_results("path/to/results.csv") + """ + import matplotlib.pyplot as plt # scope for faster 'import ultralytics' + import polars as pl + + save_dir = Path(file).parent if file else Path(dir) + files = list(save_dir.glob("results*.csv")) + assert len(files), f"No results.csv files found in {save_dir.resolve()}, nothing to plot." + + loss_keys, metric_keys = [], [] + fig, ax = None, None + for i, f in enumerate(files): + try: + data = pl.read_csv(f, infer_schema_length=None) + if i == 0: + for c in data.columns: + if "loss" in c: + loss_keys.append(c) + elif "metric" in c: + metric_keys.append(c) + loss_mid, metric_mid = len(loss_keys) // 2, len(metric_keys) // 2 + columns = ( + loss_keys[:loss_mid] + metric_keys[:metric_mid] + loss_keys[loss_mid:] + metric_keys[metric_mid:] + ) + fig, ax = plt.subplots(2, len(columns) // 2, figsize=(len(columns) + 2, 6), tight_layout=True) + ax = ax.ravel() + x = data.select(data.columns[0]).to_numpy().flatten() + for i, j in enumerate(columns): + y = data.select(j).to_numpy().flatten().astype("float") + ax[i].plot(x, y, marker=".", label=f.stem, linewidth=2, markersize=8) # actual results + ax[i].plot(x, _gaussian_filter1d(y, sigma=3), ":", label="smooth", linewidth=2) # smoothing line + ax[i].set_title(j, fontsize=12) + except Exception as e: + LOGGER.error(f"Plotting error for {f}: {e}") + if ax is not None: + ax[1].legend() + fname = save_dir / "results.png" + fig.savefig(fname, dpi=200) + plt.close() + if on_plot: + on_plot(fname) + + +@plt_settings() +def plot_multitrain_results(scores: dict, key: str = "fitness", save_dir=Path()): + """Plot per-dataset metrics from a multi-dataset training run as a bar chart with the cross-dataset mean. + + Args: + scores (dict): Mapping of dataset name to its scalar metric value. + key (str): Name of the plotted metric, used as the y-axis label. + save_dir (str | Path): Directory to save the 'multitrain_results.png' figure. + + Returns: + (Path): Path to the saved figure. + + Examples: + >>> from ultralytics.utils.plotting import plot_multitrain_results + >>> plot_multitrain_results({"coco8": 0.61, "dota8": 0.48}, key="metrics/mAP50-95(B)") + """ + import matplotlib.pyplot as plt # scope for faster 'import ultralytics' + + mean = sum(scores.values()) / len(scores) + fig, ax = plt.subplots(figsize=(max(6.0, len(scores) * 0.45), 5), tight_layout=True) + ax.bar(range(len(scores)), list(scores.values()), color="#042AFF") + ax.axhline(mean, color="orange", linestyle="--", label=f"mean = {mean:.3f}") + ax.set_xticks(range(len(scores))) + ax.set_xticklabels(list(scores), rotation=90) + ax.set_ylabel(key) + ax.set_title(f"MultiTrainer results across {len(scores)} datasets") + ax.legend() + fname = Path(save_dir) / "multitrain_results.png" + fig.savefig(fname, dpi=200) + plt.close(fig) + return fname + + +def plt_color_scatter(v, f, bins: int = 20, cmap: str = "viridis", alpha: float = 0.8, edgecolors: str = "none"): + """Plot a scatter plot with points colored based on a 2D histogram. + + Args: + v (array-like): Values for the x-axis. + f (array-like): Values for the y-axis. + bins (int, optional): Number of bins for the histogram. + cmap (str, optional): Colormap for the scatter plot. + alpha (float, optional): Alpha for the scatter plot. + edgecolors (str, optional): Edge colors for the scatter plot. + + Examples: + >>> v = np.random.rand(100) + >>> f = np.random.rand(100) + >>> plt_color_scatter(v, f) + """ + import matplotlib.pyplot as plt # scope for faster 'import ultralytics' + + # Calculate 2D histogram and corresponding colors + hist, xedges, yedges = np.histogram2d(v, f, bins=bins) + colors = [ + hist[ + np.clip(np.digitize(v[i], xedges, right=False) - 1, 0, hist.shape[0] - 1), + np.clip(np.digitize(f[i], yedges, right=False) - 1, 0, hist.shape[1] - 1), + ] + for i in range(len(v)) + ] + + # Scatter plot + plt.scatter(v, f, c=colors, cmap=cmap, alpha=alpha, edgecolors=edgecolors) + + +def plot_depth_panels( + imgs: torch.Tensor, + preds: list[torch.Tensor], + fname: str | Path, + gt: torch.Tensor | None = None, + titles: list[str] | None = None, + max_images: int = 4, +) -> None: + """Write a depth panel grid: one row per image, columns RGB | GT (if provided) | one per entry of ``preds``. + + All depth columns share the GT valid-pixel range per row, so a scale error between GT and any prediction shows up + directly as a color mismatch. Panels are resized to the RGB image size, so predictions at head stride need no prior + interpolation. + + Args: + imgs (torch.Tensor): (B,3,H,W) float image tensor in [0,1]. + preds (list): List of (B,1,H,W) or (B,H,W) predicted depth tensors; each adds one column. + fname (str | Path): Output image path. + gt (torch.Tensor, optional): (B,1,H,W) or (B,H,W) ground-truth depth in meters (pixels <= 0 invalid, drawn + black). Used for the GT column and to set the shared color scale. + titles (list, optional): List of column labels, drawn in a 24 px header strip. None keeps the strip-free layout. + max_images (int): Maximum number of rows. + """ + preds = [p.unsqueeze(1) if p.ndim == 3 else p for p in preds] + h, w = imgs.shape[-2:] + rows = [] + for i in range(min(imgs.shape[0], max_images)): + rgb = (imgs[i].detach().float().cpu().clamp(0, 1).numpy() * 255).astype(np.uint8).transpose(1, 2, 0) + panels = [cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)] + + if gt is not None: + g = gt[i, 0] if gt.ndim == 4 else gt[i] + gv = g[g > 0] + vmin = float(gv.min()) if gv.numel() else 0.0 + vmax = float(gv.max()) if gv.numel() else 1.0 + d = g.detach().float().cpu().numpy() if isinstance(g, torch.Tensor) else np.asarray(g, np.float32) + panels.append( + cv2.resize(colorize_depth(d, vmin, vmax, mode="metric"), (w, h), interpolation=cv2.INTER_NEAREST) + ) + else: + # No GT: scale each prediction by its own valid range. + vmin = vmax = None + + for p in preds: + d = p[i, 0] if p.ndim == 4 else p[i] + d = d.detach().float().cpu().numpy() if isinstance(d, torch.Tensor) else np.asarray(d, np.float32) + lo, hi = vmin, vmax + if lo is None or hi is None: + dv = d[d > 0] + lo, hi = (float(dv.min()), float(dv.max())) if dv.size else (0.0, 1.0) + panels.append(cv2.resize(colorize_depth(d, lo, hi, mode="metric"), (w, h), interpolation=cv2.INTER_NEAREST)) + + rows.append(np.hstack(panels)) + grid = np.vstack(rows) + if titles: + strip = np.full((24, grid.shape[1], 3), 255, dtype=np.uint8) + for j, t in enumerate(titles): + cv2.putText(strip, str(t), (j * w + 4, 17), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA) + grid = np.vstack([strip, grid]) + cv2.imwrite(str(fname), grid) + + +@plt_settings() +def plot_tune_results(results_file: str = "tune_results.ndjson", exclude_zero_fitness_points: bool = True): + """Plot the evolution results stored in a tuning NDJSON file. + + Args: + results_file (str, optional): Path to the NDJSON file containing the tuning results. + exclude_zero_fitness_points (bool, optional): Don't include points with zero fitness in tuning plots. + + Examples: + >>> plot_tune_results("path/to/tune_results.ndjson") + """ + import json + + import matplotlib.pyplot as plt # scope for faster 'import ultralytics' + + def _save_one_file(file): + """Save one matplotlib plot to 'file'.""" + plt.savefig(file, dpi=200) + plt.close() + LOGGER.info(f"Saved {file}") + + results_file = Path(results_file) + with open(results_file, encoding="utf-8") as f: + records = [json.loads(line) for line in f if line.strip()] + if not records: + return + + keys = list(records[0].get("hyperparameters", {})) + x = np.array( + [[r.get("fitness", 0.0)] + [r.get("hyperparameters", {}).get(k, np.nan) for k in keys] for r in records], + dtype=float, + ) + len(x) + all_fitness = x[:, 0] # fitness + zero_mask = slice(None) + if exclude_zero_fitness_points: + zero_mask = all_fitness > 0 # exclude zero-fitness points + x, all_fitness = x[zero_mask], all_fitness[zero_mask] + if len(all_fitness) == 0: + LOGGER.warning("No valid fitness values to plot (all iterations may have failed)") + return + fitness = all_fitness.copy() + # Iterative sigma rejection on lower bound only + for _ in range(3): # max 3 iterations + mean, std = fitness.mean(), fitness.std() + lower_bound = mean - 3 * std + mask = fitness >= lower_bound + if mask.all(): # no more outliers + break + x, fitness = x[mask], fitness[mask] + j = np.argmax(fitness) # max fitness index + n = math.ceil(len(keys) ** 0.5) # columns and rows in plot + plt.figure(figsize=(10, 10), tight_layout=True) + for i, k in enumerate(keys): + v = x[:, i + 1] + mu = v[j] # best single result + plt.subplot(n, n, i + 1) + plt_color_scatter(v, fitness, cmap="viridis", alpha=0.8, edgecolors="none") + plt.plot(mu, fitness.max(), "k+", markersize=15) + plt.title(f"{k} = {mu:.3g}", fontdict={"size": 9}) # limit to 40 characters + plt.tick_params(axis="both", labelsize=8) # Set axis label size to 8 + if i % n != 0: + plt.yticks([]) + _save_one_file(results_file.with_name("tune_scatter_plots.png")) + + # Fitness progress and per-dataset change from the initial to best result + plot_records = records if isinstance(zero_mask, slice) else [r for r, keep in zip(records, zero_mask) if keep] + datasets = sorted({k for r in plot_records for k in r.get("datasets", {})}) + _, (ax1, ax2) = plt.subplots( + 1, + 2, + figsize=(16, max(6, len(datasets) * 0.28)), + gridspec_kw={"width_ratios": (1, 1.35)}, + constrained_layout=True, + ) + iterations = np.array([r.get("iteration", i) for i, r in enumerate(plot_records, 1)]) + best_idx = int(all_fitness.argmax()) + ax1.scatter(iterations, all_fitness, s=28, color="0.45", alpha=0.75, label="Iteration") + ax1.plot(iterations, np.maximum.accumulate(all_fitness), color="#2563eb", linewidth=2.5, label="Best so far") + ax1.axhline(all_fitness[0], color="#dc2626", linestyle="--", label=f"Initial {all_fitness[0]:.4f}") + ax1.scatter(iterations[best_idx], all_fitness[best_idx], s=90, color="#16a34a", zorder=5, label="Best") + ax1.set(title="Fitness Progress", xlabel="Iteration", ylabel="Fitness") + ax1.grid(alpha=0.2) + ax1.legend() + if datasets: + initial = np.array([plot_records[0].get("datasets", {}).get(k, {}).get("fitness", 0.0) for k in datasets]) + best = np.array([plot_records[best_idx].get("datasets", {}).get(k, {}).get("fitness", 0.0) for k in datasets]) + order = np.argsort(best - initial) + y = np.arange(len(datasets)) + ax2.hlines(y, initial[order], best[order], color="0.8") + ax2.scatter(initial[order], y, s=24, color="#dc2626", label="Initial") + ax2.scatter(best[order], y, s=24, color="#16a34a", label=f"Best aggregate iteration {iterations[best_idx]}") + ax2.set_yticks(y) + ax2.set_yticklabels(np.array(datasets)[order], fontsize=8) + ax2.set(title="Per-Dataset Fitness: Initial vs Best Aggregate Iteration", xlabel="Fitness") + ax2.grid(axis="x", alpha=0.2) + ax2.legend() + else: + ax2.set_axis_off() + _save_one_file(results_file.with_name("tune_fitness.png")) + + +def class_activation_map( + model, + im: torch.Tensor, + paths: list[str], + save_dir: Path, + *args, + conf: float = 0.25, + classes=None, + topk: int = 16, + **kwargs, +) -> Any: + """Run inference and save a class activation heatmap for each image of the batch. + + LayerCAM weights each head-input position by its positive gradient toward the predicted class score. Each prediction + and head level is normalized independently before taking their element-wise maximum, preventing stronger predictions + or levels from hiding weaker ones. + + Args: + model (torch.nn.Module): AutoBackend wrapping a PyTorch model. + im (torch.Tensor): Preprocessed images of shape (B, 3, H, W). + paths (list[str]): Source path of each image of the batch, used to name the saved overlays. + save_dir (Path): Directory to save the overlays in. + *args (Any): Additional positional arguments passed to the model forward. + conf (float): Score threshold a prediction must pass to contribute, falling back to the single best prediction + for images where nothing passes it, so that a near miss can still be inspected. + classes (int | list[int], optional): Only let these class ids contribute, as in the predict `classes` filter. + topk (int): Maximum number of predictions to explain per image, each one costing a backward pass. + **kwargs (Any): Additional keyword arguments passed to the model forward. + + Returns: + (Any): Model predictions, detached from the autograd graph. + """ + acts, scores = [], [] + + def pre_hook(module, inputs): + """Capture the feature maps entering the head, before heads like WorldDetect overwrite them in place.""" + x = inputs[0] + acts.extend(a for a in (x if isinstance(x, (list, tuple)) else [x]) if a.ndim == 4) + + def hook(module, inputs, output): + """Capture the class logits leaving the head.""" + raw = output[1] if isinstance(output, tuple) else output # heads returning (predictions, raw) keep the raw + if isinstance(raw, dict): # Detect and subclasses: follow the selected inference branch + s = raw.get("one2one" if module.end2end else "one2many", raw)["scores"] # (B, nc, anchors) + elif isinstance(raw, tuple): # RTDETRDecoder, raw = (dec_bboxes, dec_scores, ...) + s = raw[1][-1].transpose(1, 2) # last decoder layer, (B, nc, queries) + else: # Classify (B, nc), SemanticSegment (B, nc, h, w), Depth (B, 1, h, w) + s = raw + scores.append(s.reshape(*s.shape[:2], -1)) # class logits, (B, nc, predictions) + + head = model.model.model[-1] # AutoBackend -> PyTorch model -> head + head.shape = head.shapes = None # rebuild the anchor caches, inference tensors in them break the autograd graph + handles = [head.register_forward_pre_hook(pre_hook), head.register_forward_hook(hook)] + # smart_inference_mode() wraps the caller in inference_mode from torch 1.10 and in no_grad below it, and only the + # former has to be left before autograd will record anything. + with torch.inference_mode(False) if TORCH_1_10 else contextlib.nullcontext(), torch.enable_grad(): + try: + im = im.clone().requires_grad_(True) # model parameters have requires_grad=False, so seed the graph here + preds = model(im, *args, **kwargs) + finally: + for handle in handles: + handle.remove() + s = torch.cat(scores, 2) # (B, nc, predictions) class logits + if classes is not None: + cls = torch.as_tensor(classes, dtype=torch.long, device=s.device).flatten() + cls = cls[(cls >= 0) & (cls < s.shape[1])] # drop ids outside this model's output channels + if len(cls): + s = s[:, cls] # heatmap for the requested classes only + s = s.amax(1) # (B, predictions) best class logit of each prediction + keep = (s.sigmoid() >= conf) | (s == s.amax(1, keepdim=True)) # top prediction alone if none above conf + n = min(int(keep.sum(1).amax()), topk) # predictions to explain, one backward pass each + if int(keep.sum(1).amax()) > n: + LOGGER.warning(f"Explaining the {n} strongest predictions per image out of {int(keep.sum(1).amax())}.") + rank = torch.arange(n, device=s.device) % keep.sum(1, keepdim=True).clamp(min=1) # short images repeat + order = s.masked_fill(~keep, float("-inf")).argsort(1, descending=True).gather(1, rank) # (B, n) + cam = None + for k in range(n): + levels = [] + grads = torch.autograd.grad(s.gather(1, order[:, k : k + 1]).sum(), acts, retain_graph=k < n - 1) + for a, g in zip(acts, grads): + c = (g.float().clamp(min=0) * a.float()).sum(1, keepdim=True) # LayerCAM, per-position weighting + c = c.clamp(min=0) # activations can be negative, keep only evidence for the prediction + c = torch.nn.functional.interpolate(c, im.shape[2:], mode="bilinear", align_corners=False) + levels.append(c / c.amax((2, 3), keepdim=True).clamp(min=1e-7)) + # The level a prediction is made on peaks far higher than the rest, so summing raw would shrink the + # broader evidence the other levels hold down to a faint background. + level = torch.stack(levels).amax(0) + cam = level if cam is None else torch.maximum(cam, level) + + cam = (cam.squeeze(1) * 255).byte().cpu().numpy() # (B, H, W), maps are already scaled to [0, 1] + ims = im.detach()[:, :3].float() + lo, hi = ims.amin((2, 3), keepdim=True), ims.amax((2, 3), keepdim=True) # classify inputs are mean-std normalized + ims = ((ims - lo) / (hi - lo).clamp(min=1e-7) * 255).byte().permute(0, 2, 3, 1).cpu().numpy()[..., ::-1] # to BGR + save_dir.mkdir(parents=True, exist_ok=True) + for c, img, p in zip(cam, ims, paths): + f = increment_path(save_dir / f"{Path(p).stem}_cam.jpg") + img = np.ascontiguousarray(img if img.shape[2] == 3 else img[..., :1].repeat(3, 2)) # grayscale to BGR + heatmap = cv2.addWeighted(cv2.applyColorMap(c, cv2.COLORMAP_JET), 0.5, img, 0.5, 0) + cv2.imwrite(str(f), heatmap) + LOGGER.info(f"Saving {f}... (LayerCAM)") + + def detach(x): + """Detach tensors in nested model outputs from the autograd graph.""" + if isinstance(x, torch.Tensor): + return x.detach() + if isinstance(x, dict): + return {k: detach(v) for k, v in x.items()} + if isinstance(x, (list, tuple)): + return type(x)(detach(v) for v in x) + return x + + return detach(preds) diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/tal.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/tal.py new file mode 100644 index 0000000000000000000000000000000000000000..feaaa4dd170c7f0c75263e5ec271654fae2a7235 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/tal.py @@ -0,0 +1,516 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import torch +from torch import nn + +from . import LOGGER +from .metrics import bbox_iou, probiou +from .ops import xywh2xyxy, xywhr2xyxyxyxy, xyxy2xywh +from .torch_utils import TORCH_1_11 + + +class TaskAlignedAssigner(nn.Module): + """A task-aligned assigner for object detection. + + This class assigns ground-truth (gt) objects to anchors based on the task-aligned metric, which combines both + classification and localization information. + + Attributes: + topk (int): The number of top candidates to consider. + topk2 (int): Secondary topk value for additional filtering. + num_classes (int): The number of object classes. + alpha (float): The alpha parameter for the classification component of the task-aligned metric. + beta (float): The beta parameter for the localization component of the task-aligned metric. + stride (list): List of stride values for different feature levels. + stride_val (int): The stride value used for select_candidates_in_gts. + eps (float): A small value to prevent division by zero. + """ + + def __init__( + self, + topk: int = 13, + num_classes: int = 80, + alpha: float = 1.0, + beta: float = 6.0, + stride: list | None = None, + eps: float = 1e-9, + topk2=None, + ): + """Initialize a TaskAlignedAssigner object with customizable hyperparameters. + + Args: + topk (int, optional): The number of top candidates to consider. + num_classes (int, optional): The number of object classes. + alpha (float, optional): The alpha parameter for the classification component of the task-aligned metric. + beta (float, optional): The beta parameter for the localization component of the task-aligned metric. + stride (list, optional): List of stride values for different feature levels. + eps (float, optional): A small value to prevent division by zero. + topk2 (int, optional): Secondary topk value for additional filtering. + """ + super().__init__() + self.topk = topk + self.topk2 = topk2 or topk + self.num_classes = num_classes + self.alpha = alpha + self.beta = beta + self.stride = stride if stride is not None else [8, 16, 32] + self.stride_val = self.stride[1] if len(self.stride) > 1 else self.stride[0] + self.eps = eps + self._oom_warned = False + + @torch.no_grad() + def forward(self, pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt): + """Compute the task-aligned assignment. + + Args: + pd_scores (torch.Tensor): Predicted classification scores with shape (bs, num_total_anchors, num_classes). + pd_bboxes (torch.Tensor): Predicted bounding boxes with shape (bs, num_total_anchors, 4). + anc_points (torch.Tensor): Anchor points with shape (num_total_anchors, 2). + gt_labels (torch.Tensor): Ground truth labels with shape (bs, n_max_boxes, 1). + gt_bboxes (torch.Tensor): Ground truth boxes with shape (bs, n_max_boxes, 4). + mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (bs, n_max_boxes, 1). + + Returns: + target_labels (torch.Tensor): Target labels with shape (bs, num_total_anchors). + target_bboxes (torch.Tensor): Target bounding boxes with shape (bs, num_total_anchors, 4). + target_scores (torch.Tensor): Target scores with shape (bs, num_total_anchors, num_classes). + fg_mask (torch.Tensor): Foreground mask with shape (bs, num_total_anchors). + target_gt_idx (torch.Tensor): Target ground truth indices with shape (bs, num_total_anchors). + + References: + https://github.com/Nioolek/PPYOLOE_pytorch/blob/master/ppyoloe/assigner/tal_assigner.py + """ + self.bs = pd_scores.shape[0] + self.n_max_boxes = gt_bboxes.shape[1] + if self.n_max_boxes == 0: + return ( + torch.full_like(pd_scores[..., 0], self.num_classes), + torch.zeros_like(pd_bboxes), + torch.zeros_like(pd_scores), + torch.zeros_like(pd_scores[..., 0], dtype=torch.bool), + torch.zeros_like(pd_scores[..., 0]), + ) + + try: + return self._forward(pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt) + except RuntimeError as e: + if "out of memory" not in str(e).lower(): + raise + # Recover outside the except block so e.__traceback__ releases the failed attempt's GPU intermediates. + bs, n_max_boxes = self.bs, self.n_max_boxes + if not self._oom_warned: + LOGGER.warning( + f"CUDA out of memory in TaskAlignedAssigner with batch_size={bs} and max_num_obj={n_max_boxes}; " + "retrying assignment one image at a time on GPU. Model forward batch size is unchanged." + ) + self._oom_warned = True + last_gt_idx = ( + mask_gt.squeeze(-1) + .bool() + .mul(torch.arange(1, n_max_boxes + 1, device=mask_gt.device)) + .amax(1) + .clamp_(min=1) + .tolist() + ) + self.bs = 1 + results = None + try: + for i, self.n_max_boxes in enumerate(last_gt_idx): + result = self._forward( + pd_scores[i : i + 1], + pd_bboxes[i : i + 1], + anc_points, + gt_labels[i : i + 1, : self.n_max_boxes], + gt_bboxes[i : i + 1, : self.n_max_boxes], + mask_gt[i : i + 1, : self.n_max_boxes], + ) + if results is None: + results = tuple(x.new_empty((bs, *x.shape[1:])) for x in result) + for output, x in zip(results, result): + output[i] = x[0] + finally: + self.bs, self.n_max_boxes = bs, n_max_boxes + return results + + def _forward(self, pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt): + """Compute the task-aligned assignment. + + Args: + pd_scores (torch.Tensor): Predicted classification scores with shape (bs, num_total_anchors, num_classes). + pd_bboxes (torch.Tensor): Predicted bounding boxes with shape (bs, num_total_anchors, 4). + anc_points (torch.Tensor): Anchor points with shape (num_total_anchors, 2). + gt_labels (torch.Tensor): Ground truth labels with shape (bs, n_max_boxes, 1). + gt_bboxes (torch.Tensor): Ground truth boxes with shape (bs, n_max_boxes, 4). + mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (bs, n_max_boxes, 1). + + Returns: + target_labels (torch.Tensor): Target labels with shape (bs, num_total_anchors). + target_bboxes (torch.Tensor): Target bounding boxes with shape (bs, num_total_anchors, 4). + target_scores (torch.Tensor): Target scores with shape (bs, num_total_anchors, num_classes). + fg_mask (torch.Tensor): Foreground mask with shape (bs, num_total_anchors). + target_gt_idx (torch.Tensor): Target ground truth indices with shape (bs, num_total_anchors). + """ + mask_pos, align_metric, overlaps = self.get_pos_mask( + pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points, mask_gt + ) + + target_gt_idx, fg_mask, mask_pos = self.select_highest_overlaps( + mask_pos, overlaps, self.n_max_boxes, align_metric + ) + + # Assigned target + target_labels, target_bboxes, target_scores = self.get_targets(gt_labels, gt_bboxes, target_gt_idx, fg_mask) + + # Normalize + align_metric *= mask_pos + pos_align_metrics = align_metric.amax(dim=-1, keepdim=True) # b, max_num_obj + overlaps *= mask_pos + pos_overlaps = overlaps.amax(dim=-1, keepdim=True) # b, max_num_obj + align_metric.mul_(pos_overlaps).div_(pos_align_metrics + self.eps) + norm_align_metric = align_metric.amax(-2).unsqueeze(-1) + target_scores = target_scores * norm_align_metric + + return target_labels, target_bboxes, target_scores, fg_mask.bool(), target_gt_idx + + def get_pos_mask(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points, mask_gt): + """Get positive mask for each ground truth box. + + Args: + pd_scores (torch.Tensor): Predicted classification scores with shape (bs, num_total_anchors, num_classes). + pd_bboxes (torch.Tensor): Predicted bounding boxes with shape (bs, num_total_anchors, 4). + gt_labels (torch.Tensor): Ground truth labels with shape (bs, n_max_boxes, 1). + gt_bboxes (torch.Tensor): Ground truth boxes with shape (bs, n_max_boxes, 4). + anc_points (torch.Tensor): Anchor points with shape (num_total_anchors, 2). + mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (bs, n_max_boxes, 1). + + Returns: + mask_pos (torch.Tensor): Positive mask with shape (bs, max_num_obj, h*w). + align_metric (torch.Tensor): Alignment metric with shape (bs, max_num_obj, h*w). + overlaps (torch.Tensor): Overlaps between predicted vs ground truth boxes with shape (bs, max_num_obj, h*w). + """ + mask_in_gts = self.select_candidates_in_gts(anc_points, gt_bboxes, mask_gt) + # Get anchor_align metric, (b, max_num_obj, h*w) + align_metric, overlaps = self.get_box_metrics(pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_in_gts * mask_gt) + # Get topk_metric mask, (b, max_num_obj, h*w) + mask_topk = self.select_topk_candidates(align_metric, topk_mask=mask_gt.expand(-1, -1, self.topk).bool()) + # Merge all mask to a final mask, (b, max_num_obj, h*w) + mask_pos = mask_topk.mul_(mask_in_gts).mul_(mask_gt.bool()) + + return mask_pos, align_metric, overlaps + + def get_box_metrics(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_gt): + """Compute alignment metric given predicted and ground truth bounding boxes. + + Args: + pd_scores (torch.Tensor): Predicted classification scores with shape (bs, num_total_anchors, num_classes). + pd_bboxes (torch.Tensor): Predicted bounding boxes with shape (bs, num_total_anchors, 4). + gt_labels (torch.Tensor): Ground truth labels with shape (bs, n_max_boxes, 1). + gt_bboxes (torch.Tensor): Ground truth boxes with shape (bs, n_max_boxes, 4). + mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (bs, n_max_boxes, h*w). + + Returns: + align_metric (torch.Tensor): Alignment metric combining classification and localization. + overlaps (torch.Tensor): IoU overlaps between predicted and ground truth boxes. + """ + na = pd_bboxes.shape[-2] + mask_gt = mask_gt.bool() # b, max_num_obj, h*w + shape = self.bs, self.n_max_boxes, na + indices = mask_gt.nonzero(as_tuple=True) + bbox_scores = pd_scores[indices[0], indices[2], gt_labels[indices[0], indices[1], 0].long()] + overlap_values = self.iou_calculation(gt_bboxes[indices[:2]], pd_bboxes[indices[0], indices[2]]) + align_values = bbox_scores.pow(self.alpha) * overlap_values.pow(self.beta) + + overlaps = torch.zeros(shape, dtype=pd_bboxes.dtype, device=pd_bboxes.device) + align_metric = torch.zeros(shape, dtype=align_values.dtype, device=pd_scores.device) + overlaps[indices] = overlap_values + align_metric[indices] = align_values + return align_metric, overlaps + + def iou_calculation(self, gt_bboxes, pd_bboxes): + """Calculate IoU for horizontal bounding boxes. + + Args: + gt_bboxes (torch.Tensor): Ground truth boxes. + pd_bboxes (torch.Tensor): Predicted boxes. + + Returns: + (torch.Tensor): IoU values between each pair of boxes. + """ + return bbox_iou(gt_bboxes, pd_bboxes, xywh=False, CIoU=True).squeeze(-1).clamp_(0) + + def select_topk_candidates(self, metrics, topk_mask=None): + """Select the top-k candidates based on the given metrics. + + Args: + metrics (torch.Tensor): A tensor of shape (b, max_num_obj, h*w), where b is the batch size, max_num_obj is + the maximum number of objects, and h*w represents the total number of anchor points. + topk_mask (torch.Tensor, optional): An optional boolean tensor of shape (b, max_num_obj, topk), where topk + is the number of top candidates to consider. If not provided, the top-k values are automatically + computed based on the given metrics. + + Returns: + (torch.Tensor): A tensor of shape (b, max_num_obj, h*w) containing the selected top-k candidates. + """ + # (b, max_num_obj, topk) + topk_metrics, topk_idxs = torch.topk(metrics, self.topk, dim=-1, largest=True) + if topk_mask is None: + topk_mask = (topk_metrics.max(-1, keepdim=True)[0] > self.eps).expand_as(topk_idxs) + # (b, max_num_obj, topk) + topk_idxs.masked_fill_(~topk_mask, 0) + + # Count how many of the topk lists select each anchor; scatter_add_ accumulates duplicate indices in one pass + count_tensor = torch.zeros(metrics.shape, dtype=torch.int8, device=topk_idxs.device) + count_tensor.scatter_add_(-1, topk_idxs, torch.ones_like(topk_idxs, dtype=torch.int8)) + # Filter invalid bboxes + count_tensor.masked_fill_(count_tensor > 1, 0) + + return count_tensor + + def get_targets(self, gt_labels, gt_bboxes, target_gt_idx, fg_mask): + """Compute target labels, target bounding boxes, and target scores for the positive anchor points. + + Args: + gt_labels (torch.Tensor): Ground truth labels of shape (b, max_num_obj, 1), where b is the batch size and + max_num_obj is the maximum number of objects. + gt_bboxes (torch.Tensor): Ground truth bounding boxes of shape (b, max_num_obj, 4). + target_gt_idx (torch.Tensor): Indices of the assigned ground truth objects for positive anchor points, with + shape (b, h*w), where h*w is the total number of anchor points. + fg_mask (torch.Tensor): A boolean tensor of shape (b, h*w) indicating the positive (foreground) anchor + points. + + Returns: + target_labels (torch.Tensor): Target labels for positive anchor points with shape (b, h*w). + target_bboxes (torch.Tensor): Target bounding boxes for positive anchor points with shape (b, h*w, 4). + target_scores (torch.Tensor): Target scores for positive anchor points with shape (b, h*w, num_classes). + """ + # Assigned target labels, (b, 1) + batch_ind = torch.arange(end=self.bs, dtype=torch.int64, device=gt_labels.device)[..., None] + target_gt_idx = target_gt_idx + batch_ind * self.n_max_boxes # (b, h*w) + target_labels = gt_labels.long().flatten()[target_gt_idx] # (b, h*w) + + # Assigned target boxes, (b, max_num_obj, 4) -> (b, h*w, 4) + target_bboxes = gt_bboxes.view(-1, gt_bboxes.shape[-1])[target_gt_idx] + + # Assigned target scores + target_labels.clamp_(0) + + # 10x faster than F.one_hot() + target_scores = torch.zeros( + (target_labels.shape[0], target_labels.shape[1], self.num_classes), + dtype=torch.int8, + device=target_labels.device, + ) # (b, h*w, 80) + target_scores.scatter_(2, target_labels.unsqueeze(-1), 1) + + target_scores = target_scores * (fg_mask[:, :, None] > 0) + + return target_labels, target_bboxes, target_scores + + def select_candidates_in_gts(self, xy_centers, gt_bboxes, mask_gt, eps=1e-9): + """Select positive anchor centers within ground truth bounding boxes. + + Args: + xy_centers (torch.Tensor): Anchor center coordinates, shape (h*w, 2). + gt_bboxes (torch.Tensor): Ground truth bounding boxes, shape (b, n_boxes, 4). + mask_gt (torch.Tensor): Mask for valid ground truth boxes, shape (b, n_boxes, 1). + eps (float, optional): Small value for numerical stability. + + Returns: + (torch.Tensor): Boolean mask of positive anchors, shape (b, n_boxes, h*w). + + Notes: + - b: batch size, n_boxes: number of ground truth boxes, h: height, w: width. + - Bounding box format: [x_min, y_min, x_max, y_max]. + """ + gt_bboxes_xywh = xyxy2xywh(gt_bboxes) + wh_mask = gt_bboxes_xywh[..., 2:] < self.stride_val # floor tiny sides so the pool grows monotonically + gt_bboxes_xywh[..., 2:] = torch.where( + (wh_mask * mask_gt).bool(), + torch.tensor(self.stride_val, dtype=gt_bboxes_xywh.dtype, device=gt_bboxes_xywh.device), + gt_bboxes_xywh[..., 2:], + ) + gt_bboxes = xywh2xyxy(gt_bboxes_xywh) + + lt, rb = gt_bboxes.unsqueeze(2).chunk(2, 3) # (b, n_boxes, 1, 2) left-top, right-bottom + mask = xy_centers[:, 0] - lt[..., 0] > eps + mask &= xy_centers[:, 1] - lt[..., 1] > eps + mask &= rb[..., 0] - xy_centers[:, 0] > eps + mask &= rb[..., 1] - xy_centers[:, 1] > eps + return mask + + def select_highest_overlaps(self, mask_pos, overlaps, n_max_boxes, align_metric): + """Select anchor boxes with highest IoU when assigned to multiple ground truths. + + Args: + mask_pos (torch.Tensor): Positive mask, shape (b, n_max_boxes, h*w). + overlaps (torch.Tensor): IoU overlaps, shape (b, n_max_boxes, h*w). + n_max_boxes (int): Maximum number of ground truth boxes. + align_metric (torch.Tensor): Alignment metric for selecting best matches. + + Returns: + target_gt_idx (torch.Tensor): Indices of assigned ground truths, shape (b, h*w). + fg_mask (torch.Tensor): Foreground mask, shape (b, h*w). + mask_pos (torch.Tensor): Updated positive mask, shape (b, n_max_boxes, h*w). + """ + # Convert (b, n_max_boxes, h*w) -> (b, h*w) + fg_mask = mask_pos.sum(-2) + # Anchors assigned to multiple gt_bboxes keep the highest overlap; a no-op when there are none, without a sync + mask_multi_gts = (fg_mask.unsqueeze(1) > 1).expand(-1, n_max_boxes, -1) # (b, n_max_boxes, h*w) + max_overlaps_idx = overlaps.max(1).indices # (b, h*w) + is_max_overlaps = torch.zeros(mask_pos.shape, dtype=mask_pos.dtype, device=mask_pos.device) + is_max_overlaps.scatter_(1, max_overlaps_idx.unsqueeze(1), 1) + mask_pos = torch.where(mask_multi_gts, is_max_overlaps, mask_pos) # (b, n_max_boxes, h*w) + + if self.topk2 != self.topk: + align_metric = align_metric * mask_pos # update overlaps + # (b, n_max_boxes, topk2) + max_overlaps_idx = torch.topk(align_metric, self.topk2, dim=-1, largest=True).indices + topk_idx = torch.zeros(mask_pos.shape, dtype=mask_pos.dtype, device=mask_pos.device) # update mask_pos + topk_idx.scatter_(-1, max_overlaps_idx, 1.0) + mask_pos *= topk_idx + # Each anchor now serves at most one gt, so the column max is both its foreground flag and its gt index + fg_mask, target_gt_idx = mask_pos.max(-2) # (b, h*w) + return target_gt_idx, fg_mask, mask_pos + + +class RotatedTaskAlignedAssigner(TaskAlignedAssigner): + """Assigns ground-truth objects to rotated bounding boxes using a task-aligned metric.""" + + def iou_calculation(self, gt_bboxes, pd_bboxes): + """Calculate IoU for rotated bounding boxes.""" + return probiou(gt_bboxes, pd_bboxes).squeeze(-1).clamp_(0) + + def select_candidates_in_gts(self, xy_centers, gt_bboxes, mask_gt): + """Select the positive anchor center in gt for rotated bounding boxes. + + Args: + xy_centers (torch.Tensor): Anchor center coordinates with shape (h*w, 2). + gt_bboxes (torch.Tensor): Ground truth bounding boxes with shape (b, n_boxes, 5). + mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (b, n_boxes, 1). + + Returns: + (torch.Tensor): Boolean mask of positive anchors with shape (b, n_boxes, h*w). + """ + gt_bboxes_clone = gt_bboxes.clone() + wh_mask = gt_bboxes_clone[..., 2:4] < self.stride_val + gt_bboxes_clone[..., 2:4] = torch.where( + (wh_mask * mask_gt).bool(), + torch.tensor(self.stride_val, dtype=gt_bboxes_clone.dtype, device=gt_bboxes_clone.device), + gt_bboxes_clone[..., 2:4], + ) + + # (b, n_boxes, 5) --> (b, n_boxes, 4, 2) + corners = xywhr2xyxyxyxy(gt_bboxes_clone) + # (b, n_boxes, 1, 2) + a, b, _, d = corners.split(1, dim=-2) + ab = b - a + ad = d - a + + # (b, n_boxes, h*w) per coordinate + apx = xy_centers[:, 0] - a[..., 0] + apy = xy_centers[:, 1] - a[..., 1] + norm_ab = (ab * ab).sum(dim=-1) + norm_ad = (ad * ad).sum(dim=-1) + ap_dot_ab = apx * ab[..., 0] + apy * ab[..., 1] + ap_dot_ad = apx * ad[..., 0] + apy * ad[..., 1] + return (ap_dot_ab >= 0) & (ap_dot_ab <= norm_ab) & (ap_dot_ad >= 0) & (ap_dot_ad <= norm_ad) # is_in_box + + +def make_anchors(feats, strides, grid_cell_offset=0.5): + """Generate anchors from features.""" + anchor_points, stride_tensor = [], [] + assert feats is not None + dtype = feats[0].dtype + for i in range(len(feats)): # use len(feats) to avoid TracerWarning from iterating over strides tensor + stride = strides[i] + h, w = feats[i].shape[2:] if isinstance(feats, list) else (int(feats[i][0]), int(feats[i][1])) + # no cumsum (nondeterministic on CUDA), no device= (baked into traces), no out= (does not convert to CoreML) + sx = torch.arange(w).type_as(feats[0]) + grid_cell_offset # shift x + sy = torch.arange(h).type_as(feats[0]) + grid_cell_offset # shift y + sy, sx = torch.meshgrid(sy, sx, indexing="ij") if TORCH_1_11 else torch.meshgrid(sy, sx) + anchor_points.append(torch.stack((sx, sy), -1).view(-1, 2)) + stride_tensor.append(feats[0].new_full((h * w, 1), stride, dtype=dtype)) + return torch.cat(anchor_points), torch.cat(stride_tensor) + + +def dist2bbox(distance, anchor_points, xywh=True, dim=-1): + """Transform distance(ltrb) to box(xywh or xyxy).""" + lt, rb = distance.chunk(2, dim) + x1y1 = anchor_points - lt + x2y2 = anchor_points + rb + if xywh: + c_xy = (x1y1 + x2y2) / 2 + wh = x2y2 - x1y1 + return torch.cat([c_xy, wh], dim) # xywh bbox + return torch.cat((x1y1, x2y2), dim) # xyxy bbox + + +def bbox2dist(anchor_points: torch.Tensor, bbox: torch.Tensor, reg_max: int | None = None) -> torch.Tensor: + """Transform bbox(xyxy) to dist(ltrb).""" + x1y1, x2y2 = bbox.chunk(2, -1) + dist = torch.cat((anchor_points - x1y1, x2y2 - anchor_points), -1) + if reg_max is not None: + dist = dist.clamp_(0, reg_max - 0.01) # dist (lt, rb) + return dist + + +def dist2rbox(pred_dist, pred_angle, anchor_points, dim=-1): + """Decode predicted rotated bounding box coordinates from anchor points and distribution. + + Args: + pred_dist (torch.Tensor): Predicted rotated distance with shape (bs, h*w, 4). + pred_angle (torch.Tensor): Predicted angle with shape (bs, h*w, 1). + anchor_points (torch.Tensor): Anchor points with shape (h*w, 2). + dim (int, optional): Dimension along which to split. + + Returns: + (torch.Tensor): Predicted rotated bounding boxes with shape (bs, h*w, 4). + """ + lt, rb = pred_dist.split(2, dim=dim) + cos, sin = torch.cos(pred_angle), torch.sin(pred_angle) + # (bs, h*w, 1) + xf, yf = ((rb - lt) / 2).split(1, dim=dim) + x, y = xf * cos - yf * sin, xf * sin + yf * cos + xy = torch.cat([x, y], dim=dim) + anchor_points + return torch.cat([xy, lt + rb], dim=dim) + + +def rbox2dist( + target_bboxes: torch.Tensor, + anchor_points: torch.Tensor, + target_angle: torch.Tensor, + dim: int = -1, + reg_max: int | None = None, +): + """Transform rotated bounding box (xywh) to distance (ltrb). This is the inverse of dist2rbox. + + Args: + target_bboxes (torch.Tensor): Target rotated bounding boxes with shape (bs, h*w, 4), format [x, y, w, h]. + anchor_points (torch.Tensor): Anchor points with shape (h*w, 2). + target_angle (torch.Tensor): Target angle with shape (bs, h*w, 1). + dim (int, optional): Dimension along which to split. + reg_max (int, optional): Maximum regression value for clamping. + + Returns: + (torch.Tensor): Rotated distance with shape (bs, h*w, 4), format [l, t, r, b]. + """ + xy, wh = target_bboxes.split(2, dim=dim) + offset = xy - anchor_points # (bs, h*w, 2) + offset_x, offset_y = offset.split(1, dim=dim) + cos, sin = torch.cos(target_angle), torch.sin(target_angle) + xf = offset_x * cos + offset_y * sin + yf = -offset_x * sin + offset_y * cos + + w, h = wh.split(1, dim=dim) + target_l = w / 2 - xf + target_t = h / 2 - yf + target_r = w / 2 + xf + target_b = h / 2 + yf + + dist = torch.cat([target_l, target_t, target_r, target_b], dim=dim) + if reg_max is not None: + dist = dist.clamp_(0, reg_max - 0.01) + + return dist diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/torch_utils.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/torch_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e71816658ee3b98fcd3648272c8eac205fb8aa7e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/torch_utils.py @@ -0,0 +1,1242 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import functools +import gc +import math +import os +import random +import time +from contextlib import contextmanager +from copy import deepcopy +from datetime import datetime +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.distributed as dist +import torch.nn.functional as F +from torch import nn +from torch.nn.utils.fusion import fuse_conv_bn_weights + +from ultralytics import __version__ +from ultralytics.utils import ( + ARM64, + DEFAULT_CFG_DICT, + DEFAULT_CFG_KEYS, + LOCAL_RANK, + LOGGER, + MACOS, + NUM_THREADS, + PYTHON_VERSION, + TORCH_VERSION, + TORCHVISION_VERSION, + WINDOWS, + colorstr, +) +from ultralytics.utils.checks import check_requirements, check_version +from ultralytics.utils.cpu import CPUInfo +from ultralytics.utils.patches import torch_load + +# Version checks (all default to version>=min_version) +TORCH_1_9 = check_version(TORCH_VERSION, "1.9.0") +TORCH_1_10 = check_version(TORCH_VERSION, "1.10.0") +TORCH_1_11 = check_version(TORCH_VERSION, "1.11.0") +TORCH_1_13 = check_version(TORCH_VERSION, "1.13.0") +TORCH_2_0 = check_version(TORCH_VERSION, "2.0.0") +TORCH_2_1 = check_version(TORCH_VERSION, "2.1.0") +TORCH_2_2 = check_version(TORCH_VERSION, "2.2.0") +TORCH_2_3 = check_version(TORCH_VERSION, "2.3.0") +TORCH_2_4 = check_version(TORCH_VERSION, "2.4.0") +TORCH_2_5 = check_version(TORCH_VERSION, "2.5.0") +TORCH_2_7 = check_version(TORCH_VERSION, "2.7.0") +TORCH_2_8 = check_version(TORCH_VERSION, "2.8.0") +TORCH_2_9 = check_version(TORCH_VERSION, "2.9.0") +TORCH_2_10 = check_version(TORCH_VERSION, "2.10.0") +TORCH_2_12 = check_version(TORCH_VERSION, "2.12.0") +TORCH_2_13 = check_version(TORCH_VERSION, "2.13.0") +TORCHVISION_0_10 = check_version(TORCHVISION_VERSION, "0.10.0") +TORCHVISION_0_11 = check_version(TORCHVISION_VERSION, "0.11.0") +TORCHVISION_0_13 = check_version(TORCHVISION_VERSION, "0.13.0") +TORCHVISION_0_18 = check_version(TORCHVISION_VERSION, "0.18.0") +if WINDOWS and check_version(TORCH_VERSION, "==2.4.0"): # reject version 2.4.0 on Windows + LOGGER.warning( + "Known issue with torch==2.4.0 on Windows with CPU, recommend upgrading to torch>=2.4.1 to resolve " + "https://github.com/ultralytics/ultralytics/issues/15049" + ) + + +def get_torch_device_backend(device: torch.device | str): + """Return the PyTorch module that owns the selected device backend.""" + device_type = getattr(device, "type", str(device).split(":")[0]) + return torch.get_device_module(device_type) if hasattr(torch, "get_device_module") else getattr(torch, device_type) + + +@contextmanager +def torch_distributed_zero_first(local_rank: int): + """Ensure all processes in distributed training wait for the local master (rank 0) to complete a task first.""" + initialized = dist.is_available() and dist.is_initialized() + use_ids = initialized and dist.get_backend() == "nccl" + + if initialized and local_rank not in {-1, 0}: + dist.barrier(device_ids=[torch.cuda.current_device()]) if use_ids else dist.barrier() + yield + if initialized and local_rank == 0: + dist.barrier(device_ids=[torch.cuda.current_device()]) if use_ids else dist.barrier() + + +def smart_inference_mode(mode=True): + """Apply or disable torch inference mode while supporting the minimum torch version.""" + + def decorate(fn): + """Apply appropriate torch decorator for inference mode based on torch version.""" + if not mode: + if TORCH_1_9: + + @functools.wraps(fn) + def disable(*args, **kwargs): + with torch.inference_mode(False), torch.no_grad(): + return fn(*args, **kwargs) + + return disable + return torch.no_grad()(fn) + if TORCH_1_9 and torch.is_inference_mode_enabled(): + return fn # already in inference_mode, act as a pass-through + else: + return (torch.inference_mode if TORCH_1_10 else torch.no_grad)()(fn) + + return decorate + + +def autocast(enabled: bool | torch.dtype, device: str = "cuda"): + """Get the appropriate autocast context manager based on PyTorch version and AMP setting. + + This function returns a context manager for automatic mixed precision (AMP) training that is compatible with both + older and newer versions of PyTorch. It handles the differences in the autocast API between PyTorch versions. + + Args: + enabled (bool | torch.dtype): Whether to enable AMP, or the autocast dtype to enable. + device (str, optional): Device type to use for autocast, e.g. "cuda" or "npu". + + Returns: + (torch.amp.autocast): The appropriate autocast context manager. + + Examples: + >>> with autocast(enabled=True): + ... # Your mixed precision operations here + ... pass + + Notes: + Uses `torch.amp.autocast` on torch>=1.13 and the backend-specific AMP context on older releases. + """ + dtype = enabled if isinstance(enabled, torch.dtype) else None + enabled = bool(enabled) + if dtype is torch.bfloat16: + bf16_supported = device == "cuda" and TORCH_1_13 + if bf16_supported: + bf16_supported = ( + torch.cuda.is_bf16_supported(including_emulation=False) + if TORCH_2_4 + else torch.cuda.is_bf16_supported() + and (bool(torch.version.hip) or torch.cuda.get_device_capability()[0] >= 8) + ) + if not bf16_supported: + raise RuntimeError("bfloat16 autocast requires CUDA with native bfloat16 support and torch>=1.13") + kwargs = {"dtype": dtype} if dtype is not None else {} + if device == "npu": + import torch_npu + + return torch_npu.npu.amp.autocast(enabled=enabled, **kwargs) + if TORCH_1_13: + if device == "mps" and not TORCH_2_5: # MPS autocast added in torch 2.5.0, errors on older versions + device, enabled = "cpu", False + return torch.amp.autocast(device, enabled=enabled, **kwargs) + else: + return torch.cuda.amp.autocast(enabled) + + +@functools.lru_cache +def get_cpu_info(): + """Return a string with system CPU information, i.e. 'Apple M2'.""" + return CPUInfo.name() + + +@functools.lru_cache +def get_gpu_info(index): + """Return a string with system GPU information, i.e. 'Tesla T4, 15102MiB'.""" + properties = torch.cuda.get_device_properties(index) + return f"{properties.name}, {properties.total_memory / (1 << 20):.0f}MiB" + + +def parse_device(device: str | int | list | tuple | torch.device = "") -> str: + """Parse a device request of any form into a canonical device string. + + Args: + device (str | int | list | tuple | torch.device, optional): Device request, e.g. 'cuda:0', '0,1', [0, 1], 'cpu', + 'mps', or '-1' to auto-select an idle GPU ('-1,-1' for two). + + Returns: + (str): Canonical device string, e.g. '', 'cpu', 'mps', '0', or '0,1'. + + Examples: + >>> parse_device("cuda:0") + '0' + + >>> parse_device([0, 1]) + '0,1' + + Notes: + Each '-1' is replaced with an idle GPU index. Requested ids exceeding the torch device count that match + physical GPU ids visible under an external CUDA_VISIBLE_DEVICES restriction are translated to the + corresponding torch indices, e.g. '3' -> '0' when CUDA_VISIBLE_DEVICES='3'; in-range ids are always torch + indices, keeping parsing idempotent. Returned indices are relative to the active restriction, so strings + persisted under one environment (e.g. resumed checkpoint args) address the same physical GPUs only in that + environment. + """ + if isinstance(device, torch.device): + if device.type == "cuda" and device.index is None: + return "" # indexless torch.device('cuda') means the current CUDA device, i.e. the '' default request + if device.type == "cpu": + return "cpu" # an indexed torch.device('cpu', 0) is the same cpu + if device.type in {"npu", "xpu"}: + return device.type if device.index is None else f"{device.type}:{device.index}" + device = str(device).lower() + for remove in "cuda:", "none", "(", ")", "[", "]", "'", " ": + device = device.replace(remove, "") # to string, 'cuda:0' -> '0' and '(0, 1)' -> '0,1' + if device == "cuda": + device = "0" + for backend in ("npu", "xpu"): + if device.startswith(backend): + indices = device[len(backend) :].lstrip(":").replace(f"{backend}:", "") + indices = ",".join(str(int(x)) if x.isdigit() else x for x in indices.split(",") if x) + return f"{backend}:{indices}" if indices else backend + device = ",".join(str(int(x)) if x.isdigit() else x for x in device.split(",") if x) # "0,,01" -> "0,1" + # Visible physical ids normalized like requested ids and truncated to the torch device count, mirroring CUDA's + # atoi-style parsing and its stop at the first invalid CVD entry + cvd = os.environ.get("CUDA_VISIBLE_DEVICES", "").replace(" ", "") + visible = [str(int(x)) if x.isdigit() else x for x in cvd.split(",") if x][: torch.cuda.device_count()] + indices = [x for x in device.split(",") if x.isdigit()] # requested ids, excluding '-1' and non-numeric tokens + if indices and all(x in visible for x in indices) and any(int(x) >= torch.cuda.device_count() for x in indices): + # Ids exceeding the torch device count can only be physical GPU ids under an external CUDA_VISIBLE_DEVICES + # restriction -> translate to torch indices; in-range ids are torch indices, keeping repeated parses stable + device = ",".join(str(visible.index(x)) if x.isdigit() else x for x in device.split(",")) + if "-1" in device: + from ultralytics.utils.autodevice import GPUInfo + + # Replace each -1 with an idle GPU or remove it; GPUInfo searches physical NVML ids among externally visible + # GPUs only, translated back to torch indices under a CUDA_VISIBLE_DEVICES restriction + parts = device.split(",") + candidates = [int(x) for x in visible if x.isdigit()] if visible else None + selected = GPUInfo().select_idle_gpu(count=parts.count("-1"), min_memory_fraction=0.2, indices=candidates) + selected = [visible.index(str(x)) for x in selected] if visible else selected + for i in range(len(parts)): + if parts[i] == "-1": + parts[i] = str(selected.pop(0)) if selected else "" + device = ",".join(p for p in parts if p) + return device + + +def select_device(device="", newline=False, verbose=True): + """Select the appropriate PyTorch device based on the provided arguments. + + The function takes a string specifying the device or a torch.device object and returns a torch.device object + representing the selected device. The function also validates the number of available devices and raises an + exception if the requested device(s) are not available. + + Args: + device (str | torch.device, optional): Device string or torch.device object. Options include 'cpu', 'cuda', '0', + '0,1,2,3', 'mps', 'npu:0', 'npu:0,1', 'xpu:0', 'xpu:0,1', or '-1' for auto-select. Defaults to auto-selecting + the first available GPU, or CPU if no GPU is available. + newline (bool, optional): If True, adds a newline at the end of the log string. + verbose (bool, optional): If True, logs the device information. + + Returns: + (torch.device): Selected device. + + Examples: + >>> select_device("cuda:0") + device(type='cuda', index=0) + + >>> select_device("cpu") + device(type='cpu') + + Notes: + CUDA indices are torch device indices, which reflect any externally set CUDA_VISIBLE_DEVICES. This function + never modifies CUDA_VISIBLE_DEVICES; an explicit single-GPU request is made the default CUDA device with + torch.cuda.set_device() so that indexless 'cuda' operations land on it, while default '' requests (resolved + to the current device) and multi-GPU requests (DDP ranks pin their own device in trainer._setup_ddp()) leave + the current device untouched. + """ + if isinstance(device, torch.device): + if device.type not in {"cpu", "cuda", "npu", "xpu"}: + return device # other torch.device inputs pass through; cpu and accelerator inputs canonicalize below + elif str(device).startswith(("tpu", "intel", "vulkan")): + return device + + s = f"Ultralytics {__version__} 🚀 Python-{PYTHON_VERSION} torch-{TORCH_VERSION} " + device = parse_device(device) + + if device.startswith(("npu", "xpu")): + device_type = device.split(":", 1)[0] + if device_type == "npu": + try: + import torch_npu # noqa + except ImportError: + raise ValueError( + f"Invalid NPU 'device={device}'. Install 'torch_npu' at https://github.com/Ascend/pytorch" + ) + if not hasattr(torch, device_type): + raise ValueError(f"Invalid {device_type.upper()} 'device={device}' requested. Backend is not available.") + backend = get_torch_device_backend(device_type) + if not backend.is_available(): + raise ValueError(f"Invalid {device_type.upper()} 'device={device}' requested. Backend is not available.") + + requested = ["0"] if device == device_type else device[4:].split(",") + indices = [int(x) for x in requested if x.isdigit()] + if not indices or len(indices) != len(requested) or len(indices) != len(set(indices)): + raise ValueError( + f"Invalid {device_type.upper()} 'device={device}' format. " + f"Use '{device_type}', '{device_type}:0', or '{device_type}:0,1'." + ) + n = backend.device_count() + if any(idx >= n for idx in indices): + raise ValueError( + f"Invalid {device_type.upper()} 'device={device}' requested. Only {n} device(s) available." + ) + + if len(indices) == 1: + backend.set_device(indices[0]) # multi-device DDP ranks each pin their device in trainer._setup_ddp() + if verbose: + space = " " * len(s) + for i, idx in enumerate(indices): + s += f"{'' if i == 0 else space}{device_type.upper()}:{idx} ({backend.get_device_name(idx)})\n" + LOGGER.info(s if newline else s.rstrip()) + return torch.device(device_type, indices[0]) + + cpu = device == "cpu" + mps = device in {"mps", "mps:0"} # Apple Metal Performance Shaders (MPS) + if not cpu and not mps and device: # non-cpu device requested + valid = all(x.isdigit() and int(x) < torch.cuda.device_count() for x in device.split(",")) + if not (torch.cuda.is_available() and valid): + LOGGER.info(s) + install = ( + "See https://pytorch.org/get-started/locally/ for up-to-date torch install instructions if no " + "CUDA devices are seen by torch.\n" + if torch.cuda.device_count() == 0 + else "" + ) + raise ValueError( + f"Invalid CUDA 'device={device}' requested." + f" Use 'device=cpu' or pass valid CUDA device(s) if available," + f" i.e. 'device=0' or 'device=0,1,2,3' for Multi-GPU.\n" + f"\ntorch.cuda.is_available(): {torch.cuda.is_available()}" + f"\ntorch.cuda.device_count(): {torch.cuda.device_count()}" + f"\nos.environ['CUDA_VISIBLE_DEVICES']: {os.environ.get('CUDA_VISIBLE_DEVICES')}\n" + f"{install}" + ) + + if not cpu and not mps and torch.cuda.is_available(): # prefer GPU if available + devices = device.split(",") if device else [str(torch.cuda.current_device())] # '' -> current default device + space = " " * len(s) + for i, d in enumerate(devices): + s += f"{'' if i == 0 else space}CUDA:{d} ({get_gpu_info(int(d))})\n" + arg = f"cuda:{devices[0]}" + if device and len(devices) == 1: # explicit single-GPU request only: '' never moves the current device, and + torch.cuda.set_device(int(devices[0])) # multi-GPU DDP ranks each pin their own device in _setup_ddp() + elif mps and TORCH_2_0 and torch.backends.mps.is_available(): + # Prefer MPS if available + s += f"MPS ({get_cpu_info()})\n" + arg = "mps" + else: # revert to CPU + s += f"CPU ({get_cpu_info()})\n" + arg = "cpu" + + if arg in {"cpu", "mps"}: + torch.set_num_threads(NUM_THREADS) # reset OMP_NUM_THREADS for cpu training + if arg == "cpu" and MACOS and ARM64 and TORCH_2_3: + torch.backends.nnpack.set_flags(False) # NNPACK conv2d at batch>=16 is 6x slower than im2col on Apple silicon + if verbose: + LOGGER.info(s if newline else s.rstrip()) + return torch.device(arg) + + +def time_sync(device: torch.device | None = None): + """Return PyTorch-accurate time.""" + if device is None or device.type not in {"cpu", "mps"}: + accelerator = get_torch_device_backend(device or "cuda") + if accelerator.is_available() and hasattr(accelerator, "synchronize"): + accelerator.synchronize() + return time.perf_counter() + + +def fuse_conv_and_bn(conv, bn): + """Fuse Conv2d and BatchNorm2d layers for inference optimization. + + Args: + conv (nn.Conv2d): Convolutional layer to fuse. + bn (nn.BatchNorm2d): Batch normalization layer to fuse. + + Returns: + (nn.Conv2d): The fused convolutional layer with gradients disabled. + + Examples: + >>> conv = nn.Conv2d(3, 16, 3) + >>> bn = nn.BatchNorm2d(16) + >>> fused_conv = fuse_conv_and_bn(conv, bn) + """ + conv.weight, conv.bias = fuse_conv_bn_weights( + conv.weight, conv.bias, bn.running_mean, bn.running_var, bn.eps, bn.weight, bn.bias + ) + q = getattr(conv, "weight_quantizer", None) + if q is not None: # QAT: the per-channel weight range scales with the folded BN, so the INT8 codes do not move + q.amax = q.amax * (bn.weight / torch.sqrt(bn.running_var + bn.eps)).abs().view_as(q.amax) + return conv.requires_grad_(False) + + +def fuse_deconv_and_bn(deconv, bn): + """Fuse ConvTranspose2d and BatchNorm2d layers for inference optimization. + + Args: + deconv (nn.ConvTranspose2d): Transposed convolutional layer to fuse. + bn (nn.BatchNorm2d): Batch normalization layer to fuse. + + Returns: + (nn.ConvTranspose2d): The fused transposed convolutional layer with gradients disabled. + + Examples: + >>> deconv = nn.ConvTranspose2d(16, 3, 3) + >>> bn = nn.BatchNorm2d(3) + >>> fused_deconv = fuse_deconv_and_bn(deconv, bn) + """ + if isinstance(bn, nn.Identity): # ConvTranspose(bn=False) leaves bn as nn.Identity, nothing to fuse + return deconv.requires_grad_(False) + # ConvTranspose2d weight is [in_channels, out_channels // groups, kH, kW]; view it in the Conv2d layout + # [out_channels, in_channels // groups, kH, kW] so the per-output-channel BN scale folds along axis 0 + g, (ci, co, *k) = deconv.groups, deconv.weight.shape + weight = deconv.weight.view(g, ci // g, co, *k).transpose(1, 2).reshape(g * co, ci // g, *k) + weight, deconv.bias = fuse_conv_bn_weights( + weight, deconv.bias, bn.running_mean, bn.running_var, bn.eps, bn.weight, bn.bias + ) + deconv.weight = nn.Parameter(weight.view(g, co, ci // g, *k).transpose(1, 2).reshape(ci, co, *k)) + return deconv.requires_grad_(False) + + +# ModelOpt's torch plugins import huggingface_hub unconditionally but declare it only under its heavy [hf] extra, +# so a bare install cannot import modelopt.torch at all +MODELOPT_REQUIREMENTS = ["nvidia-modelopt>=0.44", "huggingface_hub"] + + +def prepare_qat(model: nn.Module, dataloader, preprocess, batches: int = 8) -> nn.Module: + """Insert INT8 fake-quantization into a model for quantization-aware training (QAT). + + Swaps Conv and Linear layers for ModelOpt equivalents that fake-quantize their input and weight, so training learns + weights that survive INT8 export and `torch.onnx.export` emits those ranges as Q/DQ nodes. Activation and weight + ranges are calibrated once from `batches` batches and then held fixed (ModelOpt's INT8 config keeps `amax` as a + buffer, not a learnable parameter), so training adapts the weights to them. + + Training keeps BatchNorm unfused; `fuse()` folds it at export and rescales the weight ranges along. The head's + output layers, the bare convolutions and linears outside its `Conv` blocks, are left in float to limit INT8 accuracy + loss. + + Args: + model (nn.Module): Model to prepare, modified in place. + dataloader (Iterable): Loader yielding Ultralytics batches for the initial range calibration. + preprocess (Callable): Task trainer preprocessing applied to each calibration batch. + batches (int): Number of calibration batches. + + Returns: + (nn.Module): The prepared model, carrying fake-quantization modules. + """ + with torch_distributed_zero_first(LOCAL_RANK): + check_requirements(MODELOPT_REQUIREMENTS) + import modelopt.torch.quantization as mtq + + def forward_loop(m): + """Calibrate through the task batch path.""" + for batch, _ in zip(dataloader, range(batches)): + m(preprocess(batch)) + + LOGGER.info(f"Preparing INT8 quantization-aware training from {batches} calibration batches...") + training = model.training + model.eval() # freeze BatchNorm statistics + with torch.no_grad(): + model = mtq.quantize(model, mtq.INT8_DEFAULT_CFG, forward_loop) + # Keep the head's output layers, the bare convolutions and linears outside its Conv blocks, in float to limit + # INT8 accuracy loss. DFL's fixed conv is left in float too. + head = f"model.{len(model.model) - 1}." + mtq.disable_quantizer(model, lambda n: n.startswith(head) and (".conv." not in n or ".dfl." in n)) + model.train(training) + return model + + +def is_qat(model: nn.Module) -> bool: + """Return True if the model carries fake-quantization modules inserted by `prepare_qat`. + + Matched by class name so that non-QAT models, i.e. every ordinary export, never import ModelOpt. + """ + model = model.model if isinstance(getattr(model, "model", None), nn.Module) else model + return any(type(m).__name__ == "TensorQuantizer" for m in model.modules()) + + +def qat_state(model: nn.Module) -> dict[str, Any] | None: + """Return the state that reproduces a model's fake-quantization, or None if it carries none. + + Ultralytics checkpoints are pickled modules, but ModelOpt builds its quantized layers as classes created at runtime, + which pickle cannot look up on load. The quantization therefore travels beside the module as data. The checkpoint + writers read it here and `restore_qat` reconstructs it at load and resume. + + Args: + model (nn.Module): Model to read, left untouched. + + Returns: + (dict | None): ModelOpt conversion state and the calibrated quantizer ranges, or None for a plain model. + """ + model = getattr(model, "student_model", model) # distillation checkpoints quantize only the student + if not is_qat(model): + return None + import modelopt.torch.opt as mto + + return { + "modelopt": mto.modelopt_state(model), + "ranges": {k: v for k, v in model.state_dict().items() if "quantizer" in k}, + } + + +def strip_qat(model: nn.Module) -> None: + """Revert a model's fake-quantization in place, leaving the plain layers it wraps. + + Checkpoint writers call this on the copy they are about to pickle, after `qat_state` has read the quantization out + of it, since the runtime-generated layer classes cannot be pickled. + """ + model = getattr(model, "student_model", model) # distillation checkpoints quantize only the student + if not is_qat(model): + return + from modelopt.torch.opt.conversion import ModeloptStateManager + from modelopt.torch.opt.dynamic import DynamicModule + + for m in model.modules(): + if isinstance(m, DynamicModule): + m.export() # revert the runtime class to the plain layer it wraps + m.__dict__.pop("_parallel_state", None) # runtime process groups do not belong in a checkpoint + ModeloptStateManager.remove_state(model) # a reverted copy must not claim to be converted + + +def restore_qat(model: nn.Module, state: dict[str, Any]) -> None: + """Re-apply the fake-quantization captured by `qat_state` to a model, in place.""" + model = getattr(model, "student_model", model) # distillation checkpoints quantize only the student + check_requirements(MODELOPT_REQUIREMENTS) + import modelopt.torch.opt as mto + + mto.restore_from_modelopt_state(model, state["modelopt"]) + model.to(next(model.parameters()).device) + model.load_state_dict(state["ranges"], strict=False) + + +def model_info(model, detailed=False, verbose=True, imgsz=640): + """Print and return detailed model information layer by layer. + + Args: + model (nn.Module): Model to analyze. + detailed (bool, optional): Whether to print detailed layer information. + verbose (bool, optional): Whether to print model information. + imgsz (int | list, optional): Input image size. + + Returns: + (tuple): Tuple containing: + - n_l (int): Number of layers. + - n_p (int): Number of parameters. + - n_g (int): Number of gradients. + - flops (float): GFLOPs. + """ + if not verbose: + return + n_p = get_num_params(model) # number of parameters + n_g = get_num_gradients(model) # number of gradients + layers = __import__("collections").OrderedDict((n, m) for n, m in model.named_modules() if len(m._modules) == 0) + n_l = len(layers) # number of layers + if detailed: + h = f"{'layer':>5}{'name':>40}{'type':>20}{'gradient':>10}{'parameters':>12}{'shape':>20}{'mu':>10}{'sigma':>10}" + LOGGER.info(h) + for i, (mn, m) in enumerate(layers.items()): + mn = mn.replace("module_list.", "") + mt = m.__class__.__name__ + if len(m._parameters): + for pn, p in m.named_parameters(): + LOGGER.info( + f"{i:>5g}{f'{mn}.{pn}':>40}{mt:>20}{p.requires_grad!r:>10}{p.numel():>12g}{list(p.shape)!s:>20}{p.mean():>10.3g}{p.std():>10.3g}{str(p.dtype).replace('torch.', ''):>15}" + ) + else: # layers with no learnable params + LOGGER.info(f"{i:>5g}{mn:>40}{mt:>20}{False!r:>10}{0:>12g}{[]!s:>20}{'-':>10}{'-':>10}{'-':>15}") + + flops = get_flops(model, imgsz) # imgsz may be int or list, i.e. imgsz=640 or imgsz=[640, 320] + fused = " (fused)" if getattr(model, "is_fused", lambda: False)() else "" + fs = f", {flops:.1f} GFLOPs" if flops else "" + yaml_file = getattr(model, "yaml_file", "") or getattr(model, "yaml", {}).get("yaml_file", "") + model_name = Path(yaml_file).stem.replace("yolo", "YOLO") or "Model" + LOGGER.info(f"{model_name} summary{fused}: {n_l:,} layers, {n_p:,} parameters, {n_g:,} gradients{fs}") + return n_l, n_p, n_g, flops + + +def get_num_params(model): + """Return the total number of parameters in a YOLO model.""" + return sum(x.numel() for x in model.parameters()) + + +def get_num_gradients(model): + """Return the total number of parameters with gradients in a YOLO model.""" + return sum(x.numel() for x in model.parameters() if x.requires_grad) + + +def model_info_for_loggers(trainer): + """Return model info dict with useful model information. + + Args: + trainer (ultralytics.engine.trainer.BaseTrainer): The trainer object containing model and validation data. + + Returns: + (dict): Dictionary containing model parameters, GFLOPs, and inference speeds. + + Examples: + YOLOv8n info for loggers + >>> results = { + ... "model/parameters": 3151904, + ... "model/GFLOPs": 8.746, + ... "model/speed_ONNX(ms)": 41.244, + ... "model/speed_TensorRT(ms)": 3.211, + ... "model/speed_PyTorch(ms)": 18.755, + ... } + """ + if trainer.args.profile: # profile ONNX and TensorRT times + from ultralytics.utils.benchmarks import ProfileModels + + results = ProfileModels([trainer.last], device=trainer.device, imgsz=trainer.args.imgsz).run()[0] + results.pop("model/name") + else: # only return PyTorch times from most recent validation + results = { + "model/parameters": get_num_params(trainer.model), + "model/GFLOPs": round(get_flops(trainer.model, trainer.args.imgsz), 3), + } + results["model/speed_PyTorch(ms)"] = round(trainer.validator.speed["inference"], 3) + return results + + +def _attention_ops(m, x, y): + """Count the query-key and attention-value matmuls of an attention block for THOP. + + Both run functionally on reshaped tensors, so no child-module hook observes them and the block would otherwise be + charged only for its qkv/proj/pe convolutions. Each output element of the two products costs one multiply-add over + the contracted axis, giving `tokens**2 * (key_dim + head_dim)` per head. + """ + b, _, h, w = x[0].shape + area = getattr(m, "area", 1) # area attention attends within that many independent groups, AAttn only + tokens = h * w // area + key_dim = getattr(m, "key_dim", m.head_dim) # Attention narrows q and k by attn_ratio, AAttn does not + m.total_ops += b * area * m.num_heads * tokens * tokens * (key_dim + m.head_dim) + + +def get_flops(model, imgsz=640): + """Calculate FLOPs (floating point operations) for a model in GFLOPs. + + Uses THOP's stride-aware image profiling for efficiency and accurate size-independent operations. Returns 0.0 if + thop is unavailable or profiling fails. + + Args: + model (nn.Module): The model to calculate FLOPs for. + imgsz (int | list, optional): Input image size. + + Returns: + (float): The model's GFLOPs (billions of floating point operations). + """ + try: + import thop + except ImportError: + thop = None # conda support without 'ultralytics-thop' installed + + if not thop: + return 0.0 # if not installed return 0.0 GFLOPs + + try: + from ultralytics.nn.modules.block import AAttn, Attention # imported here: block.py imports this module + from ultralytics.nn.modules.head import RTDETRDecoder + + model = unwrap_model(model) + p = next(model.parameters()) + if not isinstance(imgsz, list): + imgsz = [imgsz, imgsz] # expand if int/float + attn = tuple(m for m in model.modules() if isinstance(m, (Attention, AAttn))) + rtdetr = any(isinstance(m, RTDETRDecoder) for m in model.modules()) + # Attention costs are quadratic in image area, so disable THOP's affine proxy. + stride = None if attn else max(int(model.stride.max()), 32) if hasattr(model, "stride") else 32 + im = torch.empty((1, p.shape[1], *imgsz), device=p.device, dtype=p.dtype) # input image in BCHW format + custom_ops = {Attention: _attention_ops, AAttn: _attention_ops} if attn else None + if rtdetr: # RT-DETR cannot run the stride-sized proxy input + return thop.profile(model, inputs=[im], custom_ops=custom_ops, verbose=False)[0] / 1e9 * 2 + return thop.profile(model, inputs=[im], stride=stride, custom_ops=custom_ops, verbose=False)[0] / 1e9 * 2 + except Exception: + return 0.0 + + +def initialize_weights(model): + """Initialize model weights, biases, and module settings to default values.""" + for m in model.modules(): + t = type(m) + if t is nn.Conv2d: + pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + elif t is nn.BatchNorm2d: + m.eps = 1e-3 + m.momentum = 0.03 + + +def scale_img(img, ratio=1.0, same_shape=False, gs=32): + """Scale and pad an image tensor, optionally maintaining aspect ratio and padding to gs multiple. + + Args: + img (torch.Tensor): Input image tensor. + ratio (float, optional): Scaling ratio. + same_shape (bool, optional): Whether to maintain the same shape. + gs (int, optional): Grid size for padding. + + Returns: + (torch.Tensor): Scaled and padded image tensor. + """ + if ratio == 1.0: + return img + h, w = img.shape[2:] + s = (int(h * ratio), int(w * ratio)) # new size + img = F.interpolate(img, size=s, mode="bilinear", align_corners=False) # resize + if not same_shape: # pad/crop img + h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w)) + return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean + + +def copy_attr(a, b, include=(), exclude=()): + """Copy attributes from object 'b' to object 'a', with options to include/exclude certain attributes. + + Args: + a (Any): Destination object to copy attributes to. + b (Any): Source object to copy attributes from. + include (tuple, optional): Attributes to include. If empty, all attributes are included. + exclude (tuple, optional): Attributes to exclude. + """ + for k, v in b.__dict__.items(): + if (len(include) and k not in include) or k.startswith("_") or k in exclude: + continue + else: + setattr(a, k, v) + + +def intersect_dicts(da, db, exclude=()): + """Return a dictionary of intersecting keys with matching shapes, excluding 'exclude' keys, using da values. + + Args: + da (dict): First dictionary. + db (dict): Second dictionary. + exclude (tuple, optional): Keys to exclude. + + Returns: + (dict): Dictionary of intersecting keys with matching shapes. + """ + return {k: v for k, v in da.items() if k in db and all(x not in k for x in exclude) and v.shape == db[k].shape} + + +def is_parallel(model): + """Return True if model is of type DP or DDP. + + Args: + model (nn.Module): Model to check. + + Returns: + (bool): True if model is DataParallel or DistributedDataParallel. + """ + return isinstance(model, (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)) + + +def unwrap_model(m: nn.Module) -> nn.Module: + """Unwrap compiled and parallel models to get the base model. + + Args: + m (nn.Module): A model that may be wrapped by torch.compile (._orig_mod) or parallel wrappers such as + DataParallel/DistributedDataParallel (.module). + + Returns: + (nn.Module): The unwrapped base model without compile or parallel wrappers. + """ + while True: + if hasattr(m, "_orig_mod") and isinstance(m._orig_mod, nn.Module): + m = m._orig_mod + elif hasattr(m, "module") and isinstance(m.module, nn.Module): + m = m.module + else: + return m + + +def one_cycle(y1=0.0, y2=1.0, steps=100): + """Return a lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf. + + Args: + y1 (float, optional): Initial value. + y2 (float, optional): Final value. + steps (int, optional): Number of steps. + + Returns: + (function): Lambda function for computing the sinusoidal ramp. + """ + return lambda x: max((1 - math.cos(x * math.pi / steps)) / 2, 0) * (y2 - y1) + y1 + + +def init_seeds(seed=0, deterministic=False): + """Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html. + + Args: + seed (int, optional): Random seed. + deterministic (bool, optional): Whether to set deterministic algorithms. + """ + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) # also seeds every CUDA, MPS and XPU device + # torch.backends.cudnn.benchmark = True # AutoBatch problem https://github.com/ultralytics/yolov5/issues/9287 + if deterministic: + if TORCH_2_0: + torch.use_deterministic_algorithms(True, warn_only=True) # warn if deterministic is not possible + torch.backends.cudnn.deterministic = True + if TORCH_2_2: # skip deterministic mode's NaN fill of every new tensor, one fill kernel per allocation + torch.utils.deterministic.fill_uninitialized_memory = False + os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8" + os.environ["PYTHONHASHSEED"] = str(seed) + else: + LOGGER.warning("Upgrade to torch>=2.0.0 for deterministic training.") + else: + unset_deterministic() + + +def unset_deterministic(): + """Unset all the configurations applied for deterministic training.""" + torch.use_deterministic_algorithms(False) + torch.backends.cudnn.deterministic = False + if TORCH_2_2: + torch.utils.deterministic.fill_uninitialized_memory = True + os.environ.pop("CUBLAS_WORKSPACE_CONFIG", None) + os.environ.pop("PYTHONHASHSEED", None) + + +class ModelEMA: + """Updated Exponential Moving Average (EMA) implementation. + + Keeps a moving average of everything in the model state_dict (parameters and buffers). For EMA details see + References. + + To disable EMA set the `enabled` attribute to `False`. + + Attributes: + ema (nn.Module): Copy of the model in evaluation mode. + updates (int): Number of EMA updates. + decay (function): Decay function that determines the EMA weight. + enabled (bool): Whether EMA is enabled. + + References: + - https://github.com/rwightman/pytorch-image-models + - https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage + """ + + def __init__(self, model, decay=0.9999, tau=2000, updates=0): + """Initialize EMA for 'model' with given arguments. + + Args: + model (nn.Module): Model to create EMA for. + decay (float, optional): Maximum EMA decay rate. + tau (int, optional): EMA decay time constant. + updates (int, optional): Initial number of updates. + """ + self.ema = deepcopy(unwrap_model(model)).eval() # FP32 EMA + if hasattr(self.ema, "teacher_model"): + # DistillationModel: strip the teacher so the EMA does not carry a full duplicate copy. + self.ema.teacher_model = None + self.updates = updates # number of EMA updates + self.decay = lambda x: decay * (1 - math.exp(-x / tau)) # decay exponential ramp (to help early epochs) + for p in self.ema.parameters(): + p.requires_grad_(False) + self.enabled = True + self._pairs = None # (ema tensors, model tensors) with floating dtype, built on the first update + + def update(self, model): + """Update EMA parameters. + + Args: + model (nn.Module): Model to update EMA from. + """ + if self.enabled: + self.updates += 1 + d = self.decay(self.updates) + + if self._pairs is None: # the tensors are updated in place, so the lists are built once + msd = unwrap_model(model).state_dict() # model state_dict + ema_v, model_v = [], [] + for k, v in self.ema.state_dict().items(): + if v.dtype.is_floating_point: # true for FP16 and FP32 + ema_v.append(v) + model_v.append(msd[k]) + self._pairs = ema_v, model_v + ema_v, model_v = self._pairs + if ( + ema_v and TORCH_2_0 and ema_v[0].device.type != "npu" and (TORCH_2_4 or ema_v[0].device.type != "mps") + ): # one kernel launch per op + torch._foreach_lerp_(ema_v, model_v, 1 - d) + else: # _foreach_lerp_ needs torch>=2.0, MPS torch>=2.4, and is unavailable on NPU + for v, m in zip(ema_v, model_v): + v.mul_(d).add_(m, alpha=1 - d) + + def update_attr(self, model, include=(), exclude=()): + """Copy attributes from model to EMA, with options to include/exclude certain attributes. + + Args: + model (nn.Module): Model to copy attributes from; compile and parallel wrappers are unwrapped first. + include (tuple, optional): Attributes to include. + exclude (tuple, optional): Attributes to exclude. + """ + if self.enabled: + copy_attr(self.ema, unwrap_model(model), include, exclude) + + +def strip_optimizer(f: str | Path = "best.pt", s: str = "", updates: dict[str, Any] | None = None) -> dict[str, Any]: + """Strip optimizer from 'f' to finalize training, optionally save as 's'. + + Args: + f (str | Path): File path to model to strip the optimizer from. + s (str, optional): File path to save the model with stripped optimizer to. If not provided, 'f' will be + overwritten. + updates (dict, optional): A dictionary of updates to overlay onto the checkpoint before saving. + + Returns: + (dict): The combined checkpoint dictionary. + + Examples: + >>> from pathlib import Path + >>> from ultralytics.utils.torch_utils import strip_optimizer + >>> for f in Path("path/to/model/checkpoints").rglob("*.pt"): + ... strip_optimizer(f) + """ + try: + x = torch_load(f, map_location=torch.device("cpu")) + assert isinstance(x, dict), "checkpoint is not a Python dictionary" + assert "model" in x, "'model' missing from checkpoint" + except Exception as e: + LOGGER.warning(f"Skipping {f}, not a valid Ultralytics model: {e}") + return {} + + metadata = { + "date": datetime.now().astimezone().isoformat(), + "version": __version__, + "license": "AGPL-3.0 License (https://ultralytics.com/license)", + "docs": "https://docs.ultralytics.com", + } + + # Update model + if x.get("ema"): + x["model"] = x["ema"] # replace model with EMA + + # Unwrap DistillationModel to save only the student model + from ultralytics.nn.distill_model import DistillationModel + + if isinstance(x["model"], DistillationModel): + x["model"]._remove_feature_hooks() + x["model"] = x["model"].student_model + + if hasattr(x["model"], "args"): + x["model"].args = dict(x["model"].args) # convert from IterableSimpleNamespace to dict + if hasattr(x["model"], "criterion"): + x["model"].criterion = None # strip loss criterion + x["model"].half() # to FP16 + for p in x["model"].parameters(): + p.requires_grad = False + + # Update other keys + args = {**DEFAULT_CFG_DICT, **x.get("train_args", {})} # combine args + for k in "optimizer", "best_fitness", "ema", "updates", "scaler": # keys + x[k] = None + x["epoch"] = -1 + x["train_args"] = {k: v for k, v in args.items() if k in DEFAULT_CFG_KEYS} # strip non-default keys + # x['model'].args = x['train_args'] + + # Save + combined = {**metadata, **x, **(updates or {})} + torch.save(combined, s or f) # combine dicts (prefer to the right) + mb = os.path.getsize(s or f) / 1e6 # file size + LOGGER.info(f"Optimizer stripped from {f},{f' saved as {s},' if s else ''} {mb:.1f}MB") + return combined + + +def convert_optimizer_state_dict_to_fp16(state_dict): + """Convert the state_dict of a given optimizer to FP16, focusing on the 'state' key for tensor conversions. + + Args: + state_dict (dict): Optimizer state dictionary. + + Returns: + (dict): Converted optimizer state dictionary with FP16 tensors. + """ + for state in state_dict["state"].values(): + for k, v in state.items(): + if k not in {"step", "exp_avg_sq"} and isinstance(v, torch.Tensor) and v.dtype is torch.float32: + state[k] = v.half() + + return state_dict + + +@contextmanager +def cuda_memory_usage(device=None): + """Monitor and manage accelerator memory usage. + + This function empties the active accelerator cache, yields a dictionary containing memory usage information, and + then records the reserved memory on the specified device. + + Args: + device (torch.device, optional): The accelerator device to query memory usage for. + + Yields: + (dict): A dictionary with a key 'memory' initialized to 0, updated with reserved memory. + """ + info = {"memory": 0} + if device is not None and device.type in {"cpu", "mps"}: + yield info + return + accelerator = get_torch_device_backend(device or "cuda") + if accelerator.is_available() and hasattr(accelerator, "memory_reserved"): + accelerator.empty_cache() + try: + yield info + finally: + info["memory"] = accelerator.memory_reserved(device) + else: + yield info + + +def profile_ops(input, ops, n=10, device=None, max_num_obj=0): + """Ultralytics speed, memory and FLOPs profiler. + + Args: + input (torch.Tensor | list): Input tensor(s) to profile. + ops (nn.Module | list): Model or list of operations to profile. + n (int, optional): Number of iterations to average. + device (str | torch.device, optional): Device to profile on. + max_num_obj (int, optional): Maximum number of objects for simulation. + + Returns: + (list): Profile results for each operation. + + Examples: + >>> from ultralytics.utils.torch_utils import profile_ops + >>> input = torch.randn(16, 3, 640, 640) + >>> m1 = lambda x: x * torch.sigmoid(x) + >>> m2 = nn.SiLU() + >>> profile_ops(input, [m1, m2], n=100) # profile over 100 iterations + """ + try: + import thop + except ImportError: + thop = None # conda support without 'ultralytics-thop' installed + + results = [] + device = select_device(device, verbose=False) + LOGGER.info( + f"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}" + f"{'input':>24s}{'output':>24s}" + ) + gc.collect() # attempt to free unused memory + accelerator = get_torch_device_backend(device) if device.type not in {"cpu", "mps"} else None + if accelerator is not None: + accelerator.empty_cache() + for x in input if isinstance(input, list) else [input]: + x = x.to(device) + x.requires_grad = True + for m in ops if isinstance(ops, list) else [ops]: + m = m.to(device) if hasattr(m, "to") else m # device + m = m.half() if hasattr(m, "half") and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m + tf, tb, t = 0, 0, [0, 0, 0] # dt forward, backward + try: + flops = thop.profile(m, inputs=[x], verbose=False)[0] / 1e9 * 2 if thop else 0 # GFLOPs + except Exception: + flops = 0 + + try: + mem = 0 + for _ in range(n): + with cuda_memory_usage(device) as cuda_info: + t[0] = time_sync(device) + y = m(x) + t[1] = time_sync(device) + try: + (sum(yi.sum() for yi in y) if isinstance(y, list) else y).sum().backward() + t[2] = time_sync(device) + except Exception: # no backward method + # print(e) # for debug + t[2] = float("nan") + mem += cuda_info["memory"] / 1e9 # (GB) + tf += (t[1] - t[0]) * 1000 / n # ms per op forward + tb += (t[2] - t[1]) * 1000 / n # ms per op backward + if max_num_obj: # simulate training with predictions per image grid (for AutoBatch) + with cuda_memory_usage(device) as cuda_info: + anchors = int(sum((x.shape[-1] / s) * (x.shape[-2] / s) for s in m.stride.tolist())) + # Conservative detect-loss envelope: ~6 fp32-equivalents each for TaskAlignedAssigner + # metric/top-k state and the cls path (pred/target + two op temps of unreduced BCE: + # ~4 in pure fp32, ~6 under AMP where autocast upcasts both BCE inputs to fp32 copies) + sim = ( + torch.randn(x.shape[0], 6 * max_num_obj, anchors, device=device, dtype=torch.float32), + torch.randn(x.shape[0], anchors, 6 * len(m.names), device=device, dtype=torch.float32), + ) + del sim + mem += cuda_info["memory"] / 1e9 # (GB) + s_in, s_out = (tuple(x.shape) if isinstance(x, torch.Tensor) else "list" for x in (x, y)) # shapes + p = sum(x.numel() for x in m.parameters()) if isinstance(m, nn.Module) else 0 # parameters + LOGGER.info(f"{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{s_in!s:>24s}{s_out!s:>24s}") + results.append([p, flops, mem, tf, tb, s_in, s_out]) + except Exception as e: + LOGGER.info(e) + results.append(None) + finally: + gc.collect() # attempt to free unused memory + if accelerator is not None: + accelerator.empty_cache() + return results + + +class EarlyStopping: + """Early stopping class that stops training when a specified number of epochs have passed without improvement. + + Attributes: + best_fitness (float): Best fitness value observed. + best_epoch (int): Epoch where best fitness was observed. + patience (int): Number of epochs to wait after fitness stops improving before stopping. + possible_stop (bool): Flag indicating if stopping may occur next epoch. + """ + + def __init__(self, patience=50): + """Initialize early stopping object. + + Args: + patience (int, optional): Number of epochs to wait after fitness stops improving before stopping. + """ + self.best_fitness = 0.0 # i.e. mAP + self.best_epoch = 0 + self.patience = patience or float("inf") # epochs to wait after fitness stops improving to stop + self.possible_stop = False # possible stop may occur next epoch + + def __call__(self, epoch, fitness): + """Check whether to stop training. + + Args: + epoch (int): Current epoch of training. + fitness (float): Fitness value of current epoch. + + Returns: + (bool): True if training should stop, False otherwise. + """ + if fitness is None: # check if fitness=None (happens when val=False) + return False + + if fitness > self.best_fitness or self.best_fitness == 0: # allow for early zero-fitness stage of training + self.best_epoch = epoch + self.best_fitness = fitness + delta = epoch - self.best_epoch # epochs without improvement + self.possible_stop = delta >= (self.patience - 1) # possible stop may occur next epoch + stop = delta >= self.patience # stop training if patience exceeded + if stop: + prefix = colorstr("EarlyStopping: ") + LOGGER.info( + f"{prefix}Training stopped early as no improvement observed in last {self.patience} epochs. " + f"Best results observed at epoch {self.best_epoch}, best model saved as best.pt.\n" + f"To update EarlyStopping(patience={self.patience}) pass a new patience value, " + f"i.e. `patience=300` or use `patience=0` to disable EarlyStopping." + ) + return stop + + +def attempt_compile( + model: torch.nn.Module, + device: torch.device, + imgsz: int = 640, + use_autocast: bool = False, + warmup: bool = False, + mode: bool | str = "default", +) -> torch.nn.Module: + """Compile a model with torch.compile and optionally warm up the graph to reduce first-iteration latency. + + This utility attempts to compile the provided model using the inductor backend. If compilation is unavailable or + fails, the original model is returned unchanged. An optional warmup performs a single forward pass on a dummy input + to prime the compiled graph and measure compile/warmup time. + + Args: + model (torch.nn.Module): Model to compile. + device (torch.device): Inference device used for warmup and autocast decisions. + imgsz (int, optional): Square input size to create a dummy tensor with shape (1, 3, imgsz, imgsz) for warmup. + use_autocast (bool, optional): Whether to run warmup under autocast on CUDA or MPS devices. + warmup (bool, optional): Whether to execute a single dummy forward pass to warm up the compiled model. + mode (bool | str, optional): torch.compile mode. True → "default", False → no compile, or a string like + "default", "reduce-overhead", "max-autotune-no-cudagraphs". + + Returns: + (torch.nn.Module): Compiled model if compilation succeeds, otherwise the original unmodified model. + + Examples: + >>> device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") + >>> # Try to compile and warm up a model with a 640x640 input + >>> model = attempt_compile(model, device=device, imgsz=640, use_autocast=True, warmup=True) + + Notes: + - If the current PyTorch build does not provide torch.compile, the function returns the input model immediately. + - Compilation is lazy and runs at the first forward pass, so the inductor CPU prerequisite of a host C++ + compiler is verified up front and the original model is returned if none is available. + - Warmup runs under torch.inference_mode and may use torch.autocast for CUDA/MPS to align compute precision. + - CUDA devices are synchronized after warmup to account for asynchronous kernel execution. + """ + if not hasattr(torch, "compile") or not mode: + return model + if is_qat(model): + raise ValueError("QAT models do not support torch.compile. Use compile=False.") + + if mode is True: + mode = "default" + prefix = colorstr("compile:") + if device.type == "cpu": + try: # compilation is lazy, so verify the inductor CPU requirement of a host C++ compiler before compiling + from torch._inductor.cpp_builder import get_cpp_compiler + + get_cpp_compiler() + except ImportError: + pass # older torch without cpp_builder, defer to torch.compile + except Exception as e: + LOGGER.warning(f"{prefix} no C++ compiler found for the inductor backend, continuing uncompiled: {e}") + return model + LOGGER.info(f"{prefix} starting torch.compile with '{mode}' mode...") + t0 = time.perf_counter() + try: + model = torch.compile(model, mode=mode, backend="inductor") + except Exception as e: + LOGGER.warning(f"{prefix} torch.compile failed, continuing uncompiled: {e}") + return model + t_compile = time.perf_counter() - t0 + + t_warm = 0.0 + if warmup: + # Use a single dummy tensor to build the graph shape state and reduce first-iteration latency + dummy = torch.zeros(1, 3, imgsz, imgsz, device=device) + if use_autocast and device.type == "cuda": + dummy = dummy.half() + t1 = time.perf_counter() + with torch.inference_mode(): + if use_autocast and device.type in {"cuda", "mps"}: + with torch.autocast(device.type): + _ = model(dummy) + else: + _ = model(dummy) + if device.type == "cuda": + torch.cuda.synchronize(device) + t_warm = time.perf_counter() - t1 + + total = t_compile + t_warm + if warmup: + LOGGER.info(f"{prefix} complete in {total:.1f}s (compile {t_compile:.1f}s + warmup {t_warm:.1f}s)") + else: + LOGGER.info(f"{prefix} compile complete in {t_compile:.1f}s (no warmup)") + return model diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/tqdm.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/tqdm.py new file mode 100644 index 0000000000000000000000000000000000000000..bc9e85026928a7106917e3936cc52cf43cb09704 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/tqdm.py @@ -0,0 +1,473 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import os +import shutil +import sys +import time +import unicodedata +from functools import lru_cache +from typing import IO, Any + +from typing_extensions import Self + + +@lru_cache(maxsize=1) +def is_noninteractive_console() -> bool: + """Check for known non-interactive console environments.""" + return "GITHUB_ACTIONS" in os.environ + + +class TQDM: + """Lightweight zero-dependency progress bar for Ultralytics. + + Provides clean, rich-style progress bars suitable for various environments including Weights & Biases, console + outputs, and other logging systems. Features zero external dependencies, clean single-line output, rich-style + progress bars with Unicode block characters, context manager support, iterator protocol support, and dynamic + description updates. + + Attributes: + iterable (Any): Iterable to wrap with progress bar. + desc (str): Prefix description for the progress bar. + total (int | None): Expected number of iterations. + disable (bool): Whether to disable the progress bar. + unit (str): String for units of iteration. + unit_scale (bool): Auto-scale units flag. + unit_divisor (int): Divisor for unit scaling. + leave (bool): Whether to leave the progress bar after completion. + mininterval (float): Minimum time interval between updates. + initial (int): Initial counter value. + n (int): Current iteration count. + closed (bool): Whether the progress bar is closed. + bar_format (str | None): Custom bar format string. + file (IO[str]): Output file stream. + + Methods: + update: Update progress by n steps. + set_description: Set or update the description. + set_postfix: Set postfix for the progress bar. + close: Close the progress bar and clean up. + refresh: Refresh the progress bar display. + clear: Clear the progress bar from display. + write: Write a message without breaking the progress bar. + + Examples: + Basic usage with iterator: + >>> for i in TQDM(range(100)): + ... time.sleep(0.01) + + With custom description: + >>> pbar = TQDM(range(100), desc="Processing") + >>> for i in pbar: + ... pbar.set_description(f"Processing item {i}") + + Context manager usage: + >>> with TQDM(total=100, unit="B", unit_scale=True) as pbar: + ... for i in range(100): + ... pbar.update(1) + + Manual updates: + >>> pbar = TQDM(total=100, desc="Training") + >>> for epoch in range(100): + ... # Do work + ... pbar.update(1) + >>> pbar.close() + """ + + # Constants + MIN_RATE_CALC_INTERVAL = 0.01 # Minimum time interval for rate calculation + RATE_SMOOTHING_FACTOR = 0.3 # Factor for exponential smoothing of rates + MAX_SMOOTHED_RATE = 1000000 # Maximum rate to apply smoothing to + NONINTERACTIVE_MIN_INTERVAL = 60.0 # Minimum interval for non-interactive environments + + def __init__( + self, + iterable: Any = None, + desc: str | None = None, + total: int | None = None, + leave: bool = True, + file: IO[str] | None = None, + mininterval: float = 0.1, + disable: bool | None = None, + unit: str = "it", + unit_scale: bool = True, + unit_divisor: int = 1000, + bar_format: str | None = None, # kept for API compatibility; not used for formatting + initial: int = 0, + **kwargs, + ) -> None: + """Initialize the TQDM progress bar with specified configuration options. + + Args: + iterable (Any, optional): Iterable to wrap with progress bar. + desc (str, optional): Prefix description for the progress bar. + total (int, optional): Expected number of iterations. + leave (bool, optional): Whether to leave the progress bar after completion. + file (IO[str], optional): Output file stream for progress display. + mininterval (float, optional): Minimum time interval between updates (default 0.1s, 60s in GitHub Actions). + disable (bool, optional): Whether to disable the progress bar. Auto-detected if None. + unit (str, optional): String for units of iteration (default "it" for items). + unit_scale (bool, optional): Auto-scale units for bytes/data units. + unit_divisor (int, optional): Divisor for unit scaling (default 1000). + bar_format (str, optional): Custom bar format string. + initial (int, optional): Initial counter value. + **kwargs (Any): Additional keyword arguments for compatibility (ignored). + """ + # Disable if not verbose + if disable is None: + try: + from ultralytics.utils import LOGGER, VERBOSE + + disable = not VERBOSE or LOGGER.getEffectiveLevel() > 20 + except ImportError: + disable = False + + self.iterable = iterable + self.desc = desc or "" + self.total = total or (len(iterable) if hasattr(iterable, "__len__") else None) or None # prevent total=0 + self.disable = disable + self.unit = unit + self.unit_scale = unit_scale + self.unit_divisor = unit_divisor + self.leave = leave + self.noninteractive = is_noninteractive_console() + self.mininterval = max(mininterval, self.NONINTERACTIVE_MIN_INTERVAL) if self.noninteractive else mininterval + self.initial = initial + + # Kept for API compatibility (unused for f-string formatting) + self.bar_format = bar_format + + self.file = file or sys.stdout + + # Internal state + self.n = self.initial + self.last_print_n = self.initial + self.last_print_t = time.time() + self.start_t = time.time() + self.last_rate = 0.0 + self.closed = False + self.is_bytes = unit_scale and unit in {"B", "bytes"} + self.scales = ( + [(1073741824, "GB/s"), (1048576, "MB/s"), (1024, "KB/s")] + if self.is_bytes + else [(1e9, f"G{self.unit}/s"), (1e6, f"M{self.unit}/s"), (1e3, f"K{self.unit}/s")] + ) + + if not self.disable and self.total and not self.noninteractive: + self._display() + + def _format_rate(self, rate: float) -> str: + """Format rate with units, switching between it/s and s/it for readability.""" + if rate <= 0: + return "" + + inv_rate = 1 / rate if rate else None + + # Use s/it format when inv_rate > 1 (i.e., rate < 1 it/s) for better readability + if inv_rate and inv_rate > 1: + return f"{inv_rate:.1f}s/B" if self.is_bytes else f"{inv_rate:.1f}s/{self.unit}" + + # Use it/s format for fast iterations + fallback = f"{rate:.1f}B/s" if self.is_bytes else f"{rate:.1f}{self.unit}/s" + return next((f"{rate / t:.1f}{u}" for t, u in self.scales if rate >= t), fallback) + + def _format_num(self, num: float) -> str: + """Format number with optional unit scaling.""" + if not self.unit_scale or not self.is_bytes: + return str(num) + + for unit in ("", "K", "M", "G", "T"): + if abs(num) < self.unit_divisor: + return f"{num:3.1f}{unit}B" if unit else f"{num:.0f}B" + num /= self.unit_divisor + return f"{num:.1f}PB" + + @staticmethod + def _format_time(seconds: float) -> str: + """Format time duration.""" + if seconds < 60: + return f"{seconds:.1f}s" + elif seconds < 3600: + return f"{int(seconds // 60)}:{seconds % 60:02.0f}" + else: + h, m = int(seconds // 3600), int((seconds % 3600) // 60) + return f"{h}:{m:02d}:{seconds % 60:02.0f}" + + def _generate_bar(self, width: int = 12) -> str: + """Generate progress bar.""" + if self.total is None: + return "━" * width if self.closed else "─" * width + + frac = min(1.0, self.n / self.total) + filled = int(frac * width) + bar = "━" * filled + "─" * (width - filled) + if filled < width and frac * width - filled > 0.5: + bar = f"{bar[:filled]}╸{bar[filled + 1 :]}" + return bar + + @staticmethod + def _fit(text: str, width: int) -> str: + """Truncate text to width display cells, skipping zero-width ANSI codes and counting CJK chars as 2.""" + cells = i = cut = 0 + while i < len(text): + if text[i] == "\033": # ANSI escape sequence: zero width, runs through its letter terminator + while i < len(text) and not text[i].isalpha(): + i += 1 + else: + cells += 2 if unicodedata.east_asian_width(text[i]) in "WF" else 1 + if cells > width: + return f"{text[:cut]}…\033[0m" # reset so a truncated color does not bleed + if cells < width: + cut = i + 1 # last cut that still leaves a cell for the ellipsis + i += 1 + return text + + def _should_update(self, dt: float, dn: int) -> bool: + """Check if display should update.""" + if self.noninteractive: + return False + return (self.total is not None and self.n >= self.total) or (dt >= self.mininterval) + + def _display(self, final: bool = False) -> None: + """Display progress bar.""" + if self.disable or (self.closed and not final): + return + + current_time = time.time() + dt = current_time - self.last_print_t + dn = self.n - self.last_print_n + + if not final and not self._should_update(dt, dn): + return + + # Calculate rate (avoid crazy numbers) + if dt > self.MIN_RATE_CALC_INTERVAL: + rate = dn / dt if dt else 0.0 + # Smooth rate for reasonable values, use raw rate for very high values + if rate < self.MAX_SMOOTHED_RATE: + self.last_rate = self.RATE_SMOOTHING_FACTOR * rate + (1 - self.RATE_SMOOTHING_FACTOR) * self.last_rate + rate = self.last_rate + else: + rate = self.last_rate + + # At completion, use overall rate + if self.total and self.n >= self.total: + overall_elapsed = current_time - self.start_t + if overall_elapsed > 0: + rate = self.n / overall_elapsed + + # Update counters + self.last_print_n = self.n + self.last_print_t = current_time + elapsed = current_time - self.start_t + + # Remaining time + remaining_str = "" + if self.total and 0 < self.n < self.total and elapsed > 0: + est_rate = rate or (self.n / elapsed) + remaining_str = f"<{self._format_time((self.total - self.n) / est_rate)}" + + # Numbers and percent (floor so 100% only shows at true completion) + if self.total: + percent = int(self.n / self.total * 100) + n_str = self._format_num(self.n) + t_str = self._format_num(self.total) + if self.is_bytes and n_str[-2] == t_str[-2]: # Collapse suffix only when identical (e.g. "5.4/5.4MB") + n_str = n_str.rstrip("KMGTPB") + else: + percent = 0.0 + n_str, t_str = self._format_num(self.n), "?" + + elapsed_str = self._format_time(elapsed) + rate_str = self._format_rate(rate) or (self._format_rate(self.n / elapsed) if elapsed > 0 else "") + + bar = self._generate_bar() + + # Compose progress fields via f-strings (two shapes: with/without total) + if self.total: + if self.is_bytes and self.n >= self.total: + # Completed bytes: show only final size + fields = f"{percent:.0f}% {bar} {t_str} {rate_str} {elapsed_str}" + else: + fields = f"{percent:.0f}% {bar} {n_str}/{t_str} {rate_str} {elapsed_str}{remaining_str}" + else: + fields = f"{bar} {n_str} {rate_str} {elapsed_str}" + + # Write to output, fitting real terminals only so redirected logs keep full lines + try: + progress_str = f"{self.desc}: {fields}" + if self.file.isatty() and "JPY_PARENT_PID" not in os.environ: # a notebook pane scrolls, never fit it + try: # measure self.file's own terminal, not sys.__stdout__ + width = os.get_terminal_size(self.file.fileno()).columns - 1 + except Exception: # streams without a usable fileno (io.StringIO, wrapped stdout) + width = shutil.get_terminal_size().columns - 1 # COLUMNS env, else sys.__stdout__ + if width > 0: # a pty opened without a winsize reports 0 columns, so there is no width to fit to + progress_str = self._fit(f"{self._fit(self.desc, width - len(fields) - 2)}: {fields}", width) + # Non-interactive environments avoid the carriage return which creates empty lines + frame = progress_str if self.noninteractive else f"\r\033[K{progress_str}" + if progress := getattr(self.file, "progress", None): + progress(id(self), frame) # a redraw is bar state, so log consumers keep it out of their log + else: + self.file.write(frame) + self.file.flush() + except Exception: + pass + + def update(self, n: int = 1) -> None: + """Update progress by n steps.""" + if not self.disable and not self.closed: + self.n += n + self._display() + + def set_description(self, desc: str | None) -> None: + """Set description.""" + self.desc = desc or "" + if not self.disable: + self._display() + + def set_postfix(self, **kwargs: Any) -> None: + """Set postfix (appends to description).""" + if kwargs: + postfix = ", ".join(f"{k}={v}" for k, v in kwargs.items()) + base_desc = self.desc.split(" | ")[0] if " | " in self.desc else self.desc + self.set_description(f"{base_desc} | {postfix}") + + def close(self) -> None: + """Close progress bar.""" + if self.closed: + return + + self.closed = True + + if not self.disable: + # Final display + if self.total and self.n >= self.total: + self.n = self.total + if self.n != self.last_print_n: # Skip if 100% already shown + self._display(final=True) + else: + self._display(final=True) + + if progress := getattr(self.file, "progress", None): + progress(id(self), "") # bar closed: the last frame is now log content + + # Cleanup + if self.leave: + self.file.write("\n") + else: + self.file.write("\r\033[K") + + try: + self.file.flush() + except Exception: + pass + + def __enter__(self) -> Self: + """Enter context manager.""" + return self + + def __exit__(self, *args: object) -> None: + """Exit context manager and close progress bar.""" + self.close() + + def __iter__(self) -> Any: + """Iterate over the wrapped iterable with progress updates.""" + if self.iterable is None: + raise TypeError("'NoneType' object is not iterable") + + try: + for item in self.iterable: + yield item + self.update(1) + finally: + self.close() + + def __del__(self) -> None: + """Destructor to ensure cleanup.""" + try: + self.close() + except Exception: + pass + + def refresh(self) -> None: + """Refresh display.""" + if not self.disable: + self._display() + + def clear(self) -> None: + """Clear progress bar.""" + if not self.disable: + try: + self.file.write("\r\033[K") + self.file.flush() + except Exception: + pass + + @staticmethod + def write(s: str, file: IO[str] | None = None, end: str = "\n") -> None: + """Static method to write without breaking progress bar.""" + file = file or sys.stdout + try: + file.write(s + end) + file.flush() + except Exception: + pass + + +if __name__ == "__main__": + import time + + print("1. Basic progress bar with known total:") + for i in TQDM(range(3), desc="Known total"): + time.sleep(0.05) + + print("\n2. Manual updates with known total:") + pbar = TQDM(total=300, desc="Manual updates", unit="files") + for i in range(300): + time.sleep(0.03) + pbar.update(1) + if i % 10 == 9: + pbar.set_description(f"Processing batch {i // 10 + 1}") + pbar.close() + + print("\n3. Progress bar with unknown total:") + pbar = TQDM(desc="Unknown total", unit="items") + for i in range(25): + time.sleep(0.08) + pbar.update(1) + if i % 5 == 4: + pbar.set_postfix(processed=i + 1, status="OK") + pbar.close() + + print("\n4. Context manager with unknown total:") + with TQDM(desc="Processing stream", unit="B", unit_scale=True, unit_divisor=1024) as pbar: + for i in range(30): + time.sleep(0.1) + pbar.update(1024 * 1024 * i) # Simulate processing MB of data + + print("\n5. Iterator with unknown length:") + + def data_stream(): + """Simulate a data stream of unknown length.""" + import random + + for i in range(random.randint(10, 20)): + yield f"data_chunk_{i}" + + for chunk in TQDM(data_stream(), desc="Stream processing", unit="chunks"): + time.sleep(0.1) + + print("\n6. File processing simulation (unknown size):") + + def process_files(): + """Simulate processing files of unknown count.""" + return [f"file_{i}.txt" for i in range(18)] + + pbar = TQDM(desc="Scanning files", unit="files") + files = process_files() + for i, filename in enumerate(files): + time.sleep(0.06) + pbar.update(1) + pbar.set_description(f"Processing {filename}") + pbar.close() diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/triton.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/triton.py new file mode 100644 index 0000000000000000000000000000000000000000..a6263694ab2975571b956b6afd57075756f95406 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/triton.py @@ -0,0 +1,112 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import ast +from urllib.parse import urlsplit + +import numpy as np + + +class TritonRemoteModel: + """Client for interacting with a remote Triton Inference Server model. + + This class provides a convenient interface for sending inference requests to a Triton Inference Server and + processing the responses. Supports both HTTP and gRPC communication protocols. + + Attributes: + endpoint (str): The name of the model on the Triton server. + url (str): The URL of the Triton server. + triton_client: The Triton client (either HTTP or gRPC). + InferInput: The input class for the Triton client. + InferRequestedOutput: The output request class for the Triton client. + input_formats (list[str]): The data types of the model inputs. + np_input_formats (list[type]): The numpy data types of the model inputs. + input_names (list[str]): The names of the model inputs. + output_names (list[str]): The names of the model outputs. + metadata: The metadata associated with the model. + + Methods: + __call__: Call the model with the given inputs and return the outputs. + + Examples: + Initialize a Triton client with HTTP + >>> model = TritonRemoteModel(url="localhost:8000", endpoint="yolov8", scheme="http") + + Make inference with numpy arrays + >>> outputs = model(np.random.rand(1, 3, 640, 640).astype(np.float32)) + """ + + def __init__(self, url: str, endpoint: str = "", scheme: str = ""): + """Initialize the TritonRemoteModel for interacting with a remote Triton Inference Server. + + Arguments may be provided individually or parsed from a collective 'url' argument of the form + ://// + + Args: + url (str): The URL of the Triton server. + endpoint (str, optional): The name of the model on the Triton server. + scheme (str, optional): The communication scheme ('http' or 'grpc'). + """ + if not endpoint and not scheme: # Parse all args from URL string + splits = urlsplit(url) + endpoint = splits.path.strip("/").split("/", 1)[0] + scheme = splits.scheme + url = splits.netloc + + self.endpoint = endpoint + self.url = url + + # Choose the Triton client based on the communication scheme + if scheme == "http": + import tritonclient.http as client + + self.triton_client = client.InferenceServerClient(url=self.url, verbose=False, ssl=False) + config = self.triton_client.get_model_config(endpoint) + else: + import tritonclient.grpc as client + + self.triton_client = client.InferenceServerClient(url=self.url, verbose=False, ssl=False) + config = self.triton_client.get_model_config(endpoint, as_json=True)["config"] + + # Sort output names alphabetically, i.e. 'output0', 'output1', etc. + config["output"] = sorted(config["output"], key=lambda x: x.get("name")) + + # Define model attributes + type_map = {"TYPE_FP32": np.float32, "TYPE_FP16": np.float16, "TYPE_UINT8": np.uint8} + self.InferRequestedOutput = client.InferRequestedOutput + self.InferInput = client.InferInput + self.input_formats = [x["data_type"] for x in config["input"]] + self.np_input_formats = [type_map[x] for x in self.input_formats] + self.input_names = [x["name"] for x in config["input"]] + self.output_names = [x["name"] for x in config["output"]] + self.metadata = ast.literal_eval(config.get("parameters", {}).get("metadata", {}).get("string_value", "None")) + + def __call__(self, *inputs: np.ndarray) -> list[np.ndarray]: + """Call the model with the given inputs and return inference results. + + Args: + *inputs (np.ndarray): Input data to the model. Each array should match the expected shape and type for the + corresponding model input. + + Returns: + (list[np.ndarray]): Model outputs cast to the dtype of the first input. Each element in the list corresponds + to one of the model's output tensors. + + Examples: + >>> model = TritonRemoteModel(url="localhost:8000", endpoint="yolov8", scheme="http") + >>> outputs = model(np.random.rand(1, 3, 640, 640).astype(np.float32)) + """ + infer_inputs = [] + input_format = inputs[0].dtype + for i, x in enumerate(inputs): + if x.dtype != self.np_input_formats[i]: + x = x.astype(self.np_input_formats[i]) + infer_input = self.InferInput(self.input_names[i], [*x.shape], self.input_formats[i].replace("TYPE_", "")) + infer_input.set_data_from_numpy(x) + infer_inputs.append(infer_input) + + infer_outputs = [self.InferRequestedOutput(output_name) for output_name in self.output_names] + outputs = self.triton_client.infer(model_name=self.endpoint, inputs=infer_inputs, outputs=infer_outputs) + + return [outputs.as_numpy(output_name).astype(input_format) for output_name in self.output_names] diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/tuner.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/tuner.py new file mode 100644 index 0000000000000000000000000000000000000000..67cd4fee771f5ef27a5bbda2668884d9c6b3c4c8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/tuner.py @@ -0,0 +1,526 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import numpy as np + +from ultralytics.cfg import TASK2DATA, TASK2METRIC, get_cfg, get_save_dir +from ultralytics.utils import DEFAULT_CFG, DEFAULT_CFG_DICT, LOGGER, NUM_THREADS, checks, colorstr + +RAY_SEARCH_ALG_REQUIREMENTS = { + "random": None, + "ax": "ax-platform", + "bayesopt": "bayesian-optimization==1.4.3", + "bohb": ["hpbandster", "ConfigSpace"], + "hebo": "HEBO>=0.2.0", + "hyperopt": "hyperopt", + "nevergrad": "nevergrad", + "optuna": "optuna", + "zoopt": "zoopt", +} + + +def _sanitize_tune_value(value: dict): + """Convert NumPy-backed Tune values into native Python types for YAML serialization. + + Args: + value (dict): The value to convert. Can be a dict, list, tuple, NumPy scalar, or NumPy array. + + Returns: + The converted value with NumPy types replaced by native Python types. + """ + if isinstance(value, dict): + return {k: _sanitize_tune_value(v) for k, v in value.items()} + if isinstance(value, list): + return [_sanitize_tune_value(v) for v in value] + if isinstance(value, tuple): + return tuple(_sanitize_tune_value(v) for v in value) + if isinstance(value, np.generic): + return value.item() + if isinstance(value, np.ndarray): + return value.tolist() + return value + + +def _get_ray_search_alg_kind(search_alg): + """Return the normalized Ray Tune search algorithm kind for known searcher objects. + + Args: + search_alg (str | ray.tune.search.Searcher): The search algorithm to identify. Can be None, a string, or a Ray + Tune searcher object. + + Returns: + str | None: The normalized search algorithm name, or None if not recognized. + """ + if search_alg is None: + return None + if isinstance(search_alg, str): + normalized = search_alg.strip().lower() + return normalized or None + + cls = search_alg.__class__ + module, name = cls.__module__, cls.__name__ + if name == "AxSearch" and module.startswith("ray.tune.search.ax"): + return "ax" + if name == "TuneBOHB" and module.startswith("ray.tune.search.bohb"): + return "bohb" + if name == "ZOOptSearch" and module.startswith("ray.tune.search.zoopt"): + return "zoopt" + return None + + +def _validate_ax_search_space(space): + """Validate that a Tune search space can be consumed by Ax. + + Args: + space (dict): The hyperparameter search space to validate. + + Returns: + list: The converted Ax parameters. + + Raises: + ImportError: If the required 'ax-platform' package is not installed. + """ + checks.check_requirements(RAY_SEARCH_ALG_REQUIREMENTS["ax"]) + + from ray.tune.search.ax.ax_search import AxSearch + + return AxSearch.convert_search_space(space) + + +def _create_ax_search(space, task): + """Create an Ax searcher with an initialized experiment. + + Args: + space (dict): The hyperparameter search space. + task (str): The task type (e.g., 'detect', 'segment', 'classify'). + + Returns: + AxSearch (ray.tune.search.Searcher): The configured Ax search algorithm. + + Raises: + ImportError: If required Ax packages are not installed. + """ + parameters = _validate_ax_search_space(space) + + from ax.service.ax_client import AxClient + from ax.service.utils.instantiation import ObjectiveProperties + from ray.tune.search.ax.ax_search import AxSearch + + ax_client = AxClient() + ax_client.create_experiment( + parameters=parameters, + objectives={TASK2METRIC[task]: ObjectiveProperties(minimize=False)}, + ) + return AxSearch(ax_client=ax_client) + + +def _convert_bohb_search_space(space): + """Convert a Tune search space into BOHB-compatible ConfigSpace and fixed-only Tune param_space. + + Args: + space (dict): The hyperparameter search space. + + Returns: + (tuple): A tuple containing the ConfigSpace object and a dict of fixed parameters. + + Raises: + ValueError: If the search space contains grid search parameters or unsupported samplers. + ImportError: If required BOHB packages are not installed. + """ + checks.check_requirements(RAY_SEARCH_ALG_REQUIREMENTS["bohb"]) + + import ConfigSpace + from ray.tune.search.sample import Categorical, Float, Integer, LogUniform, Quantized, Uniform + from ray.tune.search.variant_generator import parse_spec_vars + from ray.tune.utils import flatten_dict + + resolved_space = flatten_dict(space, prevent_delimiter=True) + resolved_vars, domain_vars, grid_vars = parse_spec_vars(resolved_space) + if grid_vars: + raise ValueError("Grid search parameters cannot be automatically converted to a TuneBOHB search space.") + + cs = ConfigSpace.ConfigurationSpace() + for path, domain in domain_vars: + par = "/".join(str(p) for p in path) + sampler = domain.get_sampler() + if isinstance(sampler, Quantized): + raise TypeError("TuneBOHB does not support quantized search spaces with the current ConfigSpace version.") + + if isinstance(domain, Float) and isinstance(sampler, (Uniform, LogUniform)): + cs.add( + ConfigSpace.UniformFloatHyperparameter( + par, lower=domain.lower, upper=domain.upper, log=isinstance(sampler, LogUniform) + ) + ) + elif isinstance(domain, Integer) and isinstance(sampler, (Uniform, LogUniform)): + upper = domain.upper - 1 # Tune integer search spaces are exclusive on the upper bound + cs.add( + ConfigSpace.UniformIntegerHyperparameter( + par, lower=domain.lower, upper=upper, log=isinstance(sampler, LogUniform) + ) + ) + elif isinstance(domain, Categorical) and isinstance(sampler, Uniform): + cs.add(ConfigSpace.CategoricalHyperparameter(par, choices=domain.categories)) + else: + raise TypeError( + f"TuneBOHB does not support parameters of type {type(domain).__name__} " + f"with sampler type {type(domain.sampler).__name__}." + ) + + fixed_param_space = {"/".join(str(p) for p in path): value for path, value in resolved_vars} + return cs, fixed_param_space + + +def _create_bohb_search(space, task): + """Create a BOHB searcher using a ConfigSpace definition compatible with current ConfigSpace versions. + + Args: + space (dict): The hyperparameter search space. + task (str): The task type (e.g., 'detect', 'segment', 'classify'). + + Returns: + (tuple): A tuple containing the TuneBOHB searcher and fixed parameter space dict. + + Raises: + ImportError: If required BOHB packages are not installed. + """ + cs, fixed_param_space = _convert_bohb_search_space(space) + + from ray.tune.search.bohb.bohb_search import TuneBOHB + + return TuneBOHB(space=cs, metric=TASK2METRIC[task], mode="max"), fixed_param_space + + +def _create_nevergrad_search(task): + """Create a Nevergrad searcher with a default optimizer. + + Args: + task (str): The task type (e.g., 'detect', 'segment', 'classify'). + + Returns: + (NevergradSearch): The configured Nevergrad search algorithm. + + Raises: + ImportError: If the 'nevergrad' package is not installed. + """ + checks.check_requirements(RAY_SEARCH_ALG_REQUIREMENTS["nevergrad"]) + + import nevergrad as ng + from ray.tune.search.nevergrad import NevergradSearch + + return NevergradSearch(optimizer=ng.optimizers.OnePlusOne, metric=TASK2METRIC[task], mode="max") + + +def _convert_zoopt_search_space(space): + """Convert a Tune search space into ZOOpt-compatible dimensions and fixed-only Tune param_space. + + Args: + space (dict): The hyperparameter search space. + + Returns: + (tuple): A tuple containing the ZOOpt dimension dict and fixed parameter space dict. + + Raises: + ImportError: If the 'zoopt' package is not installed. + """ + checks.check_requirements(RAY_SEARCH_ALG_REQUIREMENTS["zoopt"]) + + from ray.tune.search.variant_generator import parse_spec_vars + from ray.tune.search.zoopt import ZOOptSearch + from ray.tune.utils import flatten_dict + + resolved_space = flatten_dict(space, prevent_delimiter=True) + resolved_vars, _, _ = parse_spec_vars(resolved_space) + fixed_param_space = {"/".join(str(p) for p in path): value for path, value in resolved_vars} + dim_dict = ZOOptSearch.convert_search_space(space) + return dim_dict, fixed_param_space + + +def _create_zoopt_search(space, task, iterations): + """Create a ZOOpt searcher with required budget and converted search space. + + Args: + space (dict): The hyperparameter search space. + task (str): The task type (e.g., 'detect', 'segment', 'classify'). + iterations (int): The maximum number of trials (budget) for ZOOpt. + + Returns: + (tuple): A tuple containing the ZOOptSearch searcher and fixed parameter space dict. + + Raises: + ImportError: If the 'zoopt' package is not installed. + """ + dim_dict, fixed_param_space = _convert_zoopt_search_space(space) + + from ray.tune.search.zoopt import ZOOptSearch + + return ZOOptSearch( + algo="asracos", budget=iterations, dim_dict=dim_dict, metric=TASK2METRIC[task], mode="max" + ), fixed_param_space + + +def _resolve_ray_search_alg(search_alg, task, space, iterations): + """Resolve search algorithms and normalize Tune param_space for known Ray Tune searchers. + + Args: + search_alg (str | object | None): The search algorithm to use. Can be a string name, a pre-instantiated Ray Tune + searcher object, or None for default behavior. + task (str): The task type (e.g., 'detect', 'segment', 'classify'). + space (dict): The hyperparameter search space. + iterations (int): The maximum number of trials to run. + + Returns: + (tuple): A tuple containing (resolved_search_alg, tuner_param_space, resolved_search_alg_kind). + - resolved_search_alg: The configured searcher or None. + - tuner_param_space: The normalized parameter space for the tuner. + - resolved_search_alg_kind: The normalized algorithm name or None. + + Raises: + ValueError: If an unsupported search_alg string is provided. + ModuleNotFoundError: If required dependencies for the chosen algorithm are not installed. + """ + if search_alg is None: + return None, space, None + + normalized = _get_ray_search_alg_kind(search_alg) + if isinstance(search_alg, str): + if not normalized: + return None, space, None + if normalized not in RAY_SEARCH_ALG_REQUIREMENTS: + supported = ", ".join(sorted(RAY_SEARCH_ALG_REQUIREMENTS)) + raise ValueError(f"Unsupported Ray Tune search_alg '{search_alg}'. Supported values: {supported}.") + if normalized == "random": + return None, space, normalized + + try: + if normalized == "ax": + if isinstance(search_alg, str): + return _create_ax_search(space, task), {}, normalized + _validate_ax_search_space(space) + return search_alg, {}, normalized + if normalized == "bohb": + if isinstance(search_alg, str): + resolved_search_alg, tuner_param_space = _create_bohb_search(space, task) + else: + _, tuner_param_space = _convert_bohb_search_space(space) + resolved_search_alg = search_alg + return resolved_search_alg, tuner_param_space, normalized + if normalized == "nevergrad": + return _create_nevergrad_search(task), space, normalized + if normalized == "zoopt": + if isinstance(search_alg, str): + resolved_search_alg, tuner_param_space = _create_zoopt_search(space, task, iterations) + else: + _, tuner_param_space = _convert_zoopt_search_space(space) + resolved_search_alg = search_alg + return resolved_search_alg, tuner_param_space, normalized + if not isinstance(search_alg, str): + return search_alg, space, None + + requirements = RAY_SEARCH_ALG_REQUIREMENTS[normalized] + if requirements: + checks.check_requirements(requirements) + + if normalized == "optuna": + from optuna.samplers import TPESampler + from ray.tune.search.optuna import OptunaSearch + + return ( + OptunaSearch( + sampler=TPESampler(multivariate=True, constant_liar=True), + metric=TASK2METRIC[task], + mode="max", + ), + space, + normalized, + ) + + from ray.tune.search import create_searcher + + return create_searcher(normalized, metric=TASK2METRIC[task], mode="max"), space, normalized + except (ImportError, ModuleNotFoundError) as e: + raise ModuleNotFoundError( + f"Ray Tune search_alg '{search_alg}' requires additional dependencies. Original error: {e}" + ) from e + + +def run_ray_tune( + model, + space: dict | None = None, + grace_period: int = 10, + gpu_per_trial: int | None = None, + iterations: int = 300, + search_alg="optuna", + **train_args, +): + """Run hyperparameter tuning using Ray Tune. + + Args: + model (YOLO): Model to run the tuner on. + space (dict, optional): The hyperparameter search space. If not provided, uses default space. + grace_period (int, optional): The grace period in epochs of the ASHA scheduler. + gpu_per_trial (int, optional): The number of GPUs to allocate per trial. + iterations (int, optional): The maximum number of trials to run. + search_alg (str | ray.tune.search.Searcher | ray.tune.search.SearchAlgorithm, optional): Search algorithm to + use. Defaults to Optuna multivariate TPE. Strings are resolved to supported Ray Tune searchers, + pre-instantiated objects are reused, and known searchers with special Tune param_space requirements are + normalized automatically. + **train_args (Any): Additional arguments to pass to the `train()` method. + + Returns: + (ray.tune.ResultGrid): A ResultGrid containing the results of the hyperparameter search. + + Examples: + >>> from ultralytics import YOLO + >>> model = YOLO("yolo26n.pt") # Load a YOLO26n model + + Start tuning hyperparameters for YOLO26n training on the COCO8 dataset + >>> result_grid = model.tune(data="coco8.yaml", use_ray=True) + """ + LOGGER.info("💡 Learn about RayTune at https://docs.ultralytics.com/integrations/ray-tune") + try: + checks.check_requirements(["ray>=2.41.0", "ray[tune]"], constrain=["pydantic>=2.0,<2.12"]) + + import ray + from ray import tune + from ray.tune import RunConfig + from ray.tune.schedulers import ASHAScheduler, HyperBandForBOHB + except ImportError: + raise ModuleNotFoundError('Ray Tune required but not found. To install run: pip install "ray[tune]"') + + default_space = { + # 'optimizer': tune.choice(['SGD', 'Adam', 'AdamW', 'NAdam', 'RAdam', 'RMSProp']), + "lr0": tune.uniform(1e-5, 1e-2), # initial learning rate (i.e. SGD=1E-2, Adam=1E-3) + "lrf": tune.uniform(0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf) + "momentum": tune.uniform(0.7, 0.98), # SGD momentum/Adam beta1 + "weight_decay": tune.uniform(0.0, 0.001), # optimizer weight decay + "warmup_epochs": tune.uniform(0.0, 5.0), # warmup epochs (fractions ok) + "warmup_momentum": tune.uniform(0.0, 0.95), # warmup initial momentum + "box": tune.uniform(1.0, 20.0), # box loss gain + "cls": tune.uniform(0.1, 4.0), # cls loss gain (scale with pixels) + "cls_pw": tune.uniform(0.0, 1.0), # cls power weight (scale with pixels) + "dfl": tune.uniform(0.4, 12.0), # dfl loss gain + "hsv_h": tune.uniform(0.0, 0.1), # image HSV-Hue augmentation (fraction) + "hsv_s": tune.uniform(0.0, 0.9), # image HSV-Saturation augmentation (fraction) + "hsv_v": tune.uniform(0.0, 0.9), # image HSV-Value augmentation (fraction) + "degrees": tune.uniform(0.0, 45.0), # image rotation (+/- deg) + "translate": tune.uniform(0.0, 0.9), # image translation (+/- fraction) + "scale": tune.uniform(0.0, 0.95), # image scale (+/- gain) + "shear": tune.uniform(0.0, 10.0), # image shear (+/- deg) + "perspective": tune.uniform(0.0, 0.001), # image perspective (+/- fraction), range 0-0.001 + "flipud": tune.uniform(0.0, 1.0), # image flip up-down (probability) + "fliplr": tune.uniform(0.0, 1.0), # image flip left-right (probability) + "bgr": tune.uniform(0.0, 1.0), # swap RGB↔BGR channels (probability) + "mosaic": tune.uniform(0.0, 1.0), # image mosaic (probability) + "mixup": tune.uniform(0.0, 1.0), # image mixup (probability) + "cutmix": tune.uniform(0.0, 1.0), # image cutmix (probability) + "copy_paste": tune.uniform(0.0, 1.0), # segment/obb copy-paste (object fraction) + "close_mosaic": tune.randint(0, 11), # close dataloader mosaic (epochs) + } + + # Put the model in ray store + task = model.task + model_in_store = ray.put(model) + base_name = train_args.get("name", "tune") + + def _tune(config): + """Train the YOLO model with the specified hyperparameters and return results.""" + model_to_train = ray.get(model_in_store) # get the model from ray store for tuning + model_to_train.trainer = None + model_to_train.reset_callbacks() + config = _sanitize_tune_value(dict(config)) + config.update(train_args) + + # Set trial-specific name for W&B logging + try: + trial_id = tune.get_context().get_trial_id() + trial_suffix = trial_id.split("_")[-1] if "_" in trial_id else trial_id + config["name"] = f"{base_name}_{trial_suffix}" + except Exception: + # Not in Ray Tune context or error getting trial ID, use base name + config["name"] = base_name + + results = model_to_train.train(**config) + if isinstance(config.get("data"), (list, tuple)): + metric = TASK2METRIC[task] + return { + metric: sum((metrics or {}).get(metric, 0.0) for metrics in results.values()) / len(results), + "epoch": config.get("epochs") or DEFAULT_CFG_DICT["epochs"], + } + return results.results_dict + + # Get search space + if not space: + space = default_space + if not train_args.get("resume"): + LOGGER.warning("Search space not provided, using default search space.") + + # Get dataset + data = train_args.get("data", TASK2DATA[task]) + space["data"] = data + if "data" not in train_args: + LOGGER.warning(f'Data not provided, using default "data={data}".') + + resolved_search_alg, tuner_param_space, resolved_search_alg_kind = _resolve_ray_search_alg( + search_alg, task, space, iterations + ) + + # Define the trainable function with allocated resources + trainable_with_resources = tune.with_resources(_tune, {"cpu": NUM_THREADS, "gpu": gpu_per_trial or 0}) + + # Define the scheduler for hyperparameter search + max_t = train_args.get("epochs") or DEFAULT_CFG_DICT["epochs"] or 100 + scheduler = ASHAScheduler( + time_attr="epoch", + metric=TASK2METRIC[task], + mode="max", + max_t=max_t, + grace_period=min(grace_period, max_t), + reduction_factor=3, + ) + if resolved_search_alg_kind == "bohb": + scheduler = HyperBandForBOHB( + time_attr="epoch", + metric=TASK2METRIC[task], + mode="max", + max_t=max_t, + reduction_factor=3, + ) + + # Create the Ray Tune hyperparameter search tuner + tune_dir = get_save_dir( + get_cfg( + DEFAULT_CFG, + {**train_args, "exist_ok": train_args.pop("resume", False)}, # resume w/ same tune_dir + ), + name=train_args.pop("name", "tune"), # runs/{task}/{tune_dir} + ) # must be absolute dir + tune_dir.mkdir(parents=True, exist_ok=True) + if tune.Tuner.can_restore(tune_dir): + LOGGER.info(f"{colorstr('Tuner: ')} Resuming tuning run {tune_dir}...") + tuner = tune.Tuner.restore(str(tune_dir), trainable=trainable_with_resources, resume_errored=True) + else: + tuner = tune.Tuner( + trainable_with_resources, + param_space=tuner_param_space, + tune_config=tune.TuneConfig( + search_alg=resolved_search_alg, + scheduler=scheduler, + num_samples=iterations, + trial_name_creator=lambda trial: f"{trial.trainable_name}_{trial.trial_id}", + trial_dirname_creator=lambda trial: f"{trial.trainable_name}_{trial.trial_id}", + ), + run_config=RunConfig(storage_path=tune_dir.parent, name=tune_dir.name), + ) + + # Run the hyperparameter search + tuner.fit() + + # Get the results of the hyperparameter search + results = tuner.get_results() + + # Shut down Ray to clean up workers + ray.shutdown() + + return results diff --git a/.venv/lib/python3.12/site-packages/ultralytics/utils/uploads.py b/.venv/lib/python3.12/site-packages/ultralytics/utils/uploads.py new file mode 100644 index 0000000000000000000000000000000000000000..58f8706926c81010a94e743e91b4541fbf40d453 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics/utils/uploads.py @@ -0,0 +1,115 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Upload utilities for Ultralytics, mirroring downloads.py patterns.""" + +from __future__ import annotations + +import os +from pathlib import Path +from time import sleep + +from ultralytics.utils import LOGGER, TQDM + + +class _ProgressReader: + """File wrapper that reports read progress for upload monitoring.""" + + def __init__(self, file_path, pbar): + self.file = open(file_path, "rb") # noqa: SIM115 # kept open for streamed upload reads + self.pbar = pbar + self._size = os.path.getsize(file_path) + + def read(self, size=-1): + """Read data and update progress bar.""" + data = self.file.read(size) + if data and self.pbar: + self.pbar.update(len(data)) + return data + + def __len__(self): + """Return file size for Content-Length header.""" + return self._size + + def close(self): + """Close the file.""" + self.file.close() + + +def safe_upload( + file: str | Path, + url: str, + headers: dict | None = None, + retry: int = 2, + timeout: int = 600, + progress: bool = False, +) -> bool: + """Upload a file to a URL with retry logic and optional progress bar. + + Args: + file (str | Path): Path to the file to upload. + url (str): The URL endpoint to upload the file to (e.g., signed GCS URL). + headers (dict, optional): Additional headers to include in the request. + retry (int, optional): Number of retry attempts on failure (default: 2 for 3 total attempts). + timeout (int, optional): Request timeout in seconds. + progress (bool, optional): Whether to display a progress bar during upload. + + Returns: + (bool): True if upload succeeded, False otherwise. + + Examples: + >>> from ultralytics.utils.uploads import safe_upload + >>> success = safe_upload("model.pt", "https://storage.googleapis.com/...", progress=True) + """ + import requests + + file = Path(file) + if not file.exists(): + raise FileNotFoundError(f"File not found: {file}") + + file_size = file.stat().st_size + desc = f"Uploading {file.name}" + + # Prepare headers (Content-Length set automatically from file size) + upload_headers = {"Content-Type": "application/octet-stream"} + if headers: + upload_headers.update(headers) + + last_error = None + for attempt in range(retry + 1): + pbar = None + reader = None + try: + if progress: + pbar = TQDM(total=file_size, desc=desc, unit="B", unit_scale=True, unit_divisor=1024) + reader = _ProgressReader(file, pbar) + + r = requests.put(url, data=reader, headers=upload_headers, timeout=timeout) + r.raise_for_status() + reader.close() + reader = None # Prevent double-close in finally + if pbar: + pbar.close() + pbar = None + LOGGER.info(f"Uploaded {file.name} ✅") + return True + + except requests.exceptions.HTTPError as e: + status = e.response.status_code if e.response is not None else 0 + if 400 <= status < 500 and status not in {408, 429}: + LOGGER.warning(f"{desc} failed: {status} {getattr(e.response, 'reason', '')}") + return False + last_error = f"HTTP {status}" + except Exception as e: + last_error = str(e) + finally: + if reader: + reader.close() + if pbar: + pbar.close() + + if attempt < retry: + wait_time = 2 ** (attempt + 1) + LOGGER.warning(f"{desc} failed ({last_error}), retrying {attempt + 1}/{retry} in {wait_time}s...") + sleep(wait_time) + + LOGGER.warning(f"{desc} failed after {retry + 1} attempts: {last_error}") + return False diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/METADATA b/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..485509e0b6a9d5f146610ba211af3257823c56d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/METADATA @@ -0,0 +1,162 @@ +Metadata-Version: 2.4 +Name: ultralytics-platform +Version: 0.1.57 +Summary: Typed Python SDK for the Ultralytics Platform API +Keywords: api-client,computer-vision,machine-learning,openapi,sdk,ultralytics,yolo +Author: Ultralytics +Author-email: Ultralytics +License-Expression: AGPL-3.0-only +License-File: LICENSE +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Typing :: Typed +Requires-Dist: httpx>=0.28,<1 +Maintainer: Ultralytics +Maintainer-email: Ultralytics +Requires-Python: >=3.11 +Project-URL: Repository, https://github.com/ultralytics/sdk +Project-URL: Issues, https://github.com/ultralytics/sdk/issues +Description-Content-Type: text/markdown + +Ultralytics logo + +# 🔌 Ultralytics Platform API Python SDK + +[![Ultralytics Discord](https://img.shields.io/discord/1089800235347353640?logo=discord&logoColor=white&label=Discord&color=blue)](https://discord.com/invite/ultralytics) [![Ultralytics Forums](https://img.shields.io/discourse/users?server=https%3A%2F%2Fcommunity.ultralytics.com&logo=discourse&label=Forums&color=blue)](https://community.ultralytics.com) [![Ultralytics Reddit](https://img.shields.io/reddit/subreddit-subscribers/ultralytics?style=flat&logo=reddit&logoColor=white&label=Reddit&color=blue)](https://www.reddit.com/r/Ultralytics/) + +Typed synchronous and asynchronous Python clients generated from the [Ultralytics Platform API](https://platform.ultralytics.com) contract with [Ultralytics OpenAPI](https://github.com/ultralytics/openapi). The [interactive API reference](https://platform.ultralytics.com/api/docs) documents every resource and includes Python examples. + +## 🐍 Python + +[![PyPI - Version](https://img.shields.io/pypi/v/ultralytics-platform?logo=pypi&logoColor=white)](https://pypi.org/project/ultralytics-platform/) [![Ultralytics Downloads](https://static.pepy.tech/badge/ultralytics-platform)](https://clickpy.clickhouse.com/dashboard/ultralytics-platform) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/ultralytics-platform?logo=python&logoColor=gold)](https://pypi.org/project/ultralytics-platform/) + +Install the standalone [`ultralytics-platform`](https://pypi.org/project/ultralytics-platform/) package from PyPI in a [**Python >=3.11**](https://www.python.org/) environment. It has one lightweight runtime dependency (`httpx`) and does not install the larger `ultralytics` package: + +```bash +uv pip install ultralytics-platform +``` + +Pass your [API key](https://platform.ultralytics.com/settings?tab=api-keys) directly as shown below. Alternatively, omit `api_key` to use `ULTRALYTICS_API_KEY` or the Platform key saved by `yolo login`. Both clients use explicit credentials first, then the environment, then saved settings. Pass `api_key=""` to disable authentication. `yolo logout` removes the saved key; it does not unset an environment variable. The SDK reads the existing Ultralytics settings directory, including `YOLO_CONFIG_DIR` and Linux `XDG_CONFIG_HOME`, without importing or installing `ultralytics`. + +```python +from ultralytics_platform import Platform + +with Platform(api_key="YOUR_API_KEY") as client: + response = client.datasets.list("your_username") +``` + +The asynchronous client exposes the same resource tree: + +```python +import asyncio + +from ultralytics_platform import AsyncPlatform + + +async def main(): + async with AsyncPlatform(api_key="YOUR_API_KEY") as client: + response = await client.datasets.list("your_username") + + +asyncio.run(main()) +``` + +The package includes typed responses, multipart uploads, retries for temporary failures, structured API errors, custom HTTP clients, and context-manager cleanup. + +## Unified `ul` CLI + +This package installs `ul`. API resource commands work without the ML package. Local commands and `ul cloud train/predict/export` require `ultralytics` in the same environment. Existing `yolo` behavior, including local training with `ul://` inputs, is unchanged. + +```bash +ul login API_KEY # validate and save a Platform API key +ul logout # clear the saved key +ul train model=yolo26n.pt data=coco8.yaml epochs=100 +ul cloud train model=yolo26n.pt data=ul://you/datasets/animals epochs=100 +ul cloud train model=./best.pt data=./dataset/data.yaml epochs=100 watch # follow and download results +ul cloud download model=ul://you/cloud-training/animals +ul cloud predict model=ul://you/project/model source=image.jpg conf=0.25 +ul cloud export model=./best.pt format=onnx imgsz=640 +ul cloud --help +ul cloud datasets images --help +ul cloud datasets # list your datasets +ul cloud datasets dataset=coco8 # retrieve one dataset +ul cloud datasets images dataset=coco8 limit=20 +ul cloud models project=p model=m +ul cloud training start model_id=MODEL_ID gpu_type=rtx-4090 train_args=@train.json +ul cloud models predict project=p model=m body='{"file":"@image.jpg","conf":0.25}' +ul cloud exports create project=p model=m format=onnx +``` + +`ul cloud train`, `ul cloud predict`, `ul cloud export`, and `ul cloud download` accept YOLO `key=value` arguments and `cfg=path.yaml`; command-line values override the config. `gpu_type=` selects cloud compute for training and export. `model=` accepts official YOLO weights (yolo26, yolo11, yolov8, and yolov5 weights hosted on Platform resolve to their public `ul://ultralytics/...` models; other official names are passed to training unchanged), a local `.pt` checkpoint uploaded as its own model, or a `ul://owner/project/model` URI. The commands use the installed `ultralytics` package for local file preparation and output saving; inference and training execute on Platform. + +- **Train:** uploads local dataset YAMLs/folders or ZIP/TAR archives (other `data=` values such as the built-in `coco8.yaml` are passed to Platform unchanged), waits for ingestion, starts training, and prints the model URI, selected GPU with its estimated cost, the run URL, and the `ul cloud download` command as its last line. Add `watch` to follow training with an epoch progress bar and download the results when it finishes; `ul cloud download model=ul://owner/project/model` does the same for a run started earlier. Downloads write `weights/best.pt`, `args.yaml`, `results.csv` (when present in the checkpoint), and `results.json` under YOLO's save directory. Platform currently exposes the promoted checkpoint, not a separate `last.pt` or the worker's complete output directory. Local datasets must have split directories under one root. Classification class folders are supported; Platform infers the dataset task from the labels during ingest. Uploaded datasets print a reusable URI. A new output model is created per invocation. +- **Predict:** submits one local image or video, then uses YOLO's writers for annotated images/videos, `save_txt`, `save_conf`, `save_crop`, `save_frames`, and display options. `save=False` disables annotated output. Saved runs also include the API response as `results.json`. `conf`, `iou`, and `imgsz` run on Platform; `classes` and `max_det` are applied locally to the returned detections; other inference execution settings are accepted but ignored because Platform controls remote execution. This lets you reuse local YOLO arguments when switching to cloud prediction. Responses contain rounded detections, polygon masks, top-five classification scores, and quantized depth, so cloud artifacts need not be byte-identical to local inference. +- **Export:** clones official weights into your project first (exports require an owned model), waits for completion and downloads the same artifact exposed in Portal. `save_dir=` selects the download directory; otherwise `project=` does, then the local checkpoint's directory or the current directory for hosted weights. Archives remain archives. Existing files are replaced only after a successful download. `name=` keeps YOLO's hardware-target meaning (for example, RKNN); it is not a download filename. + +Train and predict reuse YOLO's `save_dir`, `project`, `name`, and `exist_ok` output-directory rules. For uploaded models and training runs, `project=` also selects or creates a private Platform project using the local directory's final component as its slug; the default is `cloud-training`. Explicit existing projects retain their visibility. The training worker assigns its own GPU, so `device=` is not sent. Boolean cache settings map to the API’s `ram`/`false` values. `name=` also names the output model on Platform, suffixed `-2`, `-3` on conflict the way YOLO increments local run directories; `save_dir=`, `exist_ok=`, and `device=` stay local. This also permits local paths that are longer or contain characters the API does not accept. Export consumes local output/device options before sending format arguments. It ignores `save`, `plots`, `workers`, and `cache` with one warning; artifact settings such as `quantize`, `imgsz`, and `dynamic` remain validated by Platform. Local commands (`ul train`, `ul predict`, `ul export`) remain unchanged. + +`ul cloud train ... watch`, `ul cloud download`, and `ul cloud export` return success only after completion and local output handling. Ctrl-C stops waiting (exit 130) but does not cancel the remote job; training can be downloaded later with the printed `ul cloud download` command. Failed or interrupted operations retain created resources; use the generated resource commands to inspect or cancel them before retrying. Training/export failures exit nonzero. Saved outputs from a previous run remain until a new artifact has downloaded successfully. + +For API resource commands, arguments use `key=value` with values attached to `=`, command names use hyphens (`storage-integrations`), and argument names match Python keywords (`train_args`, `from_`). A separate `help`, `--help`, or `-h` token shows help without making a request; literal help values use `name=--help`. Bare booleans mean true. Omitted values, `False`, `0`, nullable `None`/`null`, and strings such as `license=None` remain distinct. Objects, arrays, and whole union bodies use JSON; `@request.json` reads JSON from a file and `@-` from stdin (one argument only). Binary fields require `@path`, including inside multipart body JSON. + +A missing path `owner` defaults to the logged-in username through one account lookup, including for project operations; explicit owners win. For API resource commands, project identifiers (`project`) and destination owners are never inferred. Collection commands default to GET `list`, or matching GET `retrieve` when an item identifier is supplied; missing retrieval arguments fail instead of listing. Other resources show help. Writes require an explicit operation. Each API resource command invokes one SDK operation, plus any owner lookup, and prints the complete JSON, text, or binary response. Pagination is explicit; the SDK owns serialization, credentials, transport, and retries. Types and required arguments come from SDK signatures; the API validates nested JSON. + +Cloud jobs may incur charges. API resource commands submit, inspect, or cancel one operation and exit, without polling or downloading artifacts. Success means the API call succeeded, not that a job finished. Exit codes: 0 success, 1 API/network errors (including nested validation), 2 local input errors, 130 interruption. Interrupting the CLI does not cancel a submitted job; use its cancellation operation. + +Credentials prefer `ULTRALYTICS_API_KEY`, then shared YOLO settings. Login validates before saving; logout leaves environment variables unchanged. `ULTRALYTICS_PLATFORM_URL` selects another API origin. On systems with an existing Unix `ul` command, activate your Python environment or use `python -m ultralytics_platform.cli`. + +## 🧩 One Contract, Typed Python + +The [Ultralytics Platform API](https://platform.ultralytics.com) contract is the single source of truth for the generated client: + +```text +OpenAPI contract + └── Python SDK # ultralytics-platform +``` + +The [source repository](https://github.com/ultralytics/sdk) pins the consumed contract and generated output so API changes remain deterministic and reviewable. Generated SDK files should never be edited manually; update the contract, consumer configuration, [package README source](https://github.com/ultralytics/sdk/blob/main/README.python.md), or [generator](https://github.com/ultralytics/openapi) and regenerate. + +## 🛠️ Validation + +[CI](https://github.com/ultralytics/sdk/actions) regenerates the Python SDK to detect contract mismatch or generated drift. It also formats and lints Python, compiles the package, builds its wheel, installs it through the package boundary, and exercises representative synchronous and asynchronous requests. + +## 💡 Contribute + +[Ultralytics](https://www.ultralytics.com) thrives on community collaboration, and we deeply value your contributions! Please see our [Contributing Guide](https://docs.ultralytics.com/help/contributing) for details on how you can get involved. We also encourage you to share your feedback through our [Survey](https://www.ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey). A huge thank you 🙏 to all our contributors! + +API shape changes belong in the service OpenAPI contract; generated files should not be edited directly. + +[![Ultralytics open-source contributors](https://raw.githubusercontent.com/ultralytics/assets/main/im/image-contributors.png)](https://github.com/ultralytics/sdk/graphs/contributors) + +## 📄 License + +- **AGPL-3.0 License**: The generated SDK is licensed under the [AGPL-3.0 License](https://spdx.org/licenses/AGPL-3.0-only.html). +- **Enterprise License**: Commercial licensing is available separately through [Ultralytics Licensing](https://www.ultralytics.com/license). + +## 📫 Contact + +For bug reports or feature suggestions related to this SDK, please submit an issue via [GitHub Issues](https://github.com/ultralytics/sdk/issues). Join our [Discord](https://discord.com/invite/ultralytics), [Reddit](https://www.reddit.com/r/Ultralytics/), or [Community Forums](https://community.ultralytics.com) for discussions and support! + +
+
+ Ultralytics GitHub + space + Ultralytics LinkedIn + space + Ultralytics Twitter + space + Ultralytics YouTube + space + Ultralytics TikTok + space + Ultralytics BiliBili + space + Ultralytics Discord +
diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/RECORD b/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..08794022016c654c3ce55e510507786633b717e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/RECORD @@ -0,0 +1,54 @@ +../../../bin/ul,sha256=EJXgv7bf7QEFZs_du0Vzm9bbrIWypJ-I0oyqmVfn7sQ,255 +ultralytics_platform-0.1.57.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +ultralytics_platform-0.1.57.dist-info/METADATA,sha256=HK-LaYHZf4MwSMuZavWYTx3Watt8pcOUnIijbz3RvHQ,16816 +ultralytics_platform-0.1.57.dist-info/RECORD,, +ultralytics_platform-0.1.57.dist-info/WHEEL,sha256=7hzKWg-J8I3Buqyw5tBii5z_MmAVsDYXXijd_QAtNZ8,81 +ultralytics_platform-0.1.57.dist-info/entry_points.txt,sha256=TabDs1YKcLPpbH_clNB0QXZ9kNfXdgrRPibBa5CYgq8,54 +ultralytics_platform-0.1.57.dist-info/licenses/LICENSE,sha256=hIahDEOTzuHCU5J2nd07LWwkLW7Hko4UFO__ffsvB-8,34523 +ultralytics_platform/__init__.py,sha256=7OlCNkgR0xk5ZDRw0yEtJxtXb2oMnLmK3OZE5g1fTTc,335 +ultralytics_platform/__pycache__/__init__.cpython-312.pyc,, +ultralytics_platform/__pycache__/_auth.cpython-312.pyc,, +ultralytics_platform/__pycache__/_cli_metadata.cpython-312.pyc,, +ultralytics_platform/__pycache__/_client.cpython-312.pyc,, +ultralytics_platform/__pycache__/_exceptions.cpython-312.pyc,, +ultralytics_platform/__pycache__/async_client.cpython-312.pyc,, +ultralytics_platform/__pycache__/cli.cpython-312.pyc,, +ultralytics_platform/__pycache__/client.cpython-312.pyc,, +ultralytics_platform/__pycache__/types.cpython-312.pyc,, +ultralytics_platform/_auth.py,sha256=4fQFbBXbNbde89140kwdaOrkwr9HcnAVEwMY8guLVS8,1377 +ultralytics_platform/_cli_metadata.py,sha256=vh7G3OeKexR0jY5OqtBblWOhtltdwJNbCkyLGGI4xjA,151 +ultralytics_platform/_client.py,sha256=G02-PrHasdy2l0dXF7-9hu_Gl0q6S2E-ZccEYZ1kRUc,10231 +ultralytics_platform/_exceptions.py,sha256=7SpHeROiT5RuuTpcbnM0cI-aFkdcvXnISLviSBmINF0,794 +ultralytics_platform/async_client.py,sha256=621DWOhSicx0dlAHi5BIn02eome9-_rX5fk0b1MR2No,3060 +ultralytics_platform/cli.py,sha256=oQNcfdyz3k7u_bFZ7xF6eUyiKnZ7v-N19dj7L10nmWo,40341 +ultralytics_platform/client.py,sha256=h2C8bURnW7DNOD2uzHER4G3lHPRRfmf4GtAU3LdlJws,2876 +ultralytics_platform/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +ultralytics_platform/resources/__init__.py,sha256=rSvqTnUruUGS171taHHlPI57X8f7Y0B5k92nYDA7ORE,1351 +ultralytics_platform/resources/__pycache__/__init__.cpython-312.pyc,, +ultralytics_platform/resources/__pycache__/account.cpython-312.pyc,, +ultralytics_platform/resources/__pycache__/billing.cpython-312.pyc,, +ultralytics_platform/resources/__pycache__/datasets.cpython-312.pyc,, +ultralytics_platform/resources/__pycache__/deployments.cpython-312.pyc,, +ultralytics_platform/resources/__pycache__/explore.cpython-312.pyc,, +ultralytics_platform/resources/__pycache__/exports.cpython-312.pyc,, +ultralytics_platform/resources/__pycache__/images.cpython-312.pyc,, +ultralytics_platform/resources/__pycache__/lifecycle.cpython-312.pyc,, +ultralytics_platform/resources/__pycache__/models.cpython-312.pyc,, +ultralytics_platform/resources/__pycache__/projects.cpython-312.pyc,, +ultralytics_platform/resources/__pycache__/storage_integrations.cpython-312.pyc,, +ultralytics_platform/resources/__pycache__/training.cpython-312.pyc,, +ultralytics_platform/resources/__pycache__/upload.cpython-312.pyc,, +ultralytics_platform/resources/account.py,sha256=0hxCWzk5jkrEAgd-wB7ABDdIWgJO_AmTmiM86PAeb4c,11347 +ultralytics_platform/resources/billing.py,sha256=5o91hUpu5XXdNM9vCnFo1nlh_4zV_BHkeOZE3oUXTOY,5425 +ultralytics_platform/resources/datasets.py,sha256=aq1XhjD8tpa6DkwK6V_dZVV8OTmGxyGtLPWXrtV67Wk,112227 +ultralytics_platform/resources/deployments.py,sha256=Tl9vBUGp1kuw0rxlmJjrNds16jUs7kWsLlWoyXKrSgs,33623 +ultralytics_platform/resources/explore.py,sha256=JrQhadm74JBtnuzFeO5BqbMRjvd8PnC8Yrt2vOlurPU,6199 +ultralytics_platform/resources/exports.py,sha256=3i2rQE9FY-woDTLXTcOH3To-8sUV0_LA8ymCpBNmzwY,17930 +ultralytics_platform/resources/images.py,sha256=YfBvKnb09ONvm6M3jug5BluZ0OKsFhHt6yPhP3dkGgA,23895 +ultralytics_platform/resources/lifecycle.py,sha256=5xNABgzvQQ7fA3prHj69ufgPBx8irKKRiAzuN96dTWI,9215 +ultralytics_platform/resources/models.py,sha256=S1i9qYwiaw82C__Yq8NGZMa5JtoOHFu2sSDX-Eqmcgw,45457 +ultralytics_platform/resources/projects.py,sha256=rTv2sC4e0OEhD8wV9Zelb1dHS3WWnqueLbfo_EAQ8HM,27148 +ultralytics_platform/resources/storage_integrations.py,sha256=llYHMdXXQyE69yhIhphU_x6vofeFC8HG-UU9r7i-3lE,13119 +ultralytics_platform/resources/training.py,sha256=hpsucCGp4HfSJ2dTIJQ8Cx-D1eBoJzasJ9UtKOzvFz4,15096 +ultralytics_platform/resources/upload.py,sha256=nG8M8BH78RjNHue7KmZktExkQhHyPIenkaBkJ_zkZ6E,6371 +ultralytics_platform/types.py,sha256=CNEKZDybhnxcsVwY08VArOe9ntl7DAMQgB7nnjAWlH8,107118 diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..2668c9e6f45bbaec7a5fecb89b4298ff73d50f5b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: uv 0.12.18 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..0936643bade35dc953e1a83faff265ad50536228 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +ul = ultralytics_platform.cli:main + diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0ad25db4bd1d86c452db3f9602ccdbe172438f52 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform-0.1.57.dist-info/licenses/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e709c1844608858345c5f337fbcc1d27974423a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/__init__.py @@ -0,0 +1,8 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from ._client import NOT_GIVEN, NotGiven +from ._exceptions import APIConnectionError, APIError +from .async_client import AsyncPlatform +from .client import Platform + +__all__ = ["NOT_GIVEN", "APIConnectionError", "APIError", "AsyncPlatform", "NotGiven", "Platform"] diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee0075b4ca5995825d22fe4679ba1aa0c03d1c82 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/_auth.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/_auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a1532ebaf5ad13aeb3ddfcb3c56cd3788c296e1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/_auth.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/_cli_metadata.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/_cli_metadata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90670424808727a73115333449230c40d1039540 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/_cli_metadata.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/_client.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfbc36223262d8efd495af85cad252f07ec8985b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/_client.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/_exceptions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/_exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af2ffe564af7c0e68620ee6471c7078966d54609 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/_exceptions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/async_client.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/async_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db52a9dfa6af505fe721a9e9782e5a5e234b7d74 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/async_client.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/cli.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/cli.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6efd818826113de1cb24090c26d615e5f166536d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/cli.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/client.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0aa0230092ce5c9581102e454decebc35bfcad8f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/client.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a3d46359e41c9ae2f273fd5f623d353fbfd57cc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/__pycache__/types.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/_auth.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..f2b01c98378f9c7fbfc5f23e9de3764bb90bc7b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/_auth.py @@ -0,0 +1,32 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import json +import os +import sys +from pathlib import Path + + +def get_api_key() -> str | None: + """Read the Platform key saved by yolo login without importing the ML package.""" + if config_dir := os.environ.get("YOLO_CONFIG_DIR"): + directory = Path(config_dir).expanduser() / "Ultralytics" + elif sys.platform == "linux": + directory = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "Ultralytics" + elif sys.platform == "win32": + directory = Path.home() / "AppData" / "Roaming" / "Ultralytics" + elif sys.platform == "darwin": + directory = Path.home() / "Library" / "Application Support" / "Ultralytics" + else: + return None + # Select the same directory as the settings writer; never revive a key from another location after logout. + for candidate in (directory, Path("/tmp") / "Ultralytics", Path.cwd() / "Ultralytics"): + if candidate.exists() or os.access(candidate.parent, os.W_OK): + break + try: + settings = json.loads((candidate / "settings.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + api_key = settings.get("api_key") if isinstance(settings, dict) else None + return api_key if isinstance(api_key, str) else None diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/_cli_metadata.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/_cli_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..a027a83f2cea78158d902f7d10933216ba4f9412 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/_cli_metadata.py @@ -0,0 +1,3 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +MULTIPART_FILES = {"deployments.predict": ["file"], "models.predict": ["file"]} diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/_client.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..7757da9f4de55647e44f29a452161745da20fbc1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/_client.py @@ -0,0 +1,247 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import asyncio +import json +import os +import time +from collections.abc import Sequence +from typing import Any +from urllib.parse import quote + +import httpx + +from ._auth import get_api_key +from ._exceptions import APIConnectionError, APIError + + +def _resolve_api_key(api_key: str | None) -> str | None: + """Resolve explicit credentials, the environment, then the optional provider.""" + if api_key is not None: + return api_key + if api_key := os.environ.get("ULTRALYTICS_API_KEY"): + return api_key + return get_api_key() + + +class NotGiven: + """Sentinel for omitted request values.""" + + def __bool__(self) -> bool: + return False + + def __repr__(self) -> str: + return "NOT_GIVEN" + + +NOT_GIVEN = NotGiven() + + +def _path_parameter(value: Any, *, explode: bool, allow_reserved: bool) -> str: + safe = ":/?#[]@!$&'()*+,;=" if allow_reserved else "" + + def encode(item: Any) -> str: + return quote(str(item), safe=safe) + + if isinstance(value, dict): + parts = ( + [f"{encode(key)}={encode(item)}" for key, item in value.items()] + if explode + else [encode(item) for pair in value.items() for item in pair] + ) + return ",".join(parts) + if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): + return ",".join(encode(item) for item in value) + return encode(value) + + +def _query_parameter(name: str, value: Any, *, style: str, explode: bool) -> list[tuple[str, Any]]: + if value is None or isinstance(value, NotGiven): + return [] + if isinstance(value, dict): + if style == "deepObject": + return [(f"{name}[{key}]", item) for key, item in value.items()] + if explode: + return list(value.items()) + return [(name, ",".join(str(item) for pair in value.items() for item in pair))] + if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): + if style == "form" and explode: + return [(name, item) for item in value] + separator = " " if style == "spaceDelimited" else "|" if style == "pipeDelimited" else "," + return [(name, separator.join(str(item) for item in value))] + return [(name, value)] + + +def _without_none(values: dict[str, Any]) -> dict[str, Any]: + return {key: value for key, value in values.items() if value is not None and not isinstance(value, NotGiven)} + + +def _without_not_given(values: Any) -> Any: + if isinstance(values, dict): + return {key: value for key, value in values.items() if not isinstance(value, NotGiven)} + return None if isinstance(values, NotGiven) else values + + +def _json_value(value: Any) -> Any: + """Drop omitted values and turn any sequence into a list so the payload is JSON serializable.""" + if isinstance(value, dict): + return {key: _json_value(item) for key, item in value.items() if not isinstance(item, NotGiven)} + if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): + return [_json_value(item) for item in value] + return None if isinstance(value, NotGiven) else value + + +def _form_data(values: dict[str, Any], *, multipart: bool) -> dict[str, Any]: + """Encode object fields as JSON parts for multipart bodies and as exploded fields for URL-encoded bodies.""" + fields: dict[str, Any] = {} + for name, value in _without_not_given(values).items(): + if isinstance(value, dict): + if multipart: + fields[name] = json.dumps(value) + else: + fields.update(value) + else: + fields[name] = value + return fields + + +def _retry_delay(response: httpx.Response | None, attempt: int) -> float: + if response is not None: + try: + return min(max(float(response.headers.get("retry-after", "")), 0.0), 60.0) + except ValueError: + pass + return min(0.5 * 2.0**attempt, 8.0) + + +class SyncAPIClient: + def __init__( + self, + *, + api_key: str | None, + base_url: str, + timeout: float | httpx.Timeout, + max_retries: int, + retry_methods: Sequence[str], + http_client: httpx.Client | None, + ) -> None: + self._client = http_client or httpx.Client(timeout=timeout) + self._base_url = httpx.URL(f"{base_url.rstrip('/')}/") + self._api_key = api_key + self._max_retries = max_retries + self._retry_methods = {method.upper() for method in retry_methods} + + def request(self, method: str, path: str, **kwargs: Any) -> Any: + retryable = method.upper() in self._retry_methods + headers = {**_without_none(kwargs.get("headers") or {}), **(kwargs.get("extra_headers") or {})} + if self._api_key and (auth := kwargs.get("auth")): + headers.setdefault(auth[0], f"{auth[1]}{self._api_key}") + server = kwargs.get("server") + url = self._base_url.join(f"{server.rstrip('/')}/{path.lstrip('/')}" if server else path.lstrip("/")) + for attempt in range(self._max_retries + 1): + try: + response = self._client.request( + method, + url, + params=kwargs.get("params"), + headers=headers, + cookies=_without_none(kwargs.get("cookies") or {}) or None, + json=_json_value(kwargs.get("json")), + data=kwargs.get("data"), + files=_without_not_given(kwargs.get("files")), + content=_without_not_given(kwargs.get("content")), + **({"timeout": timeout} if (timeout := kwargs.get("timeout")) is not None else {}), + ) + except httpx.HTTPError as error: + if not retryable or attempt == self._max_retries: + raise APIConnectionError(str(error)) from error + time.sleep(_retry_delay(None, attempt)) + continue + if ( + (retryable or (response.status_code == 429 and kwargs.get("json") is not None)) + and attempt < self._max_retries + and (response.status_code in {408, 409, 429} or response.status_code >= 500) + ): + time.sleep(_retry_delay(response, attempt)) + continue + if response.is_error: + raise APIError(response.status_code, response.text, response.headers.get("x-request-id")) + if response.status_code == 204 or not response.content: + return None + media_type = response.headers.get("content-type", "").split(";", 1)[0].lower() + if media_type == "application/json" or media_type.endswith("+json"): + return response.json() + if kwargs.get("text") or media_type.startswith("text/"): + return response.text + return response.content + raise APIConnectionError("Request was not attempted") + + def close(self) -> None: + self._client.close() + + +class AsyncAPIClient: + def __init__( + self, + *, + api_key: str | None, + base_url: str, + timeout: float | httpx.Timeout, + max_retries: int, + retry_methods: Sequence[str], + http_client: httpx.AsyncClient | None, + ) -> None: + self._client = http_client or httpx.AsyncClient(timeout=timeout) + self._base_url = httpx.URL(f"{base_url.rstrip('/')}/") + self._api_key = api_key + self._max_retries = max_retries + self._retry_methods = {method.upper() for method in retry_methods} + + async def request(self, method: str, path: str, **kwargs: Any) -> Any: + retryable = method.upper() in self._retry_methods + headers = {**_without_none(kwargs.get("headers") or {}), **(kwargs.get("extra_headers") or {})} + if self._api_key and (auth := kwargs.get("auth")): + headers.setdefault(auth[0], f"{auth[1]}{self._api_key}") + server = kwargs.get("server") + url = self._base_url.join(f"{server.rstrip('/')}/{path.lstrip('/')}" if server else path.lstrip("/")) + for attempt in range(self._max_retries + 1): + try: + response = await self._client.request( + method, + url, + params=kwargs.get("params"), + headers=headers, + cookies=_without_none(kwargs.get("cookies") or {}) or None, + json=_json_value(kwargs.get("json")), + data=kwargs.get("data"), + files=_without_not_given(kwargs.get("files")), + content=_without_not_given(kwargs.get("content")), + **({"timeout": timeout} if (timeout := kwargs.get("timeout")) is not None else {}), + ) + except httpx.HTTPError as error: + if not retryable or attempt == self._max_retries: + raise APIConnectionError(str(error)) from error + await asyncio.sleep(_retry_delay(None, attempt)) + continue + if ( + (retryable or (response.status_code == 429 and kwargs.get("json") is not None)) + and attempt < self._max_retries + and (response.status_code in {408, 409, 429} or response.status_code >= 500) + ): + await asyncio.sleep(_retry_delay(response, attempt)) + continue + if response.is_error: + raise APIError(response.status_code, response.text, response.headers.get("x-request-id")) + if response.status_code == 204 or not response.content: + return None + media_type = response.headers.get("content-type", "").split(";", 1)[0].lower() + if media_type == "application/json" or media_type.endswith("+json"): + return response.json() + if kwargs.get("text") or media_type.startswith("text/"): + return response.text + return response.content + raise APIConnectionError("Request was not attempted") + + async def close(self) -> None: + await self._client.aclose() diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/_exceptions.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..a899a21cb8a43268bd4f34ba4a26da022dcaaaea --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/_exceptions.py @@ -0,0 +1,28 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +import json +from typing import Any + + +class APIError(Exception): + """Error returned by the API.""" + + def __init__(self, status_code: int, body: str, request_id: str | None = None) -> None: + self.status_code = status_code + self.body = body + self.request_id = request_id + super().__init__(f"API request failed with status {status_code}: {body}") + + @property + def json(self) -> Any: + """Parsed JSON body, or None when the body is not JSON.""" + try: + return json.loads(self.body) + except ValueError: + return None + + +class APIConnectionError(Exception): + """Network error raised while contacting the API.""" diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/async_client.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..44d0429d7be7b41ba8391b43749adfb6d5a2c617 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/async_client.py @@ -0,0 +1,86 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from collections.abc import Sequence + +import httpx + +from ._client import AsyncAPIClient, _resolve_api_key +from .resources import ( + AsyncAccount, + AsyncBilling, + AsyncDatasets, + AsyncDeployments, + AsyncExplore, + AsyncExports, + AsyncImages, + AsyncLifecycle, + AsyncModels, + AsyncProjects, + AsyncStorageIntegrations, + AsyncTraining, + AsyncUpload, +) + + +class AsyncPlatform: + """Client for the Ultralytics Platform API.""" + + def __init__( + self, + *, + api_key: str | None = None, + base_url: str = "https://platform.ultralytics.com", + timeout: float | httpx.Timeout = 60.0, + max_retries: int = 2, + retry_methods: Sequence[str] = ("GET", "HEAD", "OPTIONS"), + http_client: httpx.AsyncClient | None = None, + ) -> None: + """Initialize the client. + + Args: + api_key (str, optional): API key. Defaults to ULTRALYTICS_API_KEY then the configured credential provider. Pass an empty string to disable authentication. + base_url (str): API base URL. + timeout (float | httpx.Timeout): Request timeout. + max_retries (int): Retries for connection errors and retryable responses. + retry_methods (Sequence[str]): HTTP methods safe to repeat after network errors or HTTP 408, 409, 429, and 5xx responses. Defaults to GET, HEAD, OPTIONS. Opt in only when the operation is safe to repeat and its request body can be resent. + http_client (httpx.AsyncClient, optional): Custom HTTP client. + """ + resolved_api_key = _resolve_api_key(api_key) + self._client = AsyncAPIClient( + api_key=resolved_api_key, + base_url=base_url, + timeout=timeout, + max_retries=max_retries, + retry_methods=retry_methods, + http_client=http_client, + ) + self.account = AsyncAccount(self._client) + self.billing = AsyncBilling(self._client) + self.datasets = AsyncDatasets(self._client) + self.deployments = AsyncDeployments(self._client) + self.explore = AsyncExplore(self._client) + self.images = AsyncImages(self._client) + self.storage_integrations = AsyncStorageIntegrations(self._client) + self.models = AsyncModels(self._client) + self.exports = AsyncExports(self._client) + self.projects = AsyncProjects(self._client) + self.training = AsyncTraining(self._client) + self.lifecycle = AsyncLifecycle(self._client) + self.upload = AsyncUpload(self._client) + + async def close(self) -> None: + """Close the underlying HTTP client.""" + await self._client.close() + + async def __aenter__(self) -> AsyncPlatform: # noqa: PYI034 + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + traceback: object, + ) -> None: + await self.close() diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/cli.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..d28f4a845daa29989b652f47fea5fc2834d58b34 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/cli.py @@ -0,0 +1,783 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Unified Ultralytics CLI: local YOLO commands and Platform SDK operations discovered from the SDK itself.""" + +from __future__ import annotations + +import importlib.util +import inspect +import json +import os +import sys +import time +import types +import typing +import zipfile +from collections.abc import Sequence +from contextlib import ExitStack +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path +from tarfile import is_tarfile +from tempfile import TemporaryDirectory +from typing import Any, BinaryIO, Literal, get_args, get_origin, get_type_hints + +from . import NOT_GIVEN, APIConnectionError, APIError, NotGiven, Platform +from ._cli_metadata import MULTIPART_FILES + +JSON_TYPES = {type(None): "null", bool: "boolean", int: "integer", float: "number", str: "string", list: "array"} +JSON_TYPES |= {dict: "object", Sequence: "array"} +OFFICIAL_FAMILIES = ("yolo26", "yolo11", "yolov8", "yolov5") # public ultralytics/ projects on Platform + + +def platform_url() -> str: + """Platform origin, read per invocation so ULTRALYTICS_PLATFORM_URL applies after import.""" + return os.getenv("ULTRALYTICS_PLATFORM_URL", "https://platform.ultralytics.com").rstrip("/") + + +def kinds(annotation: Any) -> tuple[set[str], list | None]: + """Map a generated SDK annotation to JSON kinds and literal choices; empty kinds accept any JSON value.""" + if annotation is Any: + return set(), None + if annotation is BinaryIO: + return {"binary"}, None + origin = get_origin(annotation) + if origin is Literal: + values = list(get_args(annotation)) + return {JSON_TYPES[type(value)] for value in values}, values + if origin in {types.UnionType, typing.Union}: + members = [member for member in get_args(annotation) if member is not NotGiven] + parts = [kinds(member) for member in members] + if any(not part[0] for part in parts): + return set(), None + literal = all(get_origin(member) is Literal or member is type(None) for member in members) + return set().union(*(part[0] for part in parts)), [ + v for _, c in parts for v in c or [None] + ] if literal else None + return {JSON_TYPES[origin or annotation]}, None + + +def describe(method) -> dict[str, dict]: + """Argument descriptors from the SDK signature: positional parameters are path parameters.""" + hints = get_type_hints(method) + result = {} + for parameter in inspect.signature(method).parameters.values(): + if parameter.name in {"timeout", "extra_headers"}: + continue + types_, choices = kinds(hints[parameter.name]) + result[parameter.name] = { + "types": types_, + "choices": choices, + "required": parameter.default is parameter.empty, + "path": parameter.kind is parameter.POSITIONAL_OR_KEYWORD, + } + return result + + +def assignments(tokens: list[str]) -> dict[str, str | None]: + """Allow spaces before '=' while preserving empty values and subsequent shell arguments.""" + result = {} + i = 0 + while i < len(tokens): + token = tokens[i] + if i + 1 < len(tokens) and tokens[i + 1].startswith("=") and "=" not in token: + i += 1 + token += tokens[i] + key, separator, value = token.partition("=") + i += 1 + if (key.startswith("-") and token not in {"--help", "-h"}) or not key: + raise ValueError("Use key=value arguments, not --key value") + if key in result: + raise ValueError(f"duplicate argument: {key}") + result[key] = value if separator else None + return result + + +def parse(raw: dict[str, str | None], arguments: dict[str, dict]) -> dict: + """Convert supplied arguments using the SDK signature; only supplied values reach the SDK.""" + result = {} + stdin_used = False + for name, text in raw.items(): + if name not in arguments: + raise ValueError(f"unknown argument: {name}") + arg = arguments[name] + kinds_ = {"string"} if "binary" in arg["types"] else arg["types"] + if text is None: + if kinds_ - {"null"} != {"boolean"}: + raise ValueError(f"{name} requires a value; only booleans may be bare") + text = "True" + if text.startswith("@") and (not kinds_ or kinds_ & {"object", "array"}): + if text == "@-": + if stdin_used: + raise ValueError("stdin can supply only one input") + stdin_used = True + text = sys.stdin.read() + else: + try: + text = Path(text[1:]).read_text(encoding="utf-8") + except OSError as error: + raise ValueError(f"{name}: cannot read JSON input file") from error + expected = "|".join(sorted(kinds_)) or "JSON" + try: + if text.lower() in {"null", "none"} and (not kinds_ or "null" in kinds_): + value = None + elif kinds_ - {"null"} == {"string"}: + value = text + elif "boolean" in kinds_ and text.lower() in {"true", "false"}: + value = text.lower() == "true" + elif kinds_ - {"null"} == {"integer"}: + value = int(text) + elif kinds_ - {"null"} == {"number"}: + value = float(text) + else: + value = json.loads(text) + json.dumps(value, allow_nan=False) # Reject non-finite numbers at any depth. + except ValueError as error: + raise ValueError(f"{name}: expected {expected}; objects and arrays require valid JSON") from error + actual = JSON_TYPES.get(type(value)) + if kinds_ and actual not in kinds_ and not (actual == "integer" and "number" in kinds_): + raise ValueError(f"{name}: expected {expected}") + if arg["choices"] is not None and value not in arg["choices"]: + raise ValueError(f"{name}: choose one of {json.dumps(arg['choices'])}") + result[name] = value + missing = [ + n for n, a in arguments.items() if a["required"] and n not in result and not (a["path"] and n == "owner") + ] + if missing: + raise ValueError(f"missing arguments: {', '.join(missing)}") + return result + + +def open_inputs(values: dict, arguments: dict[str, dict], files: list[str], stack: ExitStack) -> dict: + """Open binary arguments and the multipart body fields the generator identified as binary.""" + fields = [(values, name) for name, arg in arguments.items() if "binary" in arg["types"] and name in values] + fields += [ + (values["body"], field) for field in files if isinstance(values.get("body"), dict) and field in values["body"] + ] + for container, key in fields: + value = container[key] + if not isinstance(value, str) or not value.startswith("@") or value == "@-": + raise ValueError(f"{key}: binary inputs require @path (not stdin)") + container[key] = stack.enter_context(open(value[1:], "rb")) # noqa: SIM115 - caller owns the ExitStack + return values + + +def output(value) -> None: + """Write one complete SDK response to stdout; never fetch additional pages.""" + if isinstance(value, bytes): + sys.stdout.buffer.write(value) + elif isinstance(value, str): + print(value) + else: + print(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False)) + + +def defaults(methods: dict[str, Any]) -> dict[str, list[str]]: + """Implicit verbs: bare `list`, and `retrieve` when its extra path identifiers are supplied.""" + if "list" not in methods: + return {} + result = {"list": []} + if "retrieve" in methods: + parents = {name for name, arg in describe(methods["list"]).items() if arg["path"]} + identifiers = [ + name for name, arg in describe(methods["retrieve"]).items() if arg["path"] and name not in parents + ] + if identifiers: + result["retrieve"] = identifiers + return result + + +def yolo_args(tokens: list[str], *extra: str) -> dict: + """Type key=value arguments the way `yolo` does, accepting `extra` workflow keys; Alpha validates their values.""" + from ultralytics.cfg import DEFAULT_CFG_DICT, smart_value + from ultralytics.utils import YAML + from ultralytics.utils.checks import check_model_file_from_stem + + raw = assignments(tokens) + args = YAML.load(Path(raw.pop("cfg")).expanduser()) if raw.get("cfg") else {} + args.update({key: True if value is None else smart_value(value) for key, value in raw.items()}) + if unknown := set(args) - set(DEFAULT_CFG_DICT) - {"gpu_type", "save_dir", *extra}: + raise ValueError(f"Unknown YOLO arguments: {', '.join(sorted(unknown))}") + args = {key: value for key, value in args.items() if value is not None} # null means unset, as in default.yaml + for key in args.keys() & {"project", "name", "save_dir"}: + args[key] = str(args[key]) + if "model" in args and not str(args["model"]).startswith("ul://"): # URIs may end in a stem + args["model"] = str(check_model_file_from_stem(str(args["model"]))) # yolo26n -> yolo26n.pt, as YOLO does + return args + + +def resolve_project(client: Platform, project: str | None) -> tuple[str, str]: + """Return the owner and slug of an existing project, creating the private cloud-training default.""" + from ultralytics.utils.callbacks.platform import slugify + + owner = client.account.summary()["username"] + slug = slugify(Path(str(project)).resolve().name) if project else "cloud-training" + try: + if client.projects.retrieve(owner, slug)["project"]["visibility"] != "private" and project is None: + raise ValueError("Project cloud-training is public; pass project= or make it private") + except APIError as error: + if error.status_code != 404: + raise + slug = client.projects.create(owner=owner, project=slug, name=slug, visibility="private")["project"] + return owner, slug + + +def upload_file(client: Platform, path: Path, asset_type: str, asset_id: str) -> str: + """Upload one dataset archive or checkpoint and return its completed upload session.""" + from ultralytics.utils.uploads import safe_upload + + signed = client.upload.signed_url( + body={ + "assetType": asset_type, + "assetId": asset_id, + "filename": path.name, + "contentType": "application/octet-stream", + "totalBytes": path.stat().st_size, + } + ) + if not safe_upload(path, signed["uploadUrl"], headers=signed.get("headers"), progress=True): + raise OSError(f"Upload failed: {path.name}") # reported with its message, like failed downloads + client.upload.complete(session_id=signed["sessionId"]) + return signed["sessionId"] + + +def platform_model(client: Platform, model: Any) -> str | None: + """Return the ul:// URI of a Platform model or hosted official weights; None means a checkpoint to upload.""" + from ultralytics.utils.downloads import GITHUB_ASSETS_NAMES + + model = str(model) + if model.startswith("ul://"): + return model + if Path(model).is_file(): # a local file wins over same-named official weights, as in local YOLO + return None + if model in GITHUB_ASSETS_NAMES and (family := next((f for f in OFFICIAL_FAMILIES if model.startswith(f)), None)): + try: # Platform hosts only part of each family, e.g. not the -world or -oiv7 weights + client.models.retrieve("ultralytics", family, Path(model).stem) + return f"ul://ultralytics/{family}/{Path(model).stem}" + except APIError as error: + if error.status_code != 404: + raise + return None + + +def upload_model(client: Platform, model: Any, owner: str, project: str) -> str: + """Upload a local .pt checkpoint as a new model of the project and return its ul:// URI.""" + from ultralytics import YOLO + from ultralytics.utils.callbacks.platform import slugify + + path = Path(str(model)).expanduser() + if not path.is_file() or path.suffix != ".pt": + raise ValueError( + f"model= must be a local .pt file, ul://owner/project/model, or official weights hosted on Platform: {model}" + ) + body = {"owner": owner, "project": project, "model": slugify(path.stem), "name": path.stem, "task": YOLO(path).task} + created = client.models.create(body=body) + upload_file(client, path, "models", created["id"]) + uri = f"ul://{created['owner']}/{created['project']}/{created['model']}" + print(f"Model: {uri}") + return uri + + +def package_dataset(dataset: Path, destination: str, task: str | None) -> Path: + """Zip the declared splits of a local dataset with their labels, masks, or depth maps. + + Existing archives pass through. A directory without a YAML is a classification dataset of class folders. + """ + from ultralytics.data.utils import IMG_FORMATS, check_det_dataset, find_dataset_yaml + from ultralytics.utils import YAML + + source = dataset.resolve() + task = task or ("classify" if source.is_dir() and not any(source.rglob("*.yaml")) else "detect") + if source.is_file() and (zipfile.is_zipfile(source) or is_tarfile(source)): + return source + yaml_file, declared = None, {} + if task == "classify": + root, directories = source, [source / split for split in ("train", "val", "test")] + if not (source / "train").is_dir() or not any((source / split).is_dir() for split in ("val", "test")): + raise ValueError("Classification data requires train/ and val/ or test/ class directories") + else: + yaml_file = find_dataset_yaml(source) if source.is_dir() else source + if yaml_file.suffix.lower() not in {".yaml", ".yml"}: + raise ValueError("Local data must be a dataset YAML, directory, ZIP, or TAR archive") + data = check_det_dataset(str(yaml_file), autodownload=False) + # declared paths keep symlinked splits under root; abspath also anchors a relative path: key + root, declared = Path(os.path.abspath(data["path"])), YAML.load(yaml_file) + declared.setdefault("val", declared.pop("validation", None)) # the alias check_det_dataset renames + listed = {key: declared[key] for key in ("train", "val", "test") if declared.get(key)} + items = [value for item in listed.values() for value in (item if isinstance(item, list) else [item])] + splits = [Path(os.path.abspath(root / value)) for value in items] + splits = [ # an absent '../' value resolves back under root, as check_det_dataset does for Roboflow exports + s if s.exists() or not v.startswith("../") else Path(os.path.abspath(root / v[3:])) + for v, s in zip(items, splits) + ] + if not all(split.is_dir() and split.is_relative_to(root) for split in splits): + raise ValueError("Cloud uploads require split directories under the dataset root, not image lists") + # archive members are relative to root, so absolute or ../ split values are rewritten to match + relative = {value: split.relative_to(root).as_posix() for value, split in zip(items, splits)} + declared |= {k: [relative[v] for v in i] if isinstance(i, list) else relative[i] for k, i in listed.items()} + siblings = ("labels", data.get("masks_dir") or "masks", "depth") # YOLO mirrors images/ per split + directories = splits + [ # only below root, so an images/ component of the root itself is kept + root.joinpath(*(n if p == "images" else p for p in s.relative_to(root).parts)) + for s in splits + for n in siblings + ] + archive = Path(destination) / f"{root.name}.zip" + with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as output: + if yaml_file: # splits are relative to the archive root; a local path: key would point outside it + YAML.save(archive.with_name("data.yaml"), {key: value for key, value in declared.items() if key != "path"}) + output.write(archive.with_name("data.yaml"), "data.yaml") + for file in sorted({file for directory in directories for file in directory.rglob("*")}): + if ( + file.is_file() + and not any(part.startswith(".") for part in file.relative_to(root).parts) + and file.suffix[1:].lower() in IMG_FORMATS | {"txt", "npy"} + ): + output.write(file, file.relative_to(root)) + return archive + + +def wait_job(fetch) -> dict: + """Poll a submitted cloud job until it stops, drawing epoch progress when the job reports it.""" + from ultralytics.utils.tqdm import TQDM, is_noninteractive_console + + active = {"pending", "untrained", "queued", "starting", "running"} + plain = is_noninteractive_console() # CI consoles get one line per epoch; a bar there would print only on close + bar = last = None + try: + while True: + job = fetch() + if job is None: + raise ValueError("Cloud job is no longer available") + progress = job.get("progress") or {} + if progress.get("totalEpochs") and (bar or job["status"] in active): # epoch bar, drawn at 0 right away + epoch = progress["currentEpoch"] + if bar is None: + seen = epoch + bar = TQDM( + total=progress["totalEpochs"], + initial=epoch, + desc="Training", + unit="epoch", + mininterval=0, # the default interval would hide the empty bar until the first epoch finishes + disable=plain or None, + ) + if epoch > seen: # update only on epoch changes so the rate stays accurate + bar.update(epoch - seen) + seen = epoch + if plain and epoch != last: # the disabled bar prints nothing: report each epoch, the first included + print(f"Epoch {epoch}/{progress['totalEpochs']}", flush=True) + last = epoch + elif job["status"] in active and job["status"] != last: # terminal statuses speak through what follows + print(f"{job['status'].capitalize()}...", flush=True) + last = job["status"] + if job["status"] not in active: + break + time.sleep(5) + finally: + if bar: + bar.close() # also on Ctrl-C, so the interruption message starts on its own line + if job["status"] != "completed": + raise ValueError(f"Cloud job {job['status']}: {(job.get('error') or {}).get('message', '')}") + return job + + +def download_file(url: str, target: Path) -> Path: + """Download a fresh artifact before replacing an existing output file.""" + from ultralytics.utils.downloads import safe_download + + target.parent.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(dir=target.parent) as temporary: + downloaded = safe_download(url, file=target.name, dir=temporary, unzip=False) + Path(downloaded).replace(target) + print(f"Saved: {target}") + return target + + +def download_model(client: Platform, uri: str, cfg) -> int: + """Wait for a model's training and save its checkpoint, arguments, and results under YOLO's save directory.""" + import csv + + from ultralytics import YOLO + from ultralytics.cfg import get_save_dir + from ultralytics.utils import YAML + + model_path = uri[5:].split("/") + try: + job = wait_job(lambda: client.models.training(*model_path)["job"]) + cfg.task = client.models.retrieve(*model_path)["model"].get("task") or "detect" + directory = get_save_dir(cfg) + files = client.models.files(*model_path)["files"] + if not files: + raise ValueError("Training completed without a downloadable checkpoint") + checkpoint = YOLO(download_file(files[0]["downloadUrl"], directory / "weights" / "best.pt")).ckpt + YAML.save(directory / "args.yaml", checkpoint["train_args"]) + if results := checkpoint.get("train_results"): + with directory.joinpath("results.csv").open("w", newline="") as file: + writer = csv.writer(file) + writer.writerow(results) + writer.writerows(zip(*results.values())) + directory.joinpath("results.json").write_text(json.dumps(job, indent=2)) + except KeyboardInterrupt: # the remote job is unaffected; every step above can be redone with this command + print(f"Interrupted; run `ul cloud download model={uri}` to resume once training completes", file=sys.stderr) + return 130 + return 0 + + +def cloud_train(client: Platform, tokens: list[str]) -> int: + """ul cloud train model=yolo26n.pt data=ul://owner/datasets/slug epochs=100 [gpu_type=rtx-4090] [watch] + + Local .pt weights and dataset YAMLs, directories, ZIPs, or TARs are uploaded automatically. + project= selects the output project; default: private cloud-training. + Prints the run and its `ul cloud download` command; `watch` follows training and downloads the results instead. + """ + from ultralytics.cfg import DEFAULT_CFG_DICT, TASK2MODEL, get_cfg + from ultralytics.utils.callbacks.platform import slugify + from ultralytics.utils.downloads import GITHUB_ASSETS_NAMES + + args = yolo_args(tokens, "watch") + if not isinstance(args.get("data"), str) or not args["data"]: + raise ValueError("data= is required: use a Platform dataset URI or local dataset") + args.setdefault("model", TASK2MODEL.get(args.get("task"), "yolo26n.pt")) + args.setdefault("epochs", DEFAULT_CFG_DICT["epochs"]) + cfg = get_cfg(DEFAULT_CFG_DICT | args | {"mode": "train"}) # validate local-only arguments before the paid job + gpu_type, project, name = args.pop("gpu_type", NOT_GIVEN), args.pop("project", None), args.pop("name", None) + watch = args.pop("watch", False) + for key in ("device", "exist_ok", "save_dir"): # local-only arguments; the worker assigns its own GPU + args.pop(key, None) + if "cache" in args and not isinstance(args["cache"], str): + args["cache"] = "ram" if args["cache"] else "false" + local_data = Path(args["data"]).expanduser() + if not local_data.exists(): # ul:// URIs and built-in names such as coco8.yaml are resolved by Platform + local_data = None + with TemporaryDirectory(prefix="ul-cloud-train-") as temporary: + archive = package_dataset(local_data, temporary, args.get("task")) if local_data else None + owner, project_slug = resolve_project(client, project) + model = args["model"] + if Path(model).is_file() or not (model.startswith("ul://") or model in GITHUB_ASSETS_NAMES): + args["model"] = upload_model(client, model, owner, project_slug) + else: # hosted official weights map to their public model; other official names stay bare for the worker + args["model"] = platform_model(client, model) or model + if archive: + dataset = client.datasets.create( # Platform infers the task from the labels during ingest + owner=owner, dataset=slugify(archive.stem) or "dataset", name=archive.stem, visibility="private" + ) + args["data"] = f"ul://{dataset['owner']}/datasets/{dataset['dataset']}" + print(f"Dataset: {args['data']} (reuse this URI to skip uploading next time)") + session = upload_file(client, archive, "datasets", dataset["id"]) + client.datasets.ingest(dataset["owner"], dataset["dataset"], body={"sessionId": session}) + state = {"status": "processing"} + while state.get("status") == "processing": + time.sleep(2) + state = client.datasets.retrieve(dataset["owner"], dataset["dataset"])["dataset"] + if state.get("status") == "failed": + raise ValueError(f"Dataset ingestion failed; inspect {args['data']}: {state.get('processingError')}") + body = {"owner": owner, "project": project_slug} + if name: + body |= {"model": slugify(name), "name": name} + target = client.models.create(body=body) + started = client.training.start(model_id=target["id"], train_args=args, gpu_type=gpu_type) + uri = f"ul://{target['owner']}/{target['project']}/{target['model']}" + print(f"Model: {uri}") + print( + f"GPU: {started['gpuType']} at ${started['estimatedCost']['pricePerHour']:.2f}/h, " + f"estimated {started['billing']['estimatedCostDisplay']}" + ) + print(f"Run: {platform_url()}/{uri[5:]}") + if not watch: + print(f"Download: ul cloud download model={uri}") + return 0 + return download_model(client, uri, cfg) + + +def prediction_result(image, path: str, prediction: dict, names: dict, task: str, args): + """Adapt Platform summaries to YOLO Results so its plotting and saving stay the single owner.""" + import base64 + + import cv2 + import numpy as np + from ultralytics.data.utils import polygons2masks + from ultralytics.engine.results import Results + from ultralytics.utils.ops import xyxyxyxy2xywhr + + rows, values = prediction["results"], {} + if task == "classify": + values["probs"] = np.zeros(len(names), dtype=np.float32) + for row in rows: + values["probs"][row["class"]] = row["confidence"] + elif task not in {"semantic", "depth"}: + if args.classes is not None: # Platform predicts every class; apply YOLO's class filter and detection cap here + classes = {args.classes} if isinstance(args.classes, int) else set(args.classes) + rows = [row for row in rows if row["class"] in classes] + rows = rows[: args.max_det] + boxes = np.array([list(row["box"].values()) for row in rows], dtype=np.float32).reshape( + -1, 8 if task == "obb" else 4 + ) + if task == "obb": + boxes = xyxyxyxy2xywhr(boxes) + scores = np.array([[r["confidence"], r["class"]] for r in rows], dtype=np.float32).reshape(-1, 2) + values["obb" if task == "obb" else "boxes"] = np.concatenate((boxes, scores), axis=1) + if rows and "segments" in rows[0]: + polygons = [np.array(list(zip(r["segments"]["x"], r["segments"]["y"]))).ravel() for r in rows] + values["masks"] = np.stack( # a detection without a mask contour has no polygon to fill + [ + polygons2masks(image.shape[:2], [polygon], color=1)[0] + if polygon.size + else np.zeros(image.shape[:2], np.uint8) + for polygon in polygons + ] + ) + if rows and "keypoints" in rows[0]: + values["keypoints"] = np.array( + [ + np.stack([r["keypoints"][k] for k in ("x", "y", "visible") if k in r["keypoints"]], axis=-1) + for r in rows + ], + dtype=np.float32, + ) + for key in ("semantic_mask", "depth"): + if key in prediction: + encoded = prediction[key] + pixels = cv2.imdecode(np.frombuffer(base64.b64decode(encoded["data"]), np.uint8), cv2.IMREAD_UNCHANGED) + if key == "depth": + pixels = pixels.astype(np.float32) * encoded["max"] / (255 if encoded["bits"] == 8 else 65535) + pixels = cv2.resize(pixels, (image.shape[1], image.shape[0])) + values[key] = pixels + return Results(image, path, names, speed=prediction["speed"], **values) + + +def save_predictions(source: Path, response: dict, args: dict) -> None: + """Reuse YOLO's image/video, label, crop, and display writers without running local inference.""" + import numpy as np + from ultralytics.cfg import DEFAULT_CFG_DICT + from ultralytics.data.build import load_inference_source + from ultralytics.engine.predictor import BasePredictor + from ultralytics.nn.autobackend import default_class_names + + metadata = response["metadata"] # classNames and task are optional in the contract + names = dict(enumerate(metadata["classNames"])) if metadata.get("classNames") else default_class_names() + if (task := metadata.get("task")) is None: + raise ValueError("Platform did not report the model task, so predictions cannot be converted") + writer = BasePredictor(cfg=DEFAULT_CFG_DICT | args | {"task": task, "mode": "predict"}) + directory = writer.save_dir + writer.dataset = load_inference_source(str(source), batch=1) + writer.source_type = writer.dataset.source_type + if writer.args.save or writer.args.save_txt or writer.args.save_crop: + directory.mkdir(parents=True, exist_ok=True) + directory.joinpath("results.json").write_text(json.dumps(response, indent=2)) + try: + for (paths, images, descriptions), prediction in zip(writer.dataset, response["images"], strict=True): + result = prediction_result(images[0], paths[0], prediction, names, task, writer.args) + writer.results = [result] + writer.write_results(0, Path(paths[0]), np.moveaxis(images[0], -1, 0), descriptions) + finally: + for video in writer.vid_writer.values(): + video.release() + if getattr(writer.dataset, "cap", None) is not None: + writer.dataset.cap.release() + if directory.exists(): + print(f"Results saved to {directory}") + + +def cloud_predict(client: Platform, tokens: list[str]) -> int: + """ul cloud predict model=ul://owner/project/model source=image.jpg [conf=0.25 iou=0.7 imgsz=640] + + source= is one local image or video; conf/iou/imgsz run on Platform, classes/max_det apply locally. + Saves annotated output, with optional save_txt/save_crop/save_frames. + project=, name=, save_dir=, and exist_ok= control local outputs as in YOLO. + """ + args = yolo_args(tokens) + source = Path(str(args.pop("source", ""))).expanduser() + if not source.is_file(): + raise ValueError("source= must be a local image or video file") + model, project = args.pop("model", "yolo26n.pt"), args.pop("project", None) + local_args = args | {"model": model, "project": project} + uri = platform_model(client, model) or upload_model(client, model, *resolve_project(client, project)) + owner, project, model = uri[5:].split("/") + options = {key: args[key] for key in ("conf", "iou", "imgsz") if key in args} # YOLO options the endpoint accepts + with source.open("rb") as file: + response = client.models.predict(owner, project, model, body={"file": file, **options, "normalize": False}) + output(response) + save_predictions(source, response, local_args) + return 0 + + +def cloud_export(client: Platform, tokens: list[str]) -> int: + """ul cloud export model=ul://owner/project/model format=onnx [imgsz=640 quantize=16 gpu_type=rtx-4090] + + Waits for the export and downloads its artifact to save_dir= or project=, otherwise beside local weights or in cwd. + Replaces an existing artifact only after a successful download; name= retains its export-target meaning. + """ + args = yolo_args(tokens) + local_args = args.copy() + model, project = args.pop("model", "yolo26n.pt"), args.pop("project", None) + hosted = platform_model(client, model) + uri = hosted or upload_model(client, model, *resolve_project(client, project)) + if uri.startswith("ul://ultralytics/"): # exports require your own copy of official weights + owner, slug = resolve_project(client, project) + clone = client.models.clone(*uri[5:].split("/"), owner_body=owner, project_body=slug) + uri = f"ul://{clone['owner']}/{clone['project']}/{clone['model']}" + print(f"Model: {uri}") + owner, project, model = uri[5:].split("/") + gpu_type, fmt = args.pop("gpu_type", NOT_GIVEN), args.pop("format", "torchscript") + ignored = args.keys() & {"save", "plots", "workers", "cache"} + if ignored: + print(f"Warning: cloud export ignores local options: {', '.join(sorted(ignored))}.", file=sys.stderr) + for key in ("save_dir", "device", "exist_ok", "mode", "task", *ignored): + args.pop(key, None) + job = client.exports.create(owner, project, model, format=fmt, gpu_type=gpu_type, args=args) + print(f"Export: {job['id']} ({job['status']})") + job = wait_job(lambda: client.exports.retrieve(owner, project, model, job["id"])["export"]) + output(job) + file = job.get("file") or {} + if not file.get("downloadUrl") or not file.get("downloadFilename"): + raise ValueError("Export completed without a download URL or filename") + directory = Path( + local_args.get("save_dir") + or local_args.get("project") + or (Path(str(local_args.get("model"))).parent if not hosted else ".") + ) + download_file(file["downloadUrl"], directory.expanduser() / Path(file["downloadFilename"]).name) + return 0 + + +def cloud_download(client: Platform, tokens: list[str]) -> int: + """ul cloud download model=ul://owner/project/model [project=runs/detect name=train exist_ok=True] + + Waits for training to finish, then saves weights/best.pt, args.yaml, results.csv, and results.json under YOLO's + save directory, exactly as `ul cloud train ... watch` does. + """ + from ultralytics.cfg import DEFAULT_CFG_DICT, get_cfg + + args = yolo_args(tokens) + uri = str(args.get("model", "")) + if not uri.startswith("ul://") or len(uri[5:].split("/")) != 3: + raise ValueError("model= must be a ul://owner/project/model URI") + return download_model(client, uri, get_cfg(DEFAULT_CFG_DICT | args | {"mode": "train"})) + + +CLOUD_COMMANDS = {"train": cloud_train, "predict": cloud_predict, "export": cloud_export, "download": cloud_download} + + +def dispatch(tokens: list[str]) -> int: + """Execute one SDK operation, inferring only a missing resource-path owner.""" + tokens = list(tokens) + with ExitStack() as stack: + client = stack.enter_context(Platform(base_url=platform_url())) + if tokens and tokens[0] in CLOUD_COMMANDS: + if len(tokens) == 1 or any(token in {"help", "--help", "-h"} for token in tokens): + print(inspect.getdoc(CLOUD_COMMANDS[tokens[0]])) + return 0 + try: + return CLOUD_COMMANDS[tokens[0]](client, tokens[1:]) + except (AssertionError, SyntaxError, TypeError) as error: # ultralytics reports invalid inputs this way + raise ValueError(error) from error + except ImportError as error: # the installed ultralytics predates the helpers these workflows reuse + raise ValueError(f"{error}. Update it: pip install -U ultralytics") from error + resources = { + name.replace("_", "-"): { + method.replace("_", "-"): member + for method, member in inspect.getmembers(resource, inspect.ismethod) + if not method.startswith("_") + } + for name, resource in vars(client).items() + if not name.startswith("_") + } + resource = tokens.pop(0) if tokens and tokens[0] not in {"help", "--help", "-h"} else None + if resource is not None and resource not in resources: + raise ValueError("Unknown command; use --help to list API operations") + methods = resources[resource] if resource is not None else {} + implicit = defaults(methods) + method = tokens.pop(0) if tokens and tokens[0] in methods else None + raw = assignments(tokens) + help_requested = any(key in {"help", "--help", "-h"} and value is None for key, value in raw.items()) + if resource is not None and method is None and not help_requested: + method = next((name for name, keys in implicit.items() if keys and any(key in raw for key in keys)), None) + method = method or ("list" if "list" in implicit else None) + if method is None and tokens and not help_requested: + raise ValueError("Choose a resource operation before supplying arguments") + if method is None or help_requested: + if CLOUD_COMMANDS: + print(f"ul cloud {'|'.join(CLOUD_COMMANDS)} key=value ... — YOLO workflows on Platform") + print(" [operation] key=value ... (path owner defaults to the logged-in username)") + listing = {resource: {method: methods[method]} if method else methods} if resource else resources + for resource_name, members in listing.items(): + for method_name, member in members.items(): + doc = inspect.getdoc(member) or "" + print(f" {resource_name} {method_name}: {doc.partition(chr(10))[0].rstrip('.')}") + if method is not None: + for line in doc.splitlines()[1:]: + if not line.startswith((" timeout (", " extra_headers (")): + print(line) + return 0 + arguments = describe(methods[method]) + values = parse(raw, arguments) + key = f"{resource.replace('-', '_')}.{method.replace('-', '_')}" + open_inputs(values, arguments, MULTIPART_FILES.get(key, []), stack) + if "owner" not in values and arguments.get("owner", {}).get("path"): + username = client.account.summary().get("username") + if not isinstance(username, str) or not username: + raise ValueError("Could not infer owner; supply owner= explicitly") + values["owner"] = username + output(methods[method](**values)) + return 0 + + +def main(argv: list[str] | None = None) -> int: + """Run the unified CLI and translate SDK errors into process exit codes.""" + args = list(sys.argv[1:] if argv is None else argv) + try: + if not args or args in (["help"], ["--help"], ["-h"]): + workflows = f"ul cloud {'|'.join(CLOUD_COMMANDS)} key=value ...\n" if CLOUD_COMMANDS else "" + print( + "ul login API_KEY | logout | version\n" + "ul train|val|predict|export|track|benchmark key=value ...\n" + "ul settings|checks|cfg|copy-cfg|solutions ...\n" + f"{workflows}" + "ul cloud [operation] key=value ...\n" + "Login/logout and local commands require ultralytics. Use ul cloud --help to list API commands.\n" + "Omitted path owners default to the logged-in username. No --key value options." + ) + return 0 + if args in (["version"], ["--version"]): + print(f"ultralytics-platform {version('ultralytics-platform')}") + try: + print(f"ultralytics {version('ultralytics')}") + except PackageNotFoundError: + print("ultralytics not installed") + return 0 + workflow = args[0] == "cloud" and len(args) > 1 and args[1] in CLOUD_COMMANDS + if (args[0] != "cloud" or workflow) and importlib.util.find_spec("ultralytics") is None: + raise ValueError( + "This command requires ultralytics. Install it in this environment: pip install ultralytics" + ) + if args[0] == "cloud": + return dispatch(args[1:]) + original = sys.argv[:] + try: + # YOLO aliases sys.argv as ARGV and recognizes its executable name in prediction paths. + sys.argv[:] = ["yolo", *args] + from ultralytics.cfg import entrypoint + + entrypoint() + finally: + sys.argv[:] = original + return 0 + except APIError as error: + body = error.json + detail = body.get("error") if isinstance(body, dict) else None + print( + f"API request failed (HTTP {error.status_code}){f': {detail}' if isinstance(detail, str) else '.'}", + file=sys.stderr, + ) + return 1 + except APIConnectionError: + print("Could not connect to API.", file=sys.stderr) + return 1 + except (ValueError, OSError) as error: + print(f"Error: {error}", file=sys.stderr) + return 2 + except KeyboardInterrupt: + print("Interrupted.", file=sys.stderr) + return 130 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/client.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/client.py new file mode 100644 index 0000000000000000000000000000000000000000..6eb9ce0dbb9f179fb7b00e717bb221768a621e74 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/client.py @@ -0,0 +1,86 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from collections.abc import Sequence + +import httpx + +from ._client import SyncAPIClient, _resolve_api_key +from .resources import ( + Account, + Billing, + Datasets, + Deployments, + Explore, + Exports, + Images, + Lifecycle, + Models, + Projects, + StorageIntegrations, + Training, + Upload, +) + + +class Platform: + """Client for the Ultralytics Platform API.""" + + def __init__( + self, + *, + api_key: str | None = None, + base_url: str = "https://platform.ultralytics.com", + timeout: float | httpx.Timeout = 60.0, + max_retries: int = 2, + retry_methods: Sequence[str] = ("GET", "HEAD", "OPTIONS"), + http_client: httpx.Client | None = None, + ) -> None: + """Initialize the client. + + Args: + api_key (str, optional): API key. Defaults to ULTRALYTICS_API_KEY then the configured credential provider. Pass an empty string to disable authentication. + base_url (str): API base URL. + timeout (float | httpx.Timeout): Request timeout. + max_retries (int): Retries for connection errors and retryable responses. + retry_methods (Sequence[str]): HTTP methods safe to repeat after network errors or HTTP 408, 409, 429, and 5xx responses. Defaults to GET, HEAD, OPTIONS. Opt in only when the operation is safe to repeat and its request body can be resent. + http_client (httpx.Client, optional): Custom HTTP client. + """ + resolved_api_key = _resolve_api_key(api_key) + self._client = SyncAPIClient( + api_key=resolved_api_key, + base_url=base_url, + timeout=timeout, + max_retries=max_retries, + retry_methods=retry_methods, + http_client=http_client, + ) + self.account = Account(self._client) + self.billing = Billing(self._client) + self.datasets = Datasets(self._client) + self.deployments = Deployments(self._client) + self.explore = Explore(self._client) + self.images = Images(self._client) + self.storage_integrations = StorageIntegrations(self._client) + self.models = Models(self._client) + self.exports = Exports(self._client) + self.projects = Projects(self._client) + self.training = Training(self._client) + self.lifecycle = Lifecycle(self._client) + self.upload = Upload(self._client) + + def close(self) -> None: + """Close the underlying HTTP client.""" + self._client.close() + + def __enter__(self) -> Platform: # noqa: PYI034 + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + traceback: object, + ) -> None: + self.close() diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/py.typed b/.venv/lib/python3.12/site-packages/ultralytics_platform/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__init__.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3dea6d6d58b435ab2ab3ae84b6052835a6173735 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__init__.py @@ -0,0 +1,28 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from .account import Account as Account +from .account import AsyncAccount as AsyncAccount +from .billing import AsyncBilling as AsyncBilling +from .billing import Billing as Billing +from .datasets import AsyncDatasets as AsyncDatasets +from .datasets import Datasets as Datasets +from .deployments import AsyncDeployments as AsyncDeployments +from .deployments import Deployments as Deployments +from .explore import AsyncExplore as AsyncExplore +from .explore import Explore as Explore +from .exports import AsyncExports as AsyncExports +from .exports import Exports as Exports +from .images import AsyncImages as AsyncImages +from .images import Images as Images +from .lifecycle import AsyncLifecycle as AsyncLifecycle +from .lifecycle import Lifecycle as Lifecycle +from .models import AsyncModels as AsyncModels +from .models import Models as Models +from .projects import AsyncProjects as AsyncProjects +from .projects import Projects as Projects +from .storage_integrations import AsyncStorageIntegrations as AsyncStorageIntegrations +from .storage_integrations import StorageIntegrations as StorageIntegrations +from .training import AsyncTraining as AsyncTraining +from .training import Training as Training +from .upload import AsyncUpload as AsyncUpload +from .upload import Upload as Upload diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a717b5e9366dd136e001e3c53d0f41f9cb053eed Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/account.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/account.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83522db092bbf7a624514c1c1416cf9c072e2407 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/account.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/billing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/billing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f51a89ee69ac17994c7e8d02240da146d33c0b92 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/billing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/datasets.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/datasets.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb557e66406da6b811180f78c62a3b2ba2d851af Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/datasets.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/deployments.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/deployments.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5b36e8a12ebb0c424b06364edf5748604423129 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/deployments.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/explore.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/explore.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..caf881f1f9fee0c300f522ae4c1ed01896bcf3c8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/explore.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/exports.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/exports.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ab475f0331c835c037bb8eb1e3f11eeac0f48e0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/exports.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/images.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/images.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7b0668c871f5d29eb710fe3e71c99eff15a0478 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/images.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/lifecycle.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/lifecycle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..908408cd3a6ba3dbc05d63a4551408d6268f1a26 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/lifecycle.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/models.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ef8b15f1a319be8e861ba063d85e6d025308d17 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/models.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/projects.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/projects.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0923b49ff95fe71c182e218af0c79f32da42888a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/projects.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/storage_integrations.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/storage_integrations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f355617a3ae23c3ef56b4e717481440e87c2e5da Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/storage_integrations.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/training.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/training.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9ecc664ec4782117d9b9237702786f949e41908 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/training.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/upload.cpython-312.pyc b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/upload.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19acadc03bf0dca2dbfe991f120dd612656c6866 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/__pycache__/upload.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/account.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/account.py new file mode 100644 index 0000000000000000000000000000000000000000..cf3d63a2873b797c860a5a1c254442327fea4c10 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/account.py @@ -0,0 +1,348 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Literal, cast + +import httpx + +from .._client import ( + NOT_GIVEN, + AsyncAPIClient, + NotGiven, + SyncAPIClient, + _query_parameter, +) +from ..types import ( + AccountApiKeysResponse, + AccountFollowResponse, + AccountProfileResponse, + AccountStorageResponse, + AccountSummaryResponse, +) + + +class Account: + """Account API operations.""" + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + + def summary( + self, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> AccountSummaryResponse: + """Summarize your Platform account. + + Returns your plan, credit balance, and resource counts. Browser sessions also include team workspaces. + + Args: + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (AccountSummaryResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + AccountSummaryResponse, + self._client.request( + "GET", + "/api/account/summary", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def api_keys( + self, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> AccountApiKeysResponse: + """List API keys. + + Returns active API key metadata for the API key's workspace. + + Args: + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (AccountApiKeysResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + AccountApiKeysResponse, + self._client.request( + "GET", "/api/api-keys", timeout=timeout, extra_headers=extra_headers, auth=("Authorization", "Bearer ") + ), + ) + + def storage( + self, + *, + details: Literal["true", "false"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> AccountStorageResponse: + """Check storage usage. + + Returns storage breakdown by category and, when requested, the workspace's largest items. + + Args: + details (Literal["true", "false"], optional): Include the ten largest storage consumers + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (AccountStorageResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + AccountStorageResponse, + self._client.request( + "GET", + "/api/storage", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("details", details, style="form", explode=True)], + ), + ) + + def profile( + self, + *, + username: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> AccountProfileResponse: + """Get a public user profile. + + Returns a public user profile and its follow state for the authenticated caller. + + Args: + username (str): username query parameter. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (AccountProfileResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + AccountProfileResponse, + self._client.request( + "GET", + "/api/users", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("username", username, style="form", explode=True)], + ), + ) + + def follow( + self, + *, + username: str, + followed: bool, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> AccountFollowResponse: + """Follow a user. + + Follows or unfollows a Platform user. + + Args: + username (str): username request value. + followed (bool): followed request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (AccountFollowResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + AccountFollowResponse, + self._client.request( + "PATCH", + "/api/users", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"username": username, "followed": followed}, + ), + ) + + +class AsyncAccount: + """Asynchronous Account API operations.""" + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + + async def summary( + self, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> AccountSummaryResponse: + """Summarize your Platform account. + + Returns your plan, credit balance, and resource counts. Browser sessions also include team workspaces. + + Args: + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (AccountSummaryResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + AccountSummaryResponse, + await self._client.request( + "GET", + "/api/account/summary", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def api_keys( + self, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> AccountApiKeysResponse: + """List API keys. + + Returns active API key metadata for the API key's workspace. + + Args: + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (AccountApiKeysResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + AccountApiKeysResponse, + await self._client.request( + "GET", "/api/api-keys", timeout=timeout, extra_headers=extra_headers, auth=("Authorization", "Bearer ") + ), + ) + + async def storage( + self, + *, + details: Literal["true", "false"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> AccountStorageResponse: + """Check storage usage. + + Returns storage breakdown by category and, when requested, the workspace's largest items. + + Args: + details (Literal["true", "false"], optional): Include the ten largest storage consumers + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (AccountStorageResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + AccountStorageResponse, + await self._client.request( + "GET", + "/api/storage", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("details", details, style="form", explode=True)], + ), + ) + + async def profile( + self, + *, + username: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> AccountProfileResponse: + """Get a public user profile. + + Returns a public user profile and its follow state for the authenticated caller. + + Args: + username (str): username query parameter. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (AccountProfileResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + AccountProfileResponse, + await self._client.request( + "GET", + "/api/users", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("username", username, style="form", explode=True)], + ), + ) + + async def follow( + self, + *, + username: str, + followed: bool, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> AccountFollowResponse: + """Follow a user. + + Follows or unfollows a Platform user. + + Args: + username (str): username request value. + followed (bool): followed request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (AccountFollowResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + AccountFollowResponse, + await self._client.request( + "PATCH", + "/api/users", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"username": username, "followed": followed}, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/billing.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/billing.py new file mode 100644 index 0000000000000000000000000000000000000000..eae26bf05bfc8b1732ffc85eacd457e568bf1b18 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/billing.py @@ -0,0 +1,167 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import cast + +import httpx + +from .._client import ( + NOT_GIVEN, + AsyncAPIClient, + NotGiven, + SyncAPIClient, + _query_parameter, +) +from ..types import ( + BillingTransactionsResponse, + BillingUsageSummaryResponse, +) + + +class Billing: + """Billing API operations.""" + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + + def transactions( + self, + *, + from_: str | NotGiven = NOT_GIVEN, + to: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> BillingTransactionsResponse: + """View transaction history. + + Returns credit purchases, training charges, and other billing transactions. + + Args: + from_ (str, optional): Earliest transaction timestamp + to (str, optional): Latest transaction timestamp + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (BillingTransactionsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + BillingTransactionsResponse, + self._client.request( + "GET", + "/api/billing/transactions", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("from", from_, style="form", explode=True), + *_query_parameter("to", to, style="form", explode=True), + ], + ), + ) + + def usage_summary( + self, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> BillingUsageSummaryResponse: + """View plan and usage. + + Returns plan status, storage usage, training credit, feature access, seats, and billing totals. + + Args: + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (BillingUsageSummaryResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + BillingUsageSummaryResponse, + self._client.request( + "GET", + "/api/billing/usage-summary", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + +class AsyncBilling: + """Asynchronous Billing API operations.""" + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + + async def transactions( + self, + *, + from_: str | NotGiven = NOT_GIVEN, + to: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> BillingTransactionsResponse: + """View transaction history. + + Returns credit purchases, training charges, and other billing transactions. + + Args: + from_ (str, optional): Earliest transaction timestamp + to (str, optional): Latest transaction timestamp + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (BillingTransactionsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + BillingTransactionsResponse, + await self._client.request( + "GET", + "/api/billing/transactions", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("from", from_, style="form", explode=True), + *_query_parameter("to", to, style="form", explode=True), + ], + ), + ) + + async def usage_summary( + self, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> BillingUsageSummaryResponse: + """View plan and usage. + + Returns plan status, storage usage, training credit, feature access, seats, and billing totals. + + Args: + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (BillingUsageSummaryResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + BillingUsageSummaryResponse, + await self._client.request( + "GET", + "/api/billing/usage-summary", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/datasets.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..62d2817f69b9f20c96e98595cdb8f1bb0ae5328b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/datasets.py @@ -0,0 +1,2717 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any, Literal, cast + +import httpx + +from .._client import ( + NOT_GIVEN, + AsyncAPIClient, + NotGiven, + SyncAPIClient, + _path_parameter, + _query_parameter, +) +from ..types import ( + DatasetsAdoptImagesResponse, + DatasetsBatchResponse, + DatasetsClassStatsResponse, + DatasetsCloneResponse, + DatasetsClusteringResponse, + DatasetsCreateBatchResponse, + DatasetsCreateEmbeddingsResponse, + DatasetsCreateExportResponse, + DatasetsCreateResponse, + DatasetsDeleteBatchResponse, + DatasetsDeleteClassesResponse, + DatasetsDeleteEmbeddingsResponse, + DatasetsDeleteResponse, + DatasetsEmbeddingsResponse, + DatasetsExportResponse, + DatasetsImagesResponse, + DatasetsImportRoboflowResponse, + DatasetsIngestResponse, + DatasetsListResponse, + DatasetsMergeClassesResponse, + DatasetsModelsResponse, + DatasetsPreviewRoboflowResponse, + DatasetsRedistributeSplitsResponse, + DatasetsRestoreResponse, + DatasetsRetrieveResponse, + DatasetsSelectedImagesResponse, + DatasetsUpdateExportResponse, + DatasetsUpdateResponse, +) + + +class Datasets: + """Datasets API operations.""" + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + + def class_stats( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsClassStatsResponse: + """Get dataset statistics. + + Returns class counts, image distributions, and annotation heatmaps. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsClassStatsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsClassStatsResponse, + self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/class-stats", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def delete_classes( + self, + owner: str, + dataset: str, + *, + class_ids: Sequence[int], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsDeleteClassesResponse: + """Delete dataset classes. + + Deletes annotations in the selected classes, removes the classes, and shifts remaining class IDs. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + class_ids (Sequence[int]): classIds request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsDeleteClassesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsDeleteClassesResponse, + self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/classes/delete", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"classIds": class_ids}, + ), + ) + + def merge_classes( + self, + owner: str, + dataset: str, + *, + source_class_ids: Sequence[int], + target_class_id: int, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsMergeClassesResponse: + """Merge dataset classes. + + Reassigns annotations to one target class and removes the source classes. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + source_class_ids (Sequence[int]): sourceClassIds request value. + target_class_id (int): targetClassId request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsMergeClassesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsMergeClassesResponse, + self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/classes/merge", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"sourceClassIds": source_class_ids, "targetClassId": target_class_id}, + ), + ) + + def clone( + self, + owner: str, + dataset: str, + *, + name: str | NotGiven = NOT_GIVEN, + dataset_body: str | NotGiven = NOT_GIVEN, + description: str | NotGiven = NOT_GIVEN, + visibility: Literal["public", "private"] | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "CC0-1.0", + "PDM-1.0", + "CC-BY-2.5", + "CC-BY-3.0", + "CC-BY-4.0", + "CC-BY-NC-2.0", + "CC-BY-NC-3.0", + "CC-BY-NC-4.0", + "CC-BY-SA-3.0", + "CC-BY-SA-4.0", + "CC-BY-NC-SA-3.0", + "CC-BY-NC-SA-4.0", + "CC-BY-ND-4.0", + "CC-BY-NC-ND-2.0", + "CC-BY-NC-ND-4.0", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-2.0", + "GPL-3.0", + "LGPL-3.0", + "ODbL-1.0", + "DbCL-1.0", + "Research-Only", + "Other", + ] + | NotGiven = NOT_GIVEN, + owner_body: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsCloneResponse: + """Clone a dataset. + + Copies an accessible dataset into your personal workspace or a team workspace. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + name (str, optional): name request value. + dataset_body (str, optional): Name for the cloned dataset + description (str, optional): description request value. + visibility (Literal["public", "private"], optional): Resource visibility + license (Literal["None", "CC0-1.0", "PDM-1.0", "CC-BY-2.5", "CC-BY-3.0", "CC-BY-4.0", "CC-BY-NC-2.0", "CC-BY-NC-3.0", "CC-BY-NC-4.0", "CC-BY-SA-3.0", "CC-BY-SA-4.0", "CC-BY-NC-SA-3.0", "CC-BY-NC-SA-4.0", "CC-BY-ND-4.0", "CC-BY-NC-ND-2.0", "CC-BY-NC-ND-4.0", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-2.0", "GPL-3.0", "LGPL-3.0", "ODbL-1.0", "DbCL-1.0", "Research-Only", "Other"], optional): Dataset license identifier + owner_body (str, optional): Destination owner + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsCloneResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsCloneResponse, + self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/clone", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "name": name, + "dataset": dataset_body, + "description": description, + "visibility": visibility, + "license": license, + "owner": owner_body, + }, + ), + ) + + def retrieve( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsRetrieveResponse: + """Get a dataset. + + Returns a dataset by owner and dataset name. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsRetrieveResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsRetrieveResponse, + self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def update( + self, + owner: str, + dataset: str, + *, + starred: bool | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + description: str | NotGiven = NOT_GIVEN, + metadata: dict[str, Any] | NotGiven = NOT_GIVEN, + visibility: Literal["public", "private"] | NotGiven = NOT_GIVEN, + tags: Sequence[str] | NotGiven = NOT_GIVEN, + class_names: Sequence[str] | NotGiven = NOT_GIVEN, + initialize_class_names: bool | NotGiven = NOT_GIVEN, + class_colors: dict[str, Any] | NotGiven = NOT_GIVEN, + format: Literal["yolo", "coco", "raw", "ndjson"] | NotGiven = NOT_GIVEN, + blur_faces: bool | NotGiven = NOT_GIVEN, + task: Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"] | NotGiven = NOT_GIVEN, + kpt_skeleton_id: str | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "CC0-1.0", + "PDM-1.0", + "CC-BY-2.5", + "CC-BY-3.0", + "CC-BY-4.0", + "CC-BY-NC-2.0", + "CC-BY-NC-3.0", + "CC-BY-NC-4.0", + "CC-BY-SA-3.0", + "CC-BY-SA-4.0", + "CC-BY-NC-SA-3.0", + "CC-BY-NC-SA-4.0", + "CC-BY-ND-4.0", + "CC-BY-NC-ND-2.0", + "CC-BY-NC-ND-4.0", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-2.0", + "GPL-3.0", + "LGPL-3.0", + "ODbL-1.0", + "DbCL-1.0", + "Research-Only", + "Other", + ] + | NotGiven = NOT_GIVEN, + icon_color: str | NotGiven = NOT_GIVEN, + icon_letter: str | Literal[""] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsUpdateResponse: + """Update a dataset. + + Updates dataset properties. Changing the display name also changes the dataset name used in URLs. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + starred (bool, optional): starred request value. + name (str, optional): name request value. + description (str, optional): description request value. + metadata (dict[str, Any], optional): Custom JSON metadata with keys limited to 128 characters and at most 500,000 serialized characters. + visibility (Literal["public", "private"], optional): Resource visibility + tags (Sequence[str], optional): tags request value. + class_names (Sequence[str], optional): classNames request value. + initialize_class_names (bool, optional): Require the dataset to have no classes or annotations + class_colors (dict[str, Any], optional): classColors request value. + format (Literal["yolo", "coco", "raw", "ndjson"], optional): Dataset annotation format + blur_faces (bool, optional): blurFaces request value. + task (Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"], optional): Dataset task type + kpt_skeleton_id (str, optional): kptSkeletonId request value. + license (Literal["None", "CC0-1.0", "PDM-1.0", "CC-BY-2.5", "CC-BY-3.0", "CC-BY-4.0", "CC-BY-NC-2.0", "CC-BY-NC-3.0", "CC-BY-NC-4.0", "CC-BY-SA-3.0", "CC-BY-SA-4.0", "CC-BY-NC-SA-3.0", "CC-BY-NC-SA-4.0", "CC-BY-ND-4.0", "CC-BY-NC-ND-2.0", "CC-BY-NC-ND-4.0", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-2.0", "GPL-3.0", "LGPL-3.0", "ODbL-1.0", "DbCL-1.0", "Research-Only", "Other"], optional): Dataset license identifier + icon_color (str, optional): iconColor request value. + icon_letter (str | Literal[""], optional): iconLetter request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsUpdateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsUpdateResponse, + self._client.request( + "PATCH", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "starred": starred, + "name": name, + "description": description, + "metadata": metadata, + "visibility": visibility, + "tags": tags, + "classNames": class_names, + "initializeClassNames": initialize_class_names, + "classColors": class_colors, + "format": format, + "blurFaces": blur_faces, + "task": task, + "kptSkeletonId": kpt_skeleton_id, + "license": license, + "iconColor": icon_color, + "iconLetter": icon_letter, + }, + ), + ) + + def delete( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsDeleteResponse: + """Delete a dataset. + + Moves a dataset to trash for 30 days. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsDeleteResponse, + self._client.request( + "DELETE", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def embeddings( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsEmbeddingsResponse: + """Get dataset analysis status. + + Returns embedding analysis status, progress, and freshness. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsEmbeddingsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsEmbeddingsResponse, + self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/embeddings", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def create_embeddings( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsCreateEmbeddingsResponse: + """Analyze dataset embeddings. + + Starts embedding extraction and clustering. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsCreateEmbeddingsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsCreateEmbeddingsResponse, + self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/embeddings", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def delete_embeddings( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsDeleteEmbeddingsResponse: + """Cancel dataset analysis. + + Cancels the active embedding analysis job, if present. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsDeleteEmbeddingsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsDeleteEmbeddingsResponse, + self._client.request( + "DELETE", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/embeddings", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def export( + self, + owner: str, + dataset: str, + *, + v: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsExportResponse: + """Download a dataset export. + + Returns a signed URL for the current dataset or a saved version snapshot. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + v (int, optional): Saved version number + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsExportResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsExportResponse, + self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/export", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("v", v, style="form", explode=True)], + ), + ) + + def create_export( + self, + owner: str, + dataset: str, + *, + description: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsCreateExportResponse: + """Create a dataset version. + + Creates an immutable numbered snapshot and returns its signed NDJSON download URL. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + description (str, optional): description request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsCreateExportResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsCreateExportResponse, + self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/export", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"description": description}, + ), + ) + + def update_export( + self, + owner: str, + dataset: str, + *, + version: int, + description: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsUpdateExportResponse: + """Update a dataset version description. + + Updates the description stored on an existing saved dataset version. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + version (int): version request value. + description (str): description request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsUpdateExportResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsUpdateExportResponse, + self._client.request( + "PATCH", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/export", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"version": version, "description": description}, + ), + ) + + def adopt_images( + self, + owner: str, + dataset: str, + *, + image_ids: Sequence[str], + release: bool | NotGiven = NOT_GIVEN, + class_mapping: dict[str, Any] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsAdoptImagesResponse: + """Copy or move images to a dataset. + + Copies hosted images as content-addressed references without moving bytes. Omit release and classMapping for unlabeled train images. Set release to false (copy) or true (move), or supply classMapping, to preserve annotations, metadata, depth targets, and splits from editable sources; classes match by name. Other readable sources remain unlabeled train images. Moves delete only inserted source rows in the same transaction. Existing images are skipped. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + image_ids (Sequence[str]): imageIds request value. + release (bool, optional): Set false to copy editable-source annotations, metadata, depth targets, and splits; true also deletes source rows atomically. Omit both release and classMapping to adopt unlabeled train images. + class_mapping (dict[str, Any], optional): Mapping from source class names to this dataset + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsAdoptImagesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsAdoptImagesResponse, + self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/images/adopt", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"imageIds": image_ids, "release": release, "classMapping": class_mapping}, + ), + ) + + def clustering( + self, + owner: str, + dataset: str, + *, + offset: int | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsClusteringResponse: + """Get dataset clustering layout. + + Returns paginated image coordinates from a completed dataset analysis. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + offset (int, optional): offset query parameter. + limit (int, optional): limit query parameter. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsClusteringResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsClusteringResponse, + self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/images/clustering", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("offset", offset, style="form", explode=True), + *_query_parameter("limit", limit, style="form", explode=True), + ], + ), + ) + + def images( + self, + owner: str, + dataset: str, + *, + limit: int | NotGiven = NOT_GIVEN, + offset: int | NotGiven = NOT_GIVEN, + cursor: str | NotGiven = NOT_GIVEN, + include_total: Literal["true", "false"] | NotGiven = NOT_GIVEN, + split: Literal["train", "val", "test"] | NotGiven = NOT_GIVEN, + has_error: Literal["true", "false"] | NotGiven = NOT_GIVEN, + has_label: Literal["true", "false"] | NotGiven = NOT_GIVEN, + class_ids: str | NotGiven = NOT_GIVEN, + search: str | NotGiven = NOT_GIVEN, + sort: Literal[ + "newest", + "oldest", + "name-asc", + "name-desc", + "height-asc", + "height-desc", + "width-asc", + "width-desc", + "size-asc", + "size-desc", + "labels-desc", + "labels-asc", + ] + | NotGiven = NOT_GIVEN, + include_thumbnails: Literal["true", "false"] | NotGiven = NOT_GIVEN, + include_image_urls: Literal["true", "false"] | NotGiven = NOT_GIVEN, + include_labels: Literal["true", "false"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsImagesResponse: + """List dataset images. + + Returns paginated images. Capped preview annotations are included only when requested. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + limit (int, optional): Maximum images to return + offset (int, optional): Images to skip + cursor (str, optional): Last image ID from the previous page + include_total (Literal["true", "false"], optional): Include the total matching image count + split (Literal["train", "val", "test"], optional): Dataset split + has_error (Literal["true", "false"], optional): Filter by processing error state + has_label (Literal["true", "false"], optional): Filter by annotation state + class_ids (str, optional): Comma-separated class IDs; empty matches no images + search (str, optional): Image name or metadata search + sort (Literal["newest", "oldest", "name-asc", "name-desc", "height-asc", "height-desc", "width-asc", "width-desc", "size-asc", "size-desc", "labels-desc", "labels-asc"], optional): Sort order + include_thumbnails (Literal["true", "false"], optional): Include signed thumbnail URLs + include_image_urls (Literal["true", "false"], optional): Include signed full-size image URLs + include_labels (Literal["true", "false"], optional): Include capped preview annotations + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsImagesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsImagesResponse, + self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/images", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("limit", limit, style="form", explode=True), + *_query_parameter("offset", offset, style="form", explode=True), + *_query_parameter("cursor", cursor, style="form", explode=True), + *_query_parameter("includeTotal", include_total, style="form", explode=True), + *_query_parameter("split", split, style="form", explode=True), + *_query_parameter("hasError", has_error, style="form", explode=True), + *_query_parameter("hasLabel", has_label, style="form", explode=True), + *_query_parameter("classIds", class_ids, style="form", explode=True), + *_query_parameter("search", search, style="form", explode=True), + *_query_parameter("sort", sort, style="form", explode=True), + *_query_parameter("includeThumbnails", include_thumbnails, style="form", explode=True), + *_query_parameter("includeImageUrls", include_image_urls, style="form", explode=True), + *_query_parameter("includeLabels", include_labels, style="form", explode=True), + ], + ), + ) + + def selected_images( + self, + owner: str, + dataset: str, + *, + image_ids: Sequence[str], + split: Literal["train", "val", "test"] | NotGiven = NOT_GIVEN, + has_error: Literal["true", "false"] | NotGiven = NOT_GIVEN, + has_label: Literal["true", "false"] | NotGiven = NOT_GIVEN, + class_ids: str | NotGiven = NOT_GIVEN, + search: str | NotGiven = NOT_GIVEN, + sort: Literal[ + "newest", + "oldest", + "name-asc", + "name-desc", + "height-asc", + "height-desc", + "width-asc", + "width-desc", + "size-asc", + "size-desc", + "labels-desc", + "labels-asc", + ] + | NotGiven = NOT_GIVEN, + include_thumbnails: Literal["true", "false"] | NotGiven = NOT_GIVEN, + include_image_urls: Literal["true", "false"] | NotGiven = NOT_GIVEN, + include_labels: Literal["true", "false"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsSelectedImagesResponse: + """Get selected dataset images. + + Returns the requested images with optional signed URLs and capped preview annotations. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + split (Literal["train", "val", "test"], optional): Dataset split + has_error (Literal["true", "false"], optional): Filter by processing error state + has_label (Literal["true", "false"], optional): Filter by annotation state + class_ids (str, optional): Comma-separated class IDs; empty matches no images + search (str, optional): Image name or metadata search + sort (Literal["newest", "oldest", "name-asc", "name-desc", "height-asc", "height-desc", "width-asc", "width-desc", "size-asc", "size-desc", "labels-desc", "labels-asc"], optional): Sort order + include_thumbnails (Literal["true", "false"], optional): Include signed thumbnail URLs + include_image_urls (Literal["true", "false"], optional): Include signed full-size image URLs + include_labels (Literal["true", "false"], optional): Include capped preview annotations + image_ids (Sequence[str]): imageIds request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsSelectedImagesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsSelectedImagesResponse, + self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/images", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("split", split, style="form", explode=True), + *_query_parameter("hasError", has_error, style="form", explode=True), + *_query_parameter("hasLabel", has_label, style="form", explode=True), + *_query_parameter("classIds", class_ids, style="form", explode=True), + *_query_parameter("search", search, style="form", explode=True), + *_query_parameter("sort", sort, style="form", explode=True), + *_query_parameter("includeThumbnails", include_thumbnails, style="form", explode=True), + *_query_parameter("includeImageUrls", include_image_urls, style="form", explode=True), + *_query_parameter("includeLabels", include_labels, style="form", explode=True), + ], + json={"imageIds": image_ids}, + ), + ) + + def ingest( + self, + owner: str, + dataset: str, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsIngestResponse: + """Ingest dataset data. + + Verifies and completes an upload before processing it, or imports a remote archive or connected data source into this dataset. Calling upload/complete first is optional for dataset uploads. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + body (dict[str, Any]): Input for dataset ingest job + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsIngestResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsIngestResponse, + self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/ingest", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + def models( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsModelsResponse: + """List models trained on a dataset. + + Returns accessible models whose training data references this dataset. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsModelsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsModelsResponse, + self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/models", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def batch( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsBatchResponse: + """Get image-processing run status. + + Returns the dataset's in-flight image-processing run and its progress, or the last finished run awaiting dismissal. Results include partialImages when predictions reached the output limit and only complete boxes were recovered. While applying blur previews, activeJob.previews provides refreshed signed URLs for the accepted images and their thumbnails. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsBatchResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsBatchResponse, + self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/predict/batch", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def create_batch( + self, + owner: str, + dataset: str, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsCreateBatchResponse: + """Auto-annotate images or blur faces. + + For auto-annotation, saves a dataset version, then queues a run that labels the dataset's unlabeled images with the given model, or every image when `includeAnnotated` is set. Set `operation: blur` to blur faces using the platform detector, optionally limited to `imageId`. Blurring creates no version. `confidence` defaults to 0.25; `boxScale` defaults to 1 and scales face boxes around their centers. Set `preview: true` to prepare up to six full-resolution images and their thumbnails without changing the dataset. Pass the returned `jobId` as `previewJobId` with the same settings to apply those exact assets; only remaining dataset images require processing. Existing labels are never changed, and the run is billed for the images it actually processes. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + body (dict[str, Any]): Auto-annotate images or preview and apply face blurring + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsCreateBatchResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsCreateBatchResponse, + self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/predict/batch", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + def delete_batch( + self, + owner: str, + dataset: str, + *, + preview_job_id: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsDeleteBatchResponse: + """Cancel or dismiss an image-processing run. + + Cancels an in-flight run, or settles billing and dismisses its terminal summary. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + preview_job_id (str, optional): previewJobId query parameter. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsDeleteBatchResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsDeleteBatchResponse, + self._client.request( + "DELETE", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/predict/batch", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("previewJobId", preview_job_id, style="form", explode=True)], + ), + ) + + def restore( + self, + owner: str, + dataset: str, + *, + version: int, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsRestoreResponse: + """Restore a saved dataset version. + + Restores dataset files, labels, and metadata from a previously saved version. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + version (int): version request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsRestoreResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsRestoreResponse, + self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/restore", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"version": version}, + ), + ) + + def redistribute_splits( + self, + owner: str, + dataset: str, + *, + train: int, + val: int, + test: int, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsRedistributeSplitsResponse: + """Redistribute dataset splits. + + Randomly reassigns images using train, validation, and test percentages that total 100. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + train (int): Train split percentage + val (int): Validation split percentage + test (int): Test split percentage + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsRedistributeSplitsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsRedistributeSplitsResponse, + self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/splits/redistribute", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"train": train, "val": val, "test": test}, + ), + ) + + def list( + self, + owner: str, + *, + limit: int | NotGiven = NOT_GIVEN, + include_samples: Literal["true", "false"] | NotGiven = NOT_GIVEN, + include_image_urls: Literal["true", "false"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsListResponse: + """List datasets. + + Returns datasets owned by the named owner. Private datasets require workspace access. + + Args: + owner (str): Dataset owner + limit (int, optional): Maximum datasets to return + include_samples (Literal["true", "false"], optional): Include sample image previews + include_image_urls (Literal["true", "false"], optional): Include full-size sample image fallback URLs + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsListResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsListResponse, + self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("limit", limit, style="form", explode=True), + *_query_parameter("includeSamples", include_samples, style="form", explode=True), + *_query_parameter("includeImageUrls", include_image_urls, style="form", explode=True), + ], + ), + ) + + def create( + self, + *, + dataset: str, + name: str, + description: str | NotGiven = NOT_GIVEN, + metadata: dict[str, Any] | NotGiven = NOT_GIVEN, + visibility: Literal["public", "private"] | NotGiven = NOT_GIVEN, + blur_faces: bool | NotGiven = NOT_GIVEN, + task: Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"] | NotGiven = NOT_GIVEN, + image_count: int | NotGiven = NOT_GIVEN, + class_names: Sequence[str] | NotGiven = NOT_GIVEN, + format: Literal["yolo", "coco", "raw", "ndjson"] | NotGiven = NOT_GIVEN, + tags: Sequence[str] | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "CC0-1.0", + "PDM-1.0", + "CC-BY-2.5", + "CC-BY-3.0", + "CC-BY-4.0", + "CC-BY-NC-2.0", + "CC-BY-NC-3.0", + "CC-BY-NC-4.0", + "CC-BY-SA-3.0", + "CC-BY-SA-4.0", + "CC-BY-NC-SA-3.0", + "CC-BY-NC-SA-4.0", + "CC-BY-ND-4.0", + "CC-BY-NC-ND-2.0", + "CC-BY-NC-ND-4.0", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-2.0", + "GPL-3.0", + "LGPL-3.0", + "ODbL-1.0", + "DbCL-1.0", + "Research-Only", + "Other", + ] + | NotGiven = NOT_GIVEN, + require_exact_slug: bool | NotGiven = NOT_GIVEN, + owner: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsCreateResponse: + """Create a dataset. + + Creates an empty dataset in your personal workspace or a team workspace. + + Args: + dataset (str): Dataset name used in Platform URLs + name (str): Display name + description (str, optional): description request value. + metadata (dict[str, Any], optional): Custom JSON metadata with keys limited to 128 characters and at most 500,000 serialized characters. + visibility (Literal["public", "private"], optional): Resource visibility + blur_faces (bool, optional): Automatically blur faces in uploaded images + task (Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"], optional): Dataset task type + image_count (int, optional): imageCount request value. + class_names (Sequence[str], optional): classNames request value. + format (Literal["yolo", "coco", "raw", "ndjson"], optional): Dataset annotation format + tags (Sequence[str], optional): tags request value. + license (Literal["None", "CC0-1.0", "PDM-1.0", "CC-BY-2.5", "CC-BY-3.0", "CC-BY-4.0", "CC-BY-NC-2.0", "CC-BY-NC-3.0", "CC-BY-NC-4.0", "CC-BY-SA-3.0", "CC-BY-SA-4.0", "CC-BY-NC-SA-3.0", "CC-BY-NC-SA-4.0", "CC-BY-ND-4.0", "CC-BY-NC-ND-2.0", "CC-BY-NC-ND-4.0", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-2.0", "GPL-3.0", "LGPL-3.0", "ODbL-1.0", "DbCL-1.0", "Research-Only", "Other"], optional): Dataset license identifier + require_exact_slug (bool, optional): Reject a slug conflict instead of creating an automatically suffixed dataset + owner (str, optional): Workspace owner + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsCreateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsCreateResponse, + self._client.request( + "POST", + "/api/datasets", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "dataset": dataset, + "name": name, + "description": description, + "metadata": metadata, + "visibility": visibility, + "blurFaces": blur_faces, + "task": task, + "imageCount": image_count, + "classNames": class_names, + "format": format, + "tags": tags, + "license": license, + "requireExactSlug": require_exact_slug, + "owner": owner, + }, + ), + ) + + def import_roboflow( + self, + *, + api_key: str, + items: Sequence[dict[str, Any]], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsImportRoboflowResponse: + """Import datasets from Roboflow. + + Imports selected Roboflow dataset versions into the API key's workspace. + + Args: + api_key (str): Roboflow API key + items (Sequence[dict[str, Any]]): items request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsImportRoboflowResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsImportRoboflowResponse, + self._client.request( + "POST", + "/api/integrations/roboflow/import", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"apiKey": api_key, "items": items}, + ), + ) + + def preview_roboflow( + self, *, api_key: str, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> DatasetsPreviewRoboflowResponse: + """Preview a Roboflow import. + + Validates a Roboflow API key and lists datasets available for import. + + Args: + api_key (str): Roboflow API key + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsPreviewRoboflowResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsPreviewRoboflowResponse, + self._client.request( + "POST", + "/api/integrations/roboflow/preview", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"apiKey": api_key}, + ), + ) + + +class AsyncDatasets: + """Asynchronous Datasets API operations.""" + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + + async def class_stats( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsClassStatsResponse: + """Get dataset statistics. + + Returns class counts, image distributions, and annotation heatmaps. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsClassStatsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsClassStatsResponse, + await self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/class-stats", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def delete_classes( + self, + owner: str, + dataset: str, + *, + class_ids: Sequence[int], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsDeleteClassesResponse: + """Delete dataset classes. + + Deletes annotations in the selected classes, removes the classes, and shifts remaining class IDs. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + class_ids (Sequence[int]): classIds request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsDeleteClassesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsDeleteClassesResponse, + await self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/classes/delete", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"classIds": class_ids}, + ), + ) + + async def merge_classes( + self, + owner: str, + dataset: str, + *, + source_class_ids: Sequence[int], + target_class_id: int, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsMergeClassesResponse: + """Merge dataset classes. + + Reassigns annotations to one target class and removes the source classes. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + source_class_ids (Sequence[int]): sourceClassIds request value. + target_class_id (int): targetClassId request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsMergeClassesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsMergeClassesResponse, + await self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/classes/merge", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"sourceClassIds": source_class_ids, "targetClassId": target_class_id}, + ), + ) + + async def clone( + self, + owner: str, + dataset: str, + *, + name: str | NotGiven = NOT_GIVEN, + dataset_body: str | NotGiven = NOT_GIVEN, + description: str | NotGiven = NOT_GIVEN, + visibility: Literal["public", "private"] | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "CC0-1.0", + "PDM-1.0", + "CC-BY-2.5", + "CC-BY-3.0", + "CC-BY-4.0", + "CC-BY-NC-2.0", + "CC-BY-NC-3.0", + "CC-BY-NC-4.0", + "CC-BY-SA-3.0", + "CC-BY-SA-4.0", + "CC-BY-NC-SA-3.0", + "CC-BY-NC-SA-4.0", + "CC-BY-ND-4.0", + "CC-BY-NC-ND-2.0", + "CC-BY-NC-ND-4.0", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-2.0", + "GPL-3.0", + "LGPL-3.0", + "ODbL-1.0", + "DbCL-1.0", + "Research-Only", + "Other", + ] + | NotGiven = NOT_GIVEN, + owner_body: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsCloneResponse: + """Clone a dataset. + + Copies an accessible dataset into your personal workspace or a team workspace. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + name (str, optional): name request value. + dataset_body (str, optional): Name for the cloned dataset + description (str, optional): description request value. + visibility (Literal["public", "private"], optional): Resource visibility + license (Literal["None", "CC0-1.0", "PDM-1.0", "CC-BY-2.5", "CC-BY-3.0", "CC-BY-4.0", "CC-BY-NC-2.0", "CC-BY-NC-3.0", "CC-BY-NC-4.0", "CC-BY-SA-3.0", "CC-BY-SA-4.0", "CC-BY-NC-SA-3.0", "CC-BY-NC-SA-4.0", "CC-BY-ND-4.0", "CC-BY-NC-ND-2.0", "CC-BY-NC-ND-4.0", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-2.0", "GPL-3.0", "LGPL-3.0", "ODbL-1.0", "DbCL-1.0", "Research-Only", "Other"], optional): Dataset license identifier + owner_body (str, optional): Destination owner + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsCloneResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsCloneResponse, + await self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/clone", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "name": name, + "dataset": dataset_body, + "description": description, + "visibility": visibility, + "license": license, + "owner": owner_body, + }, + ), + ) + + async def retrieve( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsRetrieveResponse: + """Get a dataset. + + Returns a dataset by owner and dataset name. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsRetrieveResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsRetrieveResponse, + await self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def update( + self, + owner: str, + dataset: str, + *, + starred: bool | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + description: str | NotGiven = NOT_GIVEN, + metadata: dict[str, Any] | NotGiven = NOT_GIVEN, + visibility: Literal["public", "private"] | NotGiven = NOT_GIVEN, + tags: Sequence[str] | NotGiven = NOT_GIVEN, + class_names: Sequence[str] | NotGiven = NOT_GIVEN, + initialize_class_names: bool | NotGiven = NOT_GIVEN, + class_colors: dict[str, Any] | NotGiven = NOT_GIVEN, + format: Literal["yolo", "coco", "raw", "ndjson"] | NotGiven = NOT_GIVEN, + blur_faces: bool | NotGiven = NOT_GIVEN, + task: Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"] | NotGiven = NOT_GIVEN, + kpt_skeleton_id: str | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "CC0-1.0", + "PDM-1.0", + "CC-BY-2.5", + "CC-BY-3.0", + "CC-BY-4.0", + "CC-BY-NC-2.0", + "CC-BY-NC-3.0", + "CC-BY-NC-4.0", + "CC-BY-SA-3.0", + "CC-BY-SA-4.0", + "CC-BY-NC-SA-3.0", + "CC-BY-NC-SA-4.0", + "CC-BY-ND-4.0", + "CC-BY-NC-ND-2.0", + "CC-BY-NC-ND-4.0", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-2.0", + "GPL-3.0", + "LGPL-3.0", + "ODbL-1.0", + "DbCL-1.0", + "Research-Only", + "Other", + ] + | NotGiven = NOT_GIVEN, + icon_color: str | NotGiven = NOT_GIVEN, + icon_letter: str | Literal[""] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsUpdateResponse: + """Update a dataset. + + Updates dataset properties. Changing the display name also changes the dataset name used in URLs. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + starred (bool, optional): starred request value. + name (str, optional): name request value. + description (str, optional): description request value. + metadata (dict[str, Any], optional): Custom JSON metadata with keys limited to 128 characters and at most 500,000 serialized characters. + visibility (Literal["public", "private"], optional): Resource visibility + tags (Sequence[str], optional): tags request value. + class_names (Sequence[str], optional): classNames request value. + initialize_class_names (bool, optional): Require the dataset to have no classes or annotations + class_colors (dict[str, Any], optional): classColors request value. + format (Literal["yolo", "coco", "raw", "ndjson"], optional): Dataset annotation format + blur_faces (bool, optional): blurFaces request value. + task (Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"], optional): Dataset task type + kpt_skeleton_id (str, optional): kptSkeletonId request value. + license (Literal["None", "CC0-1.0", "PDM-1.0", "CC-BY-2.5", "CC-BY-3.0", "CC-BY-4.0", "CC-BY-NC-2.0", "CC-BY-NC-3.0", "CC-BY-NC-4.0", "CC-BY-SA-3.0", "CC-BY-SA-4.0", "CC-BY-NC-SA-3.0", "CC-BY-NC-SA-4.0", "CC-BY-ND-4.0", "CC-BY-NC-ND-2.0", "CC-BY-NC-ND-4.0", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-2.0", "GPL-3.0", "LGPL-3.0", "ODbL-1.0", "DbCL-1.0", "Research-Only", "Other"], optional): Dataset license identifier + icon_color (str, optional): iconColor request value. + icon_letter (str | Literal[""], optional): iconLetter request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsUpdateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsUpdateResponse, + await self._client.request( + "PATCH", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "starred": starred, + "name": name, + "description": description, + "metadata": metadata, + "visibility": visibility, + "tags": tags, + "classNames": class_names, + "initializeClassNames": initialize_class_names, + "classColors": class_colors, + "format": format, + "blurFaces": blur_faces, + "task": task, + "kptSkeletonId": kpt_skeleton_id, + "license": license, + "iconColor": icon_color, + "iconLetter": icon_letter, + }, + ), + ) + + async def delete( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsDeleteResponse: + """Delete a dataset. + + Moves a dataset to trash for 30 days. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsDeleteResponse, + await self._client.request( + "DELETE", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def embeddings( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsEmbeddingsResponse: + """Get dataset analysis status. + + Returns embedding analysis status, progress, and freshness. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsEmbeddingsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsEmbeddingsResponse, + await self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/embeddings", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def create_embeddings( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsCreateEmbeddingsResponse: + """Analyze dataset embeddings. + + Starts embedding extraction and clustering. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsCreateEmbeddingsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsCreateEmbeddingsResponse, + await self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/embeddings", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def delete_embeddings( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsDeleteEmbeddingsResponse: + """Cancel dataset analysis. + + Cancels the active embedding analysis job, if present. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsDeleteEmbeddingsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsDeleteEmbeddingsResponse, + await self._client.request( + "DELETE", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/embeddings", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def export( + self, + owner: str, + dataset: str, + *, + v: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsExportResponse: + """Download a dataset export. + + Returns a signed URL for the current dataset or a saved version snapshot. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + v (int, optional): Saved version number + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsExportResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsExportResponse, + await self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/export", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("v", v, style="form", explode=True)], + ), + ) + + async def create_export( + self, + owner: str, + dataset: str, + *, + description: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsCreateExportResponse: + """Create a dataset version. + + Creates an immutable numbered snapshot and returns its signed NDJSON download URL. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + description (str, optional): description request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsCreateExportResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsCreateExportResponse, + await self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/export", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"description": description}, + ), + ) + + async def update_export( + self, + owner: str, + dataset: str, + *, + version: int, + description: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsUpdateExportResponse: + """Update a dataset version description. + + Updates the description stored on an existing saved dataset version. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + version (int): version request value. + description (str): description request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsUpdateExportResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsUpdateExportResponse, + await self._client.request( + "PATCH", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/export", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"version": version, "description": description}, + ), + ) + + async def adopt_images( + self, + owner: str, + dataset: str, + *, + image_ids: Sequence[str], + release: bool | NotGiven = NOT_GIVEN, + class_mapping: dict[str, Any] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsAdoptImagesResponse: + """Copy or move images to a dataset. + + Copies hosted images as content-addressed references without moving bytes. Omit release and classMapping for unlabeled train images. Set release to false (copy) or true (move), or supply classMapping, to preserve annotations, metadata, depth targets, and splits from editable sources; classes match by name. Other readable sources remain unlabeled train images. Moves delete only inserted source rows in the same transaction. Existing images are skipped. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + image_ids (Sequence[str]): imageIds request value. + release (bool, optional): Set false to copy editable-source annotations, metadata, depth targets, and splits; true also deletes source rows atomically. Omit both release and classMapping to adopt unlabeled train images. + class_mapping (dict[str, Any], optional): Mapping from source class names to this dataset + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsAdoptImagesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsAdoptImagesResponse, + await self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/images/adopt", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"imageIds": image_ids, "release": release, "classMapping": class_mapping}, + ), + ) + + async def clustering( + self, + owner: str, + dataset: str, + *, + offset: int | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsClusteringResponse: + """Get dataset clustering layout. + + Returns paginated image coordinates from a completed dataset analysis. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + offset (int, optional): offset query parameter. + limit (int, optional): limit query parameter. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsClusteringResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsClusteringResponse, + await self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/images/clustering", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("offset", offset, style="form", explode=True), + *_query_parameter("limit", limit, style="form", explode=True), + ], + ), + ) + + async def images( + self, + owner: str, + dataset: str, + *, + limit: int | NotGiven = NOT_GIVEN, + offset: int | NotGiven = NOT_GIVEN, + cursor: str | NotGiven = NOT_GIVEN, + include_total: Literal["true", "false"] | NotGiven = NOT_GIVEN, + split: Literal["train", "val", "test"] | NotGiven = NOT_GIVEN, + has_error: Literal["true", "false"] | NotGiven = NOT_GIVEN, + has_label: Literal["true", "false"] | NotGiven = NOT_GIVEN, + class_ids: str | NotGiven = NOT_GIVEN, + search: str | NotGiven = NOT_GIVEN, + sort: Literal[ + "newest", + "oldest", + "name-asc", + "name-desc", + "height-asc", + "height-desc", + "width-asc", + "width-desc", + "size-asc", + "size-desc", + "labels-desc", + "labels-asc", + ] + | NotGiven = NOT_GIVEN, + include_thumbnails: Literal["true", "false"] | NotGiven = NOT_GIVEN, + include_image_urls: Literal["true", "false"] | NotGiven = NOT_GIVEN, + include_labels: Literal["true", "false"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsImagesResponse: + """List dataset images. + + Returns paginated images. Capped preview annotations are included only when requested. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + limit (int, optional): Maximum images to return + offset (int, optional): Images to skip + cursor (str, optional): Last image ID from the previous page + include_total (Literal["true", "false"], optional): Include the total matching image count + split (Literal["train", "val", "test"], optional): Dataset split + has_error (Literal["true", "false"], optional): Filter by processing error state + has_label (Literal["true", "false"], optional): Filter by annotation state + class_ids (str, optional): Comma-separated class IDs; empty matches no images + search (str, optional): Image name or metadata search + sort (Literal["newest", "oldest", "name-asc", "name-desc", "height-asc", "height-desc", "width-asc", "width-desc", "size-asc", "size-desc", "labels-desc", "labels-asc"], optional): Sort order + include_thumbnails (Literal["true", "false"], optional): Include signed thumbnail URLs + include_image_urls (Literal["true", "false"], optional): Include signed full-size image URLs + include_labels (Literal["true", "false"], optional): Include capped preview annotations + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsImagesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsImagesResponse, + await self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/images", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("limit", limit, style="form", explode=True), + *_query_parameter("offset", offset, style="form", explode=True), + *_query_parameter("cursor", cursor, style="form", explode=True), + *_query_parameter("includeTotal", include_total, style="form", explode=True), + *_query_parameter("split", split, style="form", explode=True), + *_query_parameter("hasError", has_error, style="form", explode=True), + *_query_parameter("hasLabel", has_label, style="form", explode=True), + *_query_parameter("classIds", class_ids, style="form", explode=True), + *_query_parameter("search", search, style="form", explode=True), + *_query_parameter("sort", sort, style="form", explode=True), + *_query_parameter("includeThumbnails", include_thumbnails, style="form", explode=True), + *_query_parameter("includeImageUrls", include_image_urls, style="form", explode=True), + *_query_parameter("includeLabels", include_labels, style="form", explode=True), + ], + ), + ) + + async def selected_images( + self, + owner: str, + dataset: str, + *, + image_ids: Sequence[str], + split: Literal["train", "val", "test"] | NotGiven = NOT_GIVEN, + has_error: Literal["true", "false"] | NotGiven = NOT_GIVEN, + has_label: Literal["true", "false"] | NotGiven = NOT_GIVEN, + class_ids: str | NotGiven = NOT_GIVEN, + search: str | NotGiven = NOT_GIVEN, + sort: Literal[ + "newest", + "oldest", + "name-asc", + "name-desc", + "height-asc", + "height-desc", + "width-asc", + "width-desc", + "size-asc", + "size-desc", + "labels-desc", + "labels-asc", + ] + | NotGiven = NOT_GIVEN, + include_thumbnails: Literal["true", "false"] | NotGiven = NOT_GIVEN, + include_image_urls: Literal["true", "false"] | NotGiven = NOT_GIVEN, + include_labels: Literal["true", "false"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsSelectedImagesResponse: + """Get selected dataset images. + + Returns the requested images with optional signed URLs and capped preview annotations. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + split (Literal["train", "val", "test"], optional): Dataset split + has_error (Literal["true", "false"], optional): Filter by processing error state + has_label (Literal["true", "false"], optional): Filter by annotation state + class_ids (str, optional): Comma-separated class IDs; empty matches no images + search (str, optional): Image name or metadata search + sort (Literal["newest", "oldest", "name-asc", "name-desc", "height-asc", "height-desc", "width-asc", "width-desc", "size-asc", "size-desc", "labels-desc", "labels-asc"], optional): Sort order + include_thumbnails (Literal["true", "false"], optional): Include signed thumbnail URLs + include_image_urls (Literal["true", "false"], optional): Include signed full-size image URLs + include_labels (Literal["true", "false"], optional): Include capped preview annotations + image_ids (Sequence[str]): imageIds request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsSelectedImagesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsSelectedImagesResponse, + await self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/images", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("split", split, style="form", explode=True), + *_query_parameter("hasError", has_error, style="form", explode=True), + *_query_parameter("hasLabel", has_label, style="form", explode=True), + *_query_parameter("classIds", class_ids, style="form", explode=True), + *_query_parameter("search", search, style="form", explode=True), + *_query_parameter("sort", sort, style="form", explode=True), + *_query_parameter("includeThumbnails", include_thumbnails, style="form", explode=True), + *_query_parameter("includeImageUrls", include_image_urls, style="form", explode=True), + *_query_parameter("includeLabels", include_labels, style="form", explode=True), + ], + json={"imageIds": image_ids}, + ), + ) + + async def ingest( + self, + owner: str, + dataset: str, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsIngestResponse: + """Ingest dataset data. + + Verifies and completes an upload before processing it, or imports a remote archive or connected data source into this dataset. Calling upload/complete first is optional for dataset uploads. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + body (dict[str, Any]): Input for dataset ingest job + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsIngestResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsIngestResponse, + await self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/ingest", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + async def models( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsModelsResponse: + """List models trained on a dataset. + + Returns accessible models whose training data references this dataset. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsModelsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsModelsResponse, + await self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/models", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def batch( + self, + owner: str, + dataset: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsBatchResponse: + """Get image-processing run status. + + Returns the dataset's in-flight image-processing run and its progress, or the last finished run awaiting dismissal. Results include partialImages when predictions reached the output limit and only complete boxes were recovered. While applying blur previews, activeJob.previews provides refreshed signed URLs for the accepted images and their thumbnails. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsBatchResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsBatchResponse, + await self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/predict/batch", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def create_batch( + self, + owner: str, + dataset: str, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsCreateBatchResponse: + """Auto-annotate images or blur faces. + + For auto-annotation, saves a dataset version, then queues a run that labels the dataset's unlabeled images with the given model, or every image when `includeAnnotated` is set. Set `operation: blur` to blur faces using the platform detector, optionally limited to `imageId`. Blurring creates no version. `confidence` defaults to 0.25; `boxScale` defaults to 1 and scales face boxes around their centers. Set `preview: true` to prepare up to six full-resolution images and their thumbnails without changing the dataset. Pass the returned `jobId` as `previewJobId` with the same settings to apply those exact assets; only remaining dataset images require processing. Existing labels are never changed, and the run is billed for the images it actually processes. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + body (dict[str, Any]): Auto-annotate images or preview and apply face blurring + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsCreateBatchResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsCreateBatchResponse, + await self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/predict/batch", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + async def delete_batch( + self, + owner: str, + dataset: str, + *, + preview_job_id: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsDeleteBatchResponse: + """Cancel or dismiss an image-processing run. + + Cancels an in-flight run, or settles billing and dismisses its terminal summary. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + preview_job_id (str, optional): previewJobId query parameter. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsDeleteBatchResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsDeleteBatchResponse, + await self._client.request( + "DELETE", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/predict/batch", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("previewJobId", preview_job_id, style="form", explode=True)], + ), + ) + + async def restore( + self, + owner: str, + dataset: str, + *, + version: int, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsRestoreResponse: + """Restore a saved dataset version. + + Restores dataset files, labels, and metadata from a previously saved version. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + version (int): version request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsRestoreResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsRestoreResponse, + await self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/restore", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"version": version}, + ), + ) + + async def redistribute_splits( + self, + owner: str, + dataset: str, + *, + train: int, + val: int, + test: int, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsRedistributeSplitsResponse: + """Redistribute dataset splits. + + Randomly reassigns images using train, validation, and test percentages that total 100. + + Args: + owner (str): Dataset owner + dataset (str): Dataset name + train (int): Train split percentage + val (int): Validation split percentage + test (int): Test split percentage + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsRedistributeSplitsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsRedistributeSplitsResponse, + await self._client.request( + "POST", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(dataset, explode=False, allow_reserved=False)}/splits/redistribute", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"train": train, "val": val, "test": test}, + ), + ) + + async def list( + self, + owner: str, + *, + limit: int | NotGiven = NOT_GIVEN, + include_samples: Literal["true", "false"] | NotGiven = NOT_GIVEN, + include_image_urls: Literal["true", "false"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsListResponse: + """List datasets. + + Returns datasets owned by the named owner. Private datasets require workspace access. + + Args: + owner (str): Dataset owner + limit (int, optional): Maximum datasets to return + include_samples (Literal["true", "false"], optional): Include sample image previews + include_image_urls (Literal["true", "false"], optional): Include full-size sample image fallback URLs + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsListResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsListResponse, + await self._client.request( + "GET", + f"/api/datasets/{_path_parameter(owner, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("limit", limit, style="form", explode=True), + *_query_parameter("includeSamples", include_samples, style="form", explode=True), + *_query_parameter("includeImageUrls", include_image_urls, style="form", explode=True), + ], + ), + ) + + async def create( + self, + *, + dataset: str, + name: str, + description: str | NotGiven = NOT_GIVEN, + metadata: dict[str, Any] | NotGiven = NOT_GIVEN, + visibility: Literal["public", "private"] | NotGiven = NOT_GIVEN, + blur_faces: bool | NotGiven = NOT_GIVEN, + task: Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"] | NotGiven = NOT_GIVEN, + image_count: int | NotGiven = NOT_GIVEN, + class_names: Sequence[str] | NotGiven = NOT_GIVEN, + format: Literal["yolo", "coco", "raw", "ndjson"] | NotGiven = NOT_GIVEN, + tags: Sequence[str] | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "CC0-1.0", + "PDM-1.0", + "CC-BY-2.5", + "CC-BY-3.0", + "CC-BY-4.0", + "CC-BY-NC-2.0", + "CC-BY-NC-3.0", + "CC-BY-NC-4.0", + "CC-BY-SA-3.0", + "CC-BY-SA-4.0", + "CC-BY-NC-SA-3.0", + "CC-BY-NC-SA-4.0", + "CC-BY-ND-4.0", + "CC-BY-NC-ND-2.0", + "CC-BY-NC-ND-4.0", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-2.0", + "GPL-3.0", + "LGPL-3.0", + "ODbL-1.0", + "DbCL-1.0", + "Research-Only", + "Other", + ] + | NotGiven = NOT_GIVEN, + require_exact_slug: bool | NotGiven = NOT_GIVEN, + owner: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsCreateResponse: + """Create a dataset. + + Creates an empty dataset in your personal workspace or a team workspace. + + Args: + dataset (str): Dataset name used in Platform URLs + name (str): Display name + description (str, optional): description request value. + metadata (dict[str, Any], optional): Custom JSON metadata with keys limited to 128 characters and at most 500,000 serialized characters. + visibility (Literal["public", "private"], optional): Resource visibility + blur_faces (bool, optional): Automatically blur faces in uploaded images + task (Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"], optional): Dataset task type + image_count (int, optional): imageCount request value. + class_names (Sequence[str], optional): classNames request value. + format (Literal["yolo", "coco", "raw", "ndjson"], optional): Dataset annotation format + tags (Sequence[str], optional): tags request value. + license (Literal["None", "CC0-1.0", "PDM-1.0", "CC-BY-2.5", "CC-BY-3.0", "CC-BY-4.0", "CC-BY-NC-2.0", "CC-BY-NC-3.0", "CC-BY-NC-4.0", "CC-BY-SA-3.0", "CC-BY-SA-4.0", "CC-BY-NC-SA-3.0", "CC-BY-NC-SA-4.0", "CC-BY-ND-4.0", "CC-BY-NC-ND-2.0", "CC-BY-NC-ND-4.0", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-2.0", "GPL-3.0", "LGPL-3.0", "ODbL-1.0", "DbCL-1.0", "Research-Only", "Other"], optional): Dataset license identifier + require_exact_slug (bool, optional): Reject a slug conflict instead of creating an automatically suffixed dataset + owner (str, optional): Workspace owner + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsCreateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsCreateResponse, + await self._client.request( + "POST", + "/api/datasets", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "dataset": dataset, + "name": name, + "description": description, + "metadata": metadata, + "visibility": visibility, + "blurFaces": blur_faces, + "task": task, + "imageCount": image_count, + "classNames": class_names, + "format": format, + "tags": tags, + "license": license, + "requireExactSlug": require_exact_slug, + "owner": owner, + }, + ), + ) + + async def import_roboflow( + self, + *, + api_key: str, + items: Sequence[dict[str, Any]], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DatasetsImportRoboflowResponse: + """Import datasets from Roboflow. + + Imports selected Roboflow dataset versions into the API key's workspace. + + Args: + api_key (str): Roboflow API key + items (Sequence[dict[str, Any]]): items request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsImportRoboflowResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsImportRoboflowResponse, + await self._client.request( + "POST", + "/api/integrations/roboflow/import", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"apiKey": api_key, "items": items}, + ), + ) + + async def preview_roboflow( + self, *, api_key: str, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> DatasetsPreviewRoboflowResponse: + """Preview a Roboflow import. + + Validates a Roboflow API key and lists datasets available for import. + + Args: + api_key (str): Roboflow API key + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DatasetsPreviewRoboflowResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DatasetsPreviewRoboflowResponse, + await self._client.request( + "POST", + "/api/integrations/roboflow/preview", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"apiKey": api_key}, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/deployments.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/deployments.py new file mode 100644 index 0000000000000000000000000000000000000000..de4421cc0767aa1f4d27faa3bc4bacf3ee634532 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/deployments.py @@ -0,0 +1,870 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any, Literal, cast + +import httpx + +from .._client import ( + NOT_GIVEN, + AsyncAPIClient, + NotGiven, + SyncAPIClient, + _form_data, + _path_parameter, + _query_parameter, +) +from ..types import ( + DeploymentsCreateResponse, + DeploymentsDeleteResponse, + DeploymentsHealthResponse, + DeploymentsListResponse, + DeploymentsLogsResponse, + DeploymentsMetricsResponse, + DeploymentsPredictResponse, + DeploymentsRetrieveResponse, + DeploymentsUpdateResponse, +) + + +class Deployments: + """Deployments API operations.""" + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + + def retrieve( + self, + owner: str, + deployment: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsRetrieveResponse: + """Get deployment details. + + Returns deployment configuration, status, service URL, and custom metadata. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsRetrieveResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsRetrieveResponse, + self._client.request( + "GET", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def update( + self, + owner: str, + deployment: str, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsUpdateResponse: + """Update a deployment. + + Updates the display name or custom metadata, starts, stops, resizes, or rolls out another model while preserving the endpoint URL. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + body (dict[str, Any]): API request for updating a deployment + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsUpdateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsUpdateResponse, + self._client.request( + "PATCH", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + def delete( + self, + owner: str, + deployment: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsDeleteResponse: + """Delete a deployment. + + Permanently removes the inference endpoint. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsDeleteResponse, + self._client.request( + "DELETE", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def health( + self, + owner: str, + deployment: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsHealthResponse: + """Check deployment health. + + Pings and warms the deployment endpoint. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsHealthResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsHealthResponse, + self._client.request( + "GET", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}/health", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def logs( + self, + owner: str, + deployment: str, + *, + severity: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + page_token: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsLogsResponse: + """Get deployment logs. + + Returns recent deployment service logs. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + severity (str, optional): Comma-separated log severity levels + limit (int, optional): Maximum log entries to return + page_token (str, optional): Pagination token + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsLogsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsLogsResponse, + self._client.request( + "GET", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}/logs", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("severity", severity, style="form", explode=True), + *_query_parameter("limit", limit, style="form", explode=True), + *_query_parameter("pageToken", page_token, style="form", explode=True), + ], + ), + ) + + def metrics( + self, + owner: str, + deployment: str, + *, + range: Literal["1h", "6h", "24h", "7d", "30d"] | NotGiven = NOT_GIVEN, + sparkline: Literal["true", "false"] | NotGiven = NOT_GIVEN, + view: Literal["overview"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsMetricsResponse: + """Get deployment metrics. + + Returns request volume, latency, errors, and resource utilization. Use view=overview for only request, error, and P95 latency metrics. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + range (Literal["1h", "6h", "24h", "7d", "30d"], optional): Metrics time range + sparkline (Literal["true", "false"], optional): Return the compact dashboard summary + view (Literal["overview"], optional): Fetch only request, error, and P95 latency metrics + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsMetricsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsMetricsResponse, + self._client.request( + "GET", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}/metrics", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("range", range, style="form", explode=True), + *_query_parameter("sparkline", sparkline, style="form", explode=True), + *_query_parameter("view", view, style="form", explode=True), + ], + ), + ) + + def predict( + self, + owner: str, + deployment: str, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsPredictResponse: + """Run deployment inference. + + Runs inference through a dedicated deployment endpoint. Depth models accept images only. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + body (dict[str, Any]): Request body. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsPredictResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsPredictResponse, + self._client.request( + "POST", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}/predict", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + data=_form_data({key: value for key, value in body.items() if key not in ["file"]}, multipart=True), + files={key: body[key] for key in ["file"] if key in body}, + ), + ) + + def list( + self, + owner: str, + *, + status: Literal["creating", "deploying", "ready", "stopping", "stopped", "failed"] | NotGiven = NOT_GIVEN, + model: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsListResponse: + """List deployments. + + Returns workspace inference endpoints. Anonymous callers must filter by one public model; workspace-wide listing requires authentication. + + Args: + owner (str): Deployment owner + status (Literal["creating", "deploying", "ready", "stopping", "stopped", "failed"], optional): Deployment status filter + model (str, optional): Project and model names separated by a slash + limit (int, optional): Maximum deployments to return + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsListResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsListResponse, + self._client.request( + "GET", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("status", status, style="form", explode=True), + *_query_parameter("model", model, style="form", explode=True), + *_query_parameter("limit", limit, style="form", explode=True), + ], + ), + ) + + def create( + self, + owner: str, + *, + project: str, + model: str, + deployment: str, + name: str, + region: Literal[ + "asia-east1", + "asia-northeast1", + "asia-northeast2", + "asia-south1", + "asia-southeast3", + "europe-north1", + "europe-north2", + "europe-southwest1", + "europe-west1", + "europe-west4", + "europe-west8", + "europe-west9", + "me-west1", + "northamerica-south1", + "us-central1", + "us-east1", + "us-east4", + "us-east5", + "us-south1", + "us-west1", + "africa-south1", + "asia-east2", + "asia-northeast3", + "asia-southeast1", + "asia-southeast2", + "asia-south2", + "australia-southeast1", + "australia-southeast2", + "europe-central2", + "europe-west10", + "europe-west12", + "europe-west2", + "europe-west3", + "europe-west6", + "me-central1", + "northamerica-northeast1", + "northamerica-northeast2", + "southamerica-east1", + "southamerica-west1", + "us-west2", + "us-west3", + "us-west4", + ], + cpu: Literal[1, 2, 4, 6, 8] | NotGiven = NOT_GIVEN, + memory_gi: Literal[2, 4, 8, 16, 24, 32] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsCreateResponse: + """Deploy a model. + + Creates a dedicated auto-scaling inference endpoint for a model. + + Args: + owner (str): Deployment owner + project (str): Project name + model (str): Model name + deployment (str): Deployment name + name (str): Display name + region (Literal["asia-east1", "asia-northeast1", "asia-northeast2", "asia-south1", "asia-southeast3", "europe-north1", "europe-north2", "europe-southwest1", "europe-west1", "europe-west4", "europe-west8", "europe-west9", "me-west1", "northamerica-south1", "us-central1", "us-east1", "us-east4", "us-east5", "us-south1", "us-west1", "africa-south1", "asia-east2", "asia-northeast3", "asia-southeast1", "asia-southeast2", "asia-south2", "australia-southeast1", "australia-southeast2", "europe-central2", "europe-west10", "europe-west12", "europe-west2", "europe-west3", "europe-west6", "me-central1", "northamerica-northeast1", "northamerica-northeast2", "southamerica-east1", "southamerica-west1", "us-west2", "us-west3", "us-west4"]): region request value. + cpu (Literal[1, 2, 4, 6, 8], optional): vCPU cores + memory_gi (Literal[2, 4, 8, 16, 24, 32], optional): Memory in GiB + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsCreateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsCreateResponse, + self._client.request( + "POST", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "project": project, + "model": model, + "deployment": deployment, + "name": name, + "region": region, + "cpu": cpu, + "memoryGi": memory_gi, + }, + ), + ) + + +class AsyncDeployments: + """Asynchronous Deployments API operations.""" + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + + async def retrieve( + self, + owner: str, + deployment: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsRetrieveResponse: + """Get deployment details. + + Returns deployment configuration, status, service URL, and custom metadata. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsRetrieveResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsRetrieveResponse, + await self._client.request( + "GET", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def update( + self, + owner: str, + deployment: str, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsUpdateResponse: + """Update a deployment. + + Updates the display name or custom metadata, starts, stops, resizes, or rolls out another model while preserving the endpoint URL. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + body (dict[str, Any]): API request for updating a deployment + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsUpdateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsUpdateResponse, + await self._client.request( + "PATCH", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + async def delete( + self, + owner: str, + deployment: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsDeleteResponse: + """Delete a deployment. + + Permanently removes the inference endpoint. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsDeleteResponse, + await self._client.request( + "DELETE", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def health( + self, + owner: str, + deployment: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsHealthResponse: + """Check deployment health. + + Pings and warms the deployment endpoint. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsHealthResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsHealthResponse, + await self._client.request( + "GET", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}/health", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def logs( + self, + owner: str, + deployment: str, + *, + severity: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + page_token: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsLogsResponse: + """Get deployment logs. + + Returns recent deployment service logs. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + severity (str, optional): Comma-separated log severity levels + limit (int, optional): Maximum log entries to return + page_token (str, optional): Pagination token + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsLogsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsLogsResponse, + await self._client.request( + "GET", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}/logs", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("severity", severity, style="form", explode=True), + *_query_parameter("limit", limit, style="form", explode=True), + *_query_parameter("pageToken", page_token, style="form", explode=True), + ], + ), + ) + + async def metrics( + self, + owner: str, + deployment: str, + *, + range: Literal["1h", "6h", "24h", "7d", "30d"] | NotGiven = NOT_GIVEN, + sparkline: Literal["true", "false"] | NotGiven = NOT_GIVEN, + view: Literal["overview"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsMetricsResponse: + """Get deployment metrics. + + Returns request volume, latency, errors, and resource utilization. Use view=overview for only request, error, and P95 latency metrics. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + range (Literal["1h", "6h", "24h", "7d", "30d"], optional): Metrics time range + sparkline (Literal["true", "false"], optional): Return the compact dashboard summary + view (Literal["overview"], optional): Fetch only request, error, and P95 latency metrics + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsMetricsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsMetricsResponse, + await self._client.request( + "GET", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}/metrics", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("range", range, style="form", explode=True), + *_query_parameter("sparkline", sparkline, style="form", explode=True), + *_query_parameter("view", view, style="form", explode=True), + ], + ), + ) + + async def predict( + self, + owner: str, + deployment: str, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsPredictResponse: + """Run deployment inference. + + Runs inference through a dedicated deployment endpoint. Depth models accept images only. + + Args: + owner (str): Deployment owner + deployment (str): Deployment name + body (dict[str, Any]): Request body. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsPredictResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsPredictResponse, + await self._client.request( + "POST", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(deployment, explode=False, allow_reserved=False)}/predict", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + data=_form_data({key: value for key, value in body.items() if key not in ["file"]}, multipart=True), + files={key: body[key] for key in ["file"] if key in body}, + ), + ) + + async def list( + self, + owner: str, + *, + status: Literal["creating", "deploying", "ready", "stopping", "stopped", "failed"] | NotGiven = NOT_GIVEN, + model: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsListResponse: + """List deployments. + + Returns workspace inference endpoints. Anonymous callers must filter by one public model; workspace-wide listing requires authentication. + + Args: + owner (str): Deployment owner + status (Literal["creating", "deploying", "ready", "stopping", "stopped", "failed"], optional): Deployment status filter + model (str, optional): Project and model names separated by a slash + limit (int, optional): Maximum deployments to return + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsListResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsListResponse, + await self._client.request( + "GET", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("status", status, style="form", explode=True), + *_query_parameter("model", model, style="form", explode=True), + *_query_parameter("limit", limit, style="form", explode=True), + ], + ), + ) + + async def create( + self, + owner: str, + *, + project: str, + model: str, + deployment: str, + name: str, + region: Literal[ + "asia-east1", + "asia-northeast1", + "asia-northeast2", + "asia-south1", + "asia-southeast3", + "europe-north1", + "europe-north2", + "europe-southwest1", + "europe-west1", + "europe-west4", + "europe-west8", + "europe-west9", + "me-west1", + "northamerica-south1", + "us-central1", + "us-east1", + "us-east4", + "us-east5", + "us-south1", + "us-west1", + "africa-south1", + "asia-east2", + "asia-northeast3", + "asia-southeast1", + "asia-southeast2", + "asia-south2", + "australia-southeast1", + "australia-southeast2", + "europe-central2", + "europe-west10", + "europe-west12", + "europe-west2", + "europe-west3", + "europe-west6", + "me-central1", + "northamerica-northeast1", + "northamerica-northeast2", + "southamerica-east1", + "southamerica-west1", + "us-west2", + "us-west3", + "us-west4", + ], + cpu: Literal[1, 2, 4, 6, 8] | NotGiven = NOT_GIVEN, + memory_gi: Literal[2, 4, 8, 16, 24, 32] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> DeploymentsCreateResponse: + """Deploy a model. + + Creates a dedicated auto-scaling inference endpoint for a model. + + Args: + owner (str): Deployment owner + project (str): Project name + model (str): Model name + deployment (str): Deployment name + name (str): Display name + region (Literal["asia-east1", "asia-northeast1", "asia-northeast2", "asia-south1", "asia-southeast3", "europe-north1", "europe-north2", "europe-southwest1", "europe-west1", "europe-west4", "europe-west8", "europe-west9", "me-west1", "northamerica-south1", "us-central1", "us-east1", "us-east4", "us-east5", "us-south1", "us-west1", "africa-south1", "asia-east2", "asia-northeast3", "asia-southeast1", "asia-southeast2", "asia-south2", "australia-southeast1", "australia-southeast2", "europe-central2", "europe-west10", "europe-west12", "europe-west2", "europe-west3", "europe-west6", "me-central1", "northamerica-northeast1", "northamerica-northeast2", "southamerica-east1", "southamerica-west1", "us-west2", "us-west3", "us-west4"]): region request value. + cpu (Literal[1, 2, 4, 6, 8], optional): vCPU cores + memory_gi (Literal[2, 4, 8, 16, 24, 32], optional): Memory in GiB + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (DeploymentsCreateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + DeploymentsCreateResponse, + await self._client.request( + "POST", + f"/api/deployments/{_path_parameter(owner, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "project": project, + "model": model, + "deployment": deployment, + "name": name, + "region": region, + "cpu": cpu, + "memoryGi": memory_gi, + }, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/explore.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/explore.py new file mode 100644 index 0000000000000000000000000000000000000000..7d51f9f5ac5a9e6e10063d6414a10bb565fd2724 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/explore.py @@ -0,0 +1,148 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Literal, cast + +import httpx + +from .._client import ( + NOT_GIVEN, + AsyncAPIClient, + NotGiven, + SyncAPIClient, + _query_parameter, +) +from ..types import ( + ExploreSearchResponse, +) + + +class Explore: + """Explore API operations.""" + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + + def search( + self, + *, + q: str | NotGiven = NOT_GIVEN, + type: Literal["all", "projects", "datasets"] | NotGiven = NOT_GIVEN, + sort: Literal["stars", "newest", "oldest", "name-asc", "name-desc", "count-desc", "count-asc"] + | NotGiven = NOT_GIVEN, + offset: int | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + task: str | NotGiven = NOT_GIVEN, + author: str | NotGiven = NOT_GIVEN, + starred: Literal["true", "false"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ExploreSearchResponse: + """Search public projects and datasets. + + Browse public content. Authentication is only used for the caller's starred filter. + + Args: + q (str, optional): Search term + type (Literal["all", "projects", "datasets"], optional): Resource type filter + sort (Literal["stars", "newest", "oldest", "name-asc", "name-desc", "count-desc", "count-asc"], optional): Sort order + offset (int, optional): Results to skip + limit (int, optional): Maximum results per resource type + task (str, optional): Comma-separated YOLO task filters + author (str, optional): Owner username filter + starred (Literal["true", "false"], optional): Only content starred by the authenticated caller + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ExploreSearchResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ExploreSearchResponse, + self._client.request( + "GET", + "/api/explore/search", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("q", q, style="form", explode=True), + *_query_parameter("type", type, style="form", explode=True), + *_query_parameter("sort", sort, style="form", explode=True), + *_query_parameter("offset", offset, style="form", explode=True), + *_query_parameter("limit", limit, style="form", explode=True), + *_query_parameter("task", task, style="form", explode=True), + *_query_parameter("author", author, style="form", explode=True), + *_query_parameter("starred", starred, style="form", explode=True), + ], + ), + ) + + +class AsyncExplore: + """Asynchronous Explore API operations.""" + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + + async def search( + self, + *, + q: str | NotGiven = NOT_GIVEN, + type: Literal["all", "projects", "datasets"] | NotGiven = NOT_GIVEN, + sort: Literal["stars", "newest", "oldest", "name-asc", "name-desc", "count-desc", "count-asc"] + | NotGiven = NOT_GIVEN, + offset: int | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + task: str | NotGiven = NOT_GIVEN, + author: str | NotGiven = NOT_GIVEN, + starred: Literal["true", "false"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ExploreSearchResponse: + """Search public projects and datasets. + + Browse public content. Authentication is only used for the caller's starred filter. + + Args: + q (str, optional): Search term + type (Literal["all", "projects", "datasets"], optional): Resource type filter + sort (Literal["stars", "newest", "oldest", "name-asc", "name-desc", "count-desc", "count-asc"], optional): Sort order + offset (int, optional): Results to skip + limit (int, optional): Maximum results per resource type + task (str, optional): Comma-separated YOLO task filters + author (str, optional): Owner username filter + starred (Literal["true", "false"], optional): Only content starred by the authenticated caller + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ExploreSearchResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ExploreSearchResponse, + await self._client.request( + "GET", + "/api/explore/search", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("q", q, style="form", explode=True), + *_query_parameter("type", type, style="form", explode=True), + *_query_parameter("sort", sort, style="form", explode=True), + *_query_parameter("offset", offset, style="form", explode=True), + *_query_parameter("limit", limit, style="form", explode=True), + *_query_parameter("task", task, style="form", explode=True), + *_query_parameter("author", author, style="form", explode=True), + *_query_parameter("starred", starred, style="form", explode=True), + ], + ), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/exports.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/exports.py new file mode 100644 index 0000000000000000000000000000000000000000..73fa539862143210572ed98fb7b29c5f727ebf5b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/exports.py @@ -0,0 +1,482 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any, Literal, cast + +import httpx + +from .._client import ( + NOT_GIVEN, + AsyncAPIClient, + NotGiven, + SyncAPIClient, + _path_parameter, + _query_parameter, +) +from ..types import ( + ExportsCreateResponse, + ExportsDeleteResponse, + ExportsListResponse, + ExportsRetrieveResponse, +) + + +class Exports: + """Exports API operations.""" + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + + def retrieve( + self, + owner: str, + project: str, + model: str, + export_id: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ExportsRetrieveResponse: + """Get export status. + + Returns one export, including a download URL when complete. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + export_id (str): Export ID + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ExportsRetrieveResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ExportsRetrieveResponse, + self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/exports/{_path_parameter(export_id, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def delete( + self, + owner: str, + project: str, + model: str, + export_id: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ExportsDeleteResponse: + """Cancel or delete an export. + + Cancels an active export or deletes a finished export and its file. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + export_id (str): Export ID + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ExportsDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ExportsDeleteResponse, + self._client.request( + "DELETE", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/exports/{_path_parameter(export_id, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def list( + self, + owner: str, + project: str, + model: str, + *, + status: Literal["queued", "starting", "running", "completed", "failed", "cancelled"] | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ExportsListResponse: + """List model exports. + + Returns export jobs for a model, including download URLs for completed exports. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + status (Literal["queued", "starting", "running", "completed", "failed", "cancelled"], optional): Export status filter + limit (int, optional): Maximum exports to return + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ExportsListResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ExportsListResponse, + self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/exports", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("status", status, style="form", explode=True), + *_query_parameter("limit", limit, style="form", explode=True), + ], + ), + ) + + def create( + self, + owner: str, + project: str, + model: str, + *, + format: Literal[ + "onnx", + "torchscript", + "openvino", + "engine", + "coreml", + "coreai", + "litert", + "pb", + "saved_model", + "paddle", + "ncnn", + "edgetpu", + "mnn", + "rknn", + "qnn", + "imx", + "axelera", + "executorch", + "deepx", + "hailo", + "ascend", + ], + gpu_type: Literal[ + "rtx-2000-ada", + "rtx-a4500", + "rtx-a5000", + "rtx-4000-ada", + "l4", + "a40", + "rtx-3090", + "rtx-a6000", + "rtx-pro-4000", + "rtx-pro-4500", + "rtx-4090", + "rtx-6000-ada", + "l40s", + "rtx-pro-5000", + "rtx-5090", + "l40", + "a100-80gb-pcie", + "a100-80gb-sxm", + "rtx-pro-6000", + "h100-pcie", + "h100-nvl", + "h100-sxm", + "h200-nvl", + "h200-sxm", + "b200", + "b300", + "jetson-thor-t5000", + "jetson-thor-t4000", + "jetson-agx-orin-64gb", + "jetson-agx-orin-32gb", + "jetson-orin-nx-16gb", + "jetson-orin-nx-8gb", + "jetson-orin-nano-8gb", + "jetson-orin-nano-4gb", + ] + | NotGiven = NOT_GIVEN, + args: dict[str, Any] | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ExportsCreateResponse: + """Export a model. + + Converts a trained model to another deployment format. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + format (Literal["onnx", "torchscript", "openvino", "engine", "coreml", "coreai", "litert", "pb", "saved_model", "paddle", "ncnn", "edgetpu", "mnn", "rknn", "qnn", "imx", "axelera", "executorch", "deepx", "hailo", "ascend"]): Target export format + gpu_type (Literal["rtx-2000-ada", "rtx-a4500", "rtx-a5000", "rtx-4000-ada", "l4", "a40", "rtx-3090", "rtx-a6000", "rtx-pro-4000", "rtx-pro-4500", "rtx-4090", "rtx-6000-ada", "l40s", "rtx-pro-5000", "rtx-5090", "l40", "a100-80gb-pcie", "a100-80gb-sxm", "rtx-pro-6000", "h100-pcie", "h100-nvl", "h100-sxm", "h200-nvl", "h200-sxm", "b200", "b300", "jetson-thor-t5000", "jetson-thor-t4000", "jetson-agx-orin-64gb", "jetson-agx-orin-32gb", "jetson-orin-nx-16gb", "jetson-orin-nx-8gb", "jetson-orin-nano-8gb", "jetson-orin-nano-4gb"], optional): Target GPU type for TensorRT exports + args (dict[str, Any] | None, optional): Additional export options + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ExportsCreateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ExportsCreateResponse, + self._client.request( + "POST", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/exports", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"format": format, "gpuType": gpu_type, "args": args}, + ), + ) + + +class AsyncExports: + """Asynchronous Exports API operations.""" + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + + async def retrieve( + self, + owner: str, + project: str, + model: str, + export_id: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ExportsRetrieveResponse: + """Get export status. + + Returns one export, including a download URL when complete. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + export_id (str): Export ID + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ExportsRetrieveResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ExportsRetrieveResponse, + await self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/exports/{_path_parameter(export_id, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def delete( + self, + owner: str, + project: str, + model: str, + export_id: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ExportsDeleteResponse: + """Cancel or delete an export. + + Cancels an active export or deletes a finished export and its file. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + export_id (str): Export ID + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ExportsDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ExportsDeleteResponse, + await self._client.request( + "DELETE", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/exports/{_path_parameter(export_id, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def list( + self, + owner: str, + project: str, + model: str, + *, + status: Literal["queued", "starting", "running", "completed", "failed", "cancelled"] | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ExportsListResponse: + """List model exports. + + Returns export jobs for a model, including download URLs for completed exports. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + status (Literal["queued", "starting", "running", "completed", "failed", "cancelled"], optional): Export status filter + limit (int, optional): Maximum exports to return + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ExportsListResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ExportsListResponse, + await self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/exports", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("status", status, style="form", explode=True), + *_query_parameter("limit", limit, style="form", explode=True), + ], + ), + ) + + async def create( + self, + owner: str, + project: str, + model: str, + *, + format: Literal[ + "onnx", + "torchscript", + "openvino", + "engine", + "coreml", + "coreai", + "litert", + "pb", + "saved_model", + "paddle", + "ncnn", + "edgetpu", + "mnn", + "rknn", + "qnn", + "imx", + "axelera", + "executorch", + "deepx", + "hailo", + "ascend", + ], + gpu_type: Literal[ + "rtx-2000-ada", + "rtx-a4500", + "rtx-a5000", + "rtx-4000-ada", + "l4", + "a40", + "rtx-3090", + "rtx-a6000", + "rtx-pro-4000", + "rtx-pro-4500", + "rtx-4090", + "rtx-6000-ada", + "l40s", + "rtx-pro-5000", + "rtx-5090", + "l40", + "a100-80gb-pcie", + "a100-80gb-sxm", + "rtx-pro-6000", + "h100-pcie", + "h100-nvl", + "h100-sxm", + "h200-nvl", + "h200-sxm", + "b200", + "b300", + "jetson-thor-t5000", + "jetson-thor-t4000", + "jetson-agx-orin-64gb", + "jetson-agx-orin-32gb", + "jetson-orin-nx-16gb", + "jetson-orin-nx-8gb", + "jetson-orin-nano-8gb", + "jetson-orin-nano-4gb", + ] + | NotGiven = NOT_GIVEN, + args: dict[str, Any] | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ExportsCreateResponse: + """Export a model. + + Converts a trained model to another deployment format. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + format (Literal["onnx", "torchscript", "openvino", "engine", "coreml", "coreai", "litert", "pb", "saved_model", "paddle", "ncnn", "edgetpu", "mnn", "rknn", "qnn", "imx", "axelera", "executorch", "deepx", "hailo", "ascend"]): Target export format + gpu_type (Literal["rtx-2000-ada", "rtx-a4500", "rtx-a5000", "rtx-4000-ada", "l4", "a40", "rtx-3090", "rtx-a6000", "rtx-pro-4000", "rtx-pro-4500", "rtx-4090", "rtx-6000-ada", "l40s", "rtx-pro-5000", "rtx-5090", "l40", "a100-80gb-pcie", "a100-80gb-sxm", "rtx-pro-6000", "h100-pcie", "h100-nvl", "h100-sxm", "h200-nvl", "h200-sxm", "b200", "b300", "jetson-thor-t5000", "jetson-thor-t4000", "jetson-agx-orin-64gb", "jetson-agx-orin-32gb", "jetson-orin-nx-16gb", "jetson-orin-nx-8gb", "jetson-orin-nano-8gb", "jetson-orin-nano-4gb"], optional): Target GPU type for TensorRT exports + args (dict[str, Any] | None, optional): Additional export options + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ExportsCreateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ExportsCreateResponse, + await self._client.request( + "POST", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/exports", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"format": format, "gpuType": gpu_type, "args": args}, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/images.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/images.py new file mode 100644 index 0000000000000000000000000000000000000000..7fa1d4d81bcf3a194d450f5f95bef45f6ea3a16a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/images.py @@ -0,0 +1,624 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any, Literal, cast + +import httpx + +from .._client import ( + NOT_GIVEN, + AsyncAPIClient, + NotGiven, + SyncAPIClient, + _path_parameter, +) +from ..types import ( + ImagesDeleteBulkResponse, + ImagesDeleteResponse, + ImagesFindSimilarImagesResponse, + ImagesPredictResponse, + ImagesRetrieveResponse, + ImagesUpdateBulkResponse, + ImagesUpdateResponse, + ImagesUrlsResponse, +) + + +class Images: + """Images API operations.""" + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + + def retrieve( + self, image_id: str, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> ImagesRetrieveResponse: + """Get an image. + + Returns the image fields, custom metadata, annotations, and dataset class names. + + Args: + image_id (str): Image ID + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesRetrieveResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesRetrieveResponse, + self._client.request( + "GET", + f"/api/images/{_path_parameter(image_id, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def update( + self, + image_id: str, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ImagesUpdateResponse: + """Update an image. + + Replaces either custom metadata, for example `{"metadata":{"location":"strasbourg"}}`, or annotations. Use one consistent flat keypoint shape: pairs `[x1, y1, x2, y2]` or triples `[x1, y1, visibility1, x2, y2, visibility2]`. + + Args: + image_id (str): Image ID + body (dict[str, Any]): Replace labels for an image Or Replace custom metadata for an image + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesUpdateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesUpdateResponse, + self._client.request( + "PATCH", + f"/api/images/{_path_parameter(image_id, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + def delete( + self, image_id: str, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> ImagesDeleteResponse: + """Delete an image. + + Permanently deletes one image and its associated labels from a dataset. + + Args: + image_id (str): Image ID + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesDeleteResponse, + self._client.request( + "DELETE", + f"/api/images/{_path_parameter(image_id, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def predict( + self, + image_id: str, + *, + model_id: str + | Literal[ + "qwen", + "moondream", + "florence2", + "owlv2", + "yoloe26x", + "groundingdino", + "gpt-6-astra", + "gpt-6-sol", + "claude-fable-5-1", + "claude-opus-5-5", + "claude-sonnet-5", + "gemini-3.1-pro-preview", + "kimi-k3", + "gpt-6-luna", + "claude-haiku-4-5-20251001", + "gemini-3.8-flash", + "gemini-3.5-flash-lite", + "glm-5.3-flash", + "deepseek-flash", + ], + confidence: float | NotGiven = NOT_GIVEN, + iou: float | NotGiven = NOT_GIVEN, + class_mapping: Sequence[int | None] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ImagesPredictResponse: + """Auto-annotate an image. + + Generates label predictions using a YOLO model (ul:// URI), qwen, moondream, florence2, owlv2, yoloe26x, or groundingdino. Hosted models detect the dataset classes (1–100) using model-specific thresholds and return no confidence scores. Truncated generative output returns only complete boxes with partial=true; objects or classes may be missing. Depth datasets are rejected because dense maps cannot be converted to annotations. + + Args: + image_id (str): Image ID + model_id (str | Literal["qwen", "moondream", "florence2", "owlv2", "yoloe26x", "groundingdino", "gpt-6-astra", "gpt-6-sol", "claude-fable-5-1", "claude-opus-5-5", "claude-sonnet-5", "gemini-3.1-pro-preview", "kimi-k3", "gpt-6-luna", "claude-haiku-4-5-20251001", "gemini-3.8-flash", "gemini-3.5-flash-lite", "glm-5.3-flash", "deepseek-flash"]): modelId request value. + confidence (float, optional): Confidence threshold + iou (float, optional): IoU threshold for non-maximum suppression + class_mapping (Sequence[int | None], optional): Dataset class index for each model class, or null to drop it + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesPredictResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesPredictResponse, + self._client.request( + "POST", + f"/api/images/{_path_parameter(image_id, explode=False, allow_reserved=False)}/predict", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"modelId": model_id, "confidence": confidence, "iou": iou, "classMapping": class_mapping}, + ), + ) + + def find_similar_images( + self, image_id: str, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> ImagesFindSimilarImagesResponse: + """Find similar images. + + Returns visually similar images with their similarity score, source dataset, and license, automatically embedding the query image when needed, excluding images already in the source dataset and copies of the query image. + + Args: + image_id (str): Image ID + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesFindSimilarImagesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesFindSimilarImagesResponse, + self._client.request( + "GET", + f"/api/images/{_path_parameter(image_id, explode=False, allow_reserved=False)}/similar", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def update_bulk( + self, + *, + image_ids: Sequence[str], + split: Literal["train", "val", "test"], + conflict_policy: Literal["skip", "keep_both", "replace"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ImagesUpdateBulkResponse: + """Move images to a different split. + + Moves images to a target split (train, val, or test). Filename and content conflicts require one basket-wide skip, keep-both, or replace policy. Maximum 1000 per batch. + + Args: + image_ids (Sequence[str]): imageIds request value. + split (Literal["train", "val", "test"]): Dataset split type + conflict_policy (Literal["skip", "keep_both", "replace"], optional): How to handle filename or content conflicts + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesUpdateBulkResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesUpdateBulkResponse, + self._client.request( + "PATCH", + "/api/images/bulk", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"imageIds": image_ids, "split": split, "conflictPolicy": conflict_policy}, + ), + ) + + def delete_bulk( + self, + *, + image_ids: Sequence[str], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ImagesDeleteBulkResponse: + """Delete images from dataset. + + Deletes multiple images and their annotations from the dataset. Removes files from storage in the background. Maximum 1000 images per batch. + + Args: + image_ids (Sequence[str]): imageIds request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesDeleteBulkResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesDeleteBulkResponse, + self._client.request( + "DELETE", + "/api/images/bulk", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"imageIds": image_ids}, + ), + ) + + def urls( + self, + *, + image_ids: Sequence[str], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ImagesUrlsResponse: + """Get signed image URLs. + + Returns temporary signed URLs for the requested image IDs. + + Args: + image_ids (Sequence[str]): imageIds request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesUrlsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesUrlsResponse, + self._client.request( + "POST", + "/api/images/urls", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"imageIds": image_ids}, + ), + ) + + +class AsyncImages: + """Asynchronous Images API operations.""" + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + + async def retrieve( + self, image_id: str, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> ImagesRetrieveResponse: + """Get an image. + + Returns the image fields, custom metadata, annotations, and dataset class names. + + Args: + image_id (str): Image ID + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesRetrieveResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesRetrieveResponse, + await self._client.request( + "GET", + f"/api/images/{_path_parameter(image_id, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def update( + self, + image_id: str, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ImagesUpdateResponse: + """Update an image. + + Replaces either custom metadata, for example `{"metadata":{"location":"strasbourg"}}`, or annotations. Use one consistent flat keypoint shape: pairs `[x1, y1, x2, y2]` or triples `[x1, y1, visibility1, x2, y2, visibility2]`. + + Args: + image_id (str): Image ID + body (dict[str, Any]): Replace labels for an image Or Replace custom metadata for an image + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesUpdateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesUpdateResponse, + await self._client.request( + "PATCH", + f"/api/images/{_path_parameter(image_id, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + async def delete( + self, image_id: str, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> ImagesDeleteResponse: + """Delete an image. + + Permanently deletes one image and its associated labels from a dataset. + + Args: + image_id (str): Image ID + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesDeleteResponse, + await self._client.request( + "DELETE", + f"/api/images/{_path_parameter(image_id, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def predict( + self, + image_id: str, + *, + model_id: str + | Literal[ + "qwen", + "moondream", + "florence2", + "owlv2", + "yoloe26x", + "groundingdino", + "gpt-6-astra", + "gpt-6-sol", + "claude-fable-5-1", + "claude-opus-5-5", + "claude-sonnet-5", + "gemini-3.1-pro-preview", + "kimi-k3", + "gpt-6-luna", + "claude-haiku-4-5-20251001", + "gemini-3.8-flash", + "gemini-3.5-flash-lite", + "glm-5.3-flash", + "deepseek-flash", + ], + confidence: float | NotGiven = NOT_GIVEN, + iou: float | NotGiven = NOT_GIVEN, + class_mapping: Sequence[int | None] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ImagesPredictResponse: + """Auto-annotate an image. + + Generates label predictions using a YOLO model (ul:// URI), qwen, moondream, florence2, owlv2, yoloe26x, or groundingdino. Hosted models detect the dataset classes (1–100) using model-specific thresholds and return no confidence scores. Truncated generative output returns only complete boxes with partial=true; objects or classes may be missing. Depth datasets are rejected because dense maps cannot be converted to annotations. + + Args: + image_id (str): Image ID + model_id (str | Literal["qwen", "moondream", "florence2", "owlv2", "yoloe26x", "groundingdino", "gpt-6-astra", "gpt-6-sol", "claude-fable-5-1", "claude-opus-5-5", "claude-sonnet-5", "gemini-3.1-pro-preview", "kimi-k3", "gpt-6-luna", "claude-haiku-4-5-20251001", "gemini-3.8-flash", "gemini-3.5-flash-lite", "glm-5.3-flash", "deepseek-flash"]): modelId request value. + confidence (float, optional): Confidence threshold + iou (float, optional): IoU threshold for non-maximum suppression + class_mapping (Sequence[int | None], optional): Dataset class index for each model class, or null to drop it + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesPredictResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesPredictResponse, + await self._client.request( + "POST", + f"/api/images/{_path_parameter(image_id, explode=False, allow_reserved=False)}/predict", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"modelId": model_id, "confidence": confidence, "iou": iou, "classMapping": class_mapping}, + ), + ) + + async def find_similar_images( + self, image_id: str, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> ImagesFindSimilarImagesResponse: + """Find similar images. + + Returns visually similar images with their similarity score, source dataset, and license, automatically embedding the query image when needed, excluding images already in the source dataset and copies of the query image. + + Args: + image_id (str): Image ID + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesFindSimilarImagesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesFindSimilarImagesResponse, + await self._client.request( + "GET", + f"/api/images/{_path_parameter(image_id, explode=False, allow_reserved=False)}/similar", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def update_bulk( + self, + *, + image_ids: Sequence[str], + split: Literal["train", "val", "test"], + conflict_policy: Literal["skip", "keep_both", "replace"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ImagesUpdateBulkResponse: + """Move images to a different split. + + Moves images to a target split (train, val, or test). Filename and content conflicts require one basket-wide skip, keep-both, or replace policy. Maximum 1000 per batch. + + Args: + image_ids (Sequence[str]): imageIds request value. + split (Literal["train", "val", "test"]): Dataset split type + conflict_policy (Literal["skip", "keep_both", "replace"], optional): How to handle filename or content conflicts + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesUpdateBulkResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesUpdateBulkResponse, + await self._client.request( + "PATCH", + "/api/images/bulk", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"imageIds": image_ids, "split": split, "conflictPolicy": conflict_policy}, + ), + ) + + async def delete_bulk( + self, + *, + image_ids: Sequence[str], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ImagesDeleteBulkResponse: + """Delete images from dataset. + + Deletes multiple images and their annotations from the dataset. Removes files from storage in the background. Maximum 1000 images per batch. + + Args: + image_ids (Sequence[str]): imageIds request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesDeleteBulkResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesDeleteBulkResponse, + await self._client.request( + "DELETE", + "/api/images/bulk", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"imageIds": image_ids}, + ), + ) + + async def urls( + self, + *, + image_ids: Sequence[str], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ImagesUrlsResponse: + """Get signed image URLs. + + Returns temporary signed URLs for the requested image IDs. + + Args: + image_ids (Sequence[str]): imageIds request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ImagesUrlsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ImagesUrlsResponse, + await self._client.request( + "POST", + "/api/images/urls", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"imageIds": image_ids}, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/lifecycle.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/lifecycle.py new file mode 100644 index 0000000000000000000000000000000000000000..a65501b006de5279066596b8a6d692d72ab0b136 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/lifecycle.py @@ -0,0 +1,264 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any, Literal, cast + +import httpx + +from .._client import ( + NOT_GIVEN, + AsyncAPIClient, + NotGiven, + SyncAPIClient, + _query_parameter, +) +from ..types import ( + LifecycleDeleteTrashResponse, + LifecycleRestoreResponse, + LifecycleTrashResponse, +) + + +class Lifecycle: + """Lifecycle API operations.""" + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + + def trash( + self, + *, + id: str | NotGiven = NOT_GIVEN, + type: Literal["all", "project", "dataset", "model"] | NotGiven = NOT_GIVEN, + page: int | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> LifecycleTrashResponse: + """View trash. + + Returns restorable trash, or previews affected models and permanently deleted deployments when id and type are provided. Trash expires after 30 days. + + Args: + id (str, optional): Preview resources affected by deleting this model or project + type (Literal["all", "project", "dataset", "model"], optional): type query parameter. + page (int, optional): page query parameter. + limit (int, optional): limit query parameter. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (LifecycleTrashResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + LifecycleTrashResponse, + self._client.request( + "GET", + "/api/trash", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("id", id, style="form", explode=True), + *_query_parameter("type", type, style="form", explode=True), + *_query_parameter("page", page, style="form", explode=True), + *_query_parameter("limit", limit, style="form", explode=True), + ], + ), + ) + + def restore( + self, + *, + id: str, + type: Literal["project", "dataset", "model"], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> LifecycleRestoreResponse: + """Restore a trashed item. + + Restores a trashed project, dataset, or model before its retention period expires. + + Args: + id (str): Trashed resource ID + type (Literal["project", "dataset", "model"]): type request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (LifecycleRestoreResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + LifecycleRestoreResponse, + self._client.request( + "POST", + "/api/trash", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"id": id, "type": type}, + ), + ) + + def delete_trash( + self, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> LifecycleDeleteTrashResponse: + """Permanently delete trash. + + Permanently deletes one trashed resource or all workspace trash. This cannot be undone. + + Args: + body (dict[str, Any]): Permanently delete one trashable resource or all workspace trash + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (LifecycleDeleteTrashResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + LifecycleDeleteTrashResponse, + self._client.request( + "DELETE", + "/api/trash", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + +class AsyncLifecycle: + """Asynchronous Lifecycle API operations.""" + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + + async def trash( + self, + *, + id: str | NotGiven = NOT_GIVEN, + type: Literal["all", "project", "dataset", "model"] | NotGiven = NOT_GIVEN, + page: int | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> LifecycleTrashResponse: + """View trash. + + Returns restorable trash, or previews affected models and permanently deleted deployments when id and type are provided. Trash expires after 30 days. + + Args: + id (str, optional): Preview resources affected by deleting this model or project + type (Literal["all", "project", "dataset", "model"], optional): type query parameter. + page (int, optional): page query parameter. + limit (int, optional): limit query parameter. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (LifecycleTrashResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + LifecycleTrashResponse, + await self._client.request( + "GET", + "/api/trash", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("id", id, style="form", explode=True), + *_query_parameter("type", type, style="form", explode=True), + *_query_parameter("page", page, style="form", explode=True), + *_query_parameter("limit", limit, style="form", explode=True), + ], + ), + ) + + async def restore( + self, + *, + id: str, + type: Literal["project", "dataset", "model"], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> LifecycleRestoreResponse: + """Restore a trashed item. + + Restores a trashed project, dataset, or model before its retention period expires. + + Args: + id (str): Trashed resource ID + type (Literal["project", "dataset", "model"]): type request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (LifecycleRestoreResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + LifecycleRestoreResponse, + await self._client.request( + "POST", + "/api/trash", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"id": id, "type": type}, + ), + ) + + async def delete_trash( + self, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> LifecycleDeleteTrashResponse: + """Permanently delete trash. + + Permanently deletes one trashed resource or all workspace trash. This cannot be undone. + + Args: + body (dict[str, Any]): Permanently delete one trashable resource or all workspace trash + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (LifecycleDeleteTrashResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + LifecycleDeleteTrashResponse, + await self._client.request( + "DELETE", + "/api/trash", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/models.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/models.py new file mode 100644 index 0000000000000000000000000000000000000000..d312f05be8c5c43ee1e2f57660e9de9c739bfbab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/models.py @@ -0,0 +1,1136 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any, Literal, cast + +import httpx + +from .._client import ( + NOT_GIVEN, + AsyncAPIClient, + NotGiven, + SyncAPIClient, + _form_data, + _path_parameter, + _query_parameter, +) +from ..types import ( + ModelsCloneResponse, + ModelsCreateResponse, + ModelsDeleteResponse, + ModelsDeleteTrainingResponse, + ModelsFilesResponse, + ModelsFindSimilarTrainingImagesResponse, + ModelsListResponse, + ModelsPredictResponse, + ModelsRetrieveResponse, + ModelsTrainingResponse, + ModelsUpdateResponse, + ModelsUploadCheckpointResponse, +) + + +class Models: + """Models API operations.""" + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + + def clone( + self, + owner: str, + project: str, + model: str, + *, + project_body: str, + owner_body: str | NotGiven = NOT_GIVEN, + model_body: str | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + description: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsCloneResponse: + """Clone a model. + + Copies an accessible model into an existing project. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + owner_body (str, optional): Destination owner + project_body (str): Destination project + model_body (str, optional): Destination model name + name (str, optional): Destination display name + description (str, optional): description request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsCloneResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsCloneResponse, + self._client.request( + "POST", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/clone", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "owner": owner_body, + "project": project_body, + "model": model_body, + "name": name, + "description": description, + }, + ), + ) + + def retrieve( + self, + owner: str, + project: str, + model: str, + *, + analysis: Literal["1"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsRetrieveResponse: + """Get model details. + + Returns model details. Pass analysis=1 to return per-image validation analysis instead. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + analysis (Literal["1"], optional): Return per-image validation analysis instead of model details + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsRetrieveResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsRetrieveResponse, + self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("analysis", analysis, style="form", explode=True)], + ), + ) + + def update( + self, + owner: str, + project: str, + model: str, + *, + starred: bool | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + color: str | None | NotGiven = NOT_GIVEN, + description: str | NotGiven = NOT_GIVEN, + metadata: dict[str, Any] | NotGiven = NOT_GIVEN, + status: Literal["pending", "untrained", "starting", "running", "completed", "failed", "cancelled"] + | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-3.0", + "LGPL-3.0", + "MPL-2.0", + "EUPL-1.1", + "Unlicense", + "CC0-1.0", + "Ultralytics-Enterprise", + "Other", + ] + | NotGiven = NOT_GIVEN, + dataset_slug: str | None | NotGiven = NOT_GIVEN, + project_id: str | NotGiven = NOT_GIVEN, + train_args: dict[str, Any] | NotGiven = NOT_GIVEN, + train_results: Sequence[dict[str, Any]] | NotGiven = NOT_GIVEN, + epochs: float | NotGiven = NOT_GIVEN, + best_epoch: float | NotGiven = NOT_GIVEN, + best_fitness: float | NotGiven = NOT_GIVEN, + version: str | NotGiven = NOT_GIVEN, + training_error: dict[str, Any] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsUpdateResponse: + """Update a model. + + Updates model properties such as name, description, metadata, or training status. Pass projectId alone to move the model into another project owned by the same account. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + starred (bool, optional): starred request value. + name (str, optional): name request value. + color (str | None, optional): color request value. + description (str, optional): description request value. + metadata (dict[str, Any], optional): Custom JSON metadata with keys limited to 128 characters and at most 500,000 serialized characters. + status (Literal["pending", "untrained", "starting", "running", "completed", "failed", "cancelled"], optional): Training/model status + license (Literal["None", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-3.0", "LGPL-3.0", "MPL-2.0", "EUPL-1.1", "Unlicense", "CC0-1.0", "Ultralytics-Enterprise", "Other"], optional): Project/model license identifier + dataset_slug (str | None, optional): datasetSlug request value. + project_id (str, optional): Move the model into this project (same owner) + train_args (dict[str, Any], optional): Custom JSON metadata with keys limited to 128 characters and at most 500,000 serialized characters. + train_results (Sequence[dict[str, Any]], optional): trainResults request value. + epochs (float, optional): epochs request value. + best_epoch (float, optional): bestEpoch request value. + best_fitness (float, optional): bestFitness request value. + version (str, optional): version request value. + training_error (dict[str, Any], optional): trainingError request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsUpdateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsUpdateResponse, + self._client.request( + "PATCH", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "starred": starred, + "name": name, + "color": color, + "description": description, + "metadata": metadata, + "status": status, + "license": license, + "datasetSlug": dataset_slug, + "projectId": project_id, + "trainArgs": train_args, + "trainResults": train_results, + "epochs": epochs, + "bestEpoch": best_epoch, + "bestFitness": best_fitness, + "version": version, + "trainingError": training_error, + }, + ), + ) + + def delete( + self, + owner: str, + project: str, + model: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsDeleteResponse: + """Delete a model. + + Moves the model to trash for 30 days and permanently deletes every deployment using it, including pending replacements. Restoring the model does not restore deployments. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsDeleteResponse, + self._client.request( + "DELETE", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def files( + self, + owner: str, + project: str, + model: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsFilesResponse: + """Download model files. + + Returns a short-lived download URL for model weights. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsFilesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsFilesResponse, + self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/files", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def predict( + self, + owner: str, + project: str, + model: str, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsPredictResponse: + """Run model inference. + + Runs inference on an image or video using a trained model. Depth models accept images only. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + body (dict[str, Any]): Request body. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsPredictResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsPredictResponse, + self._client.request( + "POST", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/predict", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + data=_form_data({key: value for key, value in body.items() if key not in ["file"]}, multipart=True), + files={key: body[key] for key in ["file"] if key in body}, + ), + ) + + def find_similar_training_images( + self, + owner: str, + project: str, + model: str, + *, + hashes: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsFindSimilarTrainingImagesResponse: + """Find images similar to a run's worst validation images. + + Returns images from public datasets that look like the ones this training run scored worst on, drawn from each worst image's nearest neighbors in turn and excluding images the training dataset already holds. Empty when the run recorded no per-image results. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + hashes (str, optional): Comma-separated subset of the run's captured worst image hashes; defaults to the whole cohort + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsFindSimilarTrainingImagesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsFindSimilarTrainingImagesResponse, + self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/similar-images", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("hashes", hashes, style="form", explode=True)], + ), + ) + + def training( + self, + owner: str, + project: str, + model: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsTrainingResponse: + """Check training progress. + + Returns live status, epoch progress, timing, compute, metrics, and safe error details. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsTrainingResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsTrainingResponse, + self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/training", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def delete_training( + self, + owner: str, + project: str, + model: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsDeleteTrainingResponse: + """Cancel training. + + Terminates active compute and marks the model as cancelled. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsDeleteTrainingResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsDeleteTrainingResponse, + self._client.request( + "DELETE", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/training", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def list( + self, + owner: str, + project: str, + *, + limit: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsListResponse: + """List models in a project. + + Returns models by owner and project name. + + Args: + owner (str): Project owner + project (str): Project name + limit (int, optional): Maximum models to return + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsListResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsListResponse, + self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("limit", limit, style="form", explode=True)], + ), + ) + + def create( + self, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsCreateResponse: + """Create a model. + + Creates a model in an existing project. + + Args: + body (dict[str, Any]): API request for creating a new model + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsCreateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsCreateResponse, + self._client.request( + "POST", + "/api/models", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + def upload_checkpoint( + self, + *, + filename: str, + project: str | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + model_id: str | NotGiven = NOT_GIVEN, + run_id: int | NotGiven = NOT_GIVEN, + size: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsUploadCheckpointResponse: + """Get a training checkpoint upload URL. + + Uses Bearer API-key authentication. Supply modelId and runId from training_started to bind the upload to that run; worker keys require both and must be assigned to the training job. Legacy callers may supply modelId without runId, or project (username/project-slug) and name. PUT checkpoint bytes to uploadUrl with Content-Type: application/octet-stream. For runId uploads, then send checkpoint_saved with modelId and data containing runId, modelPath=gcsPath, and uploadPath from this response. The event promotes the staged checkpoint; the generic upload completion endpoint does not perform this promotion. + + Args: + project (str, optional): project request value. + name (str, optional): name request value. + filename (str): filename request value. + model_id (str, optional): modelId request value. + run_id (int, optional): runId request value. + size (float | None, optional): size request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsUploadCheckpointResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsUploadCheckpointResponse, + self._client.request( + "POST", + "/api/webhooks/models/upload", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "project": project, + "name": name, + "filename": filename, + "modelId": model_id, + "runId": run_id, + "size": size, + }, + ), + ) + + +class AsyncModels: + """Asynchronous Models API operations.""" + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + + async def clone( + self, + owner: str, + project: str, + model: str, + *, + project_body: str, + owner_body: str | NotGiven = NOT_GIVEN, + model_body: str | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + description: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsCloneResponse: + """Clone a model. + + Copies an accessible model into an existing project. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + owner_body (str, optional): Destination owner + project_body (str): Destination project + model_body (str, optional): Destination model name + name (str, optional): Destination display name + description (str, optional): description request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsCloneResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsCloneResponse, + await self._client.request( + "POST", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/clone", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "owner": owner_body, + "project": project_body, + "model": model_body, + "name": name, + "description": description, + }, + ), + ) + + async def retrieve( + self, + owner: str, + project: str, + model: str, + *, + analysis: Literal["1"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsRetrieveResponse: + """Get model details. + + Returns model details. Pass analysis=1 to return per-image validation analysis instead. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + analysis (Literal["1"], optional): Return per-image validation analysis instead of model details + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsRetrieveResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsRetrieveResponse, + await self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("analysis", analysis, style="form", explode=True)], + ), + ) + + async def update( + self, + owner: str, + project: str, + model: str, + *, + starred: bool | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + color: str | None | NotGiven = NOT_GIVEN, + description: str | NotGiven = NOT_GIVEN, + metadata: dict[str, Any] | NotGiven = NOT_GIVEN, + status: Literal["pending", "untrained", "starting", "running", "completed", "failed", "cancelled"] + | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-3.0", + "LGPL-3.0", + "MPL-2.0", + "EUPL-1.1", + "Unlicense", + "CC0-1.0", + "Ultralytics-Enterprise", + "Other", + ] + | NotGiven = NOT_GIVEN, + dataset_slug: str | None | NotGiven = NOT_GIVEN, + project_id: str | NotGiven = NOT_GIVEN, + train_args: dict[str, Any] | NotGiven = NOT_GIVEN, + train_results: Sequence[dict[str, Any]] | NotGiven = NOT_GIVEN, + epochs: float | NotGiven = NOT_GIVEN, + best_epoch: float | NotGiven = NOT_GIVEN, + best_fitness: float | NotGiven = NOT_GIVEN, + version: str | NotGiven = NOT_GIVEN, + training_error: dict[str, Any] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsUpdateResponse: + """Update a model. + + Updates model properties such as name, description, metadata, or training status. Pass projectId alone to move the model into another project owned by the same account. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + starred (bool, optional): starred request value. + name (str, optional): name request value. + color (str | None, optional): color request value. + description (str, optional): description request value. + metadata (dict[str, Any], optional): Custom JSON metadata with keys limited to 128 characters and at most 500,000 serialized characters. + status (Literal["pending", "untrained", "starting", "running", "completed", "failed", "cancelled"], optional): Training/model status + license (Literal["None", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-3.0", "LGPL-3.0", "MPL-2.0", "EUPL-1.1", "Unlicense", "CC0-1.0", "Ultralytics-Enterprise", "Other"], optional): Project/model license identifier + dataset_slug (str | None, optional): datasetSlug request value. + project_id (str, optional): Move the model into this project (same owner) + train_args (dict[str, Any], optional): Custom JSON metadata with keys limited to 128 characters and at most 500,000 serialized characters. + train_results (Sequence[dict[str, Any]], optional): trainResults request value. + epochs (float, optional): epochs request value. + best_epoch (float, optional): bestEpoch request value. + best_fitness (float, optional): bestFitness request value. + version (str, optional): version request value. + training_error (dict[str, Any], optional): trainingError request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsUpdateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsUpdateResponse, + await self._client.request( + "PATCH", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "starred": starred, + "name": name, + "color": color, + "description": description, + "metadata": metadata, + "status": status, + "license": license, + "datasetSlug": dataset_slug, + "projectId": project_id, + "trainArgs": train_args, + "trainResults": train_results, + "epochs": epochs, + "bestEpoch": best_epoch, + "bestFitness": best_fitness, + "version": version, + "trainingError": training_error, + }, + ), + ) + + async def delete( + self, + owner: str, + project: str, + model: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsDeleteResponse: + """Delete a model. + + Moves the model to trash for 30 days and permanently deletes every deployment using it, including pending replacements. Restoring the model does not restore deployments. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsDeleteResponse, + await self._client.request( + "DELETE", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def files( + self, + owner: str, + project: str, + model: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsFilesResponse: + """Download model files. + + Returns a short-lived download URL for model weights. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsFilesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsFilesResponse, + await self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/files", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def predict( + self, + owner: str, + project: str, + model: str, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsPredictResponse: + """Run model inference. + + Runs inference on an image or video using a trained model. Depth models accept images only. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + body (dict[str, Any]): Request body. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsPredictResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsPredictResponse, + await self._client.request( + "POST", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/predict", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + data=_form_data({key: value for key, value in body.items() if key not in ["file"]}, multipart=True), + files={key: body[key] for key in ["file"] if key in body}, + ), + ) + + async def find_similar_training_images( + self, + owner: str, + project: str, + model: str, + *, + hashes: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsFindSimilarTrainingImagesResponse: + """Find images similar to a run's worst validation images. + + Returns images from public datasets that look like the ones this training run scored worst on, drawn from each worst image's nearest neighbors in turn and excluding images the training dataset already holds. Empty when the run recorded no per-image results. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + hashes (str, optional): Comma-separated subset of the run's captured worst image hashes; defaults to the whole cohort + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsFindSimilarTrainingImagesResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsFindSimilarTrainingImagesResponse, + await self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/similar-images", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("hashes", hashes, style="form", explode=True)], + ), + ) + + async def training( + self, + owner: str, + project: str, + model: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsTrainingResponse: + """Check training progress. + + Returns live status, epoch progress, timing, compute, metrics, and safe error details. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsTrainingResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsTrainingResponse, + await self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/training", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def delete_training( + self, + owner: str, + project: str, + model: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsDeleteTrainingResponse: + """Cancel training. + + Terminates active compute and marks the model as cancelled. + + Args: + owner (str): Project owner + project (str): Project name + model (str): Model name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsDeleteTrainingResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsDeleteTrainingResponse, + await self._client.request( + "DELETE", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/{_path_parameter(model, explode=False, allow_reserved=False)}/training", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def list( + self, + owner: str, + project: str, + *, + limit: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsListResponse: + """List models in a project. + + Returns models by owner and project name. + + Args: + owner (str): Project owner + project (str): Project name + limit (int, optional): Maximum models to return + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsListResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsListResponse, + await self._client.request( + "GET", + f"/api/models/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("limit", limit, style="form", explode=True)], + ), + ) + + async def create( + self, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsCreateResponse: + """Create a model. + + Creates a model in an existing project. + + Args: + body (dict[str, Any]): API request for creating a new model + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsCreateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsCreateResponse, + await self._client.request( + "POST", + "/api/models", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + async def upload_checkpoint( + self, + *, + filename: str, + project: str | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + model_id: str | NotGiven = NOT_GIVEN, + run_id: int | NotGiven = NOT_GIVEN, + size: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ModelsUploadCheckpointResponse: + """Get a training checkpoint upload URL. + + Uses Bearer API-key authentication. Supply modelId and runId from training_started to bind the upload to that run; worker keys require both and must be assigned to the training job. Legacy callers may supply modelId without runId, or project (username/project-slug) and name. PUT checkpoint bytes to uploadUrl with Content-Type: application/octet-stream. For runId uploads, then send checkpoint_saved with modelId and data containing runId, modelPath=gcsPath, and uploadPath from this response. The event promotes the staged checkpoint; the generic upload completion endpoint does not perform this promotion. + + Args: + project (str, optional): project request value. + name (str, optional): name request value. + filename (str): filename request value. + model_id (str, optional): modelId request value. + run_id (int, optional): runId request value. + size (float | None, optional): size request value. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ModelsUploadCheckpointResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ModelsUploadCheckpointResponse, + await self._client.request( + "POST", + "/api/webhooks/models/upload", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "project": project, + "name": name, + "filename": filename, + "modelId": model_id, + "runId": run_id, + "size": size, + }, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/projects.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/projects.py new file mode 100644 index 0000000000000000000000000000000000000000..e1498f04228a25d6d04c662b39fea3e8d4b66828 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/projects.py @@ -0,0 +1,709 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any, Literal, cast + +import httpx + +from .._client import ( + NOT_GIVEN, + AsyncAPIClient, + NotGiven, + SyncAPIClient, + _path_parameter, + _query_parameter, +) +from ..types import ( + ProjectsCloneResponse, + ProjectsCreateResponse, + ProjectsDeleteResponse, + ProjectsListResponse, + ProjectsRetrieveResponse, + ProjectsUpdateResponse, +) + + +class Projects: + """Projects API operations.""" + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + + def clone( + self, + owner: str, + project: str, + *, + name: str | NotGiven = NOT_GIVEN, + description: str | NotGiven = NOT_GIVEN, + visibility: Literal["public", "private"] | NotGiven = NOT_GIVEN, + owner_body: str | NotGiven = NOT_GIVEN, + project_body: str | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-3.0", + "LGPL-3.0", + "MPL-2.0", + "EUPL-1.1", + "Unlicense", + "CC0-1.0", + "Ultralytics-Enterprise", + "Other", + ] + | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ProjectsCloneResponse: + """Clone a project. + + Copies an accessible project and its completed models into an account or editable workspace. + + Args: + owner (str): Project owner + project (str): Project name + name (str, optional): name request value. + description (str, optional): description request value. + visibility (Literal["public", "private"], optional): Resource visibility + owner_body (str, optional): Destination owner + project_body (str, optional): Name for the cloned project + license (Literal["None", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-3.0", "LGPL-3.0", "MPL-2.0", "EUPL-1.1", "Unlicense", "CC0-1.0", "Ultralytics-Enterprise", "Other"], optional): Project/model license identifier + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ProjectsCloneResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ProjectsCloneResponse, + self._client.request( + "POST", + f"/api/projects/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/clone", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "name": name, + "description": description, + "visibility": visibility, + "owner": owner_body, + "project": project_body, + "license": license, + }, + ), + ) + + def retrieve( + self, + owner: str, + project: str, + *, + search: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ProjectsRetrieveResponse: + """Get a project. + + Returns a project and its model summaries by owner and project name. + + Args: + owner (str): Project owner + project (str): Project name + search (str, optional): Model name or metadata search + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ProjectsRetrieveResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ProjectsRetrieveResponse, + self._client.request( + "GET", + f"/api/projects/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("search", search, style="form", explode=True)], + ), + ) + + def update( + self, + owner: str, + project: str, + *, + starred: bool | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + description: str | NotGiven = NOT_GIVEN, + metadata: dict[str, Any] | NotGiven = NOT_GIVEN, + visibility: Literal["public", "private"] | NotGiven = NOT_GIVEN, + tags: Sequence[str] | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-3.0", + "LGPL-3.0", + "MPL-2.0", + "EUPL-1.1", + "Unlicense", + "CC0-1.0", + "Ultralytics-Enterprise", + "Other", + ] + | NotGiven = NOT_GIVEN, + archived: bool | NotGiven = NOT_GIVEN, + icon_color: str | NotGiven = NOT_GIVEN, + icon_letter: str | Literal[""] | None | NotGiven = NOT_GIVEN, + view_preferences: dict[str, Any] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ProjectsUpdateResponse: + """Update a project. + + Updates project properties. Changing the display name also changes the project name used in URLs. + + Args: + owner (str): Project owner + project (str): Project name + starred (bool, optional): starred request value. + name (str, optional): name request value. + description (str, optional): description request value. + metadata (dict[str, Any], optional): Custom JSON metadata with keys limited to 128 characters and at most 500,000 serialized characters. + visibility (Literal["public", "private"], optional): Resource visibility + tags (Sequence[str], optional): tags request value. + license (Literal["None", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-3.0", "LGPL-3.0", "MPL-2.0", "EUPL-1.1", "Unlicense", "CC0-1.0", "Ultralytics-Enterprise", "Other"], optional): Project/model license identifier + archived (bool, optional): archived request value. + icon_color (str, optional): iconColor request value. + icon_letter (str | Literal[""] | None, optional): iconLetter request value. + view_preferences (dict[str, Any], optional): Shared project-level model view defaults + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ProjectsUpdateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ProjectsUpdateResponse, + self._client.request( + "PATCH", + f"/api/projects/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "starred": starred, + "name": name, + "description": description, + "metadata": metadata, + "visibility": visibility, + "tags": tags, + "license": license, + "archived": archived, + "iconColor": icon_color, + "iconLetter": icon_letter, + "viewPreferences": view_preferences, + }, + ), + ) + + def delete( + self, + owner: str, + project: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ProjectsDeleteResponse: + """Delete a project. + + Moves a project and its models to trash for 30 days and permanently deletes their deployments. Restoring the project does not restore deployments. + + Args: + owner (str): Project owner + project (str): Project name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ProjectsDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ProjectsDeleteResponse, + self._client.request( + "DELETE", + f"/api/projects/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def list( + self, + owner: str, + *, + limit: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ProjectsListResponse: + """List an owner's projects. + + Returns public projects, plus private projects when the caller can view the owner's workspace. + + Args: + owner (str): Project owner + limit (int, optional): Maximum projects to return + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ProjectsListResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ProjectsListResponse, + self._client.request( + "GET", + f"/api/projects/{_path_parameter(owner, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("limit", limit, style="form", explode=True)], + ), + ) + + def create( + self, + *, + project: str, + name: str, + description: str | NotGiven = NOT_GIVEN, + metadata: dict[str, Any] | NotGiven = NOT_GIVEN, + visibility: Literal["public", "private"] | NotGiven = NOT_GIVEN, + tags: Sequence[str] | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-3.0", + "LGPL-3.0", + "MPL-2.0", + "EUPL-1.1", + "Unlicense", + "CC0-1.0", + "Ultralytics-Enterprise", + "Other", + ] + | NotGiven = NOT_GIVEN, + owner: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ProjectsCreateResponse: + """Create a project. + + Creates a project for organizing models in an account or editable workspace. + + Args: + project (str): Project name used in Platform URLs + name (str): Display name + description (str, optional): description request value. + metadata (dict[str, Any], optional): Custom JSON metadata with keys limited to 128 characters and at most 500,000 serialized characters. + visibility (Literal["public", "private"], optional): Resource visibility + tags (Sequence[str], optional): tags request value. + license (Literal["None", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-3.0", "LGPL-3.0", "MPL-2.0", "EUPL-1.1", "Unlicense", "CC0-1.0", "Ultralytics-Enterprise", "Other"], optional): Project/model license identifier + owner (str, optional): Workspace owner + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ProjectsCreateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ProjectsCreateResponse, + self._client.request( + "POST", + "/api/projects", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "project": project, + "name": name, + "description": description, + "metadata": metadata, + "visibility": visibility, + "tags": tags, + "license": license, + "owner": owner, + }, + ), + ) + + +class AsyncProjects: + """Asynchronous Projects API operations.""" + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + + async def clone( + self, + owner: str, + project: str, + *, + name: str | NotGiven = NOT_GIVEN, + description: str | NotGiven = NOT_GIVEN, + visibility: Literal["public", "private"] | NotGiven = NOT_GIVEN, + owner_body: str | NotGiven = NOT_GIVEN, + project_body: str | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-3.0", + "LGPL-3.0", + "MPL-2.0", + "EUPL-1.1", + "Unlicense", + "CC0-1.0", + "Ultralytics-Enterprise", + "Other", + ] + | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ProjectsCloneResponse: + """Clone a project. + + Copies an accessible project and its completed models into an account or editable workspace. + + Args: + owner (str): Project owner + project (str): Project name + name (str, optional): name request value. + description (str, optional): description request value. + visibility (Literal["public", "private"], optional): Resource visibility + owner_body (str, optional): Destination owner + project_body (str, optional): Name for the cloned project + license (Literal["None", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-3.0", "LGPL-3.0", "MPL-2.0", "EUPL-1.1", "Unlicense", "CC0-1.0", "Ultralytics-Enterprise", "Other"], optional): Project/model license identifier + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ProjectsCloneResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ProjectsCloneResponse, + await self._client.request( + "POST", + f"/api/projects/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}/clone", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "name": name, + "description": description, + "visibility": visibility, + "owner": owner_body, + "project": project_body, + "license": license, + }, + ), + ) + + async def retrieve( + self, + owner: str, + project: str, + *, + search: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ProjectsRetrieveResponse: + """Get a project. + + Returns a project and its model summaries by owner and project name. + + Args: + owner (str): Project owner + project (str): Project name + search (str, optional): Model name or metadata search + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ProjectsRetrieveResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ProjectsRetrieveResponse, + await self._client.request( + "GET", + f"/api/projects/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("search", search, style="form", explode=True)], + ), + ) + + async def update( + self, + owner: str, + project: str, + *, + starred: bool | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + description: str | NotGiven = NOT_GIVEN, + metadata: dict[str, Any] | NotGiven = NOT_GIVEN, + visibility: Literal["public", "private"] | NotGiven = NOT_GIVEN, + tags: Sequence[str] | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-3.0", + "LGPL-3.0", + "MPL-2.0", + "EUPL-1.1", + "Unlicense", + "CC0-1.0", + "Ultralytics-Enterprise", + "Other", + ] + | NotGiven = NOT_GIVEN, + archived: bool | NotGiven = NOT_GIVEN, + icon_color: str | NotGiven = NOT_GIVEN, + icon_letter: str | Literal[""] | None | NotGiven = NOT_GIVEN, + view_preferences: dict[str, Any] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ProjectsUpdateResponse: + """Update a project. + + Updates project properties. Changing the display name also changes the project name used in URLs. + + Args: + owner (str): Project owner + project (str): Project name + starred (bool, optional): starred request value. + name (str, optional): name request value. + description (str, optional): description request value. + metadata (dict[str, Any], optional): Custom JSON metadata with keys limited to 128 characters and at most 500,000 serialized characters. + visibility (Literal["public", "private"], optional): Resource visibility + tags (Sequence[str], optional): tags request value. + license (Literal["None", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-3.0", "LGPL-3.0", "MPL-2.0", "EUPL-1.1", "Unlicense", "CC0-1.0", "Ultralytics-Enterprise", "Other"], optional): Project/model license identifier + archived (bool, optional): archived request value. + icon_color (str, optional): iconColor request value. + icon_letter (str | Literal[""] | None, optional): iconLetter request value. + view_preferences (dict[str, Any], optional): Shared project-level model view defaults + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ProjectsUpdateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ProjectsUpdateResponse, + await self._client.request( + "PATCH", + f"/api/projects/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "starred": starred, + "name": name, + "description": description, + "metadata": metadata, + "visibility": visibility, + "tags": tags, + "license": license, + "archived": archived, + "iconColor": icon_color, + "iconLetter": icon_letter, + "viewPreferences": view_preferences, + }, + ), + ) + + async def delete( + self, + owner: str, + project: str, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ProjectsDeleteResponse: + """Delete a project. + + Moves a project and its models to trash for 30 days and permanently deletes their deployments. Restoring the project does not restore deployments. + + Args: + owner (str): Project owner + project (str): Project name + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ProjectsDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ProjectsDeleteResponse, + await self._client.request( + "DELETE", + f"/api/projects/{_path_parameter(owner, explode=False, allow_reserved=False)}/{_path_parameter(project, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def list( + self, + owner: str, + *, + limit: int | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ProjectsListResponse: + """List an owner's projects. + + Returns public projects, plus private projects when the caller can view the owner's workspace. + + Args: + owner (str): Project owner + limit (int, optional): Maximum projects to return + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ProjectsListResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ProjectsListResponse, + await self._client.request( + "GET", + f"/api/projects/{_path_parameter(owner, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("limit", limit, style="form", explode=True)], + ), + ) + + async def create( + self, + *, + project: str, + name: str, + description: str | NotGiven = NOT_GIVEN, + metadata: dict[str, Any] | NotGiven = NOT_GIVEN, + visibility: Literal["public", "private"] | NotGiven = NOT_GIVEN, + tags: Sequence[str] | NotGiven = NOT_GIVEN, + license: Literal[ + "None", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-3.0", + "LGPL-3.0", + "MPL-2.0", + "EUPL-1.1", + "Unlicense", + "CC0-1.0", + "Ultralytics-Enterprise", + "Other", + ] + | NotGiven = NOT_GIVEN, + owner: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> ProjectsCreateResponse: + """Create a project. + + Creates a project for organizing models in an account or editable workspace. + + Args: + project (str): Project name used in Platform URLs + name (str): Display name + description (str, optional): description request value. + metadata (dict[str, Any], optional): Custom JSON metadata with keys limited to 128 characters and at most 500,000 serialized characters. + visibility (Literal["public", "private"], optional): Resource visibility + tags (Sequence[str], optional): tags request value. + license (Literal["None", "Apache-2.0", "MIT", "BSD-3-Clause", "AGPL-3.0", "GPL-3.0", "LGPL-3.0", "MPL-2.0", "EUPL-1.1", "Unlicense", "CC0-1.0", "Ultralytics-Enterprise", "Other"], optional): Project/model license identifier + owner (str, optional): Workspace owner + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (ProjectsCreateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + ProjectsCreateResponse, + await self._client.request( + "POST", + "/api/projects", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "project": project, + "name": name, + "description": description, + "metadata": metadata, + "visibility": visibility, + "tags": tags, + "license": license, + "owner": owner, + }, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/storage_integrations.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/storage_integrations.py new file mode 100644 index 0000000000000000000000000000000000000000..78ed7efff888eb99d38238ad7efee2da9cc36639 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/storage_integrations.py @@ -0,0 +1,375 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any, cast + +import httpx + +from .._client import ( + NOT_GIVEN, + AsyncAPIClient, + NotGiven, + SyncAPIClient, + _path_parameter, + _query_parameter, +) +from ..types import ( + StorageIntegrationsCreateResponse, + StorageIntegrationsDeleteResponse, + StorageIntegrationsDiscoverResponse, + StorageIntegrationsListResponse, + StorageIntegrationsObjectsResponse, +) + + +class StorageIntegrations: + """Storage Integrations API operations.""" + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + + def delete( + self, id: str, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> StorageIntegrationsDeleteResponse: + """Disconnect cloud storage. + + Removes saved credentials without deleting provider data. Connected datasets remain visible but their files are unavailable until the same storage account is reconnected. + + Args: + id (str): Cloud integration ID + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (StorageIntegrationsDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + StorageIntegrationsDeleteResponse, + self._client.request( + "DELETE", + f"/api/integrations/buckets/{_path_parameter(id, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def objects( + self, + id: str, + *, + target: str, + prefix: str | NotGiven = NOT_GIVEN, + cursor: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> StorageIntegrationsObjectsResponse: + """Browse cloud storage objects. + + Lists folders and objects beneath a prefix in a connected bucket or container. + + Args: + id (str): Cloud integration ID + target (str): Bucket or container name + prefix (str, optional): Folder prefix + cursor (str, optional): Provider pagination cursor + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (StorageIntegrationsObjectsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + StorageIntegrationsObjectsResponse, + self._client.request( + "GET", + f"/api/integrations/buckets/{_path_parameter(id, explode=False, allow_reserved=False)}/objects", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("target", target, style="form", explode=True), + *_query_parameter("prefix", prefix, style="form", explode=True), + *_query_parameter("cursor", cursor, style="form", explode=True), + ], + ), + ) + + def list( + self, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> StorageIntegrationsListResponse: + """List cloud storage integrations. + + Returns the cloud storage integrations configured for the API key's workspace. + + Args: + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (StorageIntegrationsListResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + StorageIntegrationsListResponse, + self._client.request( + "GET", + "/api/integrations/buckets", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + def create( + self, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> StorageIntegrationsCreateResponse: + """Connect cloud storage. + + Validates and saves a GCS, Amazon S3, or Azure Blob Storage integration. + + Args: + body (dict[str, Any]): Request body. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (StorageIntegrationsCreateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + StorageIntegrationsCreateResponse, + self._client.request( + "POST", + "/api/integrations/buckets", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + def discover( + self, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> StorageIntegrationsDiscoverResponse: + """Discover cloud storage locations. + + Lists accessible buckets or containers using the supplied provider credentials. + + Args: + body (dict[str, Any]): Request body. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (StorageIntegrationsDiscoverResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + StorageIntegrationsDiscoverResponse, + self._client.request( + "POST", + "/api/integrations/buckets/discover", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + +class AsyncStorageIntegrations: + """Asynchronous Storage Integrations API operations.""" + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + + async def delete( + self, id: str, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> StorageIntegrationsDeleteResponse: + """Disconnect cloud storage. + + Removes saved credentials without deleting provider data. Connected datasets remain visible but their files are unavailable until the same storage account is reconnected. + + Args: + id (str): Cloud integration ID + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (StorageIntegrationsDeleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + StorageIntegrationsDeleteResponse, + await self._client.request( + "DELETE", + f"/api/integrations/buckets/{_path_parameter(id, explode=False, allow_reserved=False)}", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def objects( + self, + id: str, + *, + target: str, + prefix: str | NotGiven = NOT_GIVEN, + cursor: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> StorageIntegrationsObjectsResponse: + """Browse cloud storage objects. + + Lists folders and objects beneath a prefix in a connected bucket or container. + + Args: + id (str): Cloud integration ID + target (str): Bucket or container name + prefix (str, optional): Folder prefix + cursor (str, optional): Provider pagination cursor + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (StorageIntegrationsObjectsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + StorageIntegrationsObjectsResponse, + await self._client.request( + "GET", + f"/api/integrations/buckets/{_path_parameter(id, explode=False, allow_reserved=False)}/objects", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[ + *_query_parameter("target", target, style="form", explode=True), + *_query_parameter("prefix", prefix, style="form", explode=True), + *_query_parameter("cursor", cursor, style="form", explode=True), + ], + ), + ) + + async def list( + self, timeout: float | httpx.Timeout | None = None, extra_headers: dict[str, str] | None = None + ) -> StorageIntegrationsListResponse: + """List cloud storage integrations. + + Returns the cloud storage integrations configured for the API key's workspace. + + Args: + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (StorageIntegrationsListResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + StorageIntegrationsListResponse, + await self._client.request( + "GET", + "/api/integrations/buckets", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + ), + ) + + async def create( + self, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> StorageIntegrationsCreateResponse: + """Connect cloud storage. + + Validates and saves a GCS, Amazon S3, or Azure Blob Storage integration. + + Args: + body (dict[str, Any]): Request body. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (StorageIntegrationsCreateResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + StorageIntegrationsCreateResponse, + await self._client.request( + "POST", + "/api/integrations/buckets", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + async def discover( + self, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> StorageIntegrationsDiscoverResponse: + """Discover cloud storage locations. + + Lists accessible buckets or containers using the supplied provider credentials. + + Args: + body (dict[str, Any]): Request body. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (StorageIntegrationsDiscoverResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + StorageIntegrationsDiscoverResponse, + await self._client.request( + "POST", + "/api/integrations/buckets/discover", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/training.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/training.py new file mode 100644 index 0000000000000000000000000000000000000000..ce681f436cda7ab1e04272036548f82919626224 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/training.py @@ -0,0 +1,350 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any, Literal, cast + +import httpx + +from .._client import ( + NOT_GIVEN, + AsyncAPIClient, + NotGiven, + SyncAPIClient, + _query_parameter, +) +from ..types import ( + TrainingGpuAvailabilityResponse, + TrainingMetricsResponse, + TrainingStartResponse, +) + + +class Training: + """Training API operations.""" + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + + def gpu_availability( + self, + *, + managed: Literal["true", "false"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> TrainingGpuAvailabilityResponse: + """Get GPU availability. + + Returns current cloud training capacity for each supported GPU type. Basic queries are public; `managed=true` additionally probes Ultralytics managed capacity and requires authentication. + + Args: + managed (Literal["true", "false"], optional): Include managed training capacity + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (TrainingGpuAvailabilityResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + TrainingGpuAvailabilityResponse, + self._client.request( + "GET", + "/api/training/gpu-availability", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("managed", managed, style="form", explode=True)], + ), + ) + + def start( + self, + *, + model_id: str, + train_args: dict[str, Any], + gpu_type: Literal[ + "rtx-2000-ada", + "rtx-a4500", + "rtx-a5000", + "rtx-4000-ada", + "l4", + "a40", + "rtx-3090", + "rtx-a6000", + "rtx-pro-4000", + "rtx-pro-4500", + "rtx-4090", + "rtx-6000-ada", + "l40s", + "rtx-pro-5000", + "rtx-5090", + "l40", + "a100-80gb-pcie", + "a100-80gb-sxm", + "rtx-pro-6000", + "h100-pcie", + "h100-nvl", + "h100-sxm", + "h200-nvl", + "h200-sxm", + "b200", + "b300", + ] + | NotGiven = NOT_GIVEN, + capture_dataset_version: bool | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> TrainingStartResponse: + """Start cloud training. + + Launches YOLO training on a cloud GPU. Training costs are deducted from your credit balance based on GPU type and duration. + + Args: + model_id (str): Model ID to train + gpu_type (Literal["rtx-2000-ada", "rtx-a4500", "rtx-a5000", "rtx-4000-ada", "l4", "a40", "rtx-3090", "rtx-a6000", "rtx-pro-4000", "rtx-pro-4500", "rtx-4090", "rtx-6000-ada", "l40s", "rtx-pro-5000", "rtx-5090", "l40", "a100-80gb-pcie", "a100-80gb-sxm", "rtx-pro-6000", "h100-pcie", "h100-nvl", "h100-sxm", "h200-nvl", "h200-sxm", "b200", "b300"], optional): Cloud GPU to use + capture_dataset_version (bool, optional): Save an immutable dataset version for this run + train_args (dict[str, Any]): YOLO training arguments + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (TrainingStartResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + TrainingStartResponse, + self._client.request( + "POST", + "/api/training/start", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "modelId": model_id, + "gpuType": gpu_type, + "captureDatasetVersion": capture_dataset_version, + "trainArgs": train_args, + }, + ), + ) + + def metrics( + self, + *, + event: Literal[ + "training_started", + "training_progress", + "epoch_end", + "system_metrics", + "console_output", + "checkpoint_saved", + "training_complete", + "training_failed", + ], + data: dict[str, Any], + model_id: str | NotGiven = NOT_GIVEN, + project: str | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> TrainingMetricsResponse: + """Send a training event. + + Receives callbacks from an existing training process; does not provision compute. For initial training_started registration, supply project and optionally name (defaults to train); the authenticated user owns the run, regardless of any username prefix in project. Retain the returned modelId, runId, and modelSlug; send modelId on subsequent events. Honor cancelled=true responses. checkpoint_saved promotes an uploaded checkpoint only for its runId. This contract covers Bearer API-key callbacks, including assigned workers. Existing signed cloud callbacks instead use X-Alpha-Job-Id (model ID) and X-Alpha-Signature (HMAC-SHA256 of the exact request body with the job webhook secret). + + Args: + model_id (str, optional): modelId request value. + project (str, optional): project request value. + name (str, optional): name request value. + event (Literal["training_started", "training_progress", "epoch_end", "system_metrics", "console_output", "checkpoint_saved", "training_complete", "training_failed"]): event request value. + data (dict[str, Any]): Event-specific callback data, preserving original field names and nested values. training_started: trainArgs, epochs, device, environment, modelInfo. epoch_end: epoch, metrics, system, fitness, modelInfo, total_epochs or epochs_total. system_metrics: cpu, memory, disk, diskIo, network, gpus. console_output: content, lineCount, chunkId, progress. checkpoint_saved: runId, modelPath (the upload response gcsPath), uploadPath. training_complete: runId, results, classNames, plots. training_failed: error, code, instanceId. training_progress: liveness data. Worker callbacks include runId when available. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (TrainingMetricsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + TrainingMetricsResponse, + self._client.request( + "POST", + "/api/webhooks/training/metrics", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"modelId": model_id, "project": project, "name": name, "event": event, "data": data}, + ), + ) + + +class AsyncTraining: + """Asynchronous Training API operations.""" + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + + async def gpu_availability( + self, + *, + managed: Literal["true", "false"] | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> TrainingGpuAvailabilityResponse: + """Get GPU availability. + + Returns current cloud training capacity for each supported GPU type. Basic queries are public; `managed=true` additionally probes Ultralytics managed capacity and requires authentication. + + Args: + managed (Literal["true", "false"], optional): Include managed training capacity + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (TrainingGpuAvailabilityResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + TrainingGpuAvailabilityResponse, + await self._client.request( + "GET", + "/api/training/gpu-availability", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + params=[*_query_parameter("managed", managed, style="form", explode=True)], + ), + ) + + async def start( + self, + *, + model_id: str, + train_args: dict[str, Any], + gpu_type: Literal[ + "rtx-2000-ada", + "rtx-a4500", + "rtx-a5000", + "rtx-4000-ada", + "l4", + "a40", + "rtx-3090", + "rtx-a6000", + "rtx-pro-4000", + "rtx-pro-4500", + "rtx-4090", + "rtx-6000-ada", + "l40s", + "rtx-pro-5000", + "rtx-5090", + "l40", + "a100-80gb-pcie", + "a100-80gb-sxm", + "rtx-pro-6000", + "h100-pcie", + "h100-nvl", + "h100-sxm", + "h200-nvl", + "h200-sxm", + "b200", + "b300", + ] + | NotGiven = NOT_GIVEN, + capture_dataset_version: bool | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> TrainingStartResponse: + """Start cloud training. + + Launches YOLO training on a cloud GPU. Training costs are deducted from your credit balance based on GPU type and duration. + + Args: + model_id (str): Model ID to train + gpu_type (Literal["rtx-2000-ada", "rtx-a4500", "rtx-a5000", "rtx-4000-ada", "l4", "a40", "rtx-3090", "rtx-a6000", "rtx-pro-4000", "rtx-pro-4500", "rtx-4090", "rtx-6000-ada", "l40s", "rtx-pro-5000", "rtx-5090", "l40", "a100-80gb-pcie", "a100-80gb-sxm", "rtx-pro-6000", "h100-pcie", "h100-nvl", "h100-sxm", "h200-nvl", "h200-sxm", "b200", "b300"], optional): Cloud GPU to use + capture_dataset_version (bool, optional): Save an immutable dataset version for this run + train_args (dict[str, Any]): YOLO training arguments + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (TrainingStartResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + TrainingStartResponse, + await self._client.request( + "POST", + "/api/training/start", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={ + "modelId": model_id, + "gpuType": gpu_type, + "captureDatasetVersion": capture_dataset_version, + "trainArgs": train_args, + }, + ), + ) + + async def metrics( + self, + *, + event: Literal[ + "training_started", + "training_progress", + "epoch_end", + "system_metrics", + "console_output", + "checkpoint_saved", + "training_complete", + "training_failed", + ], + data: dict[str, Any], + model_id: str | NotGiven = NOT_GIVEN, + project: str | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> TrainingMetricsResponse: + """Send a training event. + + Receives callbacks from an existing training process; does not provision compute. For initial training_started registration, supply project and optionally name (defaults to train); the authenticated user owns the run, regardless of any username prefix in project. Retain the returned modelId, runId, and modelSlug; send modelId on subsequent events. Honor cancelled=true responses. checkpoint_saved promotes an uploaded checkpoint only for its runId. This contract covers Bearer API-key callbacks, including assigned workers. Existing signed cloud callbacks instead use X-Alpha-Job-Id (model ID) and X-Alpha-Signature (HMAC-SHA256 of the exact request body with the job webhook secret). + + Args: + model_id (str, optional): modelId request value. + project (str, optional): project request value. + name (str, optional): name request value. + event (Literal["training_started", "training_progress", "epoch_end", "system_metrics", "console_output", "checkpoint_saved", "training_complete", "training_failed"]): event request value. + data (dict[str, Any]): Event-specific callback data, preserving original field names and nested values. training_started: trainArgs, epochs, device, environment, modelInfo. epoch_end: epoch, metrics, system, fitness, modelInfo, total_epochs or epochs_total. system_metrics: cpu, memory, disk, diskIo, network, gpus. console_output: content, lineCount, chunkId, progress. checkpoint_saved: runId, modelPath (the upload response gcsPath), uploadPath. training_complete: runId, results, classNames, plots. training_failed: error, code, instanceId. training_progress: liveness data. Worker callbacks include runId when available. + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (TrainingMetricsResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + TrainingMetricsResponse, + await self._client.request( + "POST", + "/api/webhooks/training/metrics", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"modelId": model_id, "project": project, "name": name, "event": event, "data": data}, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/upload.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/upload.py new file mode 100644 index 0000000000000000000000000000000000000000..665b2f1635fb4c28ee80ad739ad9552d8cf63ff4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/resources/upload.py @@ -0,0 +1,176 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any, cast + +import httpx + +from .._client import ( + NOT_GIVEN, + AsyncAPIClient, + NotGiven, + SyncAPIClient, +) +from ..types import ( + UploadCompleteResponse, + UploadSignedUrlResponse, +) + + +class Upload: + """Upload API operations.""" + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + + def complete( + self, + *, + session_id: str, + checksum: str | NotGiven = NOT_GIVEN, + md5: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> UploadCompleteResponse: + """Confirm file upload. + + Call this after uploading a file to the signed URL. Dataset uploads are verified here, then processed by the dataset ingest endpoint. + + Args: + session_id (str): Upload session ID from signed-url response + checksum (str, optional): checksum request value. + md5 (str, optional): Expected uploaded object MD5 digest in hexadecimal + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (UploadCompleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + UploadCompleteResponse, + self._client.request( + "POST", + "/api/upload/complete", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"sessionId": session_id, "checksum": checksum, "md5": md5}, + ), + ) + + def signed_url( + self, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> UploadSignedUrlResponse: + """Get a file upload URL. + + Generates a pre-signed URL for uploading a file directly to cloud storage. Upload the file with a PUT request to the returned URL and headers, complete the upload, then call the resource ingest endpoint with the returned sessionId. Dataset upload URLs remain valid for 12 hours, are create-only, and filenames must end in .zip, .tar, .tar.gz, .tgz, or .ndjson — package loose images into an archive. + + Args: + body (dict[str, Any]): Request body for generating a signed upload URL + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (UploadSignedUrlResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + UploadSignedUrlResponse, + self._client.request( + "POST", + "/api/upload/signed-url", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) + + +class AsyncUpload: + """Asynchronous Upload API operations.""" + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + + async def complete( + self, + *, + session_id: str, + checksum: str | NotGiven = NOT_GIVEN, + md5: str | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> UploadCompleteResponse: + """Confirm file upload. + + Call this after uploading a file to the signed URL. Dataset uploads are verified here, then processed by the dataset ingest endpoint. + + Args: + session_id (str): Upload session ID from signed-url response + checksum (str, optional): checksum request value. + md5 (str, optional): Expected uploaded object MD5 digest in hexadecimal + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (UploadCompleteResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + UploadCompleteResponse, + await self._client.request( + "POST", + "/api/upload/complete", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json={"sessionId": session_id, "checksum": checksum, "md5": md5}, + ), + ) + + async def signed_url( + self, + *, + body: dict[str, Any], + timeout: float | httpx.Timeout | None = None, + extra_headers: dict[str, str] | None = None, + ) -> UploadSignedUrlResponse: + """Get a file upload URL. + + Generates a pre-signed URL for uploading a file directly to cloud storage. Upload the file with a PUT request to the returned URL and headers, complete the upload, then call the resource ingest endpoint with the returned sessionId. Dataset upload URLs remain valid for 12 hours, are create-only, and filenames must end in .zip, .tar, .tar.gz, .tgz, or .ndjson — package loose images into an archive. + + Args: + body (dict[str, Any]): Request body for generating a signed upload URL + timeout (float | httpx.Timeout, optional): Request timeout override. + extra_headers (dict[str, str], optional): Additional request headers. + + Returns: + (UploadSignedUrlResponse): The API response. + + Raises: + (APIError): If the API returns an unsuccessful response. + """ + return cast( + UploadSignedUrlResponse, + await self._client.request( + "POST", + "/api/upload/signed-url", + timeout=timeout, + extra_headers=extra_headers, + auth=("Authorization", "Bearer "), + json=body, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_platform/types.py b/.venv/lib/python3.12/site-packages/ultralytics_platform/types.py new file mode 100644 index 0000000000000000000000000000000000000000..b0d207ce6bd96531652c0449b6ffb92bc8c57529 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_platform/types.py @@ -0,0 +1,3354 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from __future__ import annotations + +from typing import Any, Literal, NotRequired, TypedDict + +AccountSummaryResponseCounts = TypedDict( + "AccountSummaryResponseCounts", {"projects": int, "datasets": int, "models": int} +) + + +AccountSummaryResponseTeamsItem = TypedDict( + "AccountSummaryResponseTeamsItem", + { + "userId": str, + "username": str, + "fullName": NotRequired[str], + "imageUrl": NotRequired[str], + "iconColor": NotRequired[str], + "iconLetter": NotRequired[str], + "plan": str, + "region": Literal["us", "eu", "ap"], + "role": Literal["viewer", "editor", "admin", "owner"], + "deniedReason": NotRequired[str], + }, +) + + +AccountSummaryResponse = TypedDict( + "AccountSummaryResponse", + { + "username": str, + "name": str, + "accountType": Literal["personal", "team"], + "plan": Literal["free", "pro", "enterprise"], + "creditsCents": int, + "counts": AccountSummaryResponseCounts, + "teams": list[AccountSummaryResponseTeamsItem], + }, +) + + +AccountApiKeysResponseKeysItem = TypedDict( + "AccountApiKeysResponseKeysItem", {"keyId": str, "name": str, "keyPrefix": str, "createdAt": str} +) + + +AccountApiKeysResponse = TypedDict("AccountApiKeysResponse", {"keys": list[AccountApiKeysResponseKeysItem]}) + + +AccountStorageResponseUsageProjects = TypedDict( + "AccountStorageResponseUsageProjects", {"current": float, "limit": float, "percent": float} +) + + +AccountStorageResponseUsageDatasets = TypedDict( + "AccountStorageResponseUsageDatasets", {"current": float, "limit": float, "percent": float} +) + + +AccountStorageResponseUsageModels = TypedDict( + "AccountStorageResponseUsageModels", {"current": float, "limit": float, "percent": float} +) + + +AccountStorageResponseUsageImages = TypedDict( + "AccountStorageResponseUsageImages", {"current": float, "limit": float, "percent": float} +) + + +AccountStorageResponseUsageAnnotations = TypedDict("AccountStorageResponseUsageAnnotations", {"current": float}) + + +AccountStorageResponseUsageDeployments = TypedDict( + "AccountStorageResponseUsageDeployments", {"current": float, "limit": float, "percent": float} +) + + +AccountStorageResponseUsageStorage = TypedDict( + "AccountStorageResponseUsageStorage", {"current": float, "limit": float, "percent": float} +) + + +AccountStorageResponseUsage = TypedDict( + "AccountStorageResponseUsage", + { + "projects": NotRequired[AccountStorageResponseUsageProjects], + "datasets": NotRequired[AccountStorageResponseUsageDatasets], + "models": NotRequired[AccountStorageResponseUsageModels], + "images": NotRequired[AccountStorageResponseUsageImages], + "annotations": NotRequired[AccountStorageResponseUsageAnnotations], + "deployments": NotRequired[AccountStorageResponseUsageDeployments], + "storage": AccountStorageResponseUsageStorage, + }, +) + + +AccountStorageResponseBreakdownByCategoryDatasets = TypedDict( + "AccountStorageResponseBreakdownByCategoryDatasets", {"bytes": float, "count": float} +) + + +AccountStorageResponseBreakdownByCategoryModels = TypedDict( + "AccountStorageResponseBreakdownByCategoryModels", {"bytes": float, "count": float} +) + + +AccountStorageResponseBreakdownByCategoryExports = TypedDict( + "AccountStorageResponseBreakdownByCategoryExports", {"bytes": float, "count": float} +) + + +AccountStorageResponseBreakdownByCategory = TypedDict( + "AccountStorageResponseBreakdownByCategory", + { + "datasets": AccountStorageResponseBreakdownByCategoryDatasets, + "models": AccountStorageResponseBreakdownByCategoryModels, + "exports": AccountStorageResponseBreakdownByCategoryExports, + }, +) + + +AccountStorageResponseBreakdownTopItemsItem = TypedDict( + "AccountStorageResponseBreakdownTopItemsItem", + { + "_id": str, + "name": str, + "slug": NotRequired[str], + "sizeBytes": float, + "type": Literal["project", "dataset", "model", "export"], + "parentName": NotRequired[str], + "parentSlug": NotRequired[str], + }, +) + + +AccountStorageResponseBreakdown = TypedDict( + "AccountStorageResponseBreakdown", + { + "byCategory": AccountStorageResponseBreakdownByCategory, + "topItems": list[AccountStorageResponseBreakdownTopItemsItem], + }, +) + + +AccountStorageResponse = TypedDict( + "AccountStorageResponse", + { + "tier": Literal["free", "pro", "enterprise"], + "usage": AccountStorageResponseUsage, + "updatedAt": str | None, + "breakdown": AccountStorageResponseBreakdown, + "region": Literal["us", "eu", "ap"], + "username": str, + }, +) + + +AccountProfileResponseUserSocials = TypedDict( + "AccountProfileResponseUserSocials", + { + "github": NotRequired[str], + "linkedin": NotRequired[str], + "twitter": NotRequired[str], + "discord": NotRequired[str], + "youtube": NotRequired[str], + "scholar": NotRequired[str], + "website": NotRequired[str], + }, +) + + +AccountProfileResponseUser = TypedDict( + "AccountProfileResponseUser", + { + "username": str, + "fullName": NotRequired[str], + "imageUrl": NotRequired[str], + "accountType": Literal["personal", "team"], + "iconColor": NotRequired[str], + "iconLetter": NotRequired[str], + "bio": NotRequired[str], + "company": NotRequired[str], + "useCase": NotRequired[str], + "socials": NotRequired[AccountProfileResponseUserSocials], + "followerCount": int, + "isFollowed": bool, + }, +) + + +AccountProfileResponse = TypedDict("AccountProfileResponse", {"user": AccountProfileResponseUser}) + + +AccountFollowResponse = TypedDict("AccountFollowResponse", {"followed": bool, "followerCount": int}) + + +BillingTransactionsResponseTransactionsItemModel = TypedDict( + "BillingTransactionsResponseTransactionsItemModel", + { + "name": str, + "slug": str, + "projectSlug": str, + "username": str, + "datasetId": NotRequired[str], + "gpuType": NotRequired[str], + "gpuDisplayName": NotRequired[str], + "startedAt": NotRequired[str], + }, +) + + +BillingTransactionsResponseTransactionsItem = TypedDict( + "BillingTransactionsResponseTransactionsItem", + { + "id": str, + "type": Literal[ + "signup", + "purchase", + "subscription", + "monthly_grant", + "training", + "deployment", + "annotation", + "refund", + "adjustment", + "promo", + "auto_topup", + "auto_topup_failed", + "pro_credit_expiry", + ], + "amountCents": float, + "balanceAfter": float, + "modelId": NotRequired[str], + "datasetId": NotRequired[str], + "apiKeyId": NotRequired[str], + "runId": NotRequired[str], + "gpuType": NotRequired[str], + "gpuDisplayName": NotRequired[str], + "period": NotRequired[str], + "createdAt": str, + "receiptUrl": NotRequired[str | None], + "model": NotRequired[BillingTransactionsResponseTransactionsItemModel | None], + }, +) + + +BillingTransactionsResponse = TypedDict( + "BillingTransactionsResponse", {"transactions": list[BillingTransactionsResponseTransactionsItem]} +) + + +BillingUsageSummaryResponsePlan = TypedDict( + "BillingUsageSummaryResponsePlan", + { + "planId": Literal["free", "pro", "enterprise"], + "name": str, + "status": Literal["active", "past_due"], + "cancelAtPeriodEnd": bool, + "paymentFailedAt": NotRequired[str], + "billingCycle": NotRequired[Literal["monthly", "yearly"]], + "currentPeriodEnd": NotRequired[str], + "enterpriseLicenseEnd": NotRequired[str], + "licenseExpired": NotRequired[bool], + }, +) + + +BillingUsageSummaryResponseMetricsItem = TypedDict( + "BillingUsageSummaryResponseMetricsItem", + { + "metricId": Literal["storage_bytes"], + "kind": Literal["GAUGE"], + "period": Literal["NONE"], + "limit": float, + "used": float, + "remaining": float, + "overageAllowed": bool, + }, +) + + +BillingUsageSummaryResponseTrainingCredit = TypedDict( + "BillingUsageSummaryResponseTrainingCredit", {"monthlyGrant": float, "balanceAvailable": float} +) + + +BillingUsageSummaryResponseFeatures = TypedDict( + "BillingUsageSummaryResponseFeatures", {"privateProjects": bool, "teams": bool, "enterpriseLicense": bool} +) + + +BillingUsageSummaryResponse = TypedDict( + "BillingUsageSummaryResponse", + { + "plan": BillingUsageSummaryResponsePlan, + "metrics": list[BillingUsageSummaryResponseMetricsItem], + "trainingCredit": BillingUsageSummaryResponseTrainingCredit, + "features": BillingUsageSummaryResponseFeatures, + "creditsCents": float, + "paidSeats": NotRequired[float], + "currentSeats": NotRequired[float], + "maxSeats": NotRequired[float], + "nextInvoiceCents": NotRequired[float], + }, +) + + +DatasetsClassStatsResponseClassesItem = TypedDict( + "DatasetsClassStatsResponseClassesItem", {"classId": float, "count": float, "imageCount": float} +) + + +DatasetsClassStatsResponseImageStatsWidthHistogramItem = TypedDict( + "DatasetsClassStatsResponseImageStatsWidthHistogramItem", {"bin": float, "count": float, "size": NotRequired[float]} +) + + +DatasetsClassStatsResponseImageStatsHeightHistogramItem = TypedDict( + "DatasetsClassStatsResponseImageStatsHeightHistogramItem", + {"bin": float, "count": float, "size": NotRequired[float]}, +) + + +DatasetsClassStatsResponseImageStatsPointsHistogramItem = TypedDict( + "DatasetsClassStatsResponseImageStatsPointsHistogramItem", + {"bin": float, "count": float, "size": NotRequired[float]}, +) + + +DatasetsClassStatsResponseImageStatsFileSizeHistogramItem = TypedDict( + "DatasetsClassStatsResponseImageStatsFileSizeHistogramItem", + {"bin": float, "count": float, "size": NotRequired[float]}, +) + + +DatasetsClassStatsResponseImageStatsObjectsPerImageHistogramItem = TypedDict( + "DatasetsClassStatsResponseImageStatsObjectsPerImageHistogramItem", + {"bin": float, "count": float, "size": NotRequired[float]}, +) + + +DatasetsClassStatsResponseImageStatsBboxWidthHistogramItem = TypedDict( + "DatasetsClassStatsResponseImageStatsBboxWidthHistogramItem", + {"bin": float, "count": float, "size": NotRequired[float]}, +) + + +DatasetsClassStatsResponseImageStatsBboxHeightHistogramItem = TypedDict( + "DatasetsClassStatsResponseImageStatsBboxHeightHistogramItem", + {"bin": float, "count": float, "size": NotRequired[float]}, +) + + +DatasetsClassStatsResponseImageStatsBboxWidthNormHistogramItem = TypedDict( + "DatasetsClassStatsResponseImageStatsBboxWidthNormHistogramItem", + {"bin": float, "count": float, "size": NotRequired[float]}, +) + + +DatasetsClassStatsResponseImageStatsBboxHeightNormHistogramItem = TypedDict( + "DatasetsClassStatsResponseImageStatsBboxHeightNormHistogramItem", + {"bin": float, "count": float, "size": NotRequired[float]}, +) + + +DatasetsClassStatsResponseImageStats = TypedDict( + "DatasetsClassStatsResponseImageStats", + { + "widthHistogram": list[DatasetsClassStatsResponseImageStatsWidthHistogramItem], + "heightHistogram": list[DatasetsClassStatsResponseImageStatsHeightHistogramItem], + "pointsHistogram": list[DatasetsClassStatsResponseImageStatsPointsHistogramItem], + "formatDistribution": dict[str, float], + "fileSizeHistogram": list[DatasetsClassStatsResponseImageStatsFileSizeHistogramItem], + "objectsPerImageHistogram": list[DatasetsClassStatsResponseImageStatsObjectsPerImageHistogramItem], + "bboxWidthHistogram": list[DatasetsClassStatsResponseImageStatsBboxWidthHistogramItem], + "bboxHeightHistogram": list[DatasetsClassStatsResponseImageStatsBboxHeightHistogramItem], + "bboxWidthNormHistogram": list[DatasetsClassStatsResponseImageStatsBboxWidthNormHistogramItem], + "bboxHeightNormHistogram": list[DatasetsClassStatsResponseImageStatsBboxHeightNormHistogramItem], + }, +) + + +DatasetsClassStatsResponseLocationHeatmap = TypedDict( + "DatasetsClassStatsResponseLocationHeatmap", {"bins": list[list[float]], "maxCount": float} +) + + +DatasetsClassStatsResponseDimensionHeatmap = TypedDict( + "DatasetsClassStatsResponseDimensionHeatmap", + { + "bins": list[list[float]], + "maxCount": float, + "minWidth": float, + "maxWidth": float, + "minHeight": float, + "maxHeight": float, + }, +) + + +DatasetsClassStatsResponse = TypedDict( + "DatasetsClassStatsResponse", + { + "classes": list[DatasetsClassStatsResponseClassesItem], + "imageStats": DatasetsClassStatsResponseImageStats, + "locationHeatmap": DatasetsClassStatsResponseLocationHeatmap, + "dimensionHeatmap": DatasetsClassStatsResponseDimensionHeatmap, + "classNames": list[str], + "cached": bool, + "sampleSize": NotRequired[float | None], + }, +) + + +DatasetsDeleteClassesResponse = TypedDict( + "DatasetsDeleteClassesResponse", + { + "success": Literal[True], + "classNames": list[str], + "classColors": dict[str, str], + "deletedClassIds": list[int], + "deletedAnnotations": int, + }, +) + + +DatasetsMergeClassesResponse = TypedDict( + "DatasetsMergeClassesResponse", + { + "success": Literal[True], + "classNames": list[str], + "classColors": dict[str, str], + "mergedClassIds": list[int], + "targetClassId": int, + }, +) + + +DatasetsCloneResponse = TypedDict( + "DatasetsCloneResponse", + { + "id": str, + "owner": str, + "dataset": str, + "name": str, + "imageCount": int, + "classCount": NotRequired[int], + "region": Literal["us", "eu", "ap"], + }, +) + + +DatasetsRetrieveResponseDatasetSplits = TypedDict( + "DatasetsRetrieveResponseDatasetSplits", {"train": int, "val": int, "test": int, "labeled": int} +) + + +DatasetsRetrieveResponseDatasetSampleImagesItemLabelsItem = TypedDict( + "DatasetsRetrieveResponseDatasetSampleImagesItemLabelsItem", + { + "classId": int, + "bbox": NotRequired[list[Any]], + "segments": NotRequired[list[float]], + "keypoints": NotRequired[list[float]], + "obb": NotRequired[list[Any]], + "skeletonId": NotRequired[str], + }, +) + + +DatasetsRetrieveResponseDatasetSampleImagesItem = TypedDict( + "DatasetsRetrieveResponseDatasetSampleImagesItem", + { + "url": str, + "imageUrl": NotRequired[str], + "depthPreviewUrl": NotRequired[str], + "width": int, + "height": int, + "labels": NotRequired[list[DatasetsRetrieveResponseDatasetSampleImagesItemLabelsItem]], + }, +) + + +DatasetsRetrieveResponseDatasetSourceVariant1 = TypedDict( + "DatasetsRetrieveResponseDatasetSourceVariant1", {"provider": Literal["cloud"]} +) + + +DatasetsRetrieveResponseDatasetSourceVariant2 = TypedDict( + "DatasetsRetrieveResponseDatasetSourceVariant2", {"provider": Literal["roboflow"]} +) + + +DatasetsRetrieveResponseDatasetSourceVariant3 = TypedDict( + "DatasetsRetrieveResponseDatasetSourceVariant3", {"provider": Literal["local"], "keyId": NotRequired[str]} +) + + +DatasetsRetrieveResponseDatasetKptSkeletonKeypointsItem = TypedDict( + "DatasetsRetrieveResponseDatasetKptSkeletonKeypointsItem", + {"name": str, "x": float, "y": float, "color": NotRequired[str]}, +) + + +DatasetsRetrieveResponseDatasetKptSkeleton = TypedDict( + "DatasetsRetrieveResponseDatasetKptSkeleton", + { + "id": str, + "name": str, + "description": NotRequired[str], + "keypoints": list[DatasetsRetrieveResponseDatasetKptSkeletonKeypointsItem], + "connections": list[list[Any]], + "url": NotRequired[str], + }, +) + + +DatasetsRetrieveResponseDatasetProcessingError = TypedDict( + "DatasetsRetrieveResponseDatasetProcessingError", {"message": str, "timestamp": str} +) + + +DatasetsRetrieveResponseDatasetLastIngestSummary = TypedDict( + "DatasetsRetrieveResponseDatasetLastIngestSummary", + {"added": int, "paired": NotRequired[int], "errors": int, "skippedCounts": dict[str, int]}, +) + + +DatasetsRetrieveResponseDatasetVersionsItemSplits = TypedDict( + "DatasetsRetrieveResponseDatasetVersionsItemSplits", {"train": int, "val": int, "test": int, "labeled": int} +) + + +DatasetsRetrieveResponseDatasetVersionsItem = TypedDict( + "DatasetsRetrieveResponseDatasetVersionsItem", + { + "version": int, + "description": NotRequired[str], + "sizeBytes": NotRequired[float], + "contentHash": NotRequired[str], + "sourceUpdatedAt": NotRequired[str], + "imageCount": int, + "classCount": int, + "annotationCount": int, + "splits": DatasetsRetrieveResponseDatasetVersionsItemSplits, + "createdAt": str, + }, +) + + +DatasetsRetrieveResponseDataset = TypedDict( + "DatasetsRetrieveResponseDataset", + { + "id": str, + "owner": str, + "dataset": str, + "name": str, + "description": NotRequired[str], + "visibility": Literal["public", "private"], + "task": Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"], + "channels": NotRequired[int], + "blurFaces": NotRequired[bool], + "depthScale": NotRequired[float], + "imageCount": int, + "classCount": NotRequired[int], + "classNames": NotRequired[list[str]], + "format": NotRequired[Literal["yolo", "coco", "raw", "ndjson"]], + "tags": NotRequired[list[str]], + "license": NotRequired[ + Literal[ + "None", + "CC0-1.0", + "PDM-1.0", + "CC-BY-2.5", + "CC-BY-3.0", + "CC-BY-4.0", + "CC-BY-NC-2.0", + "CC-BY-NC-3.0", + "CC-BY-NC-4.0", + "CC-BY-SA-3.0", + "CC-BY-SA-4.0", + "CC-BY-NC-SA-3.0", + "CC-BY-NC-SA-4.0", + "CC-BY-ND-4.0", + "CC-BY-NC-ND-2.0", + "CC-BY-NC-ND-4.0", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-2.0", + "GPL-3.0", + "LGPL-3.0", + "ODbL-1.0", + "DbCL-1.0", + "Research-Only", + "Other", + ] + ], + "splits": DatasetsRetrieveResponseDatasetSplits, + "annotationCount": NotRequired[int], + "totalBytes": NotRequired[float], + "starCount": int, + "isStarred": bool, + "status": NotRequired[Literal["processing", "ready", "failed"]], + "sampleImages": NotRequired[list[DatasetsRetrieveResponseDatasetSampleImagesItem]], + "integrationProvider": NotRequired[Literal["gcs", "s3", "azure", "on-premise"]], + "integrationStatus": NotRequired[Literal["online", "offline", "disconnected"]], + "source": NotRequired[ + DatasetsRetrieveResponseDatasetSourceVariant1 + | DatasetsRetrieveResponseDatasetSourceVariant2 + | DatasetsRetrieveResponseDatasetSourceVariant3 + ], + "classColors": NotRequired[dict[str, str]], + "kptShape": NotRequired[list[Any]], + "kptSkeleton": NotRequired[DatasetsRetrieveResponseDatasetKptSkeleton], + "flipIdx": NotRequired[list[int]], + "processingTimeMs": NotRequired[float], + "lastIngestJobId": NotRequired[str], + "processingError": NotRequired[DatasetsRetrieveResponseDatasetProcessingError], + "lastIngestSummary": NotRequired[DatasetsRetrieveResponseDatasetLastIngestSummary], + "errorCount": NotRequired[int], + "iconColor": NotRequired[str], + "iconLetter": NotRequired[str], + "iconImage": NotRequired[str], + "clonedFrom": NotRequired[str], + "cloneCount": NotRequired[int], + "region": NotRequired[Literal["us", "eu", "ap"]], + "versions": NotRequired[list[DatasetsRetrieveResponseDatasetVersionsItem]], + "createdAt": str, + "updatedAt": str, + "metadata": dict[str, Any], + }, +) + + +DatasetsRetrieveResponse = TypedDict("DatasetsRetrieveResponse", {"dataset": DatasetsRetrieveResponseDataset}) + + +DatasetsUpdateResponse = TypedDict("DatasetsUpdateResponse", {"success": Literal[True], "dataset": str}) + + +DatasetsDeleteResponse = TypedDict("DatasetsDeleteResponse", {"success": Literal[True]}) + + +DatasetsEmbeddingsResponseActiveJobProgress = TypedDict( + "DatasetsEmbeddingsResponseActiveJobProgress", + { + "stage": Literal["embedding", "umap"], + "percent": float, + "processed": NotRequired[float], + "total": NotRequired[float], + "failedDownloads": NotRequired[float], + "failedInference": NotRequired[float], + }, +) + + +DatasetsEmbeddingsResponseActiveJob = TypedDict( + "DatasetsEmbeddingsResponseActiveJob", + { + "id": str, + "status": Literal["queued", "starting", "running"], + "progress": DatasetsEmbeddingsResponseActiveJobProgress | None, + "createdAt": str, + }, +) + + +DatasetsEmbeddingsResponse = TypedDict( + "DatasetsEmbeddingsResponse", + { + "analyzedAt": str | None, + "embeddingsCount": int, + "latestImageAt": str | None, + "activeJob": DatasetsEmbeddingsResponseActiveJob | None, + }, +) + + +DatasetsCreateEmbeddingsResponse = TypedDict("DatasetsCreateEmbeddingsResponse", {"jobId": str}) + + +DatasetsDeleteEmbeddingsResponse = TypedDict("DatasetsDeleteEmbeddingsResponse", {"cancelled": str | None}) + + +DatasetsExportResponseVariant1 = TypedDict("DatasetsExportResponseVariant1", {"downloadUrl": str, "version": int}) + + +DatasetsExportResponseVariant2 = TypedDict("DatasetsExportResponseVariant2", {"downloadUrl": str, "cached": bool}) + + +DatasetsExportResponse = DatasetsExportResponseVariant1 | DatasetsExportResponseVariant2 + + +DatasetsCreateExportResponse = TypedDict( + "DatasetsCreateExportResponse", {"version": int, "downloadUrl": str, "reused": bool} +) + + +DatasetsUpdateExportResponse = TypedDict("DatasetsUpdateExportResponse", {"ok": Literal[True]}) + + +DatasetsAdoptImagesResponse = TypedDict("DatasetsAdoptImagesResponse", {"adopted": int}) + + +DatasetsClusteringResponseImagesItem = TypedDict( + "DatasetsClusteringResponseImagesItem", + { + "id": str, + "umapX": float, + "umapY": float, + "split": Literal["train", "val", "test"] | None, + "classIds": list[int], + "width": int, + "height": int, + "bytes": int | None, + "labelCount": int, + "labeled": bool, + "missing": bool, + }, +) + + +DatasetsClusteringResponse = TypedDict( + "DatasetsClusteringResponse", + { + "images": list[DatasetsClusteringResponseImagesItem], + "total": int, + "offset": int, + "limit": int, + "hasMore": bool, + "nextOffset": int | None, + "updatedAt": str, + }, +) + + +DatasetsImagesResponseImagesItemLabelsItem = TypedDict( + "DatasetsImagesResponseImagesItemLabelsItem", + { + "classId": int, + "bbox": NotRequired[list[Any]], + "segments": NotRequired[list[float]], + "keypoints": NotRequired[list[float]], + "obb": NotRequired[list[Any]], + "skeletonId": NotRequired[str], + }, +) + + +DatasetsImagesResponseImagesItemDepth = TypedDict( + "DatasetsImagesResponseImagesItemDepth", + { + "hash": str, + "bytes": int, + "shape": list[int], + "min": NotRequired[float], + "max": NotRequired[float], + "validFraction": NotRequired[float], + "previewUrl": str, + }, +) + + +DatasetsImagesResponseImagesItem = TypedDict( + "DatasetsImagesResponseImagesItem", + { + "id": str, + "hash": str, + "ext": str, + "thumbnailUrl": NotRequired[str], + "imageUrl": NotRequired[str], + "width": int, + "height": int, + "split": Literal["train", "val", "test"], + "labelCount": int, + "name": str, + "bytes": NotRequired[int], + "error": NotRequired[str | None], + "labels": NotRequired[list[DatasetsImagesResponseImagesItemLabelsItem]], + "labelsTruncated": NotRequired[Literal[True]], + "depth": NotRequired[DatasetsImagesResponseImagesItemDepth], + }, +) + + +DatasetsImagesResponse = TypedDict( + "DatasetsImagesResponse", + { + "images": list[DatasetsImagesResponseImagesItem], + "total": NotRequired[int], + "hasMore": bool, + "classes": list[str], + "errorCount": int, + "nextCursor": NotRequired[str], + }, +) + + +DatasetsSelectedImagesResponseImagesItemLabelsItem = TypedDict( + "DatasetsSelectedImagesResponseImagesItemLabelsItem", + { + "classId": int, + "bbox": NotRequired[list[Any]], + "segments": NotRequired[list[float]], + "keypoints": NotRequired[list[float]], + "obb": NotRequired[list[Any]], + "skeletonId": NotRequired[str], + }, +) + + +DatasetsSelectedImagesResponseImagesItemDepth = TypedDict( + "DatasetsSelectedImagesResponseImagesItemDepth", + { + "hash": str, + "bytes": int, + "shape": list[int], + "min": NotRequired[float], + "max": NotRequired[float], + "validFraction": NotRequired[float], + "previewUrl": str, + }, +) + + +DatasetsSelectedImagesResponseImagesItem = TypedDict( + "DatasetsSelectedImagesResponseImagesItem", + { + "id": str, + "hash": str, + "ext": str, + "thumbnailUrl": NotRequired[str], + "imageUrl": NotRequired[str], + "width": int, + "height": int, + "split": Literal["train", "val", "test"], + "labelCount": int, + "name": str, + "bytes": NotRequired[int], + "error": NotRequired[str | None], + "labels": NotRequired[list[DatasetsSelectedImagesResponseImagesItemLabelsItem]], + "labelsTruncated": NotRequired[Literal[True]], + "depth": NotRequired[DatasetsSelectedImagesResponseImagesItemDepth], + }, +) + + +DatasetsSelectedImagesResponse = TypedDict( + "DatasetsSelectedImagesResponse", + { + "images": list[DatasetsSelectedImagesResponseImagesItem], + "total": int, + "hasMore": Literal[False], + "classes": list[str], + "errorCount": int, + "nextCursor": NotRequired[Any], + }, +) + + +DatasetsIngestResponse = TypedDict("DatasetsIngestResponse", {"jobId": str, "status": Literal["queued"]}) + + +DatasetsModelsResponseModelsItemDatasetVersion = TypedDict( + "DatasetsModelsResponseModelsItemDatasetVersion", {"version": int, "contentHash": str} +) + + +DatasetsModelsResponseModelsItem = TypedDict( + "DatasetsModelsResponseModelsItem", + { + "id": str, + "owner": str, + "project": str, + "model": str, + "name": str, + "status": Literal["pending", "untrained", "starting", "running", "completed", "failed", "cancelled"], + "task": NotRequired[Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"]], + "datasetVersion": NotRequired[DatasetsModelsResponseModelsItemDatasetVersion], + "epochs": NotRequired[int], + "bestEpoch": NotRequired[int], + "bestFitness": NotRequired[float], + "metrics": dict[str, float], + "startedAt": NotRequired[str], + "completedAt": NotRequired[str], + "createdAt": str, + "projectIconColor": NotRequired[str], + "projectIconLetter": NotRequired[str], + "projectIconImage": NotRequired[str], + }, +) + + +DatasetsModelsResponse = TypedDict( + "DatasetsModelsResponse", {"models": list[DatasetsModelsResponseModelsItem], "count": int} +) + + +DatasetsBatchResponseActiveJobPreviewsItem = TypedDict( + "DatasetsBatchResponseActiveJobPreviewsItem", {"imageId": str, "imageUrl": str, "thumbnailUrl": NotRequired[str]} +) + + +DatasetsBatchResponseActiveJobProgress = TypedDict( + "DatasetsBatchResponseActiveJobProgress", {"processed": float, "total": float} +) + + +DatasetsBatchResponseActiveJob = TypedDict( + "DatasetsBatchResponseActiveJob", + { + "id": str, + "operation": NotRequired[Literal["blur"]], + "preview": NotRequired[bool], + "confidence": float, + "boxScale": float, + "imageId": NotRequired[str], + "stopping": bool, + "previews": NotRequired[list[DatasetsBatchResponseActiveJobPreviewsItem]], + "progress": DatasetsBatchResponseActiveJobProgress, + "startedAt": str, + }, +) + + +DatasetsBatchResponseLastRunResultsPreviewsItem = TypedDict( + "DatasetsBatchResponseLastRunResultsPreviewsItem", + {"imageId": str, "imageUrl": str, "thumbnailUrl": NotRequired[str]}, +) + + +DatasetsBatchResponseLastRunResults = TypedDict( + "DatasetsBatchResponseLastRunResults", + { + "processed": int, + "faces": NotRequired[int], + "previews": NotRequired[list[DatasetsBatchResponseLastRunResultsPreviewsItem]], + "annotations": int, + "classes": int, + "partialImages": NotRequired[int], + }, +) + + +DatasetsBatchResponseLastRun = TypedDict( + "DatasetsBatchResponseLastRun", + { + "id": str, + "operation": NotRequired[Literal["blur"]], + "preview": NotRequired[bool], + "confidence": float, + "boxScale": float, + "imageId": NotRequired[str], + "failed": bool, + "stopped": bool, + "error": str | None, + "results": DatasetsBatchResponseLastRunResults | None, + }, +) + + +DatasetsBatchResponse = TypedDict( + "DatasetsBatchResponse", + {"activeJob": DatasetsBatchResponseActiveJob | None, "lastRun": DatasetsBatchResponseLastRun | None}, +) + + +DatasetsCreateBatchResponse = TypedDict("DatasetsCreateBatchResponse", {"jobId": str}) + + +DatasetsDeleteBatchResponse = TypedDict( + "DatasetsDeleteBatchResponse", {"action": Literal["cancelled", "dismissed", "none"], "jobId": str | None} +) + + +DatasetsRestoreResponse = TypedDict("DatasetsRestoreResponse", {"version": int, "imageCount": int}) + + +DatasetsRedistributeSplitsResponseSplits = TypedDict( + "DatasetsRedistributeSplitsResponseSplits", {"train": int, "val": int, "test": int} +) + + +DatasetsRedistributeSplitsResponse = TypedDict( + "DatasetsRedistributeSplitsResponse", + {"success": Literal[True], "splits": DatasetsRedistributeSplitsResponseSplits, "modified": int}, +) + + +DatasetsListResponseDatasetsItemSplits = TypedDict( + "DatasetsListResponseDatasetsItemSplits", {"train": int, "val": int, "test": int, "labeled": int} +) + + +DatasetsListResponseDatasetsItemSampleImagesItemLabelsItem = TypedDict( + "DatasetsListResponseDatasetsItemSampleImagesItemLabelsItem", + { + "classId": int, + "bbox": NotRequired[list[Any]], + "segments": NotRequired[list[float]], + "keypoints": NotRequired[list[float]], + "obb": NotRequired[list[Any]], + "skeletonId": NotRequired[str], + }, +) + + +DatasetsListResponseDatasetsItemSampleImagesItem = TypedDict( + "DatasetsListResponseDatasetsItemSampleImagesItem", + { + "url": str, + "imageUrl": NotRequired[str], + "depthPreviewUrl": NotRequired[str], + "width": int, + "height": int, + "labels": NotRequired[list[DatasetsListResponseDatasetsItemSampleImagesItemLabelsItem]], + }, +) + + +DatasetsListResponseDatasetsItemSourceVariant1 = TypedDict( + "DatasetsListResponseDatasetsItemSourceVariant1", {"provider": Literal["cloud"]} +) + + +DatasetsListResponseDatasetsItemSourceVariant2 = TypedDict( + "DatasetsListResponseDatasetsItemSourceVariant2", {"provider": Literal["roboflow"]} +) + + +DatasetsListResponseDatasetsItemSourceVariant3 = TypedDict( + "DatasetsListResponseDatasetsItemSourceVariant3", {"provider": Literal["local"], "keyId": NotRequired[str]} +) + + +DatasetsListResponseDatasetsItemKptSkeletonKeypointsItem = TypedDict( + "DatasetsListResponseDatasetsItemKptSkeletonKeypointsItem", + {"name": str, "x": float, "y": float, "color": NotRequired[str]}, +) + + +DatasetsListResponseDatasetsItemKptSkeleton = TypedDict( + "DatasetsListResponseDatasetsItemKptSkeleton", + { + "id": str, + "name": str, + "description": NotRequired[str], + "keypoints": list[DatasetsListResponseDatasetsItemKptSkeletonKeypointsItem], + "connections": list[list[Any]], + "url": NotRequired[str], + }, +) + + +DatasetsListResponseDatasetsItemProcessingError = TypedDict( + "DatasetsListResponseDatasetsItemProcessingError", {"message": str, "timestamp": str} +) + + +DatasetsListResponseDatasetsItemLastIngestSummary = TypedDict( + "DatasetsListResponseDatasetsItemLastIngestSummary", + {"added": int, "paired": NotRequired[int], "errors": int, "skippedCounts": dict[str, int]}, +) + + +DatasetsListResponseDatasetsItemVersionsItemSplits = TypedDict( + "DatasetsListResponseDatasetsItemVersionsItemSplits", {"train": int, "val": int, "test": int, "labeled": int} +) + + +DatasetsListResponseDatasetsItemVersionsItem = TypedDict( + "DatasetsListResponseDatasetsItemVersionsItem", + { + "version": int, + "description": NotRequired[str], + "sizeBytes": NotRequired[float], + "contentHash": NotRequired[str], + "sourceUpdatedAt": NotRequired[str], + "imageCount": int, + "classCount": int, + "annotationCount": int, + "splits": DatasetsListResponseDatasetsItemVersionsItemSplits, + "createdAt": str, + }, +) + + +DatasetsListResponseDatasetsItem = TypedDict( + "DatasetsListResponseDatasetsItem", + { + "id": str, + "owner": str, + "dataset": str, + "name": str, + "description": NotRequired[str], + "visibility": Literal["public", "private"], + "task": Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"], + "channels": NotRequired[int], + "blurFaces": NotRequired[bool], + "depthScale": NotRequired[float], + "imageCount": int, + "classCount": NotRequired[int], + "classNames": NotRequired[list[str]], + "format": NotRequired[Literal["yolo", "coco", "raw", "ndjson"]], + "tags": NotRequired[list[str]], + "license": NotRequired[ + Literal[ + "None", + "CC0-1.0", + "PDM-1.0", + "CC-BY-2.5", + "CC-BY-3.0", + "CC-BY-4.0", + "CC-BY-NC-2.0", + "CC-BY-NC-3.0", + "CC-BY-NC-4.0", + "CC-BY-SA-3.0", + "CC-BY-SA-4.0", + "CC-BY-NC-SA-3.0", + "CC-BY-NC-SA-4.0", + "CC-BY-ND-4.0", + "CC-BY-NC-ND-2.0", + "CC-BY-NC-ND-4.0", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-2.0", + "GPL-3.0", + "LGPL-3.0", + "ODbL-1.0", + "DbCL-1.0", + "Research-Only", + "Other", + ] + ], + "splits": DatasetsListResponseDatasetsItemSplits, + "annotationCount": NotRequired[int], + "totalBytes": NotRequired[float], + "starCount": int, + "isStarred": bool, + "status": NotRequired[Literal["processing", "ready", "failed"]], + "sampleImages": NotRequired[list[DatasetsListResponseDatasetsItemSampleImagesItem]], + "integrationProvider": NotRequired[Literal["gcs", "s3", "azure", "on-premise"]], + "integrationStatus": NotRequired[Literal["online", "offline", "disconnected"]], + "source": NotRequired[ + DatasetsListResponseDatasetsItemSourceVariant1 + | DatasetsListResponseDatasetsItemSourceVariant2 + | DatasetsListResponseDatasetsItemSourceVariant3 + ], + "classColors": NotRequired[dict[str, str]], + "kptShape": NotRequired[list[Any]], + "kptSkeleton": NotRequired[DatasetsListResponseDatasetsItemKptSkeleton], + "flipIdx": NotRequired[list[int]], + "processingTimeMs": NotRequired[float], + "lastIngestJobId": NotRequired[str], + "processingError": NotRequired[DatasetsListResponseDatasetsItemProcessingError], + "lastIngestSummary": NotRequired[DatasetsListResponseDatasetsItemLastIngestSummary], + "errorCount": NotRequired[int], + "iconColor": NotRequired[str], + "iconLetter": NotRequired[str], + "iconImage": NotRequired[str], + "clonedFrom": NotRequired[str], + "cloneCount": NotRequired[int], + "region": NotRequired[Literal["us", "eu", "ap"]], + "versions": NotRequired[list[DatasetsListResponseDatasetsItemVersionsItem]], + "createdAt": str, + "updatedAt": str, + }, +) + + +DatasetsListResponse = TypedDict( + "DatasetsListResponse", + {"datasets": list[DatasetsListResponseDatasetsItem], "total": int, "region": Literal["us", "eu", "ap"]}, +) + + +DatasetsCreateResponse = TypedDict( + "DatasetsCreateResponse", {"id": str, "owner": str, "dataset": str, "region": Literal["us", "eu", "ap"]} +) + + +DatasetsImportRoboflowResponseImportedItem = TypedDict( + "DatasetsImportRoboflowResponseImportedItem", + {"projectId": str, "projectName": str, "version": int, "datasetId": str, "slug": str}, +) + + +DatasetsImportRoboflowResponseFailedItem = TypedDict( + "DatasetsImportRoboflowResponseFailedItem", {"projectId": str, "projectName": str, "version": int, "error": str} +) + + +DatasetsImportRoboflowResponseSkippedItem = TypedDict( + "DatasetsImportRoboflowResponseSkippedItem", {"projectId": str, "projectName": str, "version": int} +) + + +DatasetsImportRoboflowResponse = TypedDict( + "DatasetsImportRoboflowResponse", + { + "imported": list[DatasetsImportRoboflowResponseImportedItem], + "failed": list[DatasetsImportRoboflowResponseFailedItem], + "skipped": list[DatasetsImportRoboflowResponseSkippedItem], + }, +) + + +DatasetsPreviewRoboflowResponseWorkspace = TypedDict( + "DatasetsPreviewRoboflowResponseWorkspace", {"url": str, "name": str} +) + + +DatasetsPreviewRoboflowResponseNewDatasetsItem = TypedDict( + "DatasetsPreviewRoboflowResponseNewDatasetsItem", + { + "workspace": str, + "projectId": str, + "projectName": str, + "projectType": str, + "latestVersion": int, + "latestVersionName": NotRequired[str], + }, +) + + +DatasetsPreviewRoboflowResponseStorage = TypedDict( + "DatasetsPreviewRoboflowResponseStorage", {"usedBytes": float, "limitBytes": float, "hasEnoughStorage": bool} +) + + +DatasetsPreviewRoboflowResponse = TypedDict( + "DatasetsPreviewRoboflowResponse", + { + "workspace": DatasetsPreviewRoboflowResponseWorkspace, + "newDatasets": list[DatasetsPreviewRoboflowResponseNewDatasetsItem], + "skippedCount": int, + "missingVersionCount": int, + "unsupportedCount": int, + "unresolvedCount": int, + "bytesTotal": int, + "storage": DatasetsPreviewRoboflowResponseStorage, + }, +) + + +DeploymentsRetrieveResponseDeploymentResources = TypedDict( + "DeploymentsRetrieveResponseDeploymentResources", + {"cpu": float, "memoryGi": float, "minInstances": float, "maxInstances": float}, +) + + +DeploymentsRetrieveResponseDeployment = TypedDict( + "DeploymentsRetrieveResponseDeployment", + { + "id": str, + "owner": str, + "project": NotRequired[str], + "model": NotRequired[str], + "task": NotRequired[Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"]], + "deployment": str, + "name": str, + "status": Literal["creating", "deploying", "ready", "stopping", "stopped", "failed"], + "statusMessage": NotRequired[str], + "region": str, + "serviceUrl": NotRequired[str], + "resources": DeploymentsRetrieveResponseDeploymentResources, + "metered": NotRequired[bool], + "deployedAt": NotRequired[str], + "apiKeyId": NotRequired[str], + "createdAt": str, + "updatedAt": str, + "metadata": dict[str, Any], + }, +) + + +DeploymentsRetrieveResponse = TypedDict( + "DeploymentsRetrieveResponse", + {"deployment": DeploymentsRetrieveResponseDeployment, "region": Literal["us", "eu", "ap"]}, +) + + +DeploymentsUpdateResponseVariant1 = TypedDict( + "DeploymentsUpdateResponseVariant1", + { + "success": Literal[True], + "status": Literal["creating", "deploying", "ready", "stopping", "stopped", "failed"], + "message": str, + }, +) + + +DeploymentsUpdateResponseVariant2 = TypedDict( + "DeploymentsUpdateResponseVariant2", + {"success": Literal[True], "status": Literal["deploying", "stopping"], "message": str}, +) + + +DeploymentsUpdateResponse = DeploymentsUpdateResponseVariant1 | DeploymentsUpdateResponseVariant2 + + +DeploymentsDeleteResponse = TypedDict("DeploymentsDeleteResponse", {"success": Literal[True]}) + + +DeploymentsHealthResponse = TypedDict( + "DeploymentsHealthResponse", + {"healthy": bool, "status": NotRequired[float], "latencyMs": float, "error": NotRequired[str]}, +) + + +DeploymentsLogsResponseEntriesItemHttpRequest = TypedDict( + "DeploymentsLogsResponseEntriesItemHttpRequest", + {"method": str, "url": str, "status": float, "latencyMs": float, "userAgent": NotRequired[str]}, +) + + +DeploymentsLogsResponseEntriesItem = TypedDict( + "DeploymentsLogsResponseEntriesItem", + { + "timestamp": str, + "severity": Literal["DEFAULT", "DEBUG", "INFO", "NOTICE", "WARNING", "ERROR", "CRITICAL", "ALERT", "EMERGENCY"], + "message": str, + "httpRequest": NotRequired[DeploymentsLogsResponseEntriesItemHttpRequest], + }, +) + + +DeploymentsLogsResponse = TypedDict( + "DeploymentsLogsResponse", {"entries": list[DeploymentsLogsResponseEntriesItem], "nextPageToken": NotRequired[str]} +) + + +DeploymentsMetricsResponseVariant1TimeRange = TypedDict( + "DeploymentsMetricsResponseVariant1TimeRange", {"start": str, "end": str} +) + + +DeploymentsMetricsResponseVariant1Summary = TypedDict( + "DeploymentsMetricsResponseVariant1Summary", + { + "totalRequests": float, + "errorCount": float, + "errorRate": float, + "avgLatencyMs": float, + "p50LatencyMs": float, + "p95LatencyMs": float, + "p99LatencyMs": float, + }, +) + + +DeploymentsMetricsResponseVariant1TimeSeriesRequestsItem = TypedDict( + "DeploymentsMetricsResponseVariant1TimeSeriesRequestsItem", {"timestamp": str, "value": float} +) + + +DeploymentsMetricsResponseVariant1TimeSeriesErrorsItem = TypedDict( + "DeploymentsMetricsResponseVariant1TimeSeriesErrorsItem", {"timestamp": str, "value": float} +) + + +DeploymentsMetricsResponseVariant1TimeSeriesLatencyP50Item = TypedDict( + "DeploymentsMetricsResponseVariant1TimeSeriesLatencyP50Item", {"timestamp": str, "value": float} +) + + +DeploymentsMetricsResponseVariant1TimeSeriesLatencyP95Item = TypedDict( + "DeploymentsMetricsResponseVariant1TimeSeriesLatencyP95Item", {"timestamp": str, "value": float} +) + + +DeploymentsMetricsResponseVariant1TimeSeriesCpuUtilizationItem = TypedDict( + "DeploymentsMetricsResponseVariant1TimeSeriesCpuUtilizationItem", {"timestamp": str, "value": float} +) + + +DeploymentsMetricsResponseVariant1TimeSeriesMemoryUtilizationItem = TypedDict( + "DeploymentsMetricsResponseVariant1TimeSeriesMemoryUtilizationItem", {"timestamp": str, "value": float} +) + + +DeploymentsMetricsResponseVariant1TimeSeriesInstanceCountItem = TypedDict( + "DeploymentsMetricsResponseVariant1TimeSeriesInstanceCountItem", {"timestamp": str, "value": float} +) + + +DeploymentsMetricsResponseVariant1TimeSeries = TypedDict( + "DeploymentsMetricsResponseVariant1TimeSeries", + { + "requests": list[DeploymentsMetricsResponseVariant1TimeSeriesRequestsItem], + "errors": list[DeploymentsMetricsResponseVariant1TimeSeriesErrorsItem], + "latencyP50": list[DeploymentsMetricsResponseVariant1TimeSeriesLatencyP50Item], + "latencyP95": list[DeploymentsMetricsResponseVariant1TimeSeriesLatencyP95Item], + "cpuUtilization": list[DeploymentsMetricsResponseVariant1TimeSeriesCpuUtilizationItem], + "memoryUtilization": list[DeploymentsMetricsResponseVariant1TimeSeriesMemoryUtilizationItem], + "instanceCount": list[DeploymentsMetricsResponseVariant1TimeSeriesInstanceCountItem], + }, +) + + +DeploymentsMetricsResponseVariant1 = TypedDict( + "DeploymentsMetricsResponseVariant1", + { + "deploymentId": str, + "region": str, + "timeRange": DeploymentsMetricsResponseVariant1TimeRange, + "summary": DeploymentsMetricsResponseVariant1Summary, + "timeSeries": DeploymentsMetricsResponseVariant1TimeSeries, + }, +) + + +DeploymentsMetricsResponseVariant2TimeRange = TypedDict( + "DeploymentsMetricsResponseVariant2TimeRange", {"start": str, "end": str} +) + + +DeploymentsMetricsResponseVariant2Summary = TypedDict( + "DeploymentsMetricsResponseVariant2Summary", {"totalRequests": float, "errorRate": float, "p95LatencyMs": float} +) + + +DeploymentsMetricsResponseVariant2TimeSeriesRequestsItem = TypedDict( + "DeploymentsMetricsResponseVariant2TimeSeriesRequestsItem", {"timestamp": str, "value": float} +) + + +DeploymentsMetricsResponseVariant2TimeSeriesErrorsItem = TypedDict( + "DeploymentsMetricsResponseVariant2TimeSeriesErrorsItem", {"timestamp": str, "value": float} +) + + +DeploymentsMetricsResponseVariant2TimeSeriesLatencyP95Item = TypedDict( + "DeploymentsMetricsResponseVariant2TimeSeriesLatencyP95Item", {"timestamp": str, "value": float} +) + + +DeploymentsMetricsResponseVariant2TimeSeries = TypedDict( + "DeploymentsMetricsResponseVariant2TimeSeries", + { + "requests": list[DeploymentsMetricsResponseVariant2TimeSeriesRequestsItem], + "errors": list[DeploymentsMetricsResponseVariant2TimeSeriesErrorsItem], + "latencyP95": list[DeploymentsMetricsResponseVariant2TimeSeriesLatencyP95Item], + }, +) + + +DeploymentsMetricsResponseVariant2 = TypedDict( + "DeploymentsMetricsResponseVariant2", + { + "deploymentId": str, + "region": str, + "timeRange": DeploymentsMetricsResponseVariant2TimeRange, + "summary": DeploymentsMetricsResponseVariant2Summary, + "timeSeries": DeploymentsMetricsResponseVariant2TimeSeries, + }, +) + + +DeploymentsMetricsResponseVariant3 = TypedDict( + "DeploymentsMetricsResponseVariant3", + {"requests24h": list[float], "totalRequests": float, "errorRate": float, "avgLatencyMs": float}, +) + + +DeploymentsMetricsResponse = ( + DeploymentsMetricsResponseVariant1 | DeploymentsMetricsResponseVariant2 | DeploymentsMetricsResponseVariant3 +) + + +DeploymentsPredictResponseImagesItemSpeed = TypedDict( + "DeploymentsPredictResponseImagesItemSpeed", {"preprocess": float, "inference": float, "postprocess": float} +) + + +DeploymentsPredictResponseImagesItemResultsItemBox = TypedDict( + "DeploymentsPredictResponseImagesItemResultsItemBox", + { + "x1": float, + "y1": float, + "x2": float, + "y2": float, + "x3": NotRequired[float], + "y3": NotRequired[float], + "x4": NotRequired[float], + "y4": NotRequired[float], + }, +) + + +DeploymentsPredictResponseImagesItemResultsItemSegments = TypedDict( + "DeploymentsPredictResponseImagesItemResultsItemSegments", {"x": list[float], "y": list[float]} +) + + +DeploymentsPredictResponseImagesItemResultsItemKeypoints = TypedDict( + "DeploymentsPredictResponseImagesItemResultsItemKeypoints", + {"x": list[float], "y": list[float], "visible": NotRequired[list[float]]}, +) + + +DeploymentsPredictResponseImagesItemResultsItem = TypedDict( + "DeploymentsPredictResponseImagesItemResultsItem", + { + "name": str, + "class": int, + "confidence": NotRequired[float], + "pixel_ratio": NotRequired[float], + "box": NotRequired[DeploymentsPredictResponseImagesItemResultsItemBox], + "segments": NotRequired[DeploymentsPredictResponseImagesItemResultsItemSegments], + "keypoints": NotRequired[DeploymentsPredictResponseImagesItemResultsItemKeypoints], + }, +) + + +DeploymentsPredictResponseImagesItemSemanticMask = TypedDict( + "DeploymentsPredictResponseImagesItemSemanticMask", {"shape": list[float], "encoding": Literal["png"], "data": str} +) + + +DeploymentsPredictResponseImagesItemDepth = TypedDict( + "DeploymentsPredictResponseImagesItemDepth", + { + "shape": list[float], + "encoding": Literal["png"], + "data": str, + "min": float, + "max": float, + "bits": Literal[8, 12, 16], + }, +) + + +DeploymentsPredictResponseImagesItem = TypedDict( + "DeploymentsPredictResponseImagesItem", + { + "shape": list[float], + "speed": DeploymentsPredictResponseImagesItemSpeed, + "results": list[DeploymentsPredictResponseImagesItemResultsItem], + "semantic_mask": NotRequired[DeploymentsPredictResponseImagesItemSemanticMask], + "depth": NotRequired[DeploymentsPredictResponseImagesItemDepth], + }, +) + + +DeploymentsPredictResponseMetadata = TypedDict( + "DeploymentsPredictResponseMetadata", + { + "imageCount": int, + "classNames": NotRequired[list[str]], + "functionTimeAlive": float, + "functionTimeCall": float, + "model": NotRequired[str], + "task": NotRequired[Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"] | None], + "version": dict[str, str], + }, +) + + +DeploymentsPredictResponse = TypedDict( + "DeploymentsPredictResponse", + {"images": list[DeploymentsPredictResponseImagesItem], "metadata": DeploymentsPredictResponseMetadata}, +) + + +DeploymentsListResponseDeploymentsItemResources = TypedDict( + "DeploymentsListResponseDeploymentsItemResources", + {"cpu": float, "memoryGi": float, "minInstances": float, "maxInstances": float}, +) + + +DeploymentsListResponseDeploymentsItem = TypedDict( + "DeploymentsListResponseDeploymentsItem", + { + "id": str, + "owner": str, + "project": NotRequired[str], + "model": NotRequired[str], + "task": NotRequired[Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"]], + "deployment": str, + "name": str, + "status": Literal["creating", "deploying", "ready", "stopping", "stopped", "failed"], + "statusMessage": NotRequired[str], + "region": str, + "serviceUrl": NotRequired[str], + "resources": DeploymentsListResponseDeploymentsItemResources, + "metered": NotRequired[bool], + "deployedAt": NotRequired[str], + "apiKeyId": NotRequired[str], + "createdAt": str, + "updatedAt": str, + }, +) + + +DeploymentsListResponse = TypedDict( + "DeploymentsListResponse", + {"deployments": list[DeploymentsListResponseDeploymentsItem], "total": float, "region": Literal["us", "eu", "ap"]}, +) + + +DeploymentsCreateResponse = TypedDict( + "DeploymentsCreateResponse", + {"id": str, "deployment": str, "status": Literal["creating"], "message": str, "region": str}, +) + + +ExploreSearchResponseProjectsItem = TypedDict( + "ExploreSearchResponseProjectsItem", + { + "id": str, + "project": str, + "name": str, + "description": NotRequired[str], + "owner": str, + "visibility": Literal["public", "private"], + "iconColor": NotRequired[str], + "iconLetter": NotRequired[str], + "iconImage": NotRequired[str], + "modelCount": int, + "modelNames": list[str], + "totalBytes": float, + "starCount": int, + "userImageUrl": NotRequired[str], + "updatedAt": str, + }, +) + + +ExploreSearchResponseDatasetsItemSplits = TypedDict( + "ExploreSearchResponseDatasetsItemSplits", {"train": int, "val": int, "test": int, "labeled": int} +) + + +ExploreSearchResponseDatasetsItemSampleImagesItemLabelsItem = TypedDict( + "ExploreSearchResponseDatasetsItemSampleImagesItemLabelsItem", + { + "classId": int, + "bbox": NotRequired[list[Any]], + "segments": NotRequired[list[float]], + "keypoints": NotRequired[list[float]], + "obb": NotRequired[list[Any]], + "skeletonId": NotRequired[str], + }, +) + + +ExploreSearchResponseDatasetsItemSampleImagesItem = TypedDict( + "ExploreSearchResponseDatasetsItemSampleImagesItem", + { + "url": str, + "imageUrl": NotRequired[str], + "width": float, + "height": float, + "labels": NotRequired[list[ExploreSearchResponseDatasetsItemSampleImagesItemLabelsItem]], + }, +) + + +ExploreSearchResponseDatasetsItem = TypedDict( + "ExploreSearchResponseDatasetsItem", + { + "id": str, + "dataset": str, + "name": str, + "description": NotRequired[str], + "owner": str, + "visibility": Literal["public", "private"], + "imageCount": int, + "classCount": NotRequired[int], + "classNames": NotRequired[list[str]], + "classColors": NotRequired[dict[str, str]], + "task": Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"], + "totalBytes": NotRequired[float], + "tags": NotRequired[list[str]], + "splits": NotRequired[ExploreSearchResponseDatasetsItemSplits], + "kptShape": NotRequired[list[Any]], + "starCount": int, + "sampleImages": list[ExploreSearchResponseDatasetsItemSampleImagesItem], + "userImageUrl": NotRequired[str], + "updatedAt": str, + }, +) + + +ExploreSearchResponse = TypedDict( + "ExploreSearchResponse", + { + "projects": list[ExploreSearchResponseProjectsItem], + "datasets": list[ExploreSearchResponseDatasetsItem], + "hasMore": bool, + }, +) + + +ImagesRetrieveResponsePropertiesDepth = TypedDict( + "ImagesRetrieveResponsePropertiesDepth", + { + "hash": str, + "bytes": int, + "shape": list[int], + "min": NotRequired[float], + "max": NotRequired[float], + "validFraction": NotRequired[float], + }, +) + + +ImagesRetrieveResponseProperties = TypedDict( + "ImagesRetrieveResponseProperties", + { + "id": str, + "datasetId": str, + "filename": str, + "hash": str, + "extension": str, + "originalExtension": NotRequired[str], + "originalPath": NotRequired[str], + "width": int, + "height": int, + "split": Literal["train", "val", "test"], + "annotationCount": int, + "classIds": NotRequired[list[int]], + "depth": NotRequired[ImagesRetrieveResponsePropertiesDepth], + "bytes": NotRequired[int], + "region": NotRequired[Literal["us", "eu", "ap"]], + "externalKey": NotRequired[str], + "externalRevision": NotRequired[str], + "retainedByVersion": bool, + "createdAt": str, + "updatedAt": NotRequired[str], + "error": NotRequired[str | None], + }, +) + + +ImagesRetrieveResponseLabelsItem = TypedDict( + "ImagesRetrieveResponseLabelsItem", + { + "classId": int, + "bbox": NotRequired[list[Any]], + "segments": NotRequired[list[float]], + "keypoints": NotRequired[list[float]], + "obb": NotRequired[list[Any]], + "skeletonId": NotRequired[str], + }, +) + + +ImagesRetrieveResponse = TypedDict( + "ImagesRetrieveResponse", + { + "metadata": dict[str, Any], + "properties": ImagesRetrieveResponseProperties, + "labels": list[ImagesRetrieveResponseLabelsItem], + "classNames": list[str], + "labelsTruncated": NotRequired[Literal[True]], + }, +) + + +ImagesUpdateResponseVariant1LabelsItem = TypedDict( + "ImagesUpdateResponseVariant1LabelsItem", + { + "classId": int, + "bbox": NotRequired[list[Any]], + "segments": NotRequired[list[float]], + "keypoints": NotRequired[list[float]], + "obb": NotRequired[list[Any]], + "skeletonId": NotRequired[str], + }, +) + + +ImagesUpdateResponseVariant1 = TypedDict( + "ImagesUpdateResponseVariant1", + {"success": Literal[True], "labels": list[ImagesUpdateResponseVariant1LabelsItem], "labelCount": int}, +) + + +ImagesUpdateResponseVariant2 = TypedDict("ImagesUpdateResponseVariant2", {"metadata": dict[str, Any], "updatedAt": str}) + + +ImagesUpdateResponse = ImagesUpdateResponseVariant1 | ImagesUpdateResponseVariant2 + + +ImagesDeleteResponse = TypedDict( + "ImagesDeleteResponse", {"success": Literal[True], "deletedImageId": str, "deletedCount": int} +) + + +ImagesPredictResponsePredictionsItem = TypedDict( + "ImagesPredictResponsePredictionsItem", + { + "classId": int, + "bbox": NotRequired[list[Any]], + "segments": NotRequired[list[float]], + "keypoints": NotRequired[list[float]], + "obb": NotRequired[list[Any]], + "skeletonId": NotRequired[str], + }, +) + + +ImagesPredictResponse = TypedDict( + "ImagesPredictResponse", + { + "success": Literal[True], + "predictions": list[ImagesPredictResponsePredictionsItem], + "partial": NotRequired[bool], + "confidences": NotRequired[list[float]], + "modelUsed": str, + "inferenceTime": NotRequired[float], + }, +) + + +ImagesFindSimilarImagesResponseImagesItemDataset = TypedDict( + "ImagesFindSimilarImagesResponseImagesItemDataset", + { + "owner": str, + "dataset": str, + "license": Literal[ + "None", + "CC0-1.0", + "PDM-1.0", + "CC-BY-2.5", + "CC-BY-3.0", + "CC-BY-4.0", + "CC-BY-NC-2.0", + "CC-BY-NC-3.0", + "CC-BY-NC-4.0", + "CC-BY-SA-3.0", + "CC-BY-SA-4.0", + "CC-BY-NC-SA-3.0", + "CC-BY-NC-SA-4.0", + "CC-BY-ND-4.0", + "CC-BY-NC-ND-2.0", + "CC-BY-NC-ND-4.0", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-2.0", + "GPL-3.0", + "LGPL-3.0", + "ODbL-1.0", + "DbCL-1.0", + "Research-Only", + "Other", + ], + }, +) + + +ImagesFindSimilarImagesResponseImagesItem = TypedDict( + "ImagesFindSimilarImagesResponseImagesItem", + { + "name": str, + "hash": str, + "width": int, + "height": int, + "id": str, + "thumbnailUrl": str, + "imageUrl": NotRequired[str], + "dataset": ImagesFindSimilarImagesResponseImagesItemDataset, + "score": float, + }, +) + + +ImagesFindSimilarImagesResponse = TypedDict( + "ImagesFindSimilarImagesResponse", {"images": list[ImagesFindSimilarImagesResponseImagesItem]} +) + + +ImagesUpdateBulkResponse = TypedDict( + "ImagesUpdateBulkResponse", + { + "success": Literal[True], + "modifiedCount": int, + "skippedCount": int, + "targetSplit": Literal["train", "val", "test"], + }, +) + + +ImagesDeleteBulkResponse = TypedDict( + "ImagesDeleteBulkResponse", {"success": Literal[True], "deletedCount": int, "deletedImageIds": list[str]} +) + + +ImagesUrlsResponseDepthsValue = TypedDict("ImagesUrlsResponseDepthsValue", {"previewUrl": str}) + + +ImagesUrlsResponse = TypedDict( + "ImagesUrlsResponse", + {"urls": dict[str, str], "thumbnails": dict[str, str], "depths": dict[str, ImagesUrlsResponseDepthsValue]}, +) + + +StorageIntegrationsDeleteResponse = TypedDict("StorageIntegrationsDeleteResponse", {"success": Literal[True]}) + + +StorageIntegrationsObjectsResponseEntriesItem = TypedDict( + "StorageIntegrationsObjectsResponseEntriesItem", + { + "kind": Literal["folder", "file"], + "name": str, + "key": str, + "size": NotRequired[float], + "updatedAt": NotRequired[str], + }, +) + + +StorageIntegrationsObjectsResponse = TypedDict( + "StorageIntegrationsObjectsResponse", + {"entries": list[StorageIntegrationsObjectsResponseEntriesItem], "cursor": NotRequired[str]}, +) + + +StorageIntegrationsListResponseIntegrationsItem = TypedDict( + "StorageIntegrationsListResponseIntegrationsItem", + { + "id": str, + "provider": Literal["gcs", "s3", "azure"], + "credentialIdentity": str, + "targets": list[str], + "createdAt": str, + }, +) + + +StorageIntegrationsListResponse = TypedDict( + "StorageIntegrationsListResponse", {"integrations": list[StorageIntegrationsListResponseIntegrationsItem]} +) + + +StorageIntegrationsCreateResponse = TypedDict( + "StorageIntegrationsCreateResponse", + { + "id": str, + "provider": Literal["gcs", "s3", "azure"], + "credentialIdentity": str, + "targets": list[str], + "createdAt": str, + }, +) + + +StorageIntegrationsDiscoverResponse = TypedDict("StorageIntegrationsDiscoverResponse", {"targets": list[str]}) + + +ModelsCloneResponse = TypedDict( + "ModelsCloneResponse", + {"id": str, "owner": str, "project": str, "model": str, "name": str, "region": Literal["us", "eu", "ap"]}, +) + + +ModelsRetrieveResponseVariant1ModelDatasetVersion = TypedDict( + "ModelsRetrieveResponseVariant1ModelDatasetVersion", {"version": int, "contentHash": str} +) + + +ModelsRetrieveResponseVariant1ModelSourceModel = TypedDict( + "ModelsRetrieveResponseVariant1ModelSourceModel", + { + "owner": str, + "project": str, + "projectName": str, + "projectIconColor": NotRequired[str], + "projectIconLetter": NotRequired[str], + "projectIconImage": NotRequired[str], + "model": str, + "modelName": str, + }, +) + + +ModelsRetrieveResponseVariant1ModelTrainResultsItem = TypedDict( + "ModelsRetrieveResponseVariant1ModelTrainResultsItem", + { + "epoch": NotRequired[int], + "metrics": NotRequired[dict[str, float]], + "fitness": NotRequired[float], + "timestamp": NotRequired[str], + }, +) + + +ModelsRetrieveResponseVariant1ModelFile = TypedDict("ModelsRetrieveResponseVariant1ModelFile", {"size": float}) + + +ModelsRetrieveResponseVariant1ModelTrainingError = TypedDict( + "ModelsRetrieveResponseVariant1ModelTrainingError", {"message": str, "code": NotRequired[str], "timestamp": str} +) + + +ModelsRetrieveResponseVariant1ModelComputeCost = TypedDict( + "ModelsRetrieveResponseVariant1ModelComputeCost", + { + "gpuType": NotRequired[str], + "gpuDisplayName": NotRequired[str], + "pricePerHour": float, + "totalCost": float, + "durationMs": NotRequired[float], + }, +) + + +ModelsRetrieveResponseVariant1ModelCloudJob = TypedDict( + "ModelsRetrieveResponseVariant1ModelCloudJob", {"gpuDisplayName": str} +) + + +ModelsRetrieveResponseVariant1ModelConsoleChunksItem = TypedDict( + "ModelsRetrieveResponseVariant1ModelConsoleChunksItem", + {"chunkId": float, "content": str, "lineCount": float, "timestamp": str}, +) + + +ModelsRetrieveResponseVariant1ModelDataset = TypedDict( + "ModelsRetrieveResponseVariant1ModelDataset", {"owner": str, "dataset": str} +) + + +ModelsRetrieveResponseVariant1Model = TypedDict( + "ModelsRetrieveResponseVariant1Model", + { + "id": str, + "owner": str, + "project": str, + "projectName": str, + "projectIconColor": NotRequired[str], + "projectIconLetter": NotRequired[str], + "projectIconImage": NotRequired[str], + "model": str, + "visibility": Literal["public", "private"], + "name": str, + "description": NotRequired[str], + "license": NotRequired[ + Literal[ + "None", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-3.0", + "LGPL-3.0", + "MPL-2.0", + "EUPL-1.1", + "Unlicense", + "CC0-1.0", + "Ultralytics-Enterprise", + "Other", + ] + ], + "status": NotRequired[ + Literal["pending", "untrained", "starting", "running", "completed", "failed", "cancelled"] + ], + "task": NotRequired[Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"]], + "depthScaleVerified": NotRequired[bool], + "color": NotRequired[str], + "datasetId": NotRequired[str], + "datasetVersion": NotRequired[ModelsRetrieveResponseVariant1ModelDatasetVersion], + "sourceModelId": NotRequired[str], + "sourceModel": NotRequired[ModelsRetrieveResponseVariant1ModelSourceModel], + "baseModel": NotRequired[str], + "epochs": NotRequired[int], + "bestEpoch": NotRequired[int | None], + "bestFitness": NotRequired[float | None], + "trainArgs": NotRequired[dict[str, Any]], + "metrics": NotRequired[dict[str, float]], + "trainResults": NotRequired[list[ModelsRetrieveResponseVariant1ModelTrainResultsItem]], + "hasWeights": bool, + "file": NotRequired[ModelsRetrieveResponseVariant1ModelFile], + "version": NotRequired[str], + "docs": NotRequired[str], + "startedAt": NotRequired[str], + "completedAt": NotRequired[str], + "classNames": NotRequired[list[str]], + "plots": NotRequired[list[Any]], + "trainingError": NotRequired[ModelsRetrieveResponseVariant1ModelTrainingError], + "starCount": int, + "isStarred": bool, + "clonedFrom": NotRequired[str], + "cloneCount": NotRequired[int], + "environment": NotRequired[dict[str, Any]], + "computeCost": NotRequired[ModelsRetrieveResponseVariant1ModelComputeCost], + "cloudJob": NotRequired[ModelsRetrieveResponseVariant1ModelCloudJob], + "consoleChunks": NotRequired[list[ModelsRetrieveResponseVariant1ModelConsoleChunksItem]], + "createdAt": str, + "updatedAt": str, + "metadata": dict[str, Any], + "dataset": NotRequired[ModelsRetrieveResponseVariant1ModelDataset], + }, +) + + +ModelsRetrieveResponseVariant1 = TypedDict( + "ModelsRetrieveResponseVariant1", {"model": ModelsRetrieveResponseVariant1Model, "isOwner": bool} +) + + +ModelsRetrieveResponseVariant2AnalysisCoverage = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisCoverage", + { + "mode": Literal["full", "sampled", "tails", "partial", "unavailable"], + "omittedMiddle": int, + "unmatchedExtremes": int, + }, +) + + +ModelsRetrieveResponseVariant2AnalysisScatterSample = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisScatterSample", {"eligible": int, "rows": list[list[Any]]} +) + + +ModelsRetrieveResponseVariant2AnalysisCohortsWorstMetricsF1 = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisCohortsWorstMetricsF1", + {"count": int, "min": float, "p25": float, "median": float, "p75": float, "max": float, "mean": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisCohortsWorstMetrics = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisCohortsWorstMetrics", + {"tp": int, "fp": int, "fn": int, "f1": ModelsRetrieveResponseVariant2AnalysisCohortsWorstMetricsF1 | None}, +) + + +ModelsRetrieveResponseVariant2AnalysisCohortsWorstExamplesItemLabelsItem = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisCohortsWorstExamplesItemLabelsItem", + { + "classId": int, + "bbox": NotRequired[list[Any]], + "segments": NotRequired[list[float]], + "keypoints": NotRequired[list[float]], + "obb": NotRequired[list[Any]], + "skeletonId": NotRequired[str], + }, +) + + +ModelsRetrieveResponseVariant2AnalysisCohortsWorstExamplesItem = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisCohortsWorstExamplesItem", + { + "imageId": NotRequired[str], + "hash": str, + "tp": int, + "fp": int, + "fn": int, + "f1": float, + "isEmptyGroundTruth": bool, + "width": NotRequired[float], + "height": NotRequired[float], + "pixels": NotRequired[float], + "aspectRatio": NotRequired[float], + "instanceCount": NotRequired[int], + "classIds": NotRequired[list[int]], + "labels": NotRequired[list[ModelsRetrieveResponseVariant2AnalysisCohortsWorstExamplesItemLabelsItem]], + }, +) + + +ModelsRetrieveResponseVariant2AnalysisCohortsWorst = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisCohortsWorst", + { + "count": int, + "matched": int, + "metrics": ModelsRetrieveResponseVariant2AnalysisCohortsWorstMetrics, + "examples": list[ModelsRetrieveResponseVariant2AnalysisCohortsWorstExamplesItem], + }, +) + + +ModelsRetrieveResponseVariant2AnalysisCohortsBestMetricsF1 = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisCohortsBestMetricsF1", + {"count": int, "min": float, "p25": float, "median": float, "p75": float, "max": float, "mean": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisCohortsBestMetrics = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisCohortsBestMetrics", + {"tp": int, "fp": int, "fn": int, "f1": ModelsRetrieveResponseVariant2AnalysisCohortsBestMetricsF1 | None}, +) + + +ModelsRetrieveResponseVariant2AnalysisCohortsBestExamplesItemLabelsItem = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisCohortsBestExamplesItemLabelsItem", + { + "classId": int, + "bbox": NotRequired[list[Any]], + "segments": NotRequired[list[float]], + "keypoints": NotRequired[list[float]], + "obb": NotRequired[list[Any]], + "skeletonId": NotRequired[str], + }, +) + + +ModelsRetrieveResponseVariant2AnalysisCohortsBestExamplesItem = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisCohortsBestExamplesItem", + { + "imageId": NotRequired[str], + "hash": str, + "tp": int, + "fp": int, + "fn": int, + "f1": float, + "isEmptyGroundTruth": bool, + "width": NotRequired[float], + "height": NotRequired[float], + "pixels": NotRequired[float], + "aspectRatio": NotRequired[float], + "instanceCount": NotRequired[int], + "classIds": NotRequired[list[int]], + "labels": NotRequired[list[ModelsRetrieveResponseVariant2AnalysisCohortsBestExamplesItemLabelsItem]], + }, +) + + +ModelsRetrieveResponseVariant2AnalysisCohortsBest = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisCohortsBest", + { + "count": int, + "matched": int, + "metrics": ModelsRetrieveResponseVariant2AnalysisCohortsBestMetrics, + "examples": list[ModelsRetrieveResponseVariant2AnalysisCohortsBestExamplesItem], + }, +) + + +ModelsRetrieveResponseVariant2AnalysisCohorts = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisCohorts", + { + "worst": ModelsRetrieveResponseVariant2AnalysisCohortsWorst, + "best": ModelsRetrieveResponseVariant2AnalysisCohortsBest, + }, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsWidthWorst = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsWidthWorst", + {"count": int, "min": float, "p25": float, "median": float, "p75": float, "max": float, "mean": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsWidthBest = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsWidthBest", + {"count": int, "min": float, "p25": float, "median": float, "p75": float, "max": float, "mean": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsWidthRelationshipFit = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsWidthRelationshipFit", + {"slope": float, "intercept": float, "pearsonR": float, "rSquared": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsWidthRelationshipCovariance = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsWidthRelationshipCovariance", + {"mean": list[Any], "eigenvalues": list[Any], "eigenvectors": list[Any]}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsWidthRelationship = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsWidthRelationship", + { + "count": int, + "fit": ModelsRetrieveResponseVariant2AnalysisComparisonsWidthRelationshipFit | None, + "covariance": ModelsRetrieveResponseVariant2AnalysisComparisonsWidthRelationshipCovariance | None, + }, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsWidth = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsWidth", + { + "worst": ModelsRetrieveResponseVariant2AnalysisComparisonsWidthWorst | None, + "best": ModelsRetrieveResponseVariant2AnalysisComparisonsWidthBest | None, + "relationship": ModelsRetrieveResponseVariant2AnalysisComparisonsWidthRelationship, + }, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsHeightWorst = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsHeightWorst", + {"count": int, "min": float, "p25": float, "median": float, "p75": float, "max": float, "mean": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsHeightBest = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsHeightBest", + {"count": int, "min": float, "p25": float, "median": float, "p75": float, "max": float, "mean": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsHeightRelationshipFit = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsHeightRelationshipFit", + {"slope": float, "intercept": float, "pearsonR": float, "rSquared": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsHeightRelationshipCovariance = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsHeightRelationshipCovariance", + {"mean": list[Any], "eigenvalues": list[Any], "eigenvectors": list[Any]}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsHeightRelationship = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsHeightRelationship", + { + "count": int, + "fit": ModelsRetrieveResponseVariant2AnalysisComparisonsHeightRelationshipFit | None, + "covariance": ModelsRetrieveResponseVariant2AnalysisComparisonsHeightRelationshipCovariance | None, + }, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsHeight = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsHeight", + { + "worst": ModelsRetrieveResponseVariant2AnalysisComparisonsHeightWorst | None, + "best": ModelsRetrieveResponseVariant2AnalysisComparisonsHeightBest | None, + "relationship": ModelsRetrieveResponseVariant2AnalysisComparisonsHeightRelationship, + }, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsWorst = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsWorst", + {"count": int, "min": float, "p25": float, "median": float, "p75": float, "max": float, "mean": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsBest = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsBest", + {"count": int, "min": float, "p25": float, "median": float, "p75": float, "max": float, "mean": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsRelationshipFit = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsRelationshipFit", + {"slope": float, "intercept": float, "pearsonR": float, "rSquared": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsRelationshipCovariance = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsRelationshipCovariance", + {"mean": list[Any], "eigenvalues": list[Any], "eigenvectors": list[Any]}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsRelationship = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsRelationship", + { + "count": int, + "fit": ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsRelationshipFit | None, + "covariance": ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsRelationshipCovariance | None, + }, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsPixels = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsPixels", + { + "worst": ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsWorst | None, + "best": ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsBest | None, + "relationship": ModelsRetrieveResponseVariant2AnalysisComparisonsPixelsRelationship, + }, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioWorst = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioWorst", + {"count": int, "min": float, "p25": float, "median": float, "p75": float, "max": float, "mean": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioBest = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioBest", + {"count": int, "min": float, "p25": float, "median": float, "p75": float, "max": float, "mean": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioRelationshipFit = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioRelationshipFit", + {"slope": float, "intercept": float, "pearsonR": float, "rSquared": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioRelationshipCovariance = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioRelationshipCovariance", + {"mean": list[Any], "eigenvalues": list[Any], "eigenvectors": list[Any]}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioRelationship = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioRelationship", + { + "count": int, + "fit": ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioRelationshipFit | None, + "covariance": ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioRelationshipCovariance | None, + }, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatio = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatio", + { + "worst": ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioWorst | None, + "best": ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioBest | None, + "relationship": ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatioRelationship, + }, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountWorst = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountWorst", + {"count": int, "min": float, "p25": float, "median": float, "p75": float, "max": float, "mean": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountBest = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountBest", + {"count": int, "min": float, "p25": float, "median": float, "p75": float, "max": float, "mean": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountRelationshipFit = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountRelationshipFit", + {"slope": float, "intercept": float, "pearsonR": float, "rSquared": float}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountRelationshipCovariance = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountRelationshipCovariance", + {"mean": list[Any], "eigenvalues": list[Any], "eigenvectors": list[Any]}, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountRelationship = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountRelationship", + { + "count": int, + "fit": ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountRelationshipFit | None, + "covariance": ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountRelationshipCovariance | None, + }, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCount = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCount", + { + "worst": ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountWorst | None, + "best": ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountBest | None, + "relationship": ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCountRelationship, + }, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsClassPresenceItemWorst = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsClassPresenceItemWorst", {"count": int, "prevalence": float} +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsClassPresenceItemBest = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsClassPresenceItemBest", {"count": int, "prevalence": float} +) + + +ModelsRetrieveResponseVariant2AnalysisComparisonsClassPresenceItem = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisonsClassPresenceItem", + { + "classId": int, + "name": str, + "worst": ModelsRetrieveResponseVariant2AnalysisComparisonsClassPresenceItemWorst, + "best": ModelsRetrieveResponseVariant2AnalysisComparisonsClassPresenceItemBest, + "prevalenceDifference": float, + }, +) + + +ModelsRetrieveResponseVariant2AnalysisComparisons = TypedDict( + "ModelsRetrieveResponseVariant2AnalysisComparisons", + { + "width": ModelsRetrieveResponseVariant2AnalysisComparisonsWidth, + "height": ModelsRetrieveResponseVariant2AnalysisComparisonsHeight, + "pixels": ModelsRetrieveResponseVariant2AnalysisComparisonsPixels, + "aspectRatio": ModelsRetrieveResponseVariant2AnalysisComparisonsAspectRatio, + "instanceCount": ModelsRetrieveResponseVariant2AnalysisComparisonsInstanceCount, + "classPresence": list[ModelsRetrieveResponseVariant2AnalysisComparisonsClassPresenceItem], + "classPresenceTruncated": bool, + }, +) + + +ModelsRetrieveResponseVariant2Analysis = TypedDict( + "ModelsRetrieveResponseVariant2Analysis", + { + "population": int, + "retained": int, + "matched": int, + "unmatched": int, + "traitsAvailable": bool, + "sourceSplit": Literal["train", "val"] | None, + "coverage": ModelsRetrieveResponseVariant2AnalysisCoverage, + "scatterSample": ModelsRetrieveResponseVariant2AnalysisScatterSample, + "cohorts": ModelsRetrieveResponseVariant2AnalysisCohorts, + "comparisons": ModelsRetrieveResponseVariant2AnalysisComparisons | None, + }, +) + + +ModelsRetrieveResponseVariant2 = TypedDict( + "ModelsRetrieveResponseVariant2", {"analysis": ModelsRetrieveResponseVariant2Analysis | None} +) + + +ModelsRetrieveResponse = ModelsRetrieveResponseVariant1 | ModelsRetrieveResponseVariant2 + + +ModelsUpdateResponseVariant1 = TypedDict( + "ModelsUpdateResponseVariant1", {"success": Literal[True], "model": str, "datasetLinked": NotRequired[bool]} +) + + +ModelsUpdateResponseVariant2 = TypedDict( + "ModelsUpdateResponseVariant2", + { + "success": Literal[True], + "slug": str, + "name": NotRequired[str], + "renamed": NotRequired[bool], + "projectSlug": NotRequired[str], + }, +) + + +ModelsUpdateResponseVariant3 = TypedDict("ModelsUpdateResponseVariant3", {"starred": bool, "starCount": int}) + + +ModelsUpdateResponse = ModelsUpdateResponseVariant1 | ModelsUpdateResponseVariant2 | ModelsUpdateResponseVariant3 + + +ModelsDeleteResponse = TypedDict("ModelsDeleteResponse", {"success": Literal[True]}) + + +ModelsFilesResponseFilesItem = TypedDict( + "ModelsFilesResponseFilesItem", {"name": str, "size": float, "downloadUrl": str} +) + + +ModelsFilesResponse = TypedDict("ModelsFilesResponse", {"files": list[ModelsFilesResponseFilesItem]}) + + +ModelsPredictResponseImagesItemSpeed = TypedDict( + "ModelsPredictResponseImagesItemSpeed", {"preprocess": float, "inference": float, "postprocess": float} +) + + +ModelsPredictResponseImagesItemResultsItemBox = TypedDict( + "ModelsPredictResponseImagesItemResultsItemBox", + { + "x1": float, + "y1": float, + "x2": float, + "y2": float, + "x3": NotRequired[float], + "y3": NotRequired[float], + "x4": NotRequired[float], + "y4": NotRequired[float], + }, +) + + +ModelsPredictResponseImagesItemResultsItemSegments = TypedDict( + "ModelsPredictResponseImagesItemResultsItemSegments", {"x": list[float], "y": list[float]} +) + + +ModelsPredictResponseImagesItemResultsItemKeypoints = TypedDict( + "ModelsPredictResponseImagesItemResultsItemKeypoints", + {"x": list[float], "y": list[float], "visible": NotRequired[list[float]]}, +) + + +ModelsPredictResponseImagesItemResultsItem = TypedDict( + "ModelsPredictResponseImagesItemResultsItem", + { + "name": str, + "class": int, + "confidence": NotRequired[float], + "pixel_ratio": NotRequired[float], + "box": NotRequired[ModelsPredictResponseImagesItemResultsItemBox], + "segments": NotRequired[ModelsPredictResponseImagesItemResultsItemSegments], + "keypoints": NotRequired[ModelsPredictResponseImagesItemResultsItemKeypoints], + }, +) + + +ModelsPredictResponseImagesItemSemanticMask = TypedDict( + "ModelsPredictResponseImagesItemSemanticMask", {"shape": list[float], "encoding": Literal["png"], "data": str} +) + + +ModelsPredictResponseImagesItemDepth = TypedDict( + "ModelsPredictResponseImagesItemDepth", + { + "shape": list[float], + "encoding": Literal["png"], + "data": str, + "min": float, + "max": float, + "bits": Literal[8, 12, 16], + }, +) + + +ModelsPredictResponseImagesItem = TypedDict( + "ModelsPredictResponseImagesItem", + { + "shape": list[float], + "speed": ModelsPredictResponseImagesItemSpeed, + "results": list[ModelsPredictResponseImagesItemResultsItem], + "semantic_mask": NotRequired[ModelsPredictResponseImagesItemSemanticMask], + "depth": NotRequired[ModelsPredictResponseImagesItemDepth], + }, +) + + +ModelsPredictResponseMetadata = TypedDict( + "ModelsPredictResponseMetadata", + { + "imageCount": int, + "classNames": NotRequired[list[str]], + "functionTimeAlive": float, + "functionTimeCall": float, + "model": NotRequired[str], + "task": NotRequired[Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"] | None], + "version": dict[str, str], + }, +) + + +ModelsPredictResponse = TypedDict( + "ModelsPredictResponse", + {"images": list[ModelsPredictResponseImagesItem], "metadata": ModelsPredictResponseMetadata}, +) + + +ModelsFindSimilarTrainingImagesResponseImagesItemDataset = TypedDict( + "ModelsFindSimilarTrainingImagesResponseImagesItemDataset", + { + "owner": str, + "dataset": str, + "license": Literal[ + "None", + "CC0-1.0", + "PDM-1.0", + "CC-BY-2.5", + "CC-BY-3.0", + "CC-BY-4.0", + "CC-BY-NC-2.0", + "CC-BY-NC-3.0", + "CC-BY-NC-4.0", + "CC-BY-SA-3.0", + "CC-BY-SA-4.0", + "CC-BY-NC-SA-3.0", + "CC-BY-NC-SA-4.0", + "CC-BY-ND-4.0", + "CC-BY-NC-ND-2.0", + "CC-BY-NC-ND-4.0", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-2.0", + "GPL-3.0", + "LGPL-3.0", + "ODbL-1.0", + "DbCL-1.0", + "Research-Only", + "Other", + ], + }, +) + + +ModelsFindSimilarTrainingImagesResponseImagesItem = TypedDict( + "ModelsFindSimilarTrainingImagesResponseImagesItem", + { + "name": str, + "hash": str, + "width": int, + "height": int, + "id": str, + "thumbnailUrl": str, + "imageUrl": NotRequired[str], + "dataset": ModelsFindSimilarTrainingImagesResponseImagesItemDataset, + "score": float, + }, +) + + +ModelsFindSimilarTrainingImagesResponse = TypedDict( + "ModelsFindSimilarTrainingImagesResponse", {"images": list[ModelsFindSimilarTrainingImagesResponseImagesItem]} +) + + +ModelsTrainingResponseJobProgress = TypedDict( + "ModelsTrainingResponseJobProgress", + { + "currentEpoch": float, + "totalEpochs": float, + "startedAt": NotRequired[str], + "completedAt": NotRequired[str], + "percentage": float, + }, +) + + +ModelsTrainingResponseJobTiming = TypedDict( + "ModelsTrainingResponseJobTiming", {"elapsedMs": float, "timePerEpochMs": float, "etaMs": float} +) + + +ModelsTrainingResponseJobCompute = TypedDict( + "ModelsTrainingResponseJobCompute", {"gpuType": str, "gpuDisplayName": str, "gpuMemoryGb": float} +) + + +ModelsTrainingResponseJobTrainArgs = TypedDict( + "ModelsTrainingResponseJobTrainArgs", + {"model": NotRequired[str], "epochs": NotRequired[float], "batch": NotRequired[float], "imgsz": NotRequired[float]}, +) + + +ModelsTrainingResponseJobError = TypedDict( + "ModelsTrainingResponseJobError", {"message": str, "code": NotRequired[str], "timestamp": str} +) + + +ModelsTrainingResponseJob = TypedDict( + "ModelsTrainingResponseJob", + { + "id": str, + "status": Literal["pending", "untrained", "starting", "running", "completed", "failed", "cancelled"], + "progress": ModelsTrainingResponseJobProgress, + "timing": ModelsTrainingResponseJobTiming, + "compute": ModelsTrainingResponseJobCompute | None, + "trainArgs": ModelsTrainingResponseJobTrainArgs | None, + "epochMetrics": dict[str, Any] | None, + "error": ModelsTrainingResponseJobError | None, + "createdAt": str, + "updatedAt": str, + }, +) + + +ModelsTrainingResponse = TypedDict("ModelsTrainingResponse", {"job": ModelsTrainingResponseJob | None}) + + +ModelsDeleteTrainingResponse = TypedDict( + "ModelsDeleteTrainingResponse", + {"success": Literal[True], "status": Literal["cancelled"], "warning": NotRequired[str]}, +) + + +ModelsListResponseModelsItemDatasetVersion = TypedDict( + "ModelsListResponseModelsItemDatasetVersion", {"version": int, "contentHash": str} +) + + +ModelsListResponseModelsItemSourceModel = TypedDict( + "ModelsListResponseModelsItemSourceModel", + { + "owner": str, + "project": str, + "projectName": str, + "projectIconColor": NotRequired[str], + "projectIconLetter": NotRequired[str], + "projectIconImage": NotRequired[str], + "model": str, + "modelName": str, + }, +) + + +ModelsListResponseModelsItemTrainResultsItem = TypedDict( + "ModelsListResponseModelsItemTrainResultsItem", + { + "epoch": NotRequired[int], + "metrics": NotRequired[dict[str, float]], + "fitness": NotRequired[float], + "timestamp": NotRequired[str], + }, +) + + +ModelsListResponseModelsItemFile = TypedDict("ModelsListResponseModelsItemFile", {"size": float}) + + +ModelsListResponseModelsItemTrainingError = TypedDict( + "ModelsListResponseModelsItemTrainingError", {"message": str, "code": NotRequired[str], "timestamp": str} +) + + +ModelsListResponseModelsItemComputeCost = TypedDict( + "ModelsListResponseModelsItemComputeCost", + { + "gpuType": NotRequired[str], + "gpuDisplayName": NotRequired[str], + "pricePerHour": float, + "totalCost": float, + "durationMs": NotRequired[float], + }, +) + + +ModelsListResponseModelsItemCloudJob = TypedDict("ModelsListResponseModelsItemCloudJob", {"gpuDisplayName": str}) + + +ModelsListResponseModelsItemConsoleChunksItem = TypedDict( + "ModelsListResponseModelsItemConsoleChunksItem", + {"chunkId": float, "content": str, "lineCount": float, "timestamp": str}, +) + + +ModelsListResponseModelsItem = TypedDict( + "ModelsListResponseModelsItem", + { + "id": str, + "owner": str, + "project": str, + "projectName": str, + "projectIconColor": NotRequired[str], + "projectIconLetter": NotRequired[str], + "projectIconImage": NotRequired[str], + "model": str, + "visibility": Literal["public", "private"], + "name": str, + "description": NotRequired[str], + "license": NotRequired[ + Literal[ + "None", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-3.0", + "LGPL-3.0", + "MPL-2.0", + "EUPL-1.1", + "Unlicense", + "CC0-1.0", + "Ultralytics-Enterprise", + "Other", + ] + ], + "status": NotRequired[ + Literal["pending", "untrained", "starting", "running", "completed", "failed", "cancelled"] + ], + "task": NotRequired[Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"]], + "depthScaleVerified": NotRequired[bool], + "color": NotRequired[str], + "datasetId": NotRequired[str], + "datasetVersion": NotRequired[ModelsListResponseModelsItemDatasetVersion], + "sourceModelId": NotRequired[str], + "sourceModel": NotRequired[ModelsListResponseModelsItemSourceModel], + "baseModel": NotRequired[str], + "epochs": NotRequired[int], + "bestEpoch": NotRequired[int | None], + "bestFitness": NotRequired[float | None], + "trainArgs": NotRequired[dict[str, Any]], + "metrics": NotRequired[dict[str, float]], + "trainResults": NotRequired[list[ModelsListResponseModelsItemTrainResultsItem]], + "hasWeights": bool, + "file": NotRequired[ModelsListResponseModelsItemFile], + "version": NotRequired[str], + "docs": NotRequired[str], + "startedAt": NotRequired[str], + "completedAt": NotRequired[str], + "classNames": NotRequired[list[str]], + "plots": NotRequired[list[Any]], + "trainingError": NotRequired[ModelsListResponseModelsItemTrainingError], + "starCount": int, + "isStarred": bool, + "clonedFrom": NotRequired[str], + "cloneCount": NotRequired[int], + "environment": NotRequired[dict[str, Any]], + "computeCost": NotRequired[ModelsListResponseModelsItemComputeCost], + "cloudJob": NotRequired[ModelsListResponseModelsItemCloudJob], + "consoleChunks": NotRequired[list[ModelsListResponseModelsItemConsoleChunksItem]], + "createdAt": str, + "updatedAt": str, + }, +) + + +ModelsListResponse = TypedDict( + "ModelsListResponse", {"models": list[ModelsListResponseModelsItem], "region": Literal["us", "eu", "ap"]} +) + + +ModelsCreateResponse = TypedDict( + "ModelsCreateResponse", {"id": str, "owner": str, "project": str, "model": str, "region": Literal["us", "eu", "ap"]} +) + + +ModelsUploadCheckpointResponse = TypedDict( + "ModelsUploadCheckpointResponse", {"uploadUrl": str, "gcsPath": str, "uploadPath": NotRequired[str], "modelId": str} +) + + +ExportsRetrieveResponseExportFile = TypedDict( + "ExportsRetrieveResponseExportFile", + {"size": NotRequired[float], "downloadUrl": NotRequired[str], "downloadFilename": NotRequired[str]}, +) + + +ExportsRetrieveResponseExportError = TypedDict("ExportsRetrieveResponseExportError", {"message": str, "timestamp": str}) + + +ExportsRetrieveResponseExport = TypedDict( + "ExportsRetrieveResponseExport", + { + "id": str, + "status": Literal["queued", "starting", "running", "completed", "failed", "cancelled"], + "format": Literal[ + "onnx", + "torchscript", + "openvino", + "engine", + "coreml", + "coreai", + "litert", + "pb", + "saved_model", + "paddle", + "ncnn", + "edgetpu", + "mnn", + "rknn", + "qnn", + "imx", + "axelera", + "executorch", + "deepx", + "hailo", + "ascend", + ], + "args": NotRequired[dict[str, Any]], + "gpuType": NotRequired[str], + "file": NotRequired[ExportsRetrieveResponseExportFile], + "error": NotRequired[ExportsRetrieveResponseExportError], + "startedAt": NotRequired[str], + "completedAt": NotRequired[str], + "createdAt": str, + "updatedAt": str, + }, +) + + +ExportsRetrieveResponse = TypedDict("ExportsRetrieveResponse", {"export": ExportsRetrieveResponseExport}) + + +ExportsDeleteResponse = TypedDict( + "ExportsDeleteResponse", {"success": Literal[True], "action": Literal["cancelled", "deleted"]} +) + + +ExportsListResponse = TypedDict( + "ExportsListResponse", {"exports": list[ExportsRetrieveResponseExport], "region": Literal["us", "eu", "ap"]} +) + + +ExportsCreateResponse = TypedDict( + "ExportsCreateResponse", + { + "id": str, + "format": Literal[ + "onnx", + "torchscript", + "openvino", + "engine", + "coreml", + "coreai", + "litert", + "pb", + "saved_model", + "paddle", + "ncnn", + "edgetpu", + "mnn", + "rknn", + "qnn", + "imx", + "axelera", + "executorch", + "deepx", + "hailo", + "ascend", + ], + "status": Literal["queued", "running"], + "gpuType": NotRequired[str], + "region": Literal["us", "eu", "ap"], + }, +) + + +ProjectsCloneResponse = TypedDict( + "ProjectsCloneResponse", + {"id": str, "owner": str, "project": str, "name": str, "modelCount": int, "region": Literal["us", "eu", "ap"]}, +) + + +ProjectsRetrieveResponseProjectViewPreferences = TypedDict( + "ProjectsRetrieveResponseProjectViewPreferences", + { + "sortBy": NotRequired[Literal["newest", "oldest", "name-asc", "name-desc", "size-asc", "size-desc"]], + "groupBy": NotRequired[Literal["none", "task"]], + "statusFilter": NotRequired[Literal["all", "completed", "untrained", "running", "starting", "failed"]], + }, +) + + +ProjectsRetrieveResponseProject = TypedDict( + "ProjectsRetrieveResponseProject", + { + "id": str, + "owner": str, + "project": str, + "name": str, + "description": NotRequired[str], + "visibility": Literal["public", "private"], + "tags": NotRequired[list[str]], + "license": NotRequired[ + Literal[ + "None", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-3.0", + "LGPL-3.0", + "MPL-2.0", + "EUPL-1.1", + "Unlicense", + "CC0-1.0", + "Ultralytics-Enterprise", + "Other", + ] + ], + "iconColor": NotRequired[str], + "iconLetter": NotRequired[str], + "iconImage": NotRequired[str], + "modelCount": int, + "modelNames": NotRequired[list[str]], + "totalBytes": NotRequired[float], + "starCount": int, + "isStarred": bool, + "archived": NotRequired[bool], + "region": NotRequired[Literal["us", "eu", "ap"]], + "task": NotRequired[Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"]], + "clonedFrom": NotRequired[str], + "cloneCount": NotRequired[int], + "viewPreferences": NotRequired[ProjectsRetrieveResponseProjectViewPreferences], + "createdAt": str, + "updatedAt": str, + "metadata": dict[str, Any], + }, +) + + +ProjectsRetrieveResponseModelsItemFile = TypedDict("ProjectsRetrieveResponseModelsItemFile", {"size": float}) + + +ProjectsRetrieveResponseModelsItem = TypedDict( + "ProjectsRetrieveResponseModelsItem", + { + "id": str, + "model": str, + "name": str, + "color": NotRequired[str], + "task": NotRequired[Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"]], + "status": NotRequired[ + Literal["pending", "untrained", "starting", "running", "completed", "failed", "cancelled"] + ], + "epochs": NotRequired[int], + "bestEpoch": NotRequired[int | None], + "bestFitness": NotRequired[float | None], + "metrics": NotRequired[dict[str, float]], + "epochCount": int, + "startedAt": NotRequired[str], + "file": NotRequired[ProjectsRetrieveResponseModelsItemFile], + "hasWeights": bool, + "trainArgs": NotRequired[dict[str, Any]], + "createdAt": str, + "updatedAt": str, + }, +) + + +ProjectsRetrieveResponse = TypedDict( + "ProjectsRetrieveResponse", + {"project": ProjectsRetrieveResponseProject, "models": list[ProjectsRetrieveResponseModelsItem], "isOwner": bool}, +) + + +ProjectsUpdateResponseVariant1 = TypedDict("ProjectsUpdateResponseVariant1", {"success": Literal[True], "project": str}) + + +ProjectsUpdateResponseVariant2 = TypedDict("ProjectsUpdateResponseVariant2", {"starred": bool, "starCount": int}) + + +ProjectsUpdateResponse = ProjectsUpdateResponseVariant1 | ProjectsUpdateResponseVariant2 + + +ProjectsDeleteResponse = TypedDict("ProjectsDeleteResponse", {"success": Literal[True], "cascadedModels": int}) + + +ProjectsListResponseProjectsItemViewPreferences = TypedDict( + "ProjectsListResponseProjectsItemViewPreferences", + { + "sortBy": NotRequired[Literal["newest", "oldest", "name-asc", "name-desc", "size-asc", "size-desc"]], + "groupBy": NotRequired[Literal["none", "task"]], + "statusFilter": NotRequired[Literal["all", "completed", "untrained", "running", "starting", "failed"]], + }, +) + + +ProjectsListResponseProjectsItem = TypedDict( + "ProjectsListResponseProjectsItem", + { + "id": str, + "owner": str, + "project": str, + "name": str, + "description": NotRequired[str], + "visibility": Literal["public", "private"], + "tags": NotRequired[list[str]], + "license": NotRequired[ + Literal[ + "None", + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "AGPL-3.0", + "GPL-3.0", + "LGPL-3.0", + "MPL-2.0", + "EUPL-1.1", + "Unlicense", + "CC0-1.0", + "Ultralytics-Enterprise", + "Other", + ] + ], + "iconColor": NotRequired[str], + "iconLetter": NotRequired[str], + "iconImage": NotRequired[str], + "modelCount": int, + "modelNames": NotRequired[list[str]], + "totalBytes": NotRequired[float], + "starCount": int, + "isStarred": bool, + "archived": NotRequired[bool], + "region": NotRequired[Literal["us", "eu", "ap"]], + "task": NotRequired[Literal["detect", "segment", "semantic", "depth", "classify", "pose", "obb"]], + "clonedFrom": NotRequired[str], + "cloneCount": NotRequired[int], + "viewPreferences": NotRequired[ProjectsListResponseProjectsItemViewPreferences], + "createdAt": str, + "updatedAt": str, + }, +) + + +ProjectsListResponse = TypedDict( + "ProjectsListResponse", + {"projects": list[ProjectsListResponseProjectsItem], "total": int, "region": Literal["us", "eu", "ap"]}, +) + + +ProjectsCreateResponse = TypedDict( + "ProjectsCreateResponse", {"id": str, "owner": str, "project": str, "region": Literal["us", "eu", "ap"]} +) + + +TrainingGpuAvailabilityResponse = dict[str, Literal["High", "Medium", "Low"] | None] + + +TrainingStartResponseEstimatedCost = TypedDict( + "TrainingStartResponseEstimatedCost", {"pricePerHour": float, "gpuMemoryGb": float} +) + + +TrainingStartResponseBilling = TypedDict( + "TrainingStartResponseBilling", {"estimatedCostCents": float, "estimatedCostDisplay": str, "balanceCents": float} +) + + +TrainingStartResponse = TypedDict( + "TrainingStartResponse", + { + "modelId": str, + "status": Literal["starting"], + "gpuType": str, + "estimatedCost": TrainingStartResponseEstimatedCost, + "billing": TrainingStartResponseBilling, + }, +) + + +TrainingMetricsResponse = TypedDict( + "TrainingMetricsResponse", + { + "received": Literal[True], + "event": str, + "mode": NotRequired[Literal["cloud", "remote"]], + "modelId": NotRequired[str], + "runId": NotRequired[int], + "modelSlug": NotRequired[str], + "cancelled": NotRequired[bool], + "action": NotRequired[Literal["training_terminated"]], + "reason": NotRequired[str], + "warning": NotRequired[str], + "ignored": NotRequired[Literal["stale_instance"]], + }, +) + + +LifecycleTrashResponseVariant1ItemsItemParentProject = TypedDict( + "LifecycleTrashResponseVariant1ItemsItemParentProject", {"_id": str, "name": str, "slug": str} +) + + +LifecycleTrashResponseVariant1ItemsItem = TypedDict( + "LifecycleTrashResponseVariant1ItemsItem", + { + "_id": str, + "type": Literal["project", "dataset", "model"], + "name": str, + "slug": str, + "trashedAt": str, + "daysRemaining": int, + "cascadedCount": NotRequired[int], + "parentProject": NotRequired[LifecycleTrashResponseVariant1ItemsItemParentProject], + "sizeBytes": NotRequired[float], + }, +) + + +LifecycleTrashResponseVariant1SummaryByTypeProjects = TypedDict( + "LifecycleTrashResponseVariant1SummaryByTypeProjects", {"count": int} +) + + +LifecycleTrashResponseVariant1SummaryByTypeDatasets = TypedDict( + "LifecycleTrashResponseVariant1SummaryByTypeDatasets", {"count": int, "sizeBytes": float} +) + + +LifecycleTrashResponseVariant1SummaryByTypeModels = TypedDict( + "LifecycleTrashResponseVariant1SummaryByTypeModels", {"count": int, "sizeBytes": float} +) + + +LifecycleTrashResponseVariant1SummaryByTypeExports = TypedDict( + "LifecycleTrashResponseVariant1SummaryByTypeExports", {"count": int, "sizeBytes": float} +) + + +LifecycleTrashResponseVariant1SummaryByType = TypedDict( + "LifecycleTrashResponseVariant1SummaryByType", + { + "projects": LifecycleTrashResponseVariant1SummaryByTypeProjects, + "datasets": LifecycleTrashResponseVariant1SummaryByTypeDatasets, + "models": LifecycleTrashResponseVariant1SummaryByTypeModels, + "exports": LifecycleTrashResponseVariant1SummaryByTypeExports, + }, +) + + +LifecycleTrashResponseVariant1Summary = TypedDict( + "LifecycleTrashResponseVariant1Summary", + {"totalItems": int, "totalSizeBytes": float, "byType": LifecycleTrashResponseVariant1SummaryByType}, +) + + +LifecycleTrashResponseVariant1 = TypedDict( + "LifecycleTrashResponseVariant1", + { + "items": list[LifecycleTrashResponseVariant1ItemsItem], + "total": int, + "page": int, + "limit": int, + "totalPages": int, + "summary": LifecycleTrashResponseVariant1Summary, + "region": Literal["us", "eu", "ap"], + }, +) + + +LifecycleTrashResponseVariant2ResourcesItem = TypedDict( + "LifecycleTrashResponseVariant2ResourcesItem", + {"id": str, "type": Literal["project", "model", "deployment"], "name": str, "region": NotRequired[str]}, +) + + +LifecycleTrashResponseVariant2 = TypedDict( + "LifecycleTrashResponseVariant2", {"resources": list[LifecycleTrashResponseVariant2ResourcesItem]} +) + + +LifecycleTrashResponse = LifecycleTrashResponseVariant1 | LifecycleTrashResponseVariant2 + + +LifecycleRestoreResponse = TypedDict( + "LifecycleRestoreResponse", {"success": Literal[True], "restoredModels": NotRequired[int]} +) + + +LifecycleDeleteTrashResponse = TypedDict( + "LifecycleDeleteTrashResponse", + { + "success": Literal[True], + "deletedCount": int, + "cascadedModels": NotRequired[int], + "survivingDeployments": NotRequired[int], + }, +) + + +UploadCompleteResponseFile = TypedDict("UploadCompleteResponseFile", {"size": float, "contentType": NotRequired[str]}) + + +UploadCompleteResponse = TypedDict( + "UploadCompleteResponse", {"success": Literal[True], "file": UploadCompleteResponseFile} +) + + +UploadSignedUrlResponse = TypedDict( + "UploadSignedUrlResponse", + {"sessionId": str, "uploadUrl": str, "expiresAt": str, "headers": NotRequired[dict[str, str]]}, +) diff --git a/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/METADATA b/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..bf51fc88b04dcd5f17a7330361b8848e1575fb03 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/METADATA @@ -0,0 +1,205 @@ +Metadata-Version: 2.4 +Name: ultralytics-thop +Version: 2.1.6 +Summary: Ultralytics THOP package for fast computation of PyTorch model FLOPs and parameters. +Author-email: Ligeng Zhu +Maintainer-email: Ultralytics +License: AGPL-3.0 +Project-URL: Homepage, https://ultralytics.com +Project-URL: Source, https://github.com/ultralytics/thop +Project-URL: Documentation, https://docs.ultralytics.com +Project-URL: Bug Reports, https://github.com/ultralytics/thop/issues +Project-URL: Changelog, https://github.com/ultralytics/thop/releases +Keywords: FLOPs,PyTorch,Model Analysis +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+) +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Software Development +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Scientific/Engineering :: Image Recognition +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: MacOS +Classifier: Operating System :: Microsoft :: Windows +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: numpy +Requires-Dist: torch +Dynamic: license-file + +Ultralytics logo + +[English](README.md) | [简体中文](README.zh-CN.md) + +# 🚀 THOP: PyTorch-OpCounter + +[THOP](https://github.com/ultralytics/thop) profiles [PyTorch](https://pytorch.org/) models by counting Multiply-Accumulate Operations (MACs) and parameters. It is lightweight, easy to extend, and maintained by [Ultralytics](https://www.ultralytics.com/). + +[![THOP CI](https://github.com/ultralytics/thop/actions/workflows/ci.yml/badge.svg)](https://github.com/ultralytics/thop/actions/workflows/ci.yml) +[![Ultralytics Actions](https://github.com/ultralytics/thop/actions/workflows/format.yml/badge.svg)](https://github.com/ultralytics/thop/actions/workflows/format.yml) +[![Ultralytics Discord](https://img.shields.io/discord/1089800235347353640?logo=discord&logoColor=white&label=Discord&color=blue)](https://discord.com/invite/ultralytics) +[![Ultralytics Forums](https://img.shields.io/discourse/users?server=https%3A%2F%2Fcommunity.ultralytics.com&logo=discourse&label=Forums&color=blue)](https://community.ultralytics.com/) +[![Ultralytics Reddit](https://img.shields.io/reddit/subreddit-subscribers/ultralytics?style=flat&logo=reddit&logoColor=white&label=Reddit&color=blue)](https://reddit.com/r/ultralytics) + +## 📄 Description + +THOP measures a model with one forward pass, making it useful for comparing architecture complexity before training or deployment. It includes counting rules for common convolutional, normalization, pooling, activation, linear, and recurrent layers, with support for custom rules. + +## 📦 Installation + +[![PyPI - Version](https://img.shields.io/pypi/v/ultralytics-thop?logo=pypi&logoColor=white)](https://pypi.org/project/ultralytics-thop/) [![Downloads](https://static.pepy.tech/badge/ultralytics-thop)](https://clickpy.clickhouse.com/dashboard/ultralytics-thop) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/ultralytics-thop?logo=python&logoColor=gold)](https://pypi.org/project/ultralytics-thop/) + +```bash +pip install ultralytics-thop +``` + +To install the latest development version: + +```bash +pip install --upgrade git+https://github.com/ultralytics/thop.git +``` + +## 🛠️ How to Use + +### Basic Usage + +Pass the model and a tuple of example inputs to `profile()`: + +```python +import torch +from torchvision.models import resnet50 + +from thop import profile + +model = resnet50() +inputs = (torch.randn(1, 3, 224, 224),) +macs, params = profile(model, inputs=inputs) + +print(f"MACs: {macs}, Parameters: {params}") +# Expected output: MACs: 4133742592.0, Parameters: 25557032.0 +``` + +For image models, pass the target-size input and the model stride to estimate MACs from smaller stride-aligned +profiles. `profile()` retains a single-profile fast path for spatial-only models, fits two points when size-independent +operations may be present, and falls back to the target input when the smaller inputs are unsuitable: + +```python +inputs = (torch.randn(1, 3, 640, 640),) +macs, params = profile(model, inputs=inputs, stride=32) +``` + +Calls that omit `stride` retain the exact profiling behavior shown in the basic example. + +### Define Custom Rules for Third-Party Modules + +Map an unsupported module type to a forward-hook function. The hook receives the module, its inputs, and its output, then adds the operation count to `module.total_ops`. Parameters need no hook — they are read from the module tree. A rule covers subclasses of the type it is registered for, the nearest registered ancestor winning, so an entry for `nn.Conv2d` also counts an `nn.Conv2d` subclass. A subclass whose forward computes something different needs its own entry, or it is counted as its base. + +```python +import torch +from torch import nn + +from thop import profile + + +def count_silu(module, inputs, output): + """Count one operation per output element as a simple example.""" + module.total_ops += output.numel() + + +model = nn.Sequential(nn.Conv2d(3, 64, 3, padding=1), nn.SiLU()) +inputs = (torch.randn(1, 3, 224, 224),) +macs, params = profile(model, inputs=inputs, custom_ops={nn.SiLU: count_silu}) + +print(f"Custom MACs: {macs}, Parameters: {params}") +# Expected output: Custom MACs: 89915392.0, Parameters: 1792.0 +``` + +### Improve Output Readability + +Use `clever_format()` to convert raw counts into human-readable values: + +```python +import torch +from torchvision.models import resnet50 + +from thop import clever_format, profile + +model = resnet50() +inputs = (torch.randn(1, 3, 224, 224),) +macs, params = profile(model, inputs=inputs) +macs_readable, params_readable = clever_format([macs, params], "%.3f") + +print(f"Formatted MACs: {macs_readable}, Formatted Parameters: {params_readable}") +# Expected output: Formatted MACs: 4.134G, Formatted Parameters: 25.557M +``` + +## 📊 Results of Recent Models + +The following detection models were profiled at 640 × 640 from their fused architecture definitions using `ultralytics==8.4.106`. Install that version, then run `python benchmark/evaluate_famous_models.py` to reproduce the table without downloading model weights. FLOPs are often approximated as twice the MAC count. + +| Model | size
(pixels) | params
(M) | MACs
(B) | +| ---------------------------------------------------------------------- | --------------------------- | ------------------------ | ---------------------- | +| [YOLOv8n](https://platform.ultralytics.com/ultralytics/yolov8/yolov8n) | 640 | 3.15 | 4.37 | +| [YOLOv8s](https://platform.ultralytics.com/ultralytics/yolov8/yolov8s) | 640 | 11.16 | 14.30 | +| [YOLOv8m](https://platform.ultralytics.com/ultralytics/yolov8/yolov8m) | 640 | 25.89 | 39.47 | +| [YOLOv8l](https://platform.ultralytics.com/ultralytics/yolov8/yolov8l) | 640 | 43.67 | 82.57 | +| [YOLOv8x](https://platform.ultralytics.com/ultralytics/yolov8/yolov8x) | 640 | 68.20 | 128.90 | +| [YOLO11n](https://platform.ultralytics.com/ultralytics/yolo11/yolo11n) | 640 | 2.62 | 3.24 | +| [YOLO11s](https://platform.ultralytics.com/ultralytics/yolo11/yolo11s) | 640 | 9.44 | 10.73 | +| [YOLO11m](https://platform.ultralytics.com/ultralytics/yolo11/yolo11m) | 640 | 20.09 | 33.99 | +| [YOLO11l](https://platform.ultralytics.com/ultralytics/yolo11/yolo11l) | 640 | 25.34 | 43.46 | +| [YOLO11x](https://platform.ultralytics.com/ultralytics/yolo11/yolo11x) | 640 | 56.92 | 97.45 | +| [YOLO26n](https://platform.ultralytics.com/ultralytics/yolo26/yolo26n) | 640 | 2.41 | 2.68 | +| [YOLO26s](https://platform.ultralytics.com/ultralytics/yolo26/yolo26s) | 640 | 9.50 | 10.34 | +| [YOLO26m](https://platform.ultralytics.com/ultralytics/yolo26/yolo26m) | 640 | 20.41 | 34.09 | +| [YOLO26l](https://platform.ultralytics.com/ultralytics/yolo26/yolo26l) | 640 | 24.81 | 43.21 | +| [YOLO26x](https://platform.ultralytics.com/ultralytics/yolo26/yolo26x) | 640 | 55.73 | 96.93 | + +## 🤝 Contribute + +We thrive on community collaboration! THOP wouldn't be the tool it is without contributions from developers like you. Please see our [Contributing Guide](https://docs.ultralytics.com/help/contributing) to get started. We also welcome your feedback—share your experience by completing our [Survey](https://www.ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey). A huge **Thank You** 🙏 to everyone who contributes! + + + +[![Ultralytics open-source contributors](https://raw.githubusercontent.com/ultralytics/assets/main/im/image-contributors.png)](https://github.com/ultralytics/thop/graphs/contributors) + +We look forward to your contributions to help make the Ultralytics ecosystem even better! + +## 📜 License + +Ultralytics offers two licensing options to suit different needs: + +- **AGPL-3.0 License**: This [OSI-approved](https://opensource.org/license/agpl-3.0) open-source license is perfect for students, researchers, and enthusiasts. It encourages open collaboration and knowledge sharing. See the [LICENSE](https://github.com/ultralytics/thop/blob/main/LICENSE) file for full details. +- **Ultralytics Enterprise License**: For development and production use, this license enables seamless integration of Ultralytics software and AI models into business products and services, including internal tools, automated workflows, and production deployments, bypassing the open-source requirements of AGPL-3.0. To get started, please contact us via [Ultralytics Licensing](https://www.ultralytics.com/license). + +## 📞 Contact + +For bug reports and feature requests related to THOP, please visit [GitHub Issues](https://github.com/ultralytics/thop/issues). For questions, discussions, and community support, join our active communities on [Discord](https://discord.com/invite/ultralytics), [Reddit](https://www.reddit.com/r/ultralytics/), and the [Ultralytics Community Forums](https://community.ultralytics.com/). We're here to help with all things Ultralytics! + +
+
+ Ultralytics GitHub + space + Ultralytics LinkedIn + space + Ultralytics Twitter + space + Ultralytics YouTube + space + Ultralytics TikTok + space + Ultralytics BiliBili + space + Ultralytics Discord +
diff --git a/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/RECORD b/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..00f2c7ed68d000ba2db6eb23ca8c2333c92454d2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/RECORD @@ -0,0 +1,20 @@ +thop/__init__.py,sha256=wxopxYk5fqXDzFnGUja-LJVLTg1b19FmOeu1E-FKA9s,292 +thop/__pycache__/__init__.cpython-312.pyc,, +thop/__pycache__/profile.cpython-312.pyc,, +thop/__pycache__/rnn_hooks.cpython-312.pyc,, +thop/__pycache__/utils.cpython-312.pyc,, +thop/profile.py,sha256=zbJjrU53FPi-i80jJkdtTnD-5LPUfV8lFzBQD-9Mop0,18994 +thop/rnn_hooks.py,sha256=l-hl3FyYxeYhC5gdYzQais9GQktOz18w_q6v8uBK2oA,6384 +thop/utils.py,sha256=ueZefDWB_s8XKqijOJK3e0n-okyuBZg8Q16YSOxk8XU,1569 +thop/vision/__init__.py,sha256=lm6MckFYCPTbqIoX7w0s_daxdjNeBeKW6DXppv1-QUM,70 +thop/vision/__pycache__/__init__.cpython-312.pyc,, +thop/vision/__pycache__/basic_hooks.cpython-312.pyc,, +thop/vision/__pycache__/calc_func.cpython-312.pyc,, +thop/vision/basic_hooks.py,sha256=F2J0fdpot_IvtDfQB5QureOb58Po3ncs-tHqQAvxiug,8297 +thop/vision/calc_func.py,sha256=GtSTZDbk6ZTXdnHMtDs4c55RzLzG5v3TnVqpjENTRvw,2279 +ultralytics_thop-2.1.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +ultralytics_thop-2.1.6.dist-info/METADATA,sha256=p5mXKQyvdLNvmE0gkjw3FllyXh0Kk2klS589xdCxD1g,13782 +ultralytics_thop-2.1.6.dist-info/RECORD,, +ultralytics_thop-2.1.6.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91 +ultralytics_thop-2.1.6.dist-info/licenses/LICENSE,sha256=hIahDEOTzuHCU5J2nd07LWwkLW7Hko4UFO__ffsvB-8,34523 +ultralytics_thop-2.1.6.dist-info/top_level.txt,sha256=HQ7D0gSvDJ31CNR-f0EuXNVve05RYBmwyIkHQKiEhU8,5 diff --git a/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1d472b6c22838de58d1c3c0dd2c795a5cde9e415 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (83.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0ad25db4bd1d86c452db3f9602ccdbe172438f52 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/licenses/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..656868771c58fe743a290d2a6b10765d643b8592 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/ultralytics_thop-2.1.6.dist-info/top_level.txt @@ -0,0 +1 @@ +thop diff --git a/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..88f02623b282feb3ec677a2e78a6309ac6f03fdf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/METADATA @@ -0,0 +1,175 @@ +Metadata-Version: 2.5 +Name: urllib3 +Version: 2.8.0 +Summary: HTTP library with thread-safe connection pooling, file post, and more. +Project-URL: Changelog, https://github.com/urllib3/urllib3/blob/main/CHANGES.rst +Project-URL: Documentation, https://urllib3.readthedocs.io +Project-URL: Code, https://github.com/urllib3/urllib3 +Project-URL: Issue tracker, https://github.com/urllib3/urllib3/issues +Project-URL: Security policy, https://urllib3.readthedocs.io/en/latest/security.html +Author-email: Andrey Petrov +Maintainer-email: Seth Michael Larson , Quentin Pradet , Illia Volochii +License-Expression: MIT +License-File: LICENSE.txt +Keywords: filepost,http,httplib,https,pooling,ssl,threadsafe,urllib +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 +Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: Software Development :: Libraries +Requires-Python: >=3.10 +Provides-Extra: brotli +Requires-Dist: brotli>=1.2.0; (platform_python_implementation == 'CPython') and extra == 'brotli' +Requires-Dist: brotlicffi>=1.2.0.0; (platform_python_implementation != 'CPython') and extra == 'brotli' +Provides-Extra: h2 +Requires-Dist: h2<5,>=4; extra == 'h2' +Provides-Extra: socks +Requires-Dist: pysocks!=1.5.7,<2.0,>=1.5.6; extra == 'socks' +Provides-Extra: zstd +Requires-Dist: backports-zstd>=1.0.0; (python_version < '3.14') and extra == 'zstd' +Description-Content-Type: text/markdown + +

+ +![urllib3](https://github.com/urllib3/urllib3/raw/main/docs/_static/banner_github.svg) + +

+ +

+ PyPI Version + Python Versions + Join our Discord + Coverage Status + Build Status on GitHub + Documentation Status
+ OpenSSF Scorecard + SLSA 3 + CII Best Practices +

+ +urllib3 is a powerful, *user-friendly* HTTP client for Python. +urllib3 brings many critical features that are missing from the Python +standard libraries: + +- Thread safety. +- Connection pooling. +- Client-side SSL/TLS verification. +- File uploads with multipart encoding. +- Helpers for retrying requests and dealing with HTTP redirects. +- Support for gzip, deflate, brotli, and zstd encoding. +- Proxy support for HTTP and SOCKS. +- 100% test coverage. + +... and many more features, but most importantly: Our maintainers have a 15+ +year track record of maintaining urllib3 with the highest code standards and +attention to security and safety. + +[Much of the Python ecosystem already uses urllib3](https://urllib3.readthedocs.io/en/stable/#who-uses) +and you should too. + + +## Installing + +urllib3 can be installed with [pip](https://pip.pypa.io): + +```bash +$ python -m pip install urllib3 +``` + +Alternatively, you can grab the latest source code from [GitHub](https://github.com/urllib3/urllib3): + +```bash +$ git clone https://github.com/urllib3/urllib3.git +$ cd urllib3 +$ pip install . +``` + +## Getting Started + +urllib3 is easy to use: + +```python3 +>>> import urllib3 +>>> resp = urllib3.request("GET", "http://httpbin.org/robots.txt") +>>> resp.status +200 +>>> resp.data +b"User-agent: *\nDisallow: /deny\n" +``` + +urllib3 has usage and reference documentation at [urllib3.readthedocs.io](https://urllib3.readthedocs.io). + + +## Community + +urllib3 has a [community Discord channel](https://discord.gg/urllib3) for asking questions and +collaborating with other contributors. Drop by and say hello 👋 + + +## Contributing + +urllib3 welcomes contributions. Please read our +[contributing documentation](https://urllib3.readthedocs.io/en/latest/contributing.html) +before starting work. + +Check for existing pull requests addressing the same issue, and share feedback +and suggestions in the existing pull request and issue. Duplicate pull +requests, including alternative solutions, will be rejected without review +unless a maintainer has approved opening an alternative pull request in +advance. + + +## Security Disclosures + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure with maintainers. + +See the repository +[Security Policy](https://urllib3.readthedocs.io/en/latest/security.html) +for more details. + + +## Maintainers + +Meet our maintainers since 2008: + +- Current Lead: [@illia-v](https://github.com/illia-v) (Illia Volochii) +- [@sethmlarson](https://github.com/sethmlarson) (Seth M. Larson) +- [@pquentin](https://github.com/pquentin) (Quentin Pradet) +- [@theacodes](https://github.com/theacodes) (Thea Flowers) +- [@haikuginger](https://github.com/haikuginger) (Jess Shapiro) +- [@lukasa](https://github.com/lukasa) (Cory Benfield) +- [@sigmavirus24](https://github.com/sigmavirus24) (Ian Stapleton Cordasco) +- [@shazow](https://github.com/shazow) (Andrey Petrov) + +👋 + + +## Sponsorship + +If your company benefits from this library, please consider [sponsoring its +development](https://urllib3.readthedocs.io/en/latest/sponsors.html). + + +## For Enterprise + +Professional support for urllib3 is available as part of the [Tidelift +Subscription][1]. Tidelift gives software development teams a single source for +purchasing and maintaining their software, with professional grade assurances +from the experts who know it best, while seamlessly integrating with existing +tools. + +[1]: https://tidelift.com/subscription/pkg/pypi-urllib3?utm_source=pypi-urllib3&utm_medium=referral&utm_campaign=readme diff --git a/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..a63226129070244810ce31a6713f4b2351d680fd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/RECORD @@ -0,0 +1,79 @@ +urllib3-2.8.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +urllib3-2.8.0.dist-info/METADATA,sha256=EImMYg6AB8Aw4H-lYitoNYpDAQAl3714oct5dpneK7Q,7389 +urllib3-2.8.0.dist-info/RECORD,, +urllib3-2.8.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87 +urllib3-2.8.0.dist-info/licenses/LICENSE.txt,sha256=Ew46ZNX91dCWp1JpRjSn2d8oRGnehuVzIQAmgEHj1oY,1093 +urllib3/__init__.py,sha256=JMo1tg1nIV1AeJ2vENC_Txfl0e5h6Gzl9DGVk1rWRbo,6979 +urllib3/__pycache__/__init__.cpython-312.pyc,, +urllib3/__pycache__/_base_connection.cpython-312.pyc,, +urllib3/__pycache__/_collections.cpython-312.pyc,, +urllib3/__pycache__/_request_methods.cpython-312.pyc,, +urllib3/__pycache__/_version.cpython-312.pyc,, +urllib3/__pycache__/connection.cpython-312.pyc,, +urllib3/__pycache__/connectionpool.cpython-312.pyc,, +urllib3/__pycache__/exceptions.cpython-312.pyc,, +urllib3/__pycache__/fields.cpython-312.pyc,, +urllib3/__pycache__/filepost.cpython-312.pyc,, +urllib3/__pycache__/poolmanager.cpython-312.pyc,, +urllib3/__pycache__/response.cpython-312.pyc,, +urllib3/_base_connection.py,sha256=HzcSEHexgDrRUr60jNniB2KQjdw97SedD5luRfHtCXg,5580 +urllib3/_collections.py,sha256=H6yLqGWdZNkZ0Lm_fnLEyqulnOcW6qtXCh2qzxg73xU,17669 +urllib3/_request_methods.py,sha256=gCeF85SO_UU4WoPwYHIoz_tw-eM_EVOkLFp8OFsC7DA,9931 +urllib3/_version.py,sha256=e4QyAYanoYBRNP2K6qDVCOgBFoUa7L0j91YQQsUHO9Q,520 +urllib3/connection.py,sha256=ilnas9e2oOGzil_W5WXvakk4G7mVcp0BXk9kQKuFI-A,47903 +urllib3/connectionpool.py,sha256=ahR4aSFrlESaBT6GnUMRy6IylFUcg-4g_l0vHq_1Cj4,45250 +urllib3/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +urllib3/contrib/__pycache__/__init__.cpython-312.pyc,, +urllib3/contrib/__pycache__/pyopenssl.cpython-312.pyc,, +urllib3/contrib/__pycache__/socks.cpython-312.pyc,, +urllib3/contrib/emscripten/__init__.py,sha256=wyXve8rmqX7s2KqRQBxD5Wl48jzWPn5-1u_XoQBELVc,836 +urllib3/contrib/emscripten/__pycache__/__init__.cpython-312.pyc,, +urllib3/contrib/emscripten/__pycache__/connection.cpython-312.pyc,, +urllib3/contrib/emscripten/__pycache__/fetch.cpython-312.pyc,, +urllib3/contrib/emscripten/__pycache__/request.cpython-312.pyc,, +urllib3/contrib/emscripten/__pycache__/response.cpython-312.pyc,, +urllib3/contrib/emscripten/connection.py,sha256=giElsBoUsKVURbZzb8GCrJmqW23Xnvj2aNyQVF42slg,8960 +urllib3/contrib/emscripten/emscripten_fetch_worker.js,sha256=z1k3zZ4_hDKd3-tN7wzz8LHjHC2pxN_uu8B3k9D9A3c,3677 +urllib3/contrib/emscripten/fetch.py,sha256=5xcd--viFxZd2nBy0aK73dtJ9Tsh1yYZU_SUXwnwibk,23520 +urllib3/contrib/emscripten/request.py,sha256=mL28szy1KvE3NJhWor5jNmarp8gwplDU-7gwGZY5g0Q,566 +urllib3/contrib/emscripten/response.py,sha256=CDpY0GFoluR3IxECkM2gH5uDfYDM0EL1FWr7B76wtgM,9719 +urllib3/contrib/pyopenssl.py,sha256=Ws8vCuZSfgI6QDHaVSJGYA9udTWB9KL0wZ_018iKgjA,21494 +urllib3/contrib/socks.py,sha256=gRQfcI1pKOAh5iI4_TDAkKaAP3N_H2IN5J5mBlKZBpE,7566 +urllib3/exceptions.py,sha256=hQPHoqo4yw46esNSVkciVQXVUgAxWAglsh6MbyQta-Q,9945 +urllib3/fields.py,sha256=aGLFAVZpVU-FbJlllve4Ahg0-pH9ZZBQ2Iz7lfpkjkM,10801 +urllib3/filepost.py,sha256=U8eNZ-mpKKHhrlbHEEiTxxgK16IejhEa7uz42yqA_dI,2388 +urllib3/http2/__init__.py,sha256=xzrASH7R5ANRkPJOot5lGnATOq3KKuyXzI42rcnwmqs,1741 +urllib3/http2/__pycache__/__init__.cpython-312.pyc,, +urllib3/http2/__pycache__/connection.cpython-312.pyc,, +urllib3/http2/__pycache__/probe.cpython-312.pyc,, +urllib3/http2/connection.py,sha256=njlgr4wLhiAJvtUqxEEn4S95vifblTRrmraRHoCcv60,12613 +urllib3/http2/probe.py,sha256=nnAkqbhAakOiF75rz7W0udZ38Eeh_uD8fjV74N73FEI,3014 +urllib3/poolmanager.py,sha256=RmVFBjOP-aDnm67vikCa99N6rQAWMxUDhKHrSl0f9Ms,25026 +urllib3/py.typed,sha256=UaCuPFa3H8UAakbt-5G8SPacldTOGvJv18pPjUJ5gDY,93 +urllib3/response.py,sha256=DkVZxzeRTU-PlB3Kns-vbK7GeSJYMCv_7HuLQdrjxxo,54628 +urllib3/util/__init__.py,sha256=-qeS0QceivazvBEKDNFCAI-6ACcdDOE4TMvo7SLNlAQ,1001 +urllib3/util/__pycache__/__init__.cpython-312.pyc,, +urllib3/util/__pycache__/connection.cpython-312.pyc,, +urllib3/util/__pycache__/proxy.cpython-312.pyc,, +urllib3/util/__pycache__/request.cpython-312.pyc,, +urllib3/util/__pycache__/response.cpython-312.pyc,, +urllib3/util/__pycache__/retry.cpython-312.pyc,, +urllib3/util/__pycache__/ssl_.cpython-312.pyc,, +urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc,, +urllib3/util/__pycache__/ssltransport.cpython-312.pyc,, +urllib3/util/__pycache__/timeout.cpython-312.pyc,, +urllib3/util/__pycache__/url.cpython-312.pyc,, +urllib3/util/__pycache__/util.cpython-312.pyc,, +urllib3/util/__pycache__/wait.cpython-312.pyc,, +urllib3/util/connection.py,sha256=JjO722lzHlzLXPTkr9ZWBdhseXnMVjMSb1DJLVrXSnQ,4444 +urllib3/util/proxy.py,sha256=seP8-Q5B6bB0dMtwPj-YcZZQ30vHuLqRu-tI0JZ2fzs,1148 +urllib3/util/request.py,sha256=2a87euUwnjylB3fyeZSz_Vs66zLGqqRKJS3bpTZsibA,10228 +urllib3/util/response.py,sha256=vQE639uoEhj1vpjEdxu5lNIhJCSUZkd7pqllUI0BZOA,3374 +urllib3/util/retry.py,sha256=D9wmtn0ezEKwyrOXLyC7ByhNeD9Nwxg5T-i5kJjEKSU,20151 +urllib3/util/ssl_.py,sha256=csd5wT9uKvoiFJ11-YpfqwzciGGTUV2drmLhI1T9YcQ,17856 +urllib3/util/ssl_match_hostname.py,sha256=Ft44KJzTzGMmKff_ZXP91li2V4WhmvEy16PKBcv4vZk,5479 +urllib3/util/ssltransport.py,sha256=Ez4O8pR_vT8dan_FvqBYS6dgDfBXEMfVfrzcdUoWfi4,8847 +urllib3/util/timeout.py,sha256=4eT1FVeZZU7h7mYD1Jq2OXNe4fxekdNvhoWUkZusRpA,10346 +urllib3/util/url.py,sha256=aigU2RmH3ZcoJ41BOhVO5Sd7FcsmLZlFQlN38qaTMR8,19579 +urllib3/util/util.py,sha256=j3lbZK1jPyiwD34T8IgJzdWEZVT-4E-0vYIJi9UjeNA,1146 +urllib3/util/wait.py,sha256=_ph8IrUR3sqPqi0OopQgJUlH4wzkGeM5CiyA7XGGtmI,4423 diff --git a/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..51abe1f5e66cc9d07fda22a3bbe1f89475795969 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.32.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/licenses/LICENSE.txt b/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..e6183d0276b26c5b87aecccf8d0d5bcd7b1148d4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3-2.8.0.dist-info/licenses/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2008-2020 Andrey Petrov and contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/urllib3/__init__.py b/.venv/lib/python3.12/site-packages/urllib3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3fe782c8a45bbabcf240f3cac4303ac12b0ec274 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/__init__.py @@ -0,0 +1,211 @@ +""" +Python HTTP library with thread-safe connection pooling, file post support, user friendly, and more +""" + +from __future__ import annotations + +# Set default logging handler to avoid "No handler found" warnings. +import logging +import sys +import typing +import warnings +from logging import NullHandler + +from . import exceptions +from ._base_connection import _TYPE_BODY +from ._collections import HTTPHeaderDict +from ._version import __version__ +from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url +from .filepost import _TYPE_FIELDS, encode_multipart_formdata +from .poolmanager import PoolManager, ProxyManager, proxy_from_url +from .response import BaseHTTPResponse, HTTPResponse +from .util.request import make_headers +from .util.retry import Retry +from .util.timeout import Timeout + +# Ensure that Python is compiled with OpenSSL 1.1.1+ +# If the 'ssl' module isn't available at all that's +# fine, we only care if the module is available. +try: + import ssl +except ImportError: + pass +else: + if not ssl.OPENSSL_VERSION.startswith("OpenSSL "): # Defensive: + warnings.warn( + "urllib3 v2 only supports OpenSSL 1.1.1+, currently " + f"the 'ssl' module is compiled with {ssl.OPENSSL_VERSION!r}. " + "See: https://github.com/urllib3/urllib3/issues/3020", + exceptions.NotOpenSSLWarning, + ) + elif ssl.OPENSSL_VERSION_INFO < (1, 1, 1): # Defensive: + raise ImportError( + "urllib3 v2 only supports OpenSSL 1.1.1+, currently " + f"the 'ssl' module is compiled with {ssl.OPENSSL_VERSION!r}. " + "See: https://github.com/urllib3/urllib3/issues/2168" + ) + +__author__ = "Andrey Petrov (andrey.petrov@shazow.net)" +__license__ = "MIT" +__version__ = __version__ + +__all__ = ( + "HTTPConnectionPool", + "HTTPHeaderDict", + "HTTPSConnectionPool", + "PoolManager", + "ProxyManager", + "HTTPResponse", + "Retry", + "Timeout", + "add_stderr_logger", + "connection_from_url", + "disable_warnings", + "encode_multipart_formdata", + "make_headers", + "proxy_from_url", + "request", + "BaseHTTPResponse", +) + +logging.getLogger(__name__).addHandler(NullHandler()) + + +def add_stderr_logger( + level: int = logging.DEBUG, +) -> logging.StreamHandler[typing.TextIO]: + """ + Helper for quickly adding a StreamHandler to the logger. Useful for + debugging. + + Returns the handler after adding it. + """ + # This method needs to be in this __init__.py to get the __name__ correct + # even if urllib3 is vendored within another package. + logger = logging.getLogger(__name__) + handler = logging.StreamHandler() + handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s")) + logger.addHandler(handler) + logger.setLevel(level) + logger.debug("Added a stderr logging handler to logger: %s", __name__) + return handler + + +# ... Clean up. +del NullHandler + + +# All warning filters *must* be appended unless you're really certain that they +# shouldn't be: otherwise, it's very hard for users to use most Python +# mechanisms to silence them. +# SecurityWarning's always go off by default. +warnings.simplefilter("always", exceptions.SecurityWarning, append=True) +# InsecurePlatformWarning's don't vary between requests, so we keep it default. +warnings.simplefilter("default", exceptions.InsecurePlatformWarning, append=True) + + +def disable_warnings(category: type[Warning] = exceptions.HTTPWarning) -> None: + """ + Helper for quickly disabling all urllib3 warnings. + """ + warnings.simplefilter("ignore", category) + + +_DEFAULT_POOL = PoolManager() + + +def request( + method: str, + url: str, + *, + body: _TYPE_BODY | None = None, + fields: _TYPE_FIELDS | None = None, + headers: typing.Mapping[str, str] | None = None, + preload_content: bool | None = True, + decode_content: bool | None = True, + redirect: bool | None = True, + retries: Retry | bool | int | None = None, + timeout: Timeout | float | int | None = 3, + json: typing.Any | None = None, +) -> BaseHTTPResponse: + """ + A convenience, top-level request method. It uses a module-global ``PoolManager`` instance. + Therefore, its side effects could be shared across dependencies relying on it. + To avoid side effects create a new ``PoolManager`` instance and use it instead. + The method does not accept low-level ``**urlopen_kw`` keyword arguments. + + :param method: + HTTP request method (such as GET, POST, PUT, etc.) + + :param url: + The URL to perform the request on. + + :param body: + Data to send in the request body, either :class:`str`, :class:`bytes`, + an iterable of :class:`str`/:class:`bytes`, or a file-like object. + + :param fields: + Data to encode and send in the request body. + + :param headers: + Dictionary of custom headers to send, such as User-Agent, + If-None-Match, etc. + + :param bool preload_content: + If True, the response's body will be preloaded into memory. + + :param bool decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + + :param redirect: + If True, automatically handle redirects (status codes 301, 302, + 303, 307, 308). Each redirect counts as a retry. Disabling retries + will disable redirect, too. + + :param retries: + Configure the number of retries to allow before raising a + :class:`~urllib3.exceptions.MaxRetryError` exception. + + If ``None`` (default) will retry 3 times, see ``Retry.DEFAULT``. Pass a + :class:`~urllib3.util.retry.Retry` object for fine-grained control + over different types of retries. + Pass an integer number to retry connection errors that many times, + but no other types of errors. Pass zero to never retry. + + If ``False``, then retries are disabled and any exception is raised + immediately. Also, instead of raising a MaxRetryError on redirects, + the redirect response will be returned. + + :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. + + :param timeout: + If specified, overrides the default timeout for this one + request. It may be a float (in seconds) or an instance of + :class:`urllib3.util.Timeout`. + + :param json: + Data to encode and send as JSON with UTF-encoded in the request body. + The ``"Content-Type"`` header will be set to ``"application/json"`` + unless specified otherwise. + """ + + return _DEFAULT_POOL.request( + method, + url, + body=body, + fields=fields, + headers=headers, + preload_content=preload_content, + decode_content=decode_content, + redirect=redirect, + retries=retries, + timeout=timeout, + json=json, + ) + + +if sys.platform == "emscripten": + from .contrib.emscripten import inject_into_urllib3 # noqa: 401 + + inject_into_urllib3() diff --git a/.venv/lib/python3.12/site-packages/urllib3/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4407b1c9974f1c372a5ebfd8fadcc11da6197de Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/__pycache__/_base_connection.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/_base_connection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..920919a65cc8f2ec9716b53028a52e3be05dbca6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/_base_connection.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/__pycache__/_collections.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/_collections.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a71197123df0d9336e262a819d9d741d3e2714c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/_collections.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/__pycache__/_request_methods.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/_request_methods.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f30642f1acca10def0103c37279e76f6a0ae0bd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/_request_methods.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/__pycache__/_version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/_version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd0d410c8f1983e86f61ff5da880074c119ed7b4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/_version.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/__pycache__/connection.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/connection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7b7167b84e184e29a080d52e299821cb5c132bc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/connection.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/__pycache__/connectionpool.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/connectionpool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec4756ae046f8ea3509be76452fff2ece046df0a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/connectionpool.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/__pycache__/exceptions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75b0420e0a0763ff62b5ab41ddc56ec74a08aaa1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/exceptions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/__pycache__/fields.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/fields.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18c88c26aabaa3d252a92ff09fb043a76f062814 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/fields.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/__pycache__/filepost.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/filepost.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2843cb61621c2953b41b61d65724e56a9651f430 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/filepost.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/__pycache__/poolmanager.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/poolmanager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52f176d984870e439a201f2a1b25c2a7332e403d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/poolmanager.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/__pycache__/response.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9be49bf00c09670b2d659790d7e6bddf5fc3cba0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/__pycache__/response.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/_base_connection.py b/.venv/lib/python3.12/site-packages/urllib3/_base_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..992ec1657a9d0a98354b56b2a55d54b75db0eaa3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/_base_connection.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import typing + +from .util.connection import _TYPE_SOCKET_OPTIONS +from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT +from .util.url import Url + +_TYPE_BODY = typing.Union[ + bytes, typing.IO[typing.Any], typing.Iterable[bytes | str], str +] + + +class ProxyConfig(typing.NamedTuple): + ssl_context: ssl.SSLContext | None + use_forwarding_for_https: bool + assert_hostname: None | str | typing.Literal[False] + assert_fingerprint: str | None + + +class _ResponseOptions(typing.NamedTuple): + # TODO: Remove this in favor of a better + # HTTP request/response lifecycle tracking. + request_method: str + request_url: str + preload_content: bool + decode_content: bool + enforce_content_length: bool + + +if typing.TYPE_CHECKING: + import ssl + from typing import Protocol + + from .response import BaseHTTPResponse + + class BaseHTTPConnection(Protocol): + default_port: typing.ClassVar[int] + default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS] + + host: str + port: int + timeout: None | ( + float + ) # Instance doesn't store _DEFAULT_TIMEOUT, must be resolved. + blocksize: int + source_address: tuple[str, int] | None + socket_options: _TYPE_SOCKET_OPTIONS | None + + proxy: Url | None + proxy_config: ProxyConfig | None + + is_verified: bool + proxy_is_verified: bool | None + + def __init__( + self, + host: str, + port: int | None = None, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + socket_options: _TYPE_SOCKET_OPTIONS | None = ..., + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + ) -> None: ... + + def set_tunnel( + self, + host: str, + port: int | None = None, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: ... + + def connect(self) -> None: ... + + def request( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + # We know *at least* botocore is depending on the order of the + # first 3 parameters so to be safe we only mark the later ones + # as keyword-only to ensure we have space to extend. + *, + chunked: bool = False, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + ) -> None: ... + + def getresponse(self) -> BaseHTTPResponse: ... + + def close(self) -> None: ... + + @property + def is_closed(self) -> bool: + """Whether the connection either is brand new or has been previously closed. + If this property is True then both ``is_connected`` and ``has_connected_to_proxy`` + properties must be False. + """ + + @property + def is_connected(self) -> bool: + """Whether the connection is actively connected to any origin (proxy or target)""" + + @property + def has_connected_to_proxy(self) -> bool: + """Whether the connection has successfully connected to its proxy. + This returns False if no proxy is in use. Used to determine whether + errors are coming from the proxy layer or from tunnelling to the target origin. + """ + + class BaseHTTPSConnection(BaseHTTPConnection, Protocol): + default_port: typing.ClassVar[int] + default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS] + + # Certificate verification methods + cert_reqs: int | str | None + assert_hostname: None | str | typing.Literal[False] + assert_fingerprint: str | None + ssl_context: ssl.SSLContext | None + + # Trusted CAs + ca_certs: str | None + ca_cert_dir: str | None + ca_cert_data: None | str | bytes + + # TLS version + ssl_minimum_version: int | None + ssl_maximum_version: int | None + ssl_version: int | str | None # Deprecated + + # Client certificates + cert_file: str | None + key_file: str | None + key_password: str | None + + def __init__( + self, + host: str, + port: int | None = None, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 16384, + socket_options: _TYPE_SOCKET_OPTIONS | None = ..., + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + cert_reqs: int | str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + server_hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + ca_certs: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + ssl_version: int | str | None = None, # Deprecated + cert_file: str | None = None, + key_file: str | None = None, + key_password: str | None = None, + ) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/urllib3/_collections.py b/.venv/lib/python3.12/site-packages/urllib3/_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..bc72773454866cc53c8f2567986732cd880653b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/_collections.py @@ -0,0 +1,490 @@ +from __future__ import annotations + +import typing +from collections import OrderedDict +from enum import Enum, auto +from threading import RLock + +if typing.TYPE_CHECKING: + # We can only import Protocol if TYPE_CHECKING because it's a development + # dependency, and is not available at runtime. + from typing import Protocol + + from typing_extensions import Self + + class HasGettableStringKeys(Protocol): + def keys(self) -> typing.Iterator[str]: ... + + def __getitem__(self, key: str) -> str: ... + + +__all__ = ["RecentlyUsedContainer", "HTTPHeaderDict"] + + +# Key type +_KT = typing.TypeVar("_KT") +# Value type +_VT = typing.TypeVar("_VT") +# Default type +_DT = typing.TypeVar("_DT") + +ValidHTTPHeaderSource = typing.Union[ + "HTTPHeaderDict", + typing.Mapping[str, str], + typing.Iterable[tuple[str, str]], + "HasGettableStringKeys", +] + + +class _Sentinel(Enum): + not_passed = auto() + + +def ensure_can_construct_http_header_dict( + potential: object, +) -> ValidHTTPHeaderSource | None: + if isinstance(potential, HTTPHeaderDict): + return potential + elif isinstance(potential, typing.Mapping): + # Full runtime checking of the contents of a Mapping is expensive, so for the + # purposes of typechecking, we assume that any Mapping is the right shape. + return typing.cast(typing.Mapping[str, str], potential) + elif isinstance(potential, typing.Iterable): + # Similarly to Mapping, full runtime checking of the contents of an Iterable is + # expensive, so for the purposes of typechecking, we assume that any Iterable + # is the right shape. + return typing.cast(typing.Iterable[tuple[str, str]], potential) + elif hasattr(potential, "keys") and hasattr(potential, "__getitem__"): + return typing.cast("HasGettableStringKeys", potential) + else: + return None + + +class RecentlyUsedContainer(typing.Generic[_KT, _VT], typing.MutableMapping[_KT, _VT]): + """ + Provides a thread-safe dict-like container which maintains up to + ``maxsize`` keys while throwing away the least-recently-used keys beyond + ``maxsize``. + + :param maxsize: + Maximum number of recent elements to retain. + + :param dispose_func: + Every time an item is evicted from the container, + ``dispose_func(value)`` is called. Callback which will get called + """ + + _container: typing.OrderedDict[_KT, _VT] + _maxsize: int + dispose_func: typing.Callable[[_VT], None] | None + lock: RLock + + def __init__( + self, + maxsize: int = 10, + dispose_func: typing.Callable[[_VT], None] | None = None, + ) -> None: + super().__init__() + self._maxsize = maxsize + self.dispose_func = dispose_func + self._container = OrderedDict() + self.lock = RLock() + + def __getitem__(self, key: _KT) -> _VT: + # Re-insert the item, moving it to the end of the eviction line. + with self.lock: + item = self._container.pop(key) + self._container[key] = item + return item + + def __setitem__(self, key: _KT, value: _VT) -> None: + evicted_item = None + with self.lock: + # Possibly evict the existing value of 'key' + try: + # If the key exists, we'll overwrite it, which won't change the + # size of the pool. Because accessing a key should move it to + # the end of the eviction line, we pop it out first. + evicted_item = key, self._container.pop(key) + self._container[key] = value + except KeyError: + # When the key does not exist, we insert the value first so that + # evicting works in all cases, including when self._maxsize is 0 + self._container[key] = value + if len(self._container) > self._maxsize: + # If we didn't evict an existing value, and we've hit our maximum + # size, then we have to evict the least recently used item from + # the beginning of the container. + evicted_item = self._container.popitem(last=False) + + # After releasing the lock on the pool, dispose of any evicted value. + if evicted_item is not None and self.dispose_func: + _, evicted_value = evicted_item + self.dispose_func(evicted_value) + + def __delitem__(self, key: _KT) -> None: + with self.lock: + value = self._container.pop(key) + + if self.dispose_func: + self.dispose_func(value) + + def __len__(self) -> int: + with self.lock: + return len(self._container) + + def __iter__(self) -> typing.NoReturn: + raise NotImplementedError( + "Iteration over this class is unlikely to be threadsafe." + ) + + def clear(self) -> None: + with self.lock: + # Copy pointers to all values, then wipe the mapping + values = list(self._container.values()) + self._container.clear() + + if self.dispose_func: + for value in values: + self.dispose_func(value) + + def keys(self) -> set[_KT]: # type: ignore[override] + with self.lock: + return set(self._container.keys()) + + +class HTTPHeaderDictItemView(set[tuple[str, str]]): + """ + HTTPHeaderDict is unusual for a Mapping[str, str] in that it has two modes of + address. + + If we directly try to get an item with a particular name, we will get a string + back that is the concatenated version of all the values: + + >>> d['X-Header-Name'] + 'Value1, Value2, Value3' + + However, if we iterate over an HTTPHeaderDict's items, we will optionally combine + these values based on whether combine=True was called when building up the dictionary + + >>> d = HTTPHeaderDict({"A": "1", "B": "foo"}) + >>> d.add("A", "2", combine=True) + >>> d.add("B", "bar") + >>> list(d.items()) + [ + ('A', '1, 2'), + ('B', 'foo'), + ('B', 'bar'), + ] + + This class conforms to the interface required by the MutableMapping ABC while + also giving us the nonstandard iteration behavior we want; items with duplicate + keys, ordered by time of first insertion. + """ + + _headers: HTTPHeaderDict + + def __init__(self, headers: HTTPHeaderDict) -> None: + self._headers = headers + + def __len__(self) -> int: + return len(list(self._headers.iteritems())) + + def __iter__(self) -> typing.Iterator[tuple[str, str]]: + return self._headers.iteritems() + + def __contains__(self, item: object) -> bool: + if isinstance(item, tuple) and len(item) == 2: + passed_key, passed_val = item + if isinstance(passed_key, str) and isinstance(passed_val, str): + return self._headers._has_value_for_header(passed_key, passed_val) + return False + + +class HTTPHeaderDict(typing.MutableMapping[str, str]): + """ + :param headers: + An iterable of field-value pairs. Must not contain multiple field names + when compared case-insensitively. + + :param kwargs: + Additional field-value pairs to pass in to ``dict.update``. + + A ``dict`` like container for storing HTTP Headers. + + Field names are stored and compared case-insensitively in compliance with + RFC 7230. Iteration provides the first case-sensitive key seen for each + case-insensitive pair. + + Using ``__setitem__`` syntax overwrites fields that compare equal + case-insensitively in order to maintain ``dict``'s api. For fields that + compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add`` + in a loop. + + If multiple fields that are equal case-insensitively are passed to the + constructor or ``.update``, the behavior is undefined and some will be + lost. + + >>> headers = HTTPHeaderDict() + >>> headers.add('Set-Cookie', 'foo=bar') + >>> headers.add('set-cookie', 'baz=quxx') + >>> headers['content-length'] = '7' + >>> headers['SET-cookie'] + 'foo=bar, baz=quxx' + >>> headers['Content-Length'] + '7' + """ + + _container: typing.MutableMapping[str, list[str]] + + def __init__(self, headers: ValidHTTPHeaderSource | None = None, **kwargs: str): + super().__init__() + self._container = {} # 'dict' is insert-ordered + if headers is not None: + if isinstance(headers, HTTPHeaderDict): + self._copy_from(headers) + else: + self.extend(headers) + if kwargs: + self.extend(kwargs) + + def __setitem__(self, key: str, val: str) -> None: + # avoid a bytes/str comparison by decoding before httplib + if isinstance(key, bytes): + key = key.decode("latin-1") + self._container[key.lower()] = [key, val] + + def __getitem__(self, key: str) -> str: + if isinstance(key, bytes): + key = key.decode("latin-1") + val = self._container[key.lower()] + return ", ".join(val[1:]) + + def __delitem__(self, key: str) -> None: + if isinstance(key, bytes): + key = key.decode("latin-1") + del self._container[key.lower()] + + def __contains__(self, key: object) -> bool: + if isinstance(key, bytes): + key = key.decode("latin-1") + if isinstance(key, str): + return key.lower() in self._container + return False + + def setdefault(self, key: str, default: str = "") -> str: + return super().setdefault(key, default) + + def __eq__(self, other: object) -> bool: + maybe_constructable = ensure_can_construct_http_header_dict(other) + if maybe_constructable is None: + return False + else: + other_as_http_header_dict = type(self)(maybe_constructable) + + return {k.lower(): v for k, v in self.itermerged()} == { + k.lower(): v for k, v in other_as_http_header_dict.itermerged() + } + + def __ne__(self, other: object) -> bool: + return not self.__eq__(other) + + def __len__(self) -> int: + return len(self._container) + + def __iter__(self) -> typing.Iterator[str]: + # Only provide the originally cased names + for vals in self._container.values(): + yield vals[0] + + def discard(self, key: str) -> None: + try: + del self[key] + except KeyError: + pass + + def add(self, key: str, val: str, *, combine: bool = False) -> None: + """Adds a (name, value) pair, doesn't overwrite the value if it already + exists. + + If this is called with combine=True, instead of adding a new header value + as a distinct item during iteration, this will instead append the value to + any existing header value with a comma. If no existing header value exists + for the key, then the value will simply be added, ignoring the combine parameter. + + >>> headers = HTTPHeaderDict(foo='bar') + >>> headers.add('Foo', 'baz') + >>> headers['foo'] + 'bar, baz' + >>> list(headers.items()) + [('foo', 'bar'), ('foo', 'baz')] + >>> headers.add('foo', 'quz', combine=True) + >>> list(headers.items()) + [('foo', 'bar, baz, quz')] + """ + # avoid a bytes/str comparison by decoding before httplib + if isinstance(key, bytes): + key = key.decode("latin-1") + key_lower = key.lower() + new_vals = [key, val] + # Keep the common case aka no item present as fast as possible + vals = self._container.setdefault(key_lower, new_vals) + if new_vals is not vals: + # if there are values here, then there is at least the initial + # key/value pair + assert len(vals) >= 2 + if combine: + vals[-1] = vals[-1] + ", " + val + else: + vals.append(val) + + def extend(self, *args: ValidHTTPHeaderSource, **kwargs: str) -> None: + """Generic import function for any type of header-like object. + Adapted version of MutableMapping.update in order to insert items + with self.add instead of self.__setitem__ + """ + if len(args) > 1: + raise TypeError( + f"extend() takes at most 1 positional arguments ({len(args)} given)" + ) + other = args[0] if len(args) >= 1 else () + + if isinstance(other, HTTPHeaderDict): + for key, val in other.iteritems(): + self.add(key, val) + elif isinstance(other, typing.Mapping): + for key, val in other.items(): + self.add(key, val) + elif isinstance(other, typing.Iterable): + for key, value in other: + self.add(key, value) + elif hasattr(other, "keys") and hasattr(other, "__getitem__"): + # THIS IS NOT A TYPESAFE BRANCH + # In this branch, the object has a `keys` attr but is not a Mapping or any of + # the other types indicated in the method signature. We do some stuff with + # it as though it partially implements the Mapping interface, but we're not + # doing that stuff safely AT ALL. + for key in other.keys(): + self.add(key, other[key]) + + for key, value in kwargs.items(): + self.add(key, value) + + @typing.overload + def getlist(self, key: str) -> list[str]: ... + + @typing.overload + def getlist(self, key: str, default: _DT) -> list[str] | _DT: ... + + def getlist( + self, key: str, default: _Sentinel | _DT = _Sentinel.not_passed + ) -> list[str] | _DT: + """Returns a list of all the values for the named field. Returns an + empty list if the key doesn't exist.""" + if isinstance(key, bytes): + key = key.decode("latin-1") + try: + vals = self._container[key.lower()] + except KeyError: + if default is _Sentinel.not_passed: + # _DT is unbound; empty list is instance of List[str] + return [] + # _DT is bound; default is instance of _DT + return default + else: + # _DT may or may not be bound; vals[1:] is instance of List[str], which + # meets our external interface requirement of `Union[List[str], _DT]`. + return vals[1:] + + def _prepare_for_method_change(self) -> Self: + """ + Remove content-specific header fields before changing the request + method to GET or HEAD according to RFC 9110, Section 15.4. + + ``Transfer-Encoding`` goes as well: it frames a request body that is + no longer going to be sent. + """ + content_specific_headers = [ + "Content-Encoding", + "Content-Language", + "Content-Location", + "Content-Type", + "Content-Length", + "Digest", + "Last-Modified", + "Transfer-Encoding", + ] + for header in content_specific_headers: + self.discard(header) + return self + + # Backwards compatibility for httplib + getheaders = getlist + getallmatchingheaders = getlist + iget = getlist + + # Backwards compatibility for http.cookiejar + get_all = getlist + + def __repr__(self) -> str: + return f"{type(self).__name__}({dict(self.itermerged())})" + + def _copy_from(self, other: HTTPHeaderDict) -> None: + for key in other: + val = other.getlist(key) + self._container[key.lower()] = [key, *val] + + def copy(self) -> Self: + clone = type(self)() + clone._copy_from(self) + return clone + + def iteritems(self) -> typing.Iterator[tuple[str, str]]: + """Iterate over all header lines, including duplicate ones.""" + for key in self: + vals = self._container[key.lower()] + for val in vals[1:]: + yield vals[0], val + + def itermerged(self) -> typing.Iterator[tuple[str, str]]: + """Iterate over all headers, merging duplicate ones together.""" + for key in self: + val = self._container[key.lower()] + yield val[0], ", ".join(val[1:]) + + def items(self) -> HTTPHeaderDictItemView: # type: ignore[override] + return HTTPHeaderDictItemView(self) + + def _has_value_for_header(self, header_name: str, potential_value: str) -> bool: + if header_name in self: + return potential_value in self._container[header_name.lower()][1:] + return False + + def __ior__(self, other: object) -> HTTPHeaderDict: + # Supports extending a header dict in-place using operator |= + # combining items with add instead of __setitem__ + maybe_constructable = ensure_can_construct_http_header_dict(other) + if maybe_constructable is None: + return NotImplemented + self.extend(maybe_constructable) + return self + + def __or__(self, other: object) -> Self: + # Supports merging header dicts using operator | + # combining items with add instead of __setitem__ + maybe_constructable = ensure_can_construct_http_header_dict(other) + if maybe_constructable is None: + return NotImplemented + result = self.copy() + result.extend(maybe_constructable) + return result + + def __ror__(self, other: object) -> Self: + # Supports merging header dicts using operator | when other is on left side + # combining items with add instead of __setitem__ + maybe_constructable = ensure_can_construct_http_header_dict(other) + if maybe_constructable is None: + return NotImplemented + result = type(self)(maybe_constructable) + result.extend(self) + return result diff --git a/.venv/lib/python3.12/site-packages/urllib3/_request_methods.py b/.venv/lib/python3.12/site-packages/urllib3/_request_methods.py new file mode 100644 index 0000000000000000000000000000000000000000..297c271bf401c1cb48c6225f8822e78f58c3ca56 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/_request_methods.py @@ -0,0 +1,278 @@ +from __future__ import annotations + +import json as _json +import typing +from urllib.parse import urlencode + +from ._base_connection import _TYPE_BODY +from ._collections import HTTPHeaderDict +from .filepost import _TYPE_FIELDS, encode_multipart_formdata +from .response import BaseHTTPResponse + +__all__ = ["RequestMethods"] + +_TYPE_ENCODE_URL_FIELDS = typing.Union[ + typing.Sequence[tuple[str, typing.Union[str, bytes]]], + typing.Mapping[str, typing.Union[str, bytes]], +] + + +class RequestMethods: + """ + Convenience mixin for classes who implement a :meth:`urlopen` method, such + as :class:`urllib3.HTTPConnectionPool` and + :class:`urllib3.PoolManager`. + + Provides behavior for making common types of HTTP request methods and + decides which type of request field encoding to use. + + Specifically, + + :meth:`.request_encode_url` is for sending requests whose fields are + encoded in the URL (such as GET, HEAD, DELETE). + + :meth:`.request_encode_body` is for sending requests whose fields are + encoded in the *body* of the request using multipart or www-form-urlencoded + (such as for POST, PUT, PATCH). + + :meth:`.request` is for making any kind of request, it will look up the + appropriate encoding format and use one of the above two methods to make + the request. + + Initializer parameters: + + :param headers: + Headers to include with all requests, unless other headers are given + explicitly. + """ + + _encode_url_methods = {"DELETE", "GET", "HEAD", "OPTIONS"} + + def __init__(self, headers: typing.Mapping[str, str] | None = None) -> None: + self.headers = headers or {} + + def urlopen( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + encode_multipart: bool = True, + multipart_boundary: str | None = None, + **kw: typing.Any, + ) -> BaseHTTPResponse: # Abstract + raise NotImplementedError( + "Classes extending RequestMethods must implement " + "their own ``urlopen`` method." + ) + + def request( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + fields: _TYPE_FIELDS | None = None, + headers: typing.Mapping[str, str] | None = None, + json: typing.Any | None = None, + **urlopen_kw: typing.Any, + ) -> BaseHTTPResponse: + """ + Make a request using :meth:`urlopen` with the appropriate encoding of + ``fields`` based on the ``method`` used. + + This is a convenience method that requires the least amount of manual + effort. It can be used in most situations, while still having the + option to drop down to more specific methods when necessary, such as + :meth:`request_encode_url`, :meth:`request_encode_body`, + or even the lowest level :meth:`urlopen`. + + :param method: + HTTP request method (such as GET, POST, PUT, etc.) + + :param url: + The URL to perform the request on. + + :param body: + Data to send in the request body, either :class:`str`, :class:`bytes`, + an iterable of :class:`str`/:class:`bytes`, or a file-like object. + + :param fields: + Data to encode and send in the URL or request body, depending on ``method``. + + :param headers: + Dictionary of custom headers to send, such as User-Agent, + If-None-Match, etc. If None, pool headers are used. If provided, + these headers completely replace any pool-specific headers. + + :param json: + Data to encode and send as JSON with UTF-encoded in the request body. + The ``"Content-Type"`` header will be set to ``"application/json"`` + unless specified otherwise. + """ + method = method.upper() + + if json is not None and body is not None: + raise TypeError( + "request got values for both 'body' and 'json' parameters which are mutually exclusive" + ) + + if json is not None: + if headers is None: + headers = self.headers + + if not ("content-type" in map(str.lower, headers.keys())): + headers = HTTPHeaderDict(headers) + headers["Content-Type"] = "application/json" + + body = _json.dumps(json, separators=(",", ":"), ensure_ascii=False).encode( + "utf-8" + ) + + if body is not None: + urlopen_kw["body"] = body + + if method in self._encode_url_methods: + return self.request_encode_url( + method, + url, + fields=fields, # type: ignore[arg-type] + headers=headers, + **urlopen_kw, + ) + else: + return self.request_encode_body( + method, url, fields=fields, headers=headers, **urlopen_kw + ) + + def request_encode_url( + self, + method: str, + url: str, + fields: _TYPE_ENCODE_URL_FIELDS | None = None, + headers: typing.Mapping[str, str] | None = None, + **urlopen_kw: str, + ) -> BaseHTTPResponse: + """ + Make a request using :meth:`urlopen` with the ``fields`` encoded in + the url. This is useful for request methods like GET, HEAD, DELETE, etc. + + :param method: + HTTP request method (such as GET, POST, PUT, etc.) + + :param url: + The URL to perform the request on. + + :param fields: + Data to encode and send in the URL. + + :param headers: + Dictionary of custom headers to send, such as User-Agent, + If-None-Match, etc. If None, pool headers are used. If provided, + these headers completely replace any pool-specific headers. + """ + if headers is None: + headers = self.headers + + extra_kw: dict[str, typing.Any] = {"headers": headers} + extra_kw.update(urlopen_kw) + + if fields: + url += "?" + urlencode(fields) + + return self.urlopen(method, url, **extra_kw) + + def request_encode_body( + self, + method: str, + url: str, + fields: _TYPE_FIELDS | None = None, + headers: typing.Mapping[str, str] | None = None, + encode_multipart: bool = True, + multipart_boundary: str | None = None, + **urlopen_kw: str, + ) -> BaseHTTPResponse: + """ + Make a request using :meth:`urlopen` with the ``fields`` encoded in + the body. This is useful for request methods like POST, PUT, PATCH, etc. + + When ``encode_multipart=True`` (default), then + :func:`urllib3.encode_multipart_formdata` is used to encode + the payload with the appropriate content type. Otherwise + :func:`urllib.parse.urlencode` is used with the + 'application/x-www-form-urlencoded' content type. + + Multipart encoding must be used when posting files, and it's reasonably + safe to use it in other times too. However, it may break request + signing, such as with OAuth. + + Supports an optional ``fields`` parameter of key/value strings AND + key/filetuple. A filetuple is a (filename, data, MIME type) tuple where + the MIME type is optional. For example:: + + fields = { + 'foo': 'bar', + 'fakefile': ('foofile.txt', 'contents of foofile'), + 'realfile': ('barfile.txt', open('realfile').read()), + 'typedfile': ('bazfile.bin', open('bazfile').read(), + 'image/jpeg'), + 'nonamefile': 'contents of nonamefile field', + } + + When uploading a file, providing a filename (the first parameter of the + tuple) is optional but recommended to best mimic behavior of browsers. + + Note that if ``headers`` are supplied, the 'Content-Type' header will + be overwritten because it depends on the dynamic random boundary string + which is used to compose the body of the request. The random boundary + string can be explicitly set with the ``multipart_boundary`` parameter. + + :param method: + HTTP request method (such as GET, POST, PUT, etc.) + + :param url: + The URL to perform the request on. + + :param fields: + Data to encode and send in the request body. + + :param headers: + Dictionary of custom headers to send, such as User-Agent, + If-None-Match, etc. If None, pool headers are used. If provided, + these headers completely replace any pool-specific headers. + + :param encode_multipart: + If True, encode the ``fields`` using the multipart/form-data MIME + format. + + :param multipart_boundary: + If not specified, then a random boundary will be generated using + :func:`urllib3.filepost.choose_boundary`. + """ + if headers is None: + headers = self.headers + + extra_kw: dict[str, typing.Any] = {"headers": HTTPHeaderDict(headers)} + body: bytes | str + + if fields: + if "body" in urlopen_kw: + raise TypeError( + "request got values for both 'fields' and 'body', can only specify one." + ) + + if encode_multipart: + body, content_type = encode_multipart_formdata( + fields, boundary=multipart_boundary + ) + else: + body, content_type = ( + urlencode(fields), # type: ignore[arg-type] + "application/x-www-form-urlencoded", + ) + + extra_kw["body"] = body + extra_kw["headers"].setdefault("Content-Type", content_type) + + extra_kw.update(urlopen_kw) + + return self.urlopen(method, url, **extra_kw) diff --git a/.venv/lib/python3.12/site-packages/urllib3/_version.py b/.venv/lib/python3.12/site-packages/urllib3/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..319b966f20a2c9d029c83aa8d263f0f23113ac60 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/_version.py @@ -0,0 +1,24 @@ +# file generated by vcs-versioning +# don't change, don't track in version control +from __future__ import annotations + +__all__ = [ + "__version__", + "__version_tuple__", + "version", + "version_tuple", + "__commit_id__", + "commit_id", +] + +version: str +__version__: str +__version_tuple__: tuple[int | str, ...] +version_tuple: tuple[int | str, ...] +commit_id: str | None +__commit_id__: str | None + +__version__ = version = '2.8.0' +__version_tuple__ = version_tuple = (2, 8, 0) + +__commit_id__ = commit_id = None diff --git a/.venv/lib/python3.12/site-packages/urllib3/connection.py b/.venv/lib/python3.12/site-packages/urllib3/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf3f57ac77ae9909c7295dddf67769d69dc5a27 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/connection.py @@ -0,0 +1,1204 @@ +from __future__ import annotations + +import datetime +import http.client +import logging +import os +import re +import socket +import sys +import threading +import typing +import warnings +from http.client import HTTPConnection as _HTTPConnection +from http.client import HTTPException as HTTPException # noqa: F401 +from http.client import ResponseNotReady +from socket import timeout as SocketTimeout + +if typing.TYPE_CHECKING: + from .response import HTTPResponse + from .util.ssl_ import _TYPE_PEER_CERT_RET_DICT + from .util.ssltransport import SSLTransport + +from ._collections import HTTPHeaderDict +from .http2 import probe as http2_probe +from .util.response import assert_header_parsing +from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT, Timeout +from .util.util import to_str +from .util.wait import wait_for_read + +try: # Compiled with SSL? + import ssl + + BaseSSLError = ssl.SSLError +except (ImportError, AttributeError): + ssl = None # type: ignore[assignment] + + class BaseSSLError(BaseException): # type: ignore[no-redef] + pass + + +from ._base_connection import _TYPE_BODY +from ._base_connection import ProxyConfig as ProxyConfig +from ._base_connection import _ResponseOptions as _ResponseOptions +from ._version import __version__ +from .exceptions import ( + ConnectTimeoutError, + HeaderParsingError, + NameResolutionError, + NewConnectionError, + ProxyError, + SystemTimeWarning, +) +from .util import SKIP_HEADER, SKIPPABLE_HEADERS, connection, ssl_ +from .util.request import body_to_chunks +from .util.ssl_ import assert_fingerprint as _assert_fingerprint +from .util.ssl_ import ( + create_urllib3_context, + is_ipaddress, + resolve_cert_reqs, + resolve_ssl_version, + ssl_wrap_socket, +) +from .util.ssl_match_hostname import CertificateError, match_hostname +from .util.url import Url + +# Not a no-op, we're adding this to the namespace so it can be imported. +ConnectionError = ConnectionError +BrokenPipeError = BrokenPipeError + + +log = logging.getLogger(__name__) + +port_by_scheme = {"http": 80, "https": 443} + +# When it comes time to update this value as a part of regular maintenance +# (ie test_recent_date is failing) update it to ~6 months before the current date. +RECENT_DATE = datetime.date(2025, 1, 1) + +_CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]") +# Starting the optional OWS match at the beginning of a whitespace run avoids +# quadratic backtracking for long header values. +_OBSOLETE_FOLD_RE = re.compile(r"(?:(? str: + if "\r\n" not in value: + return value + return _OBSOLETE_FOLD_RE.sub(" ", value) + + +def _normalize_header_values( + message: http.client.HTTPMessage, +) -> list[tuple[str, str]]: + header_items = message.items() + headers_changed = False + for index, (name, value) in enumerate(header_items): + normalized_value = _normalize_header_value(value) + if normalized_value != value: + header_items[index] = (name, normalized_value) + headers_changed = True + + if headers_changed: + # Keep the original message in sync for downstream consumers such as + # cookie jars while preserving its identity and header ordering. + for name, _ in header_items: + del message[name] + for name, value in header_items: + message[name] = value + + return header_items + + +class HTTPConnection(_HTTPConnection): + """ + Based on :class:`http.client.HTTPConnection` but provides an extra constructor + backwards-compatibility layer between older and newer Pythons. + + Additional keyword parameters are used to configure attributes of the connection. + Accepted parameters include: + + - ``source_address``: Set the source address for the current connection. + - ``socket_options``: Set specific options on the underlying socket. If not specified, then + defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling + Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy. + + For example, if you wish to enable TCP Keep Alive in addition to the defaults, + you might pass: + + .. code-block:: python + + HTTPConnection.default_socket_options + [ + (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), + ] + + Or you may want to disable the defaults by passing an empty list (e.g., ``[]``). + """ + + default_port: typing.ClassVar[int] = port_by_scheme["http"] # type: ignore[misc] + + #: Disable Nagle's algorithm by default. + #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]`` + #: + #: Use the ``socket_options`` parameter of :class:`~urllib3.PoolManager`, + #: :class:`~urllib3.ProxyManager`, or :class:`~urllib3.HTTPConnectionPool` + #: to change this behavior. + default_socket_options: typing.ClassVar[ + typing.Final[connection._TYPE_SOCKET_OPTIONS] + ] = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)] + + #: Whether this connection verifies the host's certificate. + is_verified: bool = False + + #: Whether this proxy connection verified the proxy host's certificate. + # If no proxy is currently connected to the value will be ``None``. + proxy_is_verified: bool | None = None + + blocksize: int + source_address: tuple[str, int] | None + socket_options: connection._TYPE_SOCKET_OPTIONS | None + + _has_connected_to_proxy: bool + _response_options: _ResponseOptions | None + _tunnel_host: str | None + _tunnel_port: int | None + _tunnel_scheme: str | None + + def __init__( + self, + host: str, + port: int | None = None, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 16384, + socket_options: None | ( + connection._TYPE_SOCKET_OPTIONS + ) = default_socket_options, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + ) -> None: + super().__init__( + host=host, + port=port, + timeout=Timeout.resolve_default_timeout(timeout), + source_address=source_address, + blocksize=blocksize, + ) + self.socket_options = socket_options + self.proxy = proxy + self.proxy_config = proxy_config + + self._has_connected_to_proxy = False + self._response_options = None + self._tunnel_host: str | None = None + self._tunnel_port: int | None = None + self._tunnel_scheme: str | None = None + + def __str__(self) -> str: + return f"{type(self).__name__}(host={self.host!r}, port={self.port!r})" + + def __repr__(self) -> str: + return f"<{self} at {id(self):#x}>" + + @property + def host(self) -> str: + """ + Getter method to remove any trailing dots that indicate the hostname is an FQDN. + + In general, SSL certificates don't include the trailing dot indicating a + fully-qualified domain name, and thus, they don't validate properly when + checked against a domain name that includes the dot. In addition, some + servers may not expect to receive the trailing dot when provided. + + However, the hostname with trailing dot is critical to DNS resolution; doing a + lookup with the trailing dot will properly only resolve the appropriate FQDN, + whereas a lookup without a trailing dot will search the system's search domain + list. Thus, it's important to keep the original host around for use only in + those cases where it's appropriate (i.e., when doing DNS lookup to establish the + actual TCP connection across which we're going to send HTTP requests). + """ + return self._dns_host.rstrip(".") + + @host.setter + def host(self, value: str) -> None: + """ + Setter for the `host` property. + + We assume that only urllib3 uses the _dns_host attribute; httplib itself + only uses `host`, and it seems reasonable that other libraries follow suit. + """ + self._dns_host = value + + def _new_conn(self) -> socket.socket: + """Establish a socket connection and set nodelay settings on it. + + :return: New socket connection. + """ + try: + sock = connection.create_connection( + (self._dns_host, self.port), + self.timeout, + source_address=self.source_address, + socket_options=self.socket_options, + ) + except socket.gaierror as e: + raise NameResolutionError(self.host, self, e) from e + except SocketTimeout as e: + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + + except OSError as e: + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + sys.audit("http.client.connect", self, self.host, self.port) + + return sock + + def set_tunnel( + self, + host: str, + port: int | None = None, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + if scheme not in ("http", "https"): + raise ValueError( + f"Invalid proxy scheme for tunneling: {scheme!r}, must be either 'http' or 'https'" + ) + super().set_tunnel(host, port=port, headers=headers) + self._tunnel_scheme = scheme + + if sys.version_info < (3, 11, 16) or ((3, 12) <= sys.version_info < (3, 12, 14)): + # Taken from python/cpython#100986 which was backported in 3.11.9 and 3.12.3. + # When using connection_from_host, host will come without brackets. + # With a security patch from python/cpython#146211. + def _wrap_ipv6(self, ip: bytes) -> bytes: + if b":" in ip and ip[0] != b"["[0]: + return b"[" + ip + b"]" + return ip + + # Copied from CPython 3.12.13 Lib/http/client.py + _is_legal_header_name = staticmethod(re.compile(rb"[^:\s][^:\r\n]*").fullmatch) + _is_illegal_header_value = staticmethod( + re.compile(rb"\n(?![ \t])|\r(?![ \t\n])").search + ) + _contains_disallowed_url_pchar_re = re.compile("[\x00-\x20\x7f]") + + if sys.version_info < (3, 11, 16): + # `_tunnel` copied from 3.11.15 backporting + # https://github.com/python/cpython/commit/0d4026432591d43185568dd31cef6a034c4b9261 + # and https://github.com/python/cpython/commit/6fbc61070fda2ffb8889e77e3b24bca4249ab4d1 + # plus a fix from https://github.com/python/cpython/commit/56b7100b04e44ea27989242b176beb8f016b2c53 + def _tunnel(self) -> None: + if self._contains_disallowed_url_pchar_re.search(self._tunnel_host): # type: ignore[arg-type] + raise ValueError( + "Tunnel host can't contain control characters %r" + % (self._tunnel_host,) + ) + _MAXLINE = http.client._MAXLINE # type: ignore[attr-defined] + connect = b"CONNECT %s:%d HTTP/1.0\r\n" % ( # type: ignore[str-format] + self._wrap_ipv6(self._tunnel_host.encode("ascii")), # type: ignore[union-attr] + self._tunnel_port, + ) + headers = [connect] + for header, value in self._tunnel_headers.items(): # type: ignore[attr-defined] + header_bytes = header.encode("latin-1") + value_bytes = value.encode("latin-1") + if not self._is_legal_header_name(header_bytes): + raise ValueError(f"Invalid header name {header_bytes!r}") + if self._is_illegal_header_value(value_bytes): + raise ValueError(f"Invalid header value {value_bytes!r}") + headers.append(b"%s: %s\r\n" % (header_bytes, value_bytes)) + headers.append(b"\r\n") + # Making a single send() call instead of one per line encourages + # the host OS to use a more optimal packet size instead of + # potentially emitting a series of small packets. + self.send(b"".join(headers)) + del headers + + response = self.response_class(self.sock, method=self._method) # type: ignore[attr-defined] + try: + version, code, message = response._read_status() # type: ignore[attr-defined] + + if code != http.HTTPStatus.OK: + self.close() + raise OSError( + f"Tunnel connection failed: {code} {message.strip()}" + ) + while True: + line = response.fp.readline(_MAXLINE + 1) + if len(line) > _MAXLINE: + raise http.client.LineTooLong("header line") + if not line: + # for sites which EOF without sending a trailer + break + if line in (b"\r\n", b"\n", b""): + break + + if self.debuglevel > 0: + print("header:", line.decode()) + finally: + response.close() + + elif (3, 12) <= sys.version_info < (3, 12, 14): + # `_tunnel` copied from 3.12.13 backporting + # https://github.com/python/cpython/commit/23aef575c7629abcd4aaf028ebd226fb41a4b3c8 + # plus a fix from https://github.com/python/cpython/commit/c00c386faa579ad71196d33408644478488e43ec + def _tunnel(self) -> None: # noqa: F811 + if self._contains_disallowed_url_pchar_re.search(self._tunnel_host): # type: ignore[arg-type] + raise ValueError( + "Tunnel host can't contain control characters %r" + % (self._tunnel_host,) + ) + connect = b"CONNECT %s:%d HTTP/1.1\r\n" % ( # type: ignore[str-format] + self._wrap_ipv6(self._tunnel_host.encode("idna")), # type: ignore[union-attr] + self._tunnel_port, + ) + headers = [connect] + for header, value in self._tunnel_headers.items(): # type: ignore[attr-defined] + header_bytes = header.encode("latin-1") + value_bytes = value.encode("latin-1") + if not self._is_legal_header_name(header_bytes): + raise ValueError(f"Invalid header name {header_bytes!r}") + if self._is_illegal_header_value(value_bytes): + raise ValueError(f"Invalid header value {value_bytes!r}") + headers.append(b"%s: %s\r\n" % (header_bytes, value_bytes)) + headers.append(b"\r\n") + # Making a single send() call instead of one per line encourages + # the host OS to use a more optimal packet size instead of + # potentially emitting a series of small packets. + self.send(b"".join(headers)) + del headers + + response = self.response_class(self.sock, method=self._method) # type: ignore[attr-defined] + try: + version, code, message = response._read_status() # type: ignore[attr-defined] + + self._raw_proxy_headers = http.client._read_headers(response.fp) # type: ignore[attr-defined] + + if self.debuglevel > 0: + for header in self._raw_proxy_headers: + print("header:", header.decode()) + + if code != http.HTTPStatus.OK: + self.close() + raise OSError( + f"Tunnel connection failed: {code} {message.strip()}" + ) + + finally: + response.close() + + def connect(self) -> None: + self.sock = self._new_conn() + if self._tunnel_host: + # If we're tunneling it means we're connected to our proxy. + self._has_connected_to_proxy = True + + # TODO: Fix tunnel so it doesn't depend on self.sock state. + self._tunnel() + + # If there's a proxy to be connected to we are fully connected. + # This is set twice (once above and here) due to forwarding proxies + # not using tunnelling. + self._has_connected_to_proxy = bool(self.proxy) + + if self._has_connected_to_proxy: + self.proxy_is_verified = False + + @property + def is_closed(self) -> bool: + return self.sock is None + + @property + def is_connected(self) -> bool: + if self.sock is None: + return False + return not wait_for_read(self.sock, timeout=0.0) + + @property + def has_connected_to_proxy(self) -> bool: + return self._has_connected_to_proxy + + @property + def proxy_is_forwarding(self) -> bool: + """ + Return True if a forwarding proxy is configured, else return False + """ + return bool(self.proxy) and self._tunnel_host is None + + @property + def proxy_is_tunneling(self) -> bool: + """ + Return True if a tunneling proxy is configured, else return False + """ + return self._tunnel_host is not None + + def close(self) -> None: + try: + super().close() + finally: + # Reset all stateful properties so connection + # can be re-used without leaking prior configs. + self.sock = None + self.is_verified = False + self.proxy_is_verified = None + self._has_connected_to_proxy = False + self._response_options = None + self._tunnel_host = None + self._tunnel_port = None + self._tunnel_scheme = None + + def putrequest( + self, + method: str, + url: str, + skip_host: bool = False, + skip_accept_encoding: bool = False, + ) -> None: + """""" + # Empty docstring because the indentation of CPython's implementation + # is broken but we don't want this method in our documentation. + match = _CONTAINS_CONTROL_CHAR_RE.search(method) + if match: + raise ValueError( + f"Method cannot contain non-token characters {method!r} (found at least {match.group()!r})" + ) + + return super().putrequest( + method, url, skip_host=skip_host, skip_accept_encoding=skip_accept_encoding + ) + + def putheader(self, header: str, *values: str) -> None: # type: ignore[override] + """""" + if not any(isinstance(v, str) and v == SKIP_HEADER for v in values): + super().putheader(header, *values) + elif to_str(header.lower()) not in SKIPPABLE_HEADERS: + skippable_headers = "', '".join( + [str.title(header) for header in sorted(SKIPPABLE_HEADERS)] + ) + raise ValueError( + f"urllib3.util.SKIP_HEADER only supports '{skippable_headers}'" + ) + + # `request` method's signature intentionally violates LSP. + # urllib3's API is different from `http.client.HTTPConnection` and the subclassing is only incidental. + def request( # type: ignore[override] + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + *, + chunked: bool = False, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + ) -> None: + # Update the inner socket's timeout value to send the request. + # This only triggers if the connection is re-used. + if self.sock is not None: + self.sock.settimeout(self.timeout) + + # Store these values to be fed into the HTTPResponse + # object later. TODO: Remove this in favor of a real + # HTTP lifecycle mechanism. + + # We have to store these before we call .request() + # because sometimes we can still salvage a response + # off the wire even if we aren't able to completely + # send the request body. + self._response_options = _ResponseOptions( + request_method=method, + request_url=url, + preload_content=preload_content, + decode_content=decode_content, + enforce_content_length=enforce_content_length, + ) + + if headers is None: + headers = {} + header_keys = frozenset(to_str(k.lower()) for k in headers) + skip_accept_encoding = "accept-encoding" in header_keys + skip_host = "host" in header_keys + self.putrequest( + method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host + ) + + # Transform the body into an iterable of sendall()-able chunks + # and detect if an explicit Content-Length is doable. + chunks_and_cl = body_to_chunks(body, method=method, blocksize=self.blocksize) + chunks = chunks_and_cl.chunks + content_length = chunks_and_cl.content_length + + # When chunked is explicit set to 'True' we respect that. + if chunked: + if "transfer-encoding" not in header_keys: + self.putheader("Transfer-Encoding", "chunked") + else: + # Detect whether a framing mechanism is already in use. If so + # we respect that value, otherwise we pick chunked vs content-length + # depending on the type of 'body'. + if "content-length" in header_keys: + chunked = False + elif "transfer-encoding" in header_keys: + chunked = True + + # Otherwise we go off the recommendation of 'body_to_chunks()'. + else: + chunked = False + if content_length is None: + if chunks is not None: + chunked = True + self.putheader("Transfer-Encoding", "chunked") + else: + self.putheader("Content-Length", str(content_length)) + + # Now that framing headers are out of the way we send all the other headers. + if "user-agent" not in header_keys: + self.putheader("User-Agent", _get_default_user_agent()) + for header, value in headers.items(): + self.putheader(header, value) + self.endheaders() + + # If we're given a body we start sending that in chunks. + if chunks is not None: + for chunk in chunks: + # Sending empty chunks isn't allowed for TE: chunked + # as it indicates the end of the body. + if not chunk: + continue + if isinstance(chunk, str): + chunk = chunk.encode("utf-8") + if chunked: + self.send(b"%x\r\n%b\r\n" % (len(chunk), chunk)) + else: + self.send(chunk) + + # Regardless of whether we have a body or not, if we're in + # chunked mode we want to send an explicit empty chunk. + if chunked: + self.send(b"0\r\n\r\n") + + def request_chunked( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + ) -> None: + """ + Alternative to the common request method, which sends the + body with chunked encoding and not as one block + """ + warnings.warn( + "HTTPConnection.request_chunked() is deprecated and will be removed " + "in urllib3 v3.0. Instead use HTTPConnection.request(..., chunked=True).", + category=FutureWarning, + stacklevel=2, + ) + self.request(method, url, body=body, headers=headers, chunked=True) + + def getresponse( # type: ignore[override] + self, + ) -> HTTPResponse: + """ + Get the response from the server. + + If the HTTPConnection is in the correct state, returns an instance of HTTPResponse or of whatever object is returned by the response_class variable. + + If a request has not been sent or if a previous response has not be handled, ResponseNotReady is raised. If the HTTP response indicates that the connection should be closed, then it will be closed before the response is returned. When the connection is closed, the underlying socket is closed. + """ + # Raise the same error as http.client.HTTPConnection + if self._response_options is None: + raise ResponseNotReady() + + # Reset this attribute for being used again. + resp_options = self._response_options + self._response_options = None + + # Since the connection's timeout value may have been updated + # we need to set the timeout on the socket. + self.sock.settimeout(self.timeout) + + # This is needed here to avoid circular import errors + from .response import HTTPResponse + + # Save a reference to the shutdown function before ownership is passed + # to httplib_response + # TODO should we implement it everywhere? + _shutdown = getattr(self.sock, "shutdown", None) + + # Get the response from http.client.HTTPConnection + httplib_response = super().getresponse() + + try: + assert_header_parsing(httplib_response.msg) + except (HeaderParsingError, TypeError) as hpe: + log.warning( + "Failed to parse headers (url=%s): %s", + _url_from_connection(self, resp_options.request_url), + hpe, + exc_info=True, + ) + + header_items = _normalize_header_values(httplib_response.msg) + headers = HTTPHeaderDict(header_items) + + response = HTTPResponse( + body=httplib_response, + headers=headers, + status=httplib_response.status, + version=httplib_response.version, + version_string=getattr(self, "_http_vsn_str", "HTTP/?"), + reason=httplib_response.reason, + preload_content=resp_options.preload_content, + decode_content=resp_options.decode_content, + original_response=httplib_response, + enforce_content_length=resp_options.enforce_content_length, + request_method=resp_options.request_method, + request_url=resp_options.request_url, + sock_shutdown=_shutdown, + ) + return response + + +class HTTPSConnection(HTTPConnection): + """ + Many of the parameters to this constructor are passed to the underlying SSL + socket by means of :py:func:`urllib3.util.ssl_wrap_socket`. + """ + + default_port = port_by_scheme["https"] # type: ignore[misc] + + cert_reqs: int | str | None = None + ca_certs: str | None = None + ca_cert_dir: str | None = None + ca_cert_data: None | str | bytes = None + ssl_version: int | str | None = None + ssl_minimum_version: int | None = None + ssl_maximum_version: int | None = None + assert_fingerprint: str | None = None + _connect_callback: typing.Callable[..., None] | None = None + + def __init__( + self, + host: str, + port: int | None = None, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 16384, + socket_options: None | ( + connection._TYPE_SOCKET_OPTIONS + ) = HTTPConnection.default_socket_options, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + cert_reqs: int | str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + server_hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + ca_certs: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + ssl_version: int | str | None = None, # Deprecated + cert_file: str | None = None, + key_file: str | None = None, + key_password: str | None = None, + ) -> None: + super().__init__( + host, + port=port, + timeout=timeout, + source_address=source_address, + blocksize=blocksize, + socket_options=socket_options, + proxy=proxy, + proxy_config=proxy_config, + ) + + self.key_file = key_file + self.cert_file = cert_file + self.key_password = key_password + self.ssl_context = ssl_context + self.server_hostname = server_hostname + self.assert_hostname = assert_hostname + self.assert_fingerprint = assert_fingerprint + self.ssl_version = ssl_version + self.ssl_minimum_version = ssl_minimum_version + self.ssl_maximum_version = ssl_maximum_version + self.ca_certs = ca_certs and os.path.expanduser(ca_certs) + self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) + self.ca_cert_data = ca_cert_data + + # cert_reqs depends on ssl_context so calculate last. + if cert_reqs is None: + if self.ssl_context is not None: + cert_reqs = self.ssl_context.verify_mode + else: + cert_reqs = resolve_cert_reqs(None) + self.cert_reqs = cert_reqs + self._connect_callback = None + + def set_cert( + self, + key_file: str | None = None, + cert_file: str | None = None, + cert_reqs: int | str | None = None, + key_password: str | None = None, + ca_certs: str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ) -> None: + """ + This method should only be called once, before the connection is used. + """ + warnings.warn( + "HTTPSConnection.set_cert() is deprecated and will be removed " + "in urllib3 v3.0. Instead provide the parameters to the " + "HTTPSConnection constructor.", + category=FutureWarning, + stacklevel=2, + ) + + # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also + # have an SSLContext object in which case we'll use its verify_mode. + if cert_reqs is None: + if self.ssl_context is not None: + cert_reqs = self.ssl_context.verify_mode + else: + cert_reqs = resolve_cert_reqs(None) + + self.key_file = key_file + self.cert_file = cert_file + self.cert_reqs = cert_reqs + self.key_password = key_password + self.assert_hostname = assert_hostname + self.assert_fingerprint = assert_fingerprint + self.ca_certs = ca_certs and os.path.expanduser(ca_certs) + self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) + self.ca_cert_data = ca_cert_data + + def connect(self) -> None: + # Today we don't need to be doing this step before the /actual/ socket + # connection, however in the future we'll need to decide whether to + # create a new socket or re-use an existing "shared" socket as a part + # of the HTTP/2 handshake dance. + if self._tunnel_host is not None and self._tunnel_port is not None: + probe_http2_host = self._tunnel_host + probe_http2_port = self._tunnel_port + else: + probe_http2_host = self.host + probe_http2_port = self.port + + # Check if the target origin supports HTTP/2. + # If the value comes back as 'None' it means that the current thread + # is probing for HTTP/2 support. Otherwise, we're waiting for another + # probe to complete, or we get a value right away. + target_supports_http2: bool | None + if "h2" in ssl_.ALPN_PROTOCOLS: + target_supports_http2 = http2_probe.acquire_and_get( + host=probe_http2_host, port=probe_http2_port + ) + else: + # If HTTP/2 isn't going to be offered it doesn't matter if + # the target supports HTTP/2. Don't want to make a probe. + target_supports_http2 = False + + if self._connect_callback is not None: + self._connect_callback( + "before connect", + thread_id=threading.get_ident(), + target_supports_http2=target_supports_http2, + ) + + try: + sock: socket.socket | ssl.SSLSocket + self.sock = sock = self._new_conn() + server_hostname: str = self.host + tls_in_tls = False + + # Do we need to establish a tunnel? + if self.proxy_is_tunneling: + # We're tunneling to an HTTPS origin so need to do TLS-in-TLS. + if self._tunnel_scheme == "https": + # _connect_tls_proxy will verify and assign proxy_is_verified + self.sock = sock = self._connect_tls_proxy(self.host, sock) + tls_in_tls = True + elif self._tunnel_scheme == "http": + self.proxy_is_verified = False + + # If we're tunneling it means we're connected to our proxy. + self._has_connected_to_proxy = True + + self._tunnel() + # Override the host with the one we're requesting data from. + server_hostname = typing.cast(str, self._tunnel_host) + + if self.server_hostname is not None: + server_hostname = self.server_hostname + + is_time_off = datetime.date.today() < RECENT_DATE + if is_time_off: + warnings.warn( + ( + f"System time is way off (before {RECENT_DATE}). This will probably " + "lead to SSL verification errors" + ), + SystemTimeWarning, + ) + + # Remove trailing '.' from fqdn hostnames to allow certificate validation + server_hostname_rm_dot = server_hostname.rstrip(".") + + # Forwarding proxies should use proxy SSL context for + # wrapping since that's the connection being established, + # whereas tunneling proxies should use the connection's SSL + # context. + # However, for backwards compatibility reasons, if the proxy + # is forwarding but no proxy SSL context is provided, we + # fall back to using the connection's SSL context until + # urllib3 v3.0. Appropriate warning is emitted in + # ``ProxyManager.__init__``. + wrapped_socket: ssl.SSLSocket | SSLTransport + if self.proxy_is_forwarding and self.proxy_config is not None: + wrapped_socket = self._connect_tls_proxy(self.host, sock) + is_verified = self.proxy_is_verified is True + else: + wrapped_socket, is_verified = _ssl_wrap_socket_and_match_hostname( + sock=sock, + cert_reqs=self.cert_reqs, + ssl_version=self.ssl_version, + ssl_minimum_version=self.ssl_minimum_version, + ssl_maximum_version=self.ssl_maximum_version, + ca_certs=self.ca_certs, + ca_cert_dir=self.ca_cert_dir, + ca_cert_data=self.ca_cert_data, + cert_file=self.cert_file, + key_file=self.key_file, + key_password=self.key_password, + server_hostname=server_hostname_rm_dot, + ssl_context=self.ssl_context, + tls_in_tls=tls_in_tls, + assert_hostname=self.assert_hostname, + assert_fingerprint=self.assert_fingerprint, + ) + self.sock = wrapped_socket + + # If an error occurs during connection/handshake we may need to release + # our lock so another connection can probe the origin. + except BaseException: + if self._connect_callback is not None: + self._connect_callback( + "after connect failure", + thread_id=threading.get_ident(), + target_supports_http2=target_supports_http2, + ) + + if target_supports_http2 is None: + http2_probe.set_and_release( + host=probe_http2_host, port=probe_http2_port, supports_http2=None + ) + raise + + # If this connection doesn't know if the origin supports HTTP/2 + # we report back to the HTTP/2 probe our result. + if target_supports_http2 is None: + supports_http2 = wrapped_socket.selected_alpn_protocol() == "h2" + http2_probe.set_and_release( + host=probe_http2_host, + port=probe_http2_port, + supports_http2=supports_http2, + ) + + # Forwarding proxies can never have a verified target since + # the proxy is the one doing the verification. Should instead + # use a CONNECT tunnel in order to verify the target. + # See: https://github.com/urllib3/urllib3/issues/3267. + if self.proxy_is_forwarding: + self.is_verified = False + else: + self.is_verified = is_verified + + # If there's a proxy to be connected to we are fully connected. + # This is set twice (once above and here) due to forwarding proxies + # not using tunnelling. + self._has_connected_to_proxy = bool(self.proxy) + + # Set `self.proxy_is_verified` unless it's already set while + # establishing a tunnel. + if self._has_connected_to_proxy and self.proxy_is_verified is None: + self.proxy_is_verified = is_verified + + def _connect_tls_proxy(self, hostname: str, sock: socket.socket) -> ssl.SSLSocket: + """ + Establish a TLS connection to the proxy using proxy-specific policy. + """ + proxy_config = typing.cast(ProxyConfig, self.proxy_config) + proxy_ssl_context = proxy_config.ssl_context + + ssl_context: ssl.SSLContext | None + cert_reqs: int | str | None + if proxy_ssl_context is not None: + # Prefer the proxy's cert policy for the proxy connection + ssl_context = proxy_ssl_context + cert_reqs = proxy_ssl_context.verify_mode + ca_certs = None + ca_cert_dir = None + ca_cert_data = None + ssl_version = None + ssl_minimum_version = None + ssl_maximum_version = None + else: + # Otherwise we inherit the pool's cert policies + ssl_context = self.ssl_context if self.proxy_is_forwarding else None + cert_reqs = self.cert_reqs + ca_certs = self.ca_certs + ca_cert_dir = self.ca_cert_dir + ca_cert_data = self.ca_cert_data + ssl_version = self.ssl_version + ssl_minimum_version = self.ssl_minimum_version + ssl_maximum_version = self.ssl_maximum_version + + sock_and_verified = _ssl_wrap_socket_and_match_hostname( + sock, + cert_reqs=cert_reqs, + ssl_version=ssl_version, + ssl_minimum_version=ssl_minimum_version, + ssl_maximum_version=ssl_maximum_version, + ca_certs=ca_certs, + ca_cert_dir=ca_cert_dir, + ca_cert_data=ca_cert_data, + server_hostname=hostname, + ssl_context=ssl_context, + assert_hostname=proxy_config.assert_hostname, + assert_fingerprint=proxy_config.assert_fingerprint, + # Features that aren't implemented for proxies yet: + cert_file=None, + key_file=None, + key_password=None, + tls_in_tls=False, + ) + self.proxy_is_verified = sock_and_verified.is_verified + return sock_and_verified.socket # type: ignore[return-value] + + +class _WrappedAndVerifiedSocket(typing.NamedTuple): + """ + Wrapped socket and whether the connection is + verified after the TLS handshake + """ + + socket: ssl.SSLSocket | SSLTransport + is_verified: bool + + +def _ssl_wrap_socket_and_match_hostname( + sock: socket.socket, + *, + cert_reqs: None | str | int, + ssl_version: None | str | int, + ssl_minimum_version: int | None, + ssl_maximum_version: int | None, + cert_file: str | None, + key_file: str | None, + key_password: str | None, + ca_certs: str | None, + ca_cert_dir: str | None, + ca_cert_data: None | str | bytes, + assert_hostname: None | str | typing.Literal[False], + assert_fingerprint: str | None, + server_hostname: str | None, + ssl_context: ssl.SSLContext | None, + tls_in_tls: bool = False, +) -> _WrappedAndVerifiedSocket: + """Logic for constructing an SSLContext from all TLS parameters, passing + that down into ssl_wrap_socket, and then doing certificate verification + either via hostname or fingerprint. This function exists to guarantee + that both proxies and targets have the same behavior when connecting via TLS. + """ + default_ssl_context = False + if ssl_context is None: + default_ssl_context = True + context = create_urllib3_context( + ssl_version=resolve_ssl_version(ssl_version), + ssl_minimum_version=ssl_minimum_version, + ssl_maximum_version=ssl_maximum_version, + cert_reqs=resolve_cert_reqs(cert_reqs), + ) + else: + context = ssl_context + + context.verify_mode = resolve_cert_reqs(cert_reqs) + + # In some cases, we want to verify hostnames ourselves + if ( + # `ssl` can't verify fingerprints or alternate hostnames + assert_fingerprint + or assert_hostname + # assert_hostname can be set to False to disable hostname checking + or assert_hostname is False + # We still support OpenSSL 1.0.2, which prevents us from verifying + # hostnames easily: https://github.com/pyca/pyopenssl/pull/933 + or ssl_.IS_PYOPENSSL + or not ssl_.HAS_NEVER_CHECK_COMMON_NAME + ): + context.check_hostname = False + + # Try to load OS default certs if none are given. We need to do the hasattr() check + # for custom pyOpenSSL SSLContext objects because they don't support + # load_default_certs(). + if ( + not ca_certs + and not ca_cert_dir + and not ca_cert_data + and default_ssl_context + and hasattr(context, "load_default_certs") + ): + context.load_default_certs() + + # Ensure that IPv6 addresses are in the proper format and don't have a + # scope ID. Python's SSL module fails to recognize scoped IPv6 addresses + # and interprets them as DNS hostnames. + if server_hostname is not None: + normalized = server_hostname.strip("[]") + if "%" in normalized: + normalized = normalized[: normalized.rfind("%")] + if is_ipaddress(normalized): + server_hostname = normalized + + ssl_sock = ssl_wrap_socket( + sock=sock, + keyfile=key_file, + certfile=cert_file, + key_password=key_password, + ca_certs=ca_certs, + ca_cert_dir=ca_cert_dir, + ca_cert_data=ca_cert_data, + server_hostname=server_hostname, + ssl_context=context, + tls_in_tls=tls_in_tls, + ) + + try: + if assert_fingerprint: + _assert_fingerprint( + ssl_sock.getpeercert(binary_form=True), assert_fingerprint + ) + elif ( + context.verify_mode != ssl.CERT_NONE + and not context.check_hostname + and assert_hostname is not False + ): + cert: _TYPE_PEER_CERT_RET_DICT = ssl_sock.getpeercert() # type: ignore[assignment] + + # Need to signal to our match_hostname whether to use 'commonName' or not. + # If we're using our own constructed SSLContext we explicitly set 'False' + # because PyPy hard-codes 'True' from SSLContext.hostname_checks_common_name. + if default_ssl_context: + hostname_checks_common_name = False + else: + hostname_checks_common_name = ( + getattr(context, "hostname_checks_common_name", False) or False + ) + + _match_hostname( + cert, + assert_hostname or server_hostname, # type: ignore[arg-type] + hostname_checks_common_name, + ) + + return _WrappedAndVerifiedSocket( + socket=ssl_sock, + is_verified=context.verify_mode == ssl.CERT_REQUIRED + or bool(assert_fingerprint), + ) + except BaseException: + ssl_sock.close() + raise + + +def _match_hostname( + cert: _TYPE_PEER_CERT_RET_DICT | None, + asserted_hostname: str, + hostname_checks_common_name: bool = False, +) -> None: + # Our upstream implementation of ssl.match_hostname() + # only applies this normalization to IP addresses so it doesn't + # match DNS SANs so we do the same thing! + stripped_hostname = asserted_hostname.strip("[]") + if is_ipaddress(stripped_hostname): + asserted_hostname = stripped_hostname + + try: + match_hostname(cert, asserted_hostname, hostname_checks_common_name) + except CertificateError as e: + log.warning( + "Certificate did not match expected hostname: %s. Certificate: %s", + asserted_hostname, + cert, + ) + # Add cert to exception and reraise so client code can inspect + # the cert when catching the exception, if they want to + e._peer_cert = cert # type: ignore[attr-defined] + raise + + +def _wrap_proxy_error(err: Exception, proxy_scheme: str | None) -> ProxyError: + # Look for the phrase 'wrong version number', if found + # then we should warn the user that we're very sure that + # this proxy is HTTP-only and they have a configuration issue. + error_normalized = " ".join(re.split("[^a-z]", str(err).lower())) + is_likely_http_proxy = ( + "wrong version number" in error_normalized + or "unknown protocol" in error_normalized + or "record layer failure" in error_normalized + ) + http_proxy_warning = ( + ". Your proxy appears to only use HTTP and not HTTPS, " + "try changing your proxy URL to be HTTP. See: " + "https://urllib3.readthedocs.io/en/latest/advanced-usage.html" + "#https-proxy-error-http-proxy" + ) + new_err = ProxyError( + f"Unable to connect to proxy" + f"{http_proxy_warning if is_likely_http_proxy and proxy_scheme == 'https' else ''}", + err, + ) + new_err.__cause__ = err + return new_err + + +def _get_default_user_agent() -> str: + return f"python-urllib3/{__version__}" + + +class DummyConnection: + """Used to detect a failed ConnectionCls import.""" + + +if not ssl: + HTTPSConnection = DummyConnection # type: ignore[misc, assignment] # noqa: F811 + + +VerifiedHTTPSConnection = HTTPSConnection + + +def _url_from_connection( + conn: HTTPConnection | HTTPSConnection, path: str | None = None +) -> str: + """Returns the URL from a given connection. This is mainly used for testing and logging.""" + + scheme = "https" if isinstance(conn, HTTPSConnection) else "http" + + return Url(scheme=scheme, host=conn.host, port=conn.port, path=path).url diff --git a/.venv/lib/python3.12/site-packages/urllib3/connectionpool.py b/.venv/lib/python3.12/site-packages/urllib3/connectionpool.py new file mode 100644 index 0000000000000000000000000000000000000000..5ed9444df6bd53b52f6913c4e58edb9c36d9aea3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/connectionpool.py @@ -0,0 +1,1211 @@ +from __future__ import annotations + +import errno +import logging +import queue +import sys +import typing +import warnings +import weakref +from socket import timeout as SocketTimeout +from types import TracebackType + +from ._base_connection import _TYPE_BODY +from ._collections import HTTPHeaderDict +from ._request_methods import RequestMethods +from .connection import ( + BaseSSLError, + BrokenPipeError, + DummyConnection, + HTTPConnection, + HTTPException, + HTTPSConnection, + ProxyConfig, + _wrap_proxy_error, +) +from .connection import port_by_scheme as port_by_scheme +from .exceptions import ( + ClosedPoolError, + EmptyPoolError, + FullPoolError, + HostChangedError, + InsecureRequestWarning, + LocationValueError, + MaxRetryError, + NewConnectionError, + ProtocolError, + ProxyError, + ReadTimeoutError, + SSLError, + TimeoutError, +) +from .response import BaseHTTPResponse +from .util.connection import is_connection_dropped +from .util.proxy import connection_requires_http_tunnel +from .util.request import _TYPE_BODY_POSITION, set_file_position +from .util.retry import Retry +from .util.ssl_match_hostname import CertificateError +from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_DEFAULT, Timeout +from .util.url import Url, _encode_target +from .util.url import _normalize_host as normalize_host +from .util.url import parse_url +from .util.util import to_str + +if typing.TYPE_CHECKING: + import ssl + + from typing_extensions import Self + + from ._base_connection import BaseHTTPConnection, BaseHTTPSConnection + +log = logging.getLogger(__name__) + +_TYPE_TIMEOUT = typing.Union[Timeout, float, _TYPE_DEFAULT, None] +_DEFAULT_QUEUE_CLASS = queue.LifoQueue + + +# Pool objects +class ConnectionPool: + """ + Base class for all connection pools, such as + :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`. + + .. note:: + ConnectionPool.urlopen() does not normalize or percent-encode target URIs + which is useful if your target server doesn't support percent-encoded + target URIs. + """ + + scheme: str | None = None + QueueCls = _DEFAULT_QUEUE_CLASS + + def __init__(self, host: str, port: int | None = None) -> None: + if not host: + raise LocationValueError("No host specified.") + + self.host = _normalize_host(host, scheme=self.scheme) + self.port = port + + # This property uses 'normalize_host()' (not '_normalize_host()') + # to avoid removing square braces around IPv6 addresses. + # This value is sent to `HTTPConnection.set_tunnel()` if called + # because square braces are required for HTTP CONNECT tunneling. + self._tunnel_host = normalize_host(host, scheme=self.scheme).lower() + + def __str__(self) -> str: + return f"{type(self).__name__}(host={self.host!r}, port={self.port!r})" + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> typing.Literal[False]: + self.close() + # Return False to re-raise any potential exceptions + return False + + def close(self) -> None: + """ + Close all pooled connections and disable the pool. + """ + + def _new_pool_queue(self, maxsize: int) -> queue.LifoQueue[typing.Any]: + if self.QueueCls is _DEFAULT_QUEUE_CLASS: + return queue.LifoQueue(maxsize) + return self.QueueCls(maxsize) + + +# This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252 +_blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK} + + +class HTTPConnectionPool(ConnectionPool, RequestMethods): + """ + Thread-safe connection pool for one host. + + :param host: + Host used for this HTTP Connection (e.g. "localhost"), passed into + :class:`http.client.HTTPConnection`. + + :param port: + Port used for this HTTP Connection (None is equivalent to 80), passed + into :class:`http.client.HTTPConnection`. + + :param timeout: + Socket timeout in seconds for each individual connection. This can + be a float or integer, which sets the timeout for the HTTP request, + or an instance of :class:`urllib3.util.Timeout` which gives you more + fine-grained control over request timeouts. After the constructor has + been parsed, this is always a `urllib3.util.Timeout` object. + + :param maxsize: + Number of connections to save that can be reused. More than 1 is useful + in multithreaded situations. If ``block`` is set to False, more + connections will be created but they will not be saved once they've + been used. + + :param block: + If set to True, no more than ``maxsize`` connections will be used at + a time. When no free connections are available, the call will block + until a connection has been released. This is a useful side effect for + particular multithreaded situations where one does not want to use more + than maxsize connections per host to prevent flooding. + + :param headers: + Headers to include with all requests, unless other headers are given + explicitly. + + :param retries: + Retry configuration to use by default with requests in this pool. + + :param _proxy: + Parsed proxy URL, should not be used directly, instead, see + :class:`urllib3.ProxyManager` + + :param _proxy_headers: + A dictionary with proxy headers, should not be used directly, + instead, see :class:`urllib3.ProxyManager` + + :param \\**conn_kw: + Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`, + :class:`urllib3.connection.HTTPSConnection` instances. + """ + + scheme = "http" + ConnectionCls: type[BaseHTTPConnection] | type[BaseHTTPSConnection] = HTTPConnection + + def __init__( + self, + host: str, + port: int | None = None, + timeout: _TYPE_TIMEOUT | None = _DEFAULT_TIMEOUT, + maxsize: int = 1, + block: bool = False, + headers: typing.Mapping[str, str] | None = None, + retries: Retry | bool | int | None = None, + _proxy: Url | None = None, + _proxy_headers: typing.Mapping[str, str] | None = None, + _proxy_config: ProxyConfig | None = None, + **conn_kw: typing.Any, + ): + ConnectionPool.__init__(self, host, port) + RequestMethods.__init__(self, headers) + + if not isinstance(timeout, Timeout): + timeout = Timeout.from_float(timeout) + + if retries is None: + retries = Retry.DEFAULT + + self.timeout = timeout + self.retries = retries + + self.pool: queue.LifoQueue[typing.Any] | None = self._new_pool_queue(maxsize) + self.block = block + + self.proxy = _proxy + self.proxy_headers = _proxy_headers or {} + self.proxy_config = _proxy_config + + # Fill the queue up so that doing get() on it will block properly + for _ in range(maxsize): + self.pool.put(None) + + # These are mostly for testing and debugging purposes. + self.num_connections = 0 + self.num_requests = 0 + self.conn_kw = conn_kw + + if self.proxy: + # Enable Nagle's algorithm for proxies, to avoid packet fragmentation. + # Defaulting `socket_options` to an empty list avoids it defaulting to + # ``HTTPConnection.default_socket_options``. + self.conn_kw.setdefault("socket_options", []) + + self.conn_kw["proxy"] = self.proxy + self.conn_kw["proxy_config"] = self.proxy_config + + # Do not pass 'self' as callback to 'finalize'. + # Then the 'finalize' would keep an endless living (leak) to self. + # By just passing a reference to the pool allows the garbage collector + # to free self if nobody else has a reference to it. + pool = self.pool + + # Close all the HTTPConnections in the pool before the + # HTTPConnectionPool object is garbage collected. + weakref.finalize(self, _close_pool_connections, pool) + + def _new_conn(self) -> BaseHTTPConnection: + """ + Return a fresh :class:`HTTPConnection`. + """ + self.num_connections += 1 + log.debug( + "Starting new HTTP connection (%d): %s:%s", + self.num_connections, + self.host, + self.port or "80", + ) + + conn = self.ConnectionCls( + host=self.host, + port=self.port, + timeout=self.timeout.connect_timeout, + **self.conn_kw, + ) + return conn + + def _get_conn(self, timeout: float | None = None) -> BaseHTTPConnection: + """ + Get a connection. Will return a pooled connection if one is available. + + If no connections are available and :prop:`.block` is ``False``, then a + fresh connection is returned. + + :param timeout: + Seconds to wait before giving up and raising + :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and + :prop:`.block` is ``True``. + """ + conn = None + + if self.pool is None: + raise ClosedPoolError(self, "Pool is closed.") + + try: + conn = self.pool.get(block=self.block, timeout=timeout) + + except AttributeError: # self.pool is None + raise ClosedPoolError(self, "Pool is closed.") from None # Defensive: + + except queue.Empty: + if self.block: + raise EmptyPoolError( + self, + "Pool is empty and a new connection can't be opened due to blocking mode.", + ) from None + pass # Oh well, we'll create a new connection then + + # If this is a persistent connection, check if it got disconnected + if conn and is_connection_dropped(conn): + log.debug("Resetting dropped connection: %s", self.host) + conn.close() + + return conn or self._new_conn() + + def _put_conn(self, conn: BaseHTTPConnection | None) -> None: + """ + Put a connection back into the pool. + + :param conn: + Connection object for the current host and port as returned by + :meth:`._new_conn` or :meth:`._get_conn`. + + If the pool is already full, the connection is closed and discarded + because we exceeded maxsize. If connections are discarded frequently, + then maxsize should be increased. + + If the pool is closed, then the connection will be closed and discarded. + """ + if self.pool is not None: + try: + self.pool.put(conn, block=False) + return # Everything is dandy, done. + except AttributeError: + # self.pool is None. + pass + except queue.Full: + # Connection never got put back into the pool, close it. + if conn: + conn.close() + + if self.block: + # This should never happen if you got the conn from self._get_conn + raise FullPoolError( + self, + "Pool reached maximum size and no more connections are allowed.", + ) from None + + log.warning( + "Connection pool is full, discarding connection: %s. Connection pool size: %s", + self.host, + self.pool.qsize(), + ) + + # Connection never got put back into the pool, close it. + if conn: + conn.close() + + def _validate_conn(self, conn: BaseHTTPConnection) -> None: + """ + Called right before a request is made, after the socket is created. + """ + + def _prepare_proxy(self, conn: BaseHTTPConnection) -> None: + # Nothing to do for HTTP connections. + pass + + def _get_timeout(self, timeout: _TYPE_TIMEOUT) -> Timeout: + """Helper that always returns a :class:`urllib3.util.Timeout`""" + if timeout is _DEFAULT_TIMEOUT: + return self.timeout.clone() + + if isinstance(timeout, Timeout): + return timeout.clone() + else: + # User passed us an int/float. This is for backwards compatibility, + # can be removed later + return Timeout.from_float(timeout) + + def _raise_timeout( + self, + err: BaseSSLError | OSError | SocketTimeout, + url: str, + timeout_value: _TYPE_TIMEOUT | None, + ) -> None: + """Is the error actually a timeout? Will raise a ReadTimeout or pass""" + + if isinstance(err, SocketTimeout): + raise ReadTimeoutError( + self, url, f"Read timed out. (read timeout={timeout_value})" + ) from err + + # See the above comment about EAGAIN in Python 3. + if hasattr(err, "errno") and err.errno in _blocking_errnos: + raise ReadTimeoutError( + self, url, f"Read timed out. (read timeout={timeout_value})" + ) from err + + def _make_request( + self, + conn: BaseHTTPConnection, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + retries: Retry | None = None, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + chunked: bool = False, + response_conn: BaseHTTPConnection | None = None, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + ) -> BaseHTTPResponse: + """ + Perform a request on a given urllib connection object taken from our + pool. + + :param conn: + a connection from one of our connection pools + + :param method: + HTTP request method (such as GET, POST, PUT, etc.) + + :param url: + The URL to perform the request on. + + :param body: + Data to send in the request body, either :class:`str`, :class:`bytes`, + an iterable of :class:`str`/:class:`bytes`, or a file-like object. + + :param headers: + Dictionary of custom headers to send, such as User-Agent, + If-None-Match, etc. If None, pool headers are used. If provided, + these headers completely replace any pool-specific headers. + + :param retries: + Configure the number of retries to allow before raising a + :class:`~urllib3.exceptions.MaxRetryError` exception. + + Pass ``None`` to retry until you receive a response. Pass a + :class:`~urllib3.util.retry.Retry` object for fine-grained control + over different types of retries. + Pass an integer number to retry connection errors that many times, + but no other types of errors. Pass zero to never retry. + + If ``False``, then retries are disabled and any exception is raised + immediately. Also, instead of raising a MaxRetryError on redirects, + the redirect response will be returned. + + :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. + + :param timeout: + If specified, overrides the default timeout for this one + request. It may be a float (in seconds) or an instance of + :class:`urllib3.util.Timeout`. + + :param chunked: + If True, urllib3 will send the body using chunked transfer + encoding. Otherwise, urllib3 will send the body using the standard + content-length form. Defaults to False. + + :param response_conn: + Set this to ``None`` if you will handle releasing the connection or + set the connection to have the response release it. + + :param preload_content: + If True, the response's body will be preloaded during construction. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + + :param enforce_content_length: + Enforce content length checking. Body returned by server must match + value of Content-Length header, if present. Otherwise, raise error. + """ + self.num_requests += 1 + + timeout_obj = self._get_timeout(timeout) + timeout_obj.start_connect() + conn.timeout = Timeout.resolve_default_timeout(timeout_obj.connect_timeout) + + try: + # Trigger any extra validation we need to do. + try: + self._validate_conn(conn) + except (SocketTimeout, BaseSSLError) as e: + self._raise_timeout(err=e, url=url, timeout_value=conn.timeout) + raise + + # _validate_conn() starts the connection to an HTTPS proxy + # so we need to wrap errors with 'ProxyError' here too. + except ( + OSError, + NewConnectionError, + TimeoutError, + BaseSSLError, + CertificateError, + SSLError, + ) as e: + new_e: Exception = e + if isinstance(e, (BaseSSLError, CertificateError)): + new_e = SSLError(e) + # If the connection didn't successfully connect to it's proxy + # then there + if isinstance( + new_e, (OSError, NewConnectionError, TimeoutError, SSLError) + ) and (conn and conn.proxy and not conn.has_connected_to_proxy): + new_e = _wrap_proxy_error(new_e, conn.proxy.scheme) + raise new_e + + # conn.request() calls http.client.*.request, not the method in + # urllib3.request. It also calls makefile (recv) on the socket. + try: + conn.request( + method, + url, + body=body, + headers=headers, + chunked=chunked, + preload_content=preload_content, + decode_content=decode_content, + enforce_content_length=enforce_content_length, + ) + + # We are swallowing BrokenPipeError (errno.EPIPE) since the server is + # legitimately able to close the connection after sending a valid response. + # With this behaviour, the received response is still readable. + except BrokenPipeError: + pass + except OSError as e: + # MacOS/Linux + # EPROTOTYPE and ECONNRESET are needed on macOS + # https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/ + # Condition changed later to emit ECONNRESET instead of only EPROTOTYPE. + if e.errno != errno.EPROTOTYPE and e.errno != errno.ECONNRESET: + raise + + # Reset the timeout for the recv() on the socket + read_timeout = timeout_obj.read_timeout + + if not conn.is_closed: + # In Python 3 socket.py will catch EAGAIN and return None when you + # try and read into the file pointer created by http.client, which + # instead raises a BadStatusLine exception. Instead of catching + # the exception and assuming all BadStatusLine exceptions are read + # timeouts, check for a zero timeout before making the request. + if read_timeout == 0: + raise ReadTimeoutError( + self, url, f"Read timed out. (read timeout={read_timeout})" + ) + conn.timeout = read_timeout + + # Receive the response from the server + try: + response = conn.getresponse() + except (BaseSSLError, OSError) as e: + self._raise_timeout(err=e, url=url, timeout_value=read_timeout) + raise + + # Set properties that are used by the pooling layer. + response.retries = retries + response._connection = response_conn # type: ignore[attr-defined] + response._pool = self # type: ignore[attr-defined] + + log.debug( + '%s://%s:%s "%s %s %s" %s %s', + self.scheme, + self.host, + self.port, + method, + url, + response.version_string, + response.status, + response.length_remaining, + ) + + return response + + def close(self) -> None: + """ + Close all pooled connections and disable the pool. + """ + if self.pool is None: + return + # Disable access to the pool + old_pool, self.pool = self.pool, None + + # Close all the HTTPConnections in the pool. + _close_pool_connections(old_pool) + + def is_same_host(self, url: str) -> bool: + """ + Check if the given ``url`` is a member of the same host as this + connection pool. + """ + if url.startswith("/"): + return True + + # TODO: Add optional support for socket.gethostbyname checking. + scheme, _, host, port, *_ = parse_url(url) + scheme = scheme or "http" + if host is not None: + host = _normalize_host(host, scheme=scheme) + + # Use explicit default port for comparison when none is given + if self.port is not None and port is None: + port = port_by_scheme.get(scheme) + elif self.port is None and port == port_by_scheme.get(scheme): + port = None + + return (scheme, host, port) == (self.scheme, self.host, self.port) + + def urlopen( # type: ignore[override] + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + retries: Retry | bool | int | None = None, + redirect: bool = True, + assert_same_host: bool = True, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + pool_timeout: int | None = None, + release_conn: bool | None = None, + chunked: bool = False, + body_pos: _TYPE_BODY_POSITION | None = None, + preload_content: bool = True, + decode_content: bool = True, + **response_kw: typing.Any, + ) -> BaseHTTPResponse: + """ + Get a connection from the pool and perform an HTTP request. This is the + lowest level call for making a request, so you'll need to specify all + the raw details. + + .. note:: + + More commonly, it's appropriate to use a convenience method + such as :meth:`request`. + + .. note:: + + `release_conn` will only behave as expected if + `preload_content=False` because we want to make + `preload_content=False` the default behaviour someday soon without + breaking backwards compatibility. + + :param method: + HTTP request method (such as GET, POST, PUT, etc.) + + :param url: + The URL to perform the request on. + + :param body: + Data to send in the request body, either :class:`str`, :class:`bytes`, + an iterable of :class:`str`/:class:`bytes`, or a file-like object. + + :param headers: + Dictionary of custom headers to send, such as User-Agent, + If-None-Match, etc. If None, pool headers are used. If provided, + these headers completely replace any pool-specific headers. + + :param retries: + Configure the number of retries to allow before raising a + :class:`~urllib3.exceptions.MaxRetryError` exception. + + If ``None`` (default) will retry 3 times, see ``Retry.DEFAULT``. Pass a + :class:`~urllib3.util.retry.Retry` object for fine-grained control + over different types of retries. + Pass an integer number to retry connection errors that many times, + but no other types of errors. Pass zero to never retry. + + If ``False``, then retries are disabled and any exception is raised + immediately. Also, instead of raising a MaxRetryError on redirects, + the redirect response will be returned. + + :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. + + :param redirect: + If True, automatically handle redirects (status codes 301, 302, + 303, 307, 308). Each redirect counts as a retry. Disabling retries + will disable redirect, too. + + :param assert_same_host: + If ``True``, will make sure that the host of the pool requests is + consistent else will raise HostChangedError. When ``False``, you can + use the pool on an HTTP proxy and request foreign hosts. + + :param timeout: + If specified, overrides the default timeout for this one + request. It may be a float (in seconds) or an instance of + :class:`urllib3.util.Timeout`. + + :param pool_timeout: + If set and the pool is set to block=True, then this method will + block for ``pool_timeout`` seconds and raise EmptyPoolError if no + connection is available within the time period. + + :param bool preload_content: + If True, the response's body will be preloaded into memory. + + :param bool decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + + :param release_conn: + If False, then the urlopen call will not release the connection + back into the pool once a response is received (but will release if + you read the entire contents of the response such as when + `preload_content=True`). This is useful if you're not preloading + the response's content immediately. You will need to call + ``r.release_conn()`` on the response ``r`` to return the connection + back into the pool. If None, it takes the value of ``preload_content`` + which defaults to ``True``. + + :param bool chunked: + If True, urllib3 will send the body using chunked transfer + encoding. Otherwise, urllib3 will send the body using the standard + content-length form. Defaults to False. + + :param int body_pos: + Position to seek to in file-like body in the event of a retry or + redirect. Typically this won't need to be set because urllib3 will + auto-populate the value when needed. + """ + # Ensure that the URL we're connecting to is properly encoded + if url.startswith("/"): + # URLs starting with / are inherently schemeless. + url = to_str(_encode_target(url)) + destination_scheme = None + else: + parsed_url = parse_url(url) + destination_scheme = parsed_url.scheme + url = to_str(parsed_url._replace(fragment=None).url) + + if headers is None: + headers = self.headers + + if not isinstance(retries, Retry): + retries = Retry.from_int(retries, redirect=redirect, default=self.retries) + + if release_conn is None: + release_conn = preload_content + + # Check host + if assert_same_host and not self.is_same_host(url): + raise HostChangedError(self, url, retries) + + conn = None + + # Track whether `conn` needs to be released before + # returning/raising/recursing. Update this variable if necessary, and + # leave `release_conn` constant throughout the function. That way, if + # the function recurses, the original value of `release_conn` will be + # passed down into the recursive call, and its value will be respected. + # + # See issue #651 [1] for details. + # + # [1] + release_this_conn = release_conn + + http_tunnel_required = connection_requires_http_tunnel( + self.proxy, self.proxy_config, destination_scheme + ) + + # Merge the proxy headers. Only done when not using HTTP CONNECT. We + # have to copy the headers dict so we can safely change it without those + # changes being reflected in anyone else's copy. + if not http_tunnel_required: + headers = headers.copy() # type: ignore[attr-defined] + headers.update(self.proxy_headers) # type: ignore[union-attr] + + # Must keep the exception bound to a separate variable or else Python 3 + # complains about UnboundLocalError. + err = None + + # Keep track of whether we cleanly exited the except block. This + # ensures we do proper cleanup in finally. + clean_exit = False + + # Rewind body position, if needed. Record current position + # for future rewinds in the event of a redirect/retry. + body_pos = set_file_position(body, body_pos) + + timeout_obj = self._get_timeout(timeout) + try: + # Request a connection from the queue. + conn = self._get_conn(timeout=pool_timeout) + conn.timeout = timeout_obj.connect_timeout # type: ignore[assignment] + + # Is this a closed/new connection that requires CONNECT tunnelling? + if self.proxy is not None and http_tunnel_required and conn.is_closed: + try: + self._prepare_proxy(conn) + except (BaseSSLError, OSError, SocketTimeout) as e: + self._raise_timeout( + err=e, url=self.proxy.url, timeout_value=conn.timeout + ) + raise + + # If we're going to release the connection in ``finally:``, then + # the response doesn't need to know about the connection. Otherwise + # it will also try to release it and we'll have a double-release + # mess. + response_conn = conn if not release_conn else None + + # Make the request on the HTTPConnection object + response = self._make_request( + conn, + method, + url, + timeout=timeout_obj, + body=body, + headers=headers, + chunked=chunked, + retries=retries, + response_conn=response_conn, + preload_content=preload_content, + decode_content=decode_content, + **response_kw, + ) + + # Everything went great! + clean_exit = True + + except EmptyPoolError: + # Didn't get a connection from the pool, no need to clean up + clean_exit = True + release_this_conn = False + raise + + except ( + TimeoutError, + HTTPException, + OSError, + ProtocolError, + BaseSSLError, + SSLError, + CertificateError, + ProxyError, + ) as e: + # Discard the connection for these exceptions. It will be + # replaced during the next _get_conn() call. + clean_exit = False + new_e: Exception = e + if isinstance(e, (BaseSSLError, CertificateError)): + new_e = SSLError(e) + if isinstance( + new_e, + ( + OSError, + NewConnectionError, + TimeoutError, + SSLError, + HTTPException, + ), + ) and (conn and conn.proxy and not conn.has_connected_to_proxy): + new_e = _wrap_proxy_error(new_e, conn.proxy.scheme) + elif isinstance(new_e, (OSError, HTTPException)): + new_e = ProtocolError("Connection aborted.", new_e) + + retries = retries.increment( + method, url, error=new_e, _pool=self, _stacktrace=sys.exc_info()[2] + ) + retries.sleep() + + # Keep track of the error for the retry warning. + err = e + + finally: + if not clean_exit: + # We hit some kind of exception, handled or otherwise. We need + # to throw the connection away unless explicitly told not to. + # Close the connection, set the variable to None, and make sure + # we put the None back in the pool to avoid leaking it. + if conn: + conn.close() + conn = None + release_this_conn = True + + if release_this_conn: + # Put the connection back to be reused. If the connection is + # expired then it will be None, which will get replaced with a + # fresh connection during _get_conn. + self._put_conn(conn) + + if not conn: + # Try again + log.warning( + "Retrying (%r) after connection broken by '%r': %s", + retries, + err, + url, + # Provide an unique attribute with the host needed by pip to + # rewrite this warning. Ideally, we'd go with a better solution, + # but backwards compatibility and other constraints make those + # unfeasible, so this is the least bad option. + # See also: https://github.com/urllib3/urllib3/issues/2580. + extra={"__urllib3-retry-warning": {"host": self.host}}, + ) + return self.urlopen( + method, + url, + body, + headers, + retries, + redirect, + assert_same_host, + timeout=timeout, + pool_timeout=pool_timeout, + release_conn=release_conn, + chunked=chunked, + body_pos=body_pos, + preload_content=preload_content, + decode_content=decode_content, + **response_kw, + ) + + # Handle redirect? + redirect_location = redirect and response.get_redirect_location() + if redirect_location: + if response.status == 303: + # Change the method according to RFC 9110, Section 15.4.4. + method = "GET" + # And lose the body not to transfer anything sensitive. + body = None + # The body is gone, so the state that describes it has to go + # too: there is nothing left to frame with chunked transfer + # encoding, and nothing left to rewind. + chunked = False + body_pos = None + headers = HTTPHeaderDict(headers)._prepare_for_method_change() + + # Strip headers marked as unsafe to forward to the redirected location. + # Check remove_headers_on_redirect to avoid a potential network call within + # self.is_same_host() which may use socket.gethostbyname() in the future. + if retries.remove_headers_on_redirect and not self.is_same_host( + redirect_location + ): + new_headers = headers.copy() # type: ignore[union-attr] + for header in headers: + if header.lower() in retries.remove_headers_on_redirect: + new_headers.pop(header, None) + headers = new_headers + + try: + retries = retries.increment(method, url, response=response, _pool=self) + except MaxRetryError: + if retries.raise_on_redirect: + response.drain_conn() + raise + return response + + response.drain_conn() + retries.sleep_for_retry(response) + log.debug("Redirecting %s -> %s", url, redirect_location) + return self.urlopen( + method, + redirect_location, + body, + headers, + retries=retries, + redirect=redirect, + assert_same_host=assert_same_host, + timeout=timeout, + pool_timeout=pool_timeout, + release_conn=release_conn, + chunked=chunked, + body_pos=body_pos, + preload_content=preload_content, + decode_content=decode_content, + **response_kw, + ) + + # Check if we should retry the HTTP response. + has_retry_after = bool(response.headers.get("Retry-After")) + if retries.is_retry(method, response.status, has_retry_after): + try: + retries = retries.increment(method, url, response=response, _pool=self) + except MaxRetryError: + if retries.raise_on_status: + response.drain_conn() + raise + return response + + response.drain_conn() + retries.sleep(response) + log.debug("Retry: %s", url) + return self.urlopen( + method, + url, + body, + headers, + retries=retries, + redirect=redirect, + assert_same_host=assert_same_host, + timeout=timeout, + pool_timeout=pool_timeout, + release_conn=release_conn, + chunked=chunked, + body_pos=body_pos, + preload_content=preload_content, + decode_content=decode_content, + **response_kw, + ) + + return response + + +class HTTPSConnectionPool(HTTPConnectionPool): + """ + Same as :class:`.HTTPConnectionPool`, but HTTPS. + + :class:`.HTTPSConnection` uses one of ``assert_fingerprint``, + ``assert_hostname`` and ``host`` in this order to verify connections. + If ``assert_hostname`` is False, no verification is done. + + The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``, + ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl` + is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade + the connection socket into an SSL socket. + """ + + scheme = "https" + ConnectionCls: type[BaseHTTPSConnection] = HTTPSConnection + + def __init__( + self, + host: str, + port: int | None = None, + timeout: _TYPE_TIMEOUT | None = _DEFAULT_TIMEOUT, + maxsize: int = 1, + block: bool = False, + headers: typing.Mapping[str, str] | None = None, + retries: Retry | bool | int | None = None, + _proxy: Url | None = None, + _proxy_headers: typing.Mapping[str, str] | None = None, + key_file: str | None = None, + cert_file: str | None = None, + cert_reqs: int | str | None = None, + key_password: str | None = None, + ca_certs: str | None = None, + ssl_version: int | str | None = None, + ssl_minimum_version: ssl.TLSVersion | None = None, + ssl_maximum_version: ssl.TLSVersion | None = None, + assert_hostname: str | typing.Literal[False] | None = None, + assert_fingerprint: str | None = None, + ca_cert_dir: str | None = None, + **conn_kw: typing.Any, + ) -> None: + super().__init__( + host, + port, + timeout, + maxsize, + block, + headers, + retries, + _proxy, + _proxy_headers, + **conn_kw, + ) + + self.key_file = key_file + self.cert_file = cert_file + self.cert_reqs = cert_reqs + self.key_password = key_password + self.ca_certs = ca_certs + self.ca_cert_dir = ca_cert_dir + self.ssl_version = ssl_version + self.ssl_minimum_version = ssl_minimum_version + self.ssl_maximum_version = ssl_maximum_version + self.assert_hostname = assert_hostname + self.assert_fingerprint = assert_fingerprint + + def _prepare_proxy(self, conn: HTTPSConnection) -> None: # type: ignore[override] + """Establishes a tunnel connection through HTTP CONNECT.""" + if self.proxy and self.proxy.scheme == "https": + tunnel_scheme = "https" + else: + tunnel_scheme = "http" + + conn.set_tunnel( + scheme=tunnel_scheme, + host=self._tunnel_host, + port=self.port, + headers=self.proxy_headers, + ) + conn.connect() + + def _new_conn(self) -> BaseHTTPSConnection: + """ + Return a fresh :class:`urllib3.connection.HTTPConnection`. + """ + self.num_connections += 1 + log.debug( + "Starting new HTTPS connection (%d): %s:%s", + self.num_connections, + self.host, + self.port or "443", + ) + + if not self.ConnectionCls or self.ConnectionCls is DummyConnection: # type: ignore[comparison-overlap] + raise ImportError( + "Can't connect to HTTPS URL because the SSL module is not available." + ) + + actual_host: str = self.host + actual_port = self.port + if self.proxy is not None and self.proxy.host is not None: + actual_host = self.proxy.host + actual_port = self.proxy.port + + return self.ConnectionCls( + host=actual_host, + port=actual_port, + timeout=self.timeout.connect_timeout, + cert_file=self.cert_file, + key_file=self.key_file, + key_password=self.key_password, + cert_reqs=self.cert_reqs, + ca_certs=self.ca_certs, + ca_cert_dir=self.ca_cert_dir, + assert_hostname=self.assert_hostname, + assert_fingerprint=self.assert_fingerprint, + ssl_version=self.ssl_version, + ssl_minimum_version=self.ssl_minimum_version, + ssl_maximum_version=self.ssl_maximum_version, + **self.conn_kw, + ) + + def _validate_conn(self, conn: BaseHTTPConnection) -> None: + """ + Called right before a request is made, after the socket is created. + """ + super()._validate_conn(conn) + + # Force connect early to allow us to validate the connection. + if conn.is_closed: + conn.connect() + + # TODO revise this, see https://github.com/urllib3/urllib3/issues/2791 + if not conn.is_verified and not conn.proxy_is_verified: + warnings.warn( + ( + f"Unverified HTTPS request is being made to host '{conn.host}'. " + "Adding certificate verification is strongly advised. See: " + "https://urllib3.readthedocs.io/en/latest/advanced-usage.html" + "#tls-warnings" + ), + InsecureRequestWarning, + ) + + +def connection_from_url(url: str, **kw: typing.Any) -> HTTPConnectionPool: + """ + Given a url, return an :class:`.ConnectionPool` instance of its host. + + This is a shortcut for not having to parse out the scheme, host, and port + of the url before creating an :class:`.ConnectionPool` instance. + + :param url: + Absolute URL string that must include the scheme. Port is optional. + + :param \\**kw: + Passes additional parameters to the constructor of the appropriate + :class:`.ConnectionPool`. Useful for specifying things like + timeout, maxsize, headers, etc. + + Example:: + + >>> conn = connection_from_url('http://google.com/') + >>> r = conn.request('GET', '/') + """ + scheme, _, host, port, *_ = parse_url(url) + scheme = scheme or "http" + if port is None: + port = port_by_scheme.get(scheme, 80) + if scheme == "https": + return HTTPSConnectionPool(host, port=port, **kw) # type: ignore[arg-type] + else: + return HTTPConnectionPool(host, port=port, **kw) # type: ignore[arg-type] + + +@typing.overload +def _normalize_host(host: None, scheme: str | None) -> None: ... + + +@typing.overload +def _normalize_host(host: str, scheme: str | None) -> str: ... + + +def _normalize_host(host: str | None, scheme: str | None) -> str | None: + """ + Normalize hosts for comparisons and use with sockets. + """ + + host = normalize_host(host, scheme) + + # httplib doesn't like it when we include brackets in IPv6 addresses + # Specifically, if we include brackets but also pass the port then + # httplib crazily doubles up the square brackets on the Host header. + # Instead, we need to make sure we never pass ``None`` as the port. + # However, for backward compatibility reasons we can't actually + # *assert* that. See http://bugs.python.org/issue28539 + if host and host.startswith("[") and host.endswith("]"): + host = host[1:-1] + return host + + +def _url_from_pool( + pool: HTTPConnectionPool | HTTPSConnectionPool, path: str | None = None +) -> str: + """Returns the URL from a given connection pool. This is mainly used for testing and logging.""" + return Url(scheme=pool.scheme, host=pool.host, port=pool.port, path=path).url + + +def _close_pool_connections(pool: queue.LifoQueue[typing.Any]) -> None: + """Drains a queue of connections and closes each one.""" + try: + while True: + conn = pool.get(block=False) + if conn: + conn.close() + except queue.Empty: + pass # Done. diff --git a/.venv/lib/python3.12/site-packages/urllib3/contrib/__init__.py b/.venv/lib/python3.12/site-packages/urllib3/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/urllib3/contrib/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/contrib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60b56ca73e6c7f905cac2a60024b0bd5c3f47185 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/contrib/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/contrib/__pycache__/socks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/contrib/__pycache__/socks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a49bd347bf3e9414e85ff2164291cef98fc6af9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/contrib/__pycache__/socks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/__init__.py b/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b62b25e932566f7ae7599c1cedec2b8f30d95b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/__init__.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +import urllib3.connection + +from ...connectionpool import HTTPConnectionPool, HTTPSConnectionPool +from .connection import EmscriptenHTTPConnection, EmscriptenHTTPSConnection + + +def inject_into_urllib3() -> None: + # override connection classes to use emscripten specific classes + # n.b. mypy complains about the overriding of classes below + # if it isn't ignored + HTTPConnectionPool.ConnectionCls = EmscriptenHTTPConnection + HTTPSConnectionPool.ConnectionCls = EmscriptenHTTPSConnection + urllib3.connection.HTTPConnection = EmscriptenHTTPConnection # type: ignore[misc,assignment] + urllib3.connection.HTTPSConnection = EmscriptenHTTPSConnection # type: ignore[misc,assignment] + urllib3.connection.VerifiedHTTPSConnection = EmscriptenHTTPSConnection # type: ignore[assignment] diff --git a/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/connection.py b/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..63f79dd3be803db09671c909f79316c3f65d6916 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/connection.py @@ -0,0 +1,260 @@ +from __future__ import annotations + +import os +import typing + +# use http.client.HTTPException for consistency with non-emscripten +from http.client import HTTPException as HTTPException # noqa: F401 +from http.client import ResponseNotReady + +from ..._base_connection import _TYPE_BODY +from ...connection import HTTPConnection, ProxyConfig, port_by_scheme +from ...exceptions import TimeoutError +from ...response import BaseHTTPResponse +from ...util.connection import _TYPE_SOCKET_OPTIONS +from ...util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT +from ...util.url import Url +from .fetch import _RequestError, _TimeoutError, send_request, send_streaming_request +from .request import EmscriptenRequest +from .response import EmscriptenHttpResponseWrapper, EmscriptenResponse + +if typing.TYPE_CHECKING: + from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection + + +class EmscriptenHTTPConnection: + default_port: typing.ClassVar[int] = port_by_scheme["http"] + default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS] + + timeout: None | (float) + + host: str + port: int + blocksize: int + source_address: tuple[str, int] | None + socket_options: _TYPE_SOCKET_OPTIONS | None + + proxy: Url | None + proxy_config: ProxyConfig | None + + is_verified: bool = False + proxy_is_verified: bool | None = None + + response_class: type[BaseHTTPResponse] = EmscriptenHttpResponseWrapper + _response: EmscriptenResponse | None + + def __init__( + self, + host: str, + port: int = 0, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + socket_options: _TYPE_SOCKET_OPTIONS | None = None, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + ) -> None: + self.host = host + self.port = port + self.timeout = timeout if isinstance(timeout, float) else 0.0 + self.scheme = "http" + self._closed = True + self._response = None + # ignore these things because we don't + # have control over that stuff + self.proxy = None + self.proxy_config = None + self.blocksize = blocksize + self.source_address = None + self.socket_options = None + self.is_verified = False + + def set_tunnel( + self, + host: str, + port: int | None = 0, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + pass + + def connect(self) -> None: + pass + + def request( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + # We know *at least* botocore is depending on the order of the + # first 3 parameters so to be safe we only mark the later ones + # as keyword-only to ensure we have space to extend. + *, + chunked: bool = False, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + ) -> None: + self._closed = False + if url.startswith("/"): + if self.port is not None: + port = f":{self.port}" + else: + port = "" + # no scheme / host / port included, make a full url + url = f"{self.scheme}://{self.host}{port}{url}" + request = EmscriptenRequest( + url=url, + method=method, + timeout=self.timeout if self.timeout else 0, + decode_content=decode_content, + ) + request.set_body(body) + if headers: + for k, v in headers.items(): + request.set_header(k, v) + self._response = None + try: + if not preload_content: + self._response = send_streaming_request(request) + if self._response is None: + self._response = send_request(request) + except _TimeoutError as e: + raise TimeoutError(e.message) from e + except _RequestError as e: + raise HTTPException(e.message) from e + + def getresponse(self) -> BaseHTTPResponse: + if self._response is not None: + return EmscriptenHttpResponseWrapper( + internal_response=self._response, + url=self._response.request.url, + connection=self, + ) + else: + raise ResponseNotReady() + + def close(self) -> None: + self._closed = True + self._response = None + + @property + def is_closed(self) -> bool: + """Whether the connection either is brand new or has been previously closed. + If this property is True then both ``is_connected`` and ``has_connected_to_proxy`` + properties must be False. + """ + return self._closed + + @property + def is_connected(self) -> bool: + """Whether the connection is actively connected to any origin (proxy or target)""" + return True + + @property + def has_connected_to_proxy(self) -> bool: + """Whether the connection has successfully connected to its proxy. + This returns False if no proxy is in use. Used to determine whether + errors are coming from the proxy layer or from tunnelling to the target origin. + """ + return False + + +class EmscriptenHTTPSConnection(EmscriptenHTTPConnection): + default_port = port_by_scheme["https"] + # all this is basically ignored, as browser handles https + cert_reqs: int | str | None = None + ca_certs: str | None = None + ca_cert_dir: str | None = None + ca_cert_data: None | str | bytes = None + cert_file: str | None + key_file: str | None + key_password: str | None + ssl_context: typing.Any | None + ssl_version: int | str | None = None + ssl_minimum_version: int | None = None + ssl_maximum_version: int | None = None + assert_hostname: None | str | typing.Literal[False] + assert_fingerprint: str | None = None + + def __init__( + self, + host: str, + port: int = 0, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 16384, + socket_options: ( + None | _TYPE_SOCKET_OPTIONS + ) = HTTPConnection.default_socket_options, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + cert_reqs: int | str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + server_hostname: str | None = None, + ssl_context: typing.Any | None = None, + ca_certs: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + ssl_version: int | str | None = None, # Deprecated + cert_file: str | None = None, + key_file: str | None = None, + key_password: str | None = None, + ) -> None: + super().__init__( + host, + port=port, + timeout=timeout, + source_address=source_address, + blocksize=blocksize, + socket_options=socket_options, + proxy=proxy, + proxy_config=proxy_config, + ) + self.scheme = "https" + + self.key_file = key_file + self.cert_file = cert_file + self.key_password = key_password + self.ssl_context = ssl_context + self.server_hostname = server_hostname + self.assert_hostname = assert_hostname + self.assert_fingerprint = assert_fingerprint + self.ssl_version = ssl_version + self.ssl_minimum_version = ssl_minimum_version + self.ssl_maximum_version = ssl_maximum_version + self.ca_certs = ca_certs and os.path.expanduser(ca_certs) + self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) + self.ca_cert_data = ca_cert_data + + self.cert_reqs = None + + # The browser will automatically verify all requests. + # We have no control over that setting. + self.is_verified = True + + def set_cert( + self, + key_file: str | None = None, + cert_file: str | None = None, + cert_reqs: int | str | None = None, + key_password: str | None = None, + ca_certs: str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ) -> None: + pass + + +# verify that this class implements BaseHTTP(s) connection correctly +if typing.TYPE_CHECKING: + _supports_http_protocol: BaseHTTPConnection = EmscriptenHTTPConnection("", 0) + _supports_https_protocol: BaseHTTPSConnection = EmscriptenHTTPSConnection("", 0) diff --git a/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js b/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js new file mode 100644 index 0000000000000000000000000000000000000000..faf141e1fa4113a0c14480d1681ddecb9678ced4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js @@ -0,0 +1,110 @@ +let Status = { + SUCCESS_HEADER: -1, + SUCCESS_EOF: -2, + ERROR_TIMEOUT: -3, + ERROR_EXCEPTION: -4, +}; + +let connections = new Map(); +let nextConnectionID = 1; +const encoder = new TextEncoder(); + +self.addEventListener("message", async function (event) { + if (event.data.close) { + let connectionID = event.data.close; + connections.delete(connectionID); + return; + } else if (event.data.getMore) { + let connectionID = event.data.getMore; + let { curOffset, value, reader, intBuffer, byteBuffer } = + connections.get(connectionID); + // if we still have some in buffer, then just send it back straight away + if (!value || curOffset >= value.length) { + // read another buffer if required + try { + let readResponse = await reader.read(); + + if (readResponse.done) { + // read everything - clear connection and return + connections.delete(connectionID); + Atomics.store(intBuffer, 0, Status.SUCCESS_EOF); + Atomics.notify(intBuffer, 0); + // finished reading successfully + // return from event handler + return; + } + curOffset = 0; + connections.get(connectionID).value = readResponse.value; + value = readResponse.value; + } catch (error) { + console.log("Request exception:", error); + let errorBytes = encoder.encode(error.message); + let written = errorBytes.length; + byteBuffer.set(errorBytes); + intBuffer[1] = written; + Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); + Atomics.notify(intBuffer, 0); + } + } + + // send as much buffer as we can + let curLen = value.length - curOffset; + if (curLen > byteBuffer.length) { + curLen = byteBuffer.length; + } + byteBuffer.set(value.subarray(curOffset, curOffset + curLen), 0); + + Atomics.store(intBuffer, 0, curLen); // store current length in bytes + Atomics.notify(intBuffer, 0); + curOffset += curLen; + connections.get(connectionID).curOffset = curOffset; + + return; + } else { + // start fetch + let connectionID = nextConnectionID; + nextConnectionID += 1; + const intBuffer = new Int32Array(event.data.buffer); + const byteBuffer = new Uint8Array(event.data.buffer, 8); + try { + const response = await fetch(event.data.url, event.data.fetchParams); + // return the headers first via textencoder + var headers = []; + for (const pair of response.headers.entries()) { + headers.push([pair[0], pair[1]]); + } + let headerObj = { + headers: headers, + status: response.status, + connectionID, + }; + const headerText = JSON.stringify(headerObj); + let headerBytes = encoder.encode(headerText); + let written = headerBytes.length; + byteBuffer.set(headerBytes); + intBuffer[1] = written; + // make a connection + connections.set(connectionID, { + reader: response.body.getReader(), + intBuffer: intBuffer, + byteBuffer: byteBuffer, + value: undefined, + curOffset: 0, + }); + // set header ready + Atomics.store(intBuffer, 0, Status.SUCCESS_HEADER); + Atomics.notify(intBuffer, 0); + // all fetching after this goes through a new postmessage call with getMore + // this allows for parallel requests + } catch (error) { + console.log("Request exception:", error); + let errorBytes = encoder.encode(error.message); + let written = errorBytes.length; + byteBuffer.set(errorBytes); + intBuffer[1] = written; + Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); + Atomics.notify(intBuffer, 0); + } + } +}); +self.postMessage({ inited: true }); diff --git a/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/fetch.py b/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/fetch.py new file mode 100644 index 0000000000000000000000000000000000000000..612cfddc4c28d2f0edf47522278fa6d9b7906623 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/fetch.py @@ -0,0 +1,726 @@ +""" +Support for streaming http requests in emscripten. + +A few caveats - + +If your browser (or Node.js) has WebAssembly JavaScript Promise Integration enabled +https://github.com/WebAssembly/js-promise-integration/blob/main/proposals/js-promise-integration/Overview.md +*and* you launch pyodide using `pyodide.runPythonAsync`, this will fetch data using the +JavaScript asynchronous fetch api (wrapped via `pyodide.ffi.call_sync`). In this case +timeouts and streaming should just work. + +Otherwise, it uses a combination of XMLHttpRequest and a web-worker for streaming. + +This approach has several caveats: + +Firstly, you can't do streaming http in the main UI thread, because atomics.wait isn't allowed. +Streaming only works if you're running pyodide in a web worker. + +Secondly, this uses an extra web worker and SharedArrayBuffer to do the asynchronous fetch +operation, so it requires that you have crossOriginIsolation enabled, by serving over https +(or from localhost) with the two headers below set: + + Cross-Origin-Opener-Policy: same-origin + Cross-Origin-Embedder-Policy: require-corp + +You can tell if cross origin isolation is successfully enabled by looking at the global crossOriginIsolated variable in +JavaScript console. If it isn't, streaming requests will fallback to XMLHttpRequest, i.e. getting the whole +request into a buffer and then returning it. it shows a warning in the JavaScript console in this case. + +Finally, the webworker which does the streaming fetch is created on initial import, but will only be started once +control is returned to javascript. Call `await wait_for_streaming_ready()` to wait for streaming fetch. + +NB: in this code, there are a lot of JavaScript objects. They are named js_* +to make it clear what type of object they are. +""" + +from __future__ import annotations + +import io +import json +from email.parser import Parser +from importlib.resources import files +from typing import TYPE_CHECKING, Any + +import js # type: ignore[import-not-found] +from pyodide.ffi import ( # type: ignore[import-not-found] + JsArray, + JsException, + JsProxy, + to_js, +) + +if TYPE_CHECKING: + from typing_extensions import Buffer + +from .request import EmscriptenRequest +from .response import EmscriptenResponse + +""" +There are some headers that trigger unintended CORS preflight requests. +See also https://github.com/koenvo/pyodide-http/issues/22 +""" +HEADERS_TO_IGNORE = ("user-agent",) + +SUCCESS_HEADER = -1 +SUCCESS_EOF = -2 +ERROR_TIMEOUT = -3 +ERROR_EXCEPTION = -4 + + +class _RequestError(Exception): + def __init__( + self, + message: str | None = None, + *, + request: EmscriptenRequest | None = None, + response: EmscriptenResponse | None = None, + ): + self.request = request + self.response = response + self.message = message + super().__init__(self.message) + + +class _StreamingError(_RequestError): + pass + + +class _TimeoutError(_RequestError): + pass + + +def _obj_from_dict(dict_val: dict[str, Any]) -> JsProxy: + return to_js(dict_val, dict_converter=js.Object.fromEntries) + + +class _ReadStream(io.RawIOBase): + def __init__( + self, + int_buffer: JsArray, + byte_buffer: JsArray, + timeout: float, + worker: JsProxy, + connection_id: int, + request: EmscriptenRequest, + ): + self.int_buffer = int_buffer + self.byte_buffer = byte_buffer + self.read_pos = 0 + self.read_len = 0 + self.connection_id = connection_id + self.worker = worker + self.timeout = int(1000 * timeout) if timeout > 0 else None + self.is_live = True + self._is_closed = False + self.request: EmscriptenRequest | None = request + + def __del__(self) -> None: + self.close() + + # this is compatible with _base_connection + def is_closed(self) -> bool: + return self._is_closed + + # for compatibility with RawIOBase + @property + def closed(self) -> bool: + return self.is_closed() + + def close(self) -> None: + if self.is_closed(): + return + self.read_len = 0 + self.read_pos = 0 + self.int_buffer = None + self.byte_buffer = None + self._is_closed = True + self.request = None + if self.is_live: + self.worker.postMessage(_obj_from_dict({"close": self.connection_id})) + self.is_live = False + super().close() + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return False + + def seekable(self) -> bool: + return False + + def readinto(self, byte_obj: Buffer) -> int: + if not self.int_buffer: + raise _StreamingError( + "No buffer for stream in _ReadStream.readinto", + request=self.request, + response=None, + ) + if self.read_len == 0: + # wait for the worker to send something + js.Atomics.store(self.int_buffer, 0, ERROR_TIMEOUT) + self.worker.postMessage(_obj_from_dict({"getMore": self.connection_id})) + if ( + js.Atomics.wait(self.int_buffer, 0, ERROR_TIMEOUT, self.timeout) + == "timed-out" + ): + raise _TimeoutError + data_len = self.int_buffer[0] + if data_len > 0: + self.read_len = data_len + self.read_pos = 0 + elif data_len == ERROR_EXCEPTION: + string_len = self.int_buffer[1] + # decode the error string + js_decoder = js.TextDecoder.new() + json_str = js_decoder.decode(self.byte_buffer.slice(0, string_len)) + raise _StreamingError( + f"Exception thrown in fetch: {json_str}", + request=self.request, + response=None, + ) + else: + # EOF, free the buffers and return zero + # and free the request + self.is_live = False + self.close() + return 0 + # copy from int32array to python bytes + ret_length = min(self.read_len, len(memoryview(byte_obj))) + subarray = self.byte_buffer.subarray( + self.read_pos, self.read_pos + ret_length + ).to_py() + memoryview(byte_obj)[0:ret_length] = subarray + self.read_len -= ret_length + self.read_pos += ret_length + return ret_length + + +class _StreamingFetcher: + def __init__(self) -> None: + # make web-worker and data buffer on startup + self.streaming_ready = False + streaming_worker_code = ( + files(__package__) + .joinpath("emscripten_fetch_worker.js") + .read_text(encoding="utf-8") + ) + js_data_blob = js.Blob.new( + to_js([streaming_worker_code], create_pyproxies=False), + _obj_from_dict({"type": "application/javascript"}), + ) + + def promise_resolver(js_resolve_fn: JsProxy, js_reject_fn: JsProxy) -> None: + def onMsg(e: JsProxy) -> None: + self.streaming_ready = True + js_resolve_fn(e) + + def onErr(e: JsProxy) -> None: + js_reject_fn(e) # Defensive: never happens in ci + + self.js_worker.onmessage = onMsg + self.js_worker.onerror = onErr + + js_data_url = js.URL.createObjectURL(js_data_blob) + self.js_worker = js.globalThis.Worker.new(js_data_url) + self.js_worker_ready_promise = js.globalThis.Promise.new(promise_resolver) + + def send(self, request: EmscriptenRequest) -> EmscriptenResponse: + headers = { + k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE + } + + body = request.body + fetch_data = {"headers": headers, "body": to_js(body), "method": request.method} + # start the request off in the worker + timeout = int(1000 * request.timeout) if request.timeout > 0 else None + js_shared_buffer = js.SharedArrayBuffer.new(1048576) + js_int_buffer = js.Int32Array.new(js_shared_buffer) + js_byte_buffer = js.Uint8Array.new(js_shared_buffer, 8) + + js.Atomics.store(js_int_buffer, 0, ERROR_TIMEOUT) + js.Atomics.notify(js_int_buffer, 0) + js_absolute_url = js.URL.new(request.url, js.location).href + self.js_worker.postMessage( + _obj_from_dict( + { + "buffer": js_shared_buffer, + "url": js_absolute_url, + "fetchParams": fetch_data, + } + ) + ) + # wait for the worker to send something + js.Atomics.wait(js_int_buffer, 0, ERROR_TIMEOUT, timeout) + if js_int_buffer[0] == ERROR_TIMEOUT: + raise _TimeoutError( + "Timeout connecting to streaming request", + request=request, + response=None, + ) + elif js_int_buffer[0] == SUCCESS_HEADER: + # got response + # header length is in second int of intBuffer + string_len = js_int_buffer[1] + # decode the rest to a JSON string + js_decoder = js.TextDecoder.new() + # this does a copy (the slice) because decode can't work on shared array + # for some silly reason + json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) + # get it as an object + response_obj = json.loads(json_str) + return EmscriptenResponse( + request=request, + status_code=response_obj["status"], + headers=response_obj["headers"], + body=_ReadStream( + js_int_buffer, + js_byte_buffer, + request.timeout, + self.js_worker, + response_obj["connectionID"], + request, + ), + ) + elif js_int_buffer[0] == ERROR_EXCEPTION: + string_len = js_int_buffer[1] + # decode the error string + js_decoder = js.TextDecoder.new() + json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) + raise _StreamingError( + f"Exception thrown in fetch: {json_str}", request=request, response=None + ) + else: + raise _StreamingError( + f"Unknown status from worker in fetch: {js_int_buffer[0]}", + request=request, + response=None, + ) + + +class _JSPIReadStream(io.RawIOBase): + """ + A read stream that uses pyodide.ffi.run_sync to read from a JavaScript fetch + response. This requires support for WebAssembly JavaScript Promise Integration + in the containing browser, and for pyodide to be launched via runPythonAsync. + + :param js_read_stream: + The JavaScript stream reader + + :param timeout: + Timeout in seconds + + :param request: + The request we're handling + + :param response: + The response this stream relates to + + :param js_abort_controller: + A JavaScript AbortController object, used for timeouts + """ + + def __init__( + self, + js_read_stream: Any, + timeout: float, + request: EmscriptenRequest, + response: EmscriptenResponse, + js_abort_controller: Any, # JavaScript AbortController for timeouts + ): + self.js_read_stream = js_read_stream + self.timeout = timeout + self._is_closed = False + self._is_done = False + self.request: EmscriptenRequest | None = request + self.response: EmscriptenResponse | None = response + self.current_buffer = None + self.current_buffer_pos = 0 + self.js_abort_controller = js_abort_controller + + def __del__(self) -> None: + self.close() + + # this is compatible with _base_connection + def is_closed(self) -> bool: + return self._is_closed + + # for compatibility with RawIOBase + @property + def closed(self) -> bool: + return self.is_closed() + + def close(self) -> None: + if self.is_closed(): + return + self.read_len = 0 + self.read_pos = 0 + self.js_read_stream.cancel() + self.js_read_stream = None + self._is_closed = True + self._is_done = True + self.request = None + self.response = None + super().close() + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return False + + def seekable(self) -> bool: + return False + + def _get_next_buffer(self) -> bool: + result_js = _run_sync_with_timeout( + self.js_read_stream.read(), + self.timeout, + self.js_abort_controller, + request=self.request, + response=self.response, + ) + if result_js.done: + self._is_done = True + return False + else: + self.current_buffer = result_js.value.to_py() + self.current_buffer_pos = 0 + return True + + def readinto(self, byte_obj: Buffer) -> int: + if self.current_buffer is None: + if not self._get_next_buffer() or self.current_buffer is None: + self.close() + return 0 + ret_length = min( + len(byte_obj), len(self.current_buffer) - self.current_buffer_pos + ) + byte_obj[0:ret_length] = self.current_buffer[ + self.current_buffer_pos : self.current_buffer_pos + ret_length + ] + self.current_buffer_pos += ret_length + if self.current_buffer_pos == len(self.current_buffer): + self.current_buffer = None + return ret_length + + +# check if we are in a worker or not +def is_in_browser_main_thread() -> bool: + return hasattr(js, "window") and hasattr(js, "self") and js.self == js.window + + +def is_cross_origin_isolated() -> bool: + return hasattr(js, "crossOriginIsolated") and js.crossOriginIsolated + + +def is_in_node() -> bool: + return ( + hasattr(js, "process") + and hasattr(js.process, "release") + and hasattr(js.process.release, "name") + and js.process.release.name == "node" + ) + + +def is_worker_available() -> bool: + return hasattr(js, "Worker") and hasattr(js, "Blob") + + +_fetcher: _StreamingFetcher | None = None + +if is_worker_available() and ( + (is_cross_origin_isolated() and not is_in_browser_main_thread()) + and (not is_in_node()) +): + _fetcher = _StreamingFetcher() +else: + _fetcher = None + + +NODE_JSPI_ERROR = ( + "urllib3 only works in Node.js with pyodide.runPythonAsync" + " and requires the flag --experimental-wasm-stack-switching in " + " versions of node <24." +) + + +def send_streaming_request(request: EmscriptenRequest) -> EmscriptenResponse | None: + if has_jspi(): + return send_jspi_request(request, True) + elif is_in_node(): + raise _RequestError( + message=NODE_JSPI_ERROR, + request=request, + response=None, + ) + + if _fetcher and streaming_ready(): + return _fetcher.send(request) + else: + _show_streaming_warning() + return None + + +_SHOWN_TIMEOUT_WARNING = False + + +def _show_timeout_warning() -> None: + global _SHOWN_TIMEOUT_WARNING + if not _SHOWN_TIMEOUT_WARNING: + _SHOWN_TIMEOUT_WARNING = True + message = "Warning: Timeout is not available on main browser thread" + js.console.warn(message) + + +_SHOWN_STREAMING_WARNING = False + + +def _show_streaming_warning() -> None: + global _SHOWN_STREAMING_WARNING + if not _SHOWN_STREAMING_WARNING: + _SHOWN_STREAMING_WARNING = True + message = "Can't stream HTTP requests because: \n" + if not is_cross_origin_isolated(): + message += " Page is not cross-origin isolated\n" + if is_in_browser_main_thread(): + message += " Python is running in main browser thread\n" + if not is_worker_available(): + message += " Worker or Blob classes are not available in this environment." # Defensive: this is always False in browsers that we test in + if streaming_ready() is False: + message += """ Streaming fetch worker isn't ready. If you want to be sure that streaming fetch +is working, you need to call: 'await urllib3.contrib.emscripten.fetch.wait_for_streaming_ready()`""" + from js import console + + console.warn(message) + + +def send_request(request: EmscriptenRequest) -> EmscriptenResponse: + if has_jspi(): + return send_jspi_request(request, False) + elif is_in_node(): + raise _RequestError( + message=NODE_JSPI_ERROR, + request=request, + response=None, + ) + try: + js_xhr = js.XMLHttpRequest.new() + + if not is_in_browser_main_thread(): + js_xhr.responseType = "arraybuffer" + if request.timeout: + js_xhr.timeout = int(request.timeout * 1000) + else: + js_xhr.overrideMimeType("text/plain; charset=ISO-8859-15") + if request.timeout: + # timeout isn't available on the main thread - show a warning in console + # if it is set + _show_timeout_warning() + + js_xhr.open(request.method, request.url, False) + for name, value in request.headers.items(): + if name.lower() not in HEADERS_TO_IGNORE: + js_xhr.setRequestHeader(name, value) + + js_xhr.send(to_js(request.body)) + + headers = dict(Parser().parsestr(js_xhr.getAllResponseHeaders())) + + if not is_in_browser_main_thread(): + body = js_xhr.response.to_py().tobytes() + else: + body = js_xhr.response.encode("ISO-8859-15") + return EmscriptenResponse( + status_code=js_xhr.status, headers=headers, body=body, request=request + ) + except JsException as err: + if err.name == "TimeoutError": + raise _TimeoutError(err.message, request=request) + elif err.name == "NetworkError": + raise _RequestError(err.message, request=request) + else: + # general http error + raise _RequestError(err.message, request=request) + + +def send_jspi_request( + request: EmscriptenRequest, streaming: bool +) -> EmscriptenResponse: + """ + Send a request using WebAssembly JavaScript Promise Integration + to wrap the asynchronous JavaScript fetch api (experimental). + + :param request: + Request to send + + :param streaming: + Whether to stream the response + + :return: The response object + :rtype: EmscriptenResponse + """ + timeout = request.timeout + js_abort_controller = js.AbortController.new() + headers = {k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE} + req_body = request.body + fetch_data = { + "headers": headers, + "body": to_js(req_body), + "method": request.method, + "signal": js_abort_controller.signal, + } + # Node.js returns the whole response (unlike opaqueredirect in browsers), + # so urllib3 can set `redirect: manual` to control redirects itself. + # https://stackoverflow.com/a/78524615 + if _is_node_js(): + fetch_data["redirect"] = "manual" + # Call JavaScript fetch (async api, returns a promise) + fetcher_promise_js = js.fetch(request.url, _obj_from_dict(fetch_data)) + # Now suspend WebAssembly until we resolve that promise + # or time out. + response_js = _run_sync_with_timeout( + fetcher_promise_js, + timeout, + js_abort_controller, + request=request, + response=None, + ) + headers = {} + header_iter = response_js.headers.entries() + while True: + iter_value_js = header_iter.next() + if getattr(iter_value_js, "done", False): + break + else: + headers[str(iter_value_js.value[0])] = str(iter_value_js.value[1]) + status_code = response_js.status + body: bytes | io.RawIOBase = b"" + + response = EmscriptenResponse( + status_code=status_code, headers=headers, body=b"", request=request + ) + if streaming: + # get via inputstream + if response_js.body is not None: + # get a reader from the fetch response + body_stream_js = response_js.body.getReader() + body = _JSPIReadStream( + body_stream_js, timeout, request, response, js_abort_controller + ) + else: + # get directly via arraybuffer + # n.b. this is another async JavaScript call. + body = _run_sync_with_timeout( + response_js.arrayBuffer(), + timeout, + js_abort_controller, + request=request, + response=response, + ).to_py() + response.body = body + return response + + +def _run_sync_with_timeout( + promise: Any, + timeout: float, + js_abort_controller: Any, + request: EmscriptenRequest | None, + response: EmscriptenResponse | None, +) -> Any: + """ + Await a JavaScript promise synchronously with a timeout which is implemented + via the AbortController + + :param promise: + Javascript promise to await + + :param timeout: + Timeout in seconds + + :param js_abort_controller: + A JavaScript AbortController object, used on timeout + + :param request: + The request being handled + + :param response: + The response being handled (if it exists yet) + + :raises _TimeoutError: If the request times out + :raises _RequestError: If the request raises a JavaScript exception + + :return: The result of awaiting the promise. + """ + timer_id = None + if timeout > 0: + timer_id = js.setTimeout( + js_abort_controller.abort.bind(js_abort_controller), int(timeout * 1000) + ) + try: + from pyodide.ffi import run_sync + + # run_sync here uses WebAssembly JavaScript Promise Integration to + # suspend python until the JavaScript promise resolves. + return run_sync(promise) + except JsException as err: + if err.name == "AbortError": + raise _TimeoutError( + message="Request timed out", request=request, response=response + ) + else: + raise _RequestError(message=err.message, request=request, response=response) + finally: + if timer_id is not None: + js.clearTimeout(timer_id) + + +def has_jspi() -> bool: + """ + Return true if jspi can be used. + + This requires both browser support and also WebAssembly + to be in the correct state - i.e. that the javascript + call into python was async not sync. + + :return: True if jspi can be used. + :rtype: bool + """ + try: + from pyodide.ffi import can_run_sync, run_sync # noqa: F401 + + return bool(can_run_sync()) + except ImportError: + return False + + +def _is_node_js() -> bool: + """ + Check if we are in Node.js. + + :return: True if we are in Node.js. + :rtype: bool + """ + return ( + hasattr(js, "process") + and hasattr(js.process, "release") + # According to the Node.js documentation, the release name is always "node". + and js.process.release.name == "node" + ) + + +def streaming_ready() -> bool | None: + if _fetcher: + return _fetcher.streaming_ready + else: + return None # no fetcher, return None to signify that + + +async def wait_for_streaming_ready() -> bool: + if _fetcher: + await _fetcher.js_worker_ready_promise + return True + else: + return False diff --git a/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/request.py b/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/request.py new file mode 100644 index 0000000000000000000000000000000000000000..e692e692bd0d38f6a0677992a6993fc68050dff3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/request.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from dataclasses import dataclass, field + +from ..._base_connection import _TYPE_BODY + + +@dataclass +class EmscriptenRequest: + method: str + url: str + params: dict[str, str] | None = None + body: _TYPE_BODY | None = None + headers: dict[str, str] = field(default_factory=dict) + timeout: float = 0 + decode_content: bool = True + + def set_header(self, name: str, value: str) -> None: + self.headers[name.capitalize()] = value + + def set_body(self, body: _TYPE_BODY | None) -> None: + self.body = body diff --git a/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/response.py b/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/response.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1e1dbe83722c5fb16290a852859252ae616826 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/contrib/emscripten/response.py @@ -0,0 +1,281 @@ +from __future__ import annotations + +import json as _json +import logging +import typing +from contextlib import contextmanager +from dataclasses import dataclass +from http.client import HTTPException as HTTPException +from io import BytesIO, IOBase + +from ...exceptions import InvalidHeader, TimeoutError +from ...response import BaseHTTPResponse +from ...util.retry import Retry +from .request import EmscriptenRequest + +if typing.TYPE_CHECKING: + from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection + +log = logging.getLogger(__name__) + + +@dataclass +class EmscriptenResponse: + status_code: int + headers: dict[str, str] + body: IOBase | bytes + request: EmscriptenRequest + + +class EmscriptenHttpResponseWrapper(BaseHTTPResponse): + def __init__( + self, + internal_response: EmscriptenResponse, + url: str | None = None, + connection: BaseHTTPConnection | BaseHTTPSConnection | None = None, + ): + self._pool = None # set by pool class + self._body = None + self._uncached_read_occurred = False + self._response = internal_response + self._url = url + self._connection = connection + self._closed = False + super().__init__( + headers=internal_response.headers, + status=internal_response.status_code, + request_url=url, + version=0, + version_string="HTTP/?", + reason="", + decode_content=True, + ) + self.length_remaining = self._init_length(self._response.request.method) + self.length_is_certain = False + + @property + def url(self) -> str | None: + return self._url + + @url.setter + def url(self, url: str | None) -> None: + self._url = url + + @property + def connection(self) -> BaseHTTPConnection | BaseHTTPSConnection | None: + return self._connection + + @property + def retries(self) -> Retry | None: + return self._retries + + @retries.setter + def retries(self, retries: Retry | None) -> None: + # Override the request_url if retries has a redirect location. + self._retries = retries + + def stream( + self, amt: int | None = 2**16, decode_content: bool | None = None + ) -> typing.Generator[bytes]: + """ + A generator wrapper for the read() method. A call will block until + ``amt`` bytes have been read from the connection or until the + connection is closed. + + :param amt: + How much of the content to read. The generator will return up to + much data per iteration, but may return less. This is particularly + likely when using compressed data. However, the empty string will + never be returned. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + """ + while True: + data = self.read(amt=amt, decode_content=decode_content) + + if data: + yield data + else: + break + + def _init_length(self, request_method: str | None) -> int | None: + length: int | None + content_length: str | None = self.headers.get("content-length") + + if content_length is not None: + try: + # RFC 7230 section 3.3.2 specifies multiple content lengths can + # be sent in a single Content-Length header + # (e.g. Content-Length: 42, 42). This line ensures the values + # are all valid ints and that as long as the `set` length is 1, + # all values are the same. Otherwise, the header is invalid. + lengths = {int(val) for val in content_length.split(",")} + if len(lengths) > 1: + raise InvalidHeader( + "Content-Length contained multiple " + "unmatching values (%s)" % content_length + ) + length = lengths.pop() + except ValueError: + length = None + else: + if length < 0: + length = None + + else: # if content_length is None + length = None + + # Check for responses that shouldn't include a body + if ( + self.status in (204, 304) + or 100 <= self.status < 200 + or request_method == "HEAD" + ): + length = 0 + + return length + + def read( + self, + amt: int | None = None, + decode_content: bool | None = None, # ignored because browser decodes always + cache_content: bool = False, + ) -> bytes: + if ( + self._closed + or self._response is None + or (isinstance(self._response.body, IOBase) and self._response.body.closed) + ): + return b"" + + with self._error_catcher(): + # body has been preloaded as a string by XmlHttpRequest + if not isinstance(self._response.body, IOBase): + self.length_remaining = len(self._response.body) + self.length_is_certain = True + # wrap body in IOStream + self._response.body = BytesIO(self._response.body) + if amt is not None and amt >= 0: + # don't cache partial content + cache_content = False + data = self._response.body.read(amt) + self._uncached_read_occurred = True + else: # read all we can (and cache it) + data = self._response.body.read() + if cache_content and not self._uncached_read_occurred: + self._body = data + else: + self._uncached_read_occurred = True + if self.length_remaining is not None: + self.length_remaining = max(self.length_remaining - len(data), 0) + if len(data) == 0 or ( + self.length_is_certain and self.length_remaining == 0 + ): + # definitely finished reading, close response stream + self._response.body.close() + return typing.cast(bytes, data) + + def read_chunked( + self, + amt: int | None = None, + decode_content: bool | None = None, + ) -> typing.Generator[bytes]: + # chunked is handled by browser + while True: + bytes = self.read(amt, decode_content) + if not bytes: + break + yield bytes + + def release_conn(self) -> None: + if not self._pool or not self._connection: + return None + + self._pool._put_conn(self._connection) + self._connection = None + + def drain_conn(self) -> None: + self.close() + + @property + def data(self) -> bytes: + if self._body: + return self._body + else: + return self.read(cache_content=True) + + def json(self) -> typing.Any: + """ + Deserializes the body of the HTTP response as a Python object. + + The body of the HTTP response must be encoded using UTF-8, as per + `RFC 8529 Section 8.1 `_. + + To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to + your custom decoder instead. + + If the body of the HTTP response is not decodable to UTF-8, a + `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a + valid JSON document, a `json.JSONDecodeError` will be raised. + + Read more :ref:`here `. + + :returns: The body of the HTTP response as a Python object. + """ + data = self.data.decode("utf-8") + return _json.loads(data) + + def close(self) -> None: + if not self._closed: + if isinstance(self._response.body, IOBase): + self._response.body.close() + if self._connection: + self._connection.close() + self._connection = None + self._closed = True + + @contextmanager + def _error_catcher(self) -> typing.Generator[None]: + """ + Catch Emscripten specific exceptions thrown by fetch.py, + instead re-raising urllib3 variants, so that low-level exceptions + are not leaked in the high-level api. + + On exit, release the connection back to the pool. + """ + from .fetch import _RequestError, _TimeoutError # avoid circular import + + clean_exit = False + + try: + yield + # If no exception is thrown, we should avoid cleaning up + # unnecessarily. + clean_exit = True + except _TimeoutError as e: + raise TimeoutError(str(e)) + except _RequestError as e: + raise HTTPException(str(e)) + finally: + # If we didn't terminate cleanly, we need to throw away our + # connection. + if not clean_exit: + # The response may not be closed but we're not going to use it + # anymore so close it now + if ( + isinstance(self._response.body, IOBase) + and not self._response.body.closed + ): + self._response.body.close() + # release the connection back to the pool + self.release_conn() + else: + # If we have read everything from the response stream, + # return the connection back to the pool. + if ( + isinstance(self._response.body, IOBase) + and self._response.body.closed + ): + self.release_conn() diff --git a/.venv/lib/python3.12/site-packages/urllib3/contrib/pyopenssl.py b/.venv/lib/python3.12/site-packages/urllib3/contrib/pyopenssl.py new file mode 100644 index 0000000000000000000000000000000000000000..62887ba406a3c11230fc19890941eb4c67ed25ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/contrib/pyopenssl.py @@ -0,0 +1,603 @@ +""" +Module for using pyOpenSSL as a TLS backend. This module was relevant before +the standard library ``ssl`` module supported SNI, but now that we've dropped +support for Python 2.7 all relevant Python versions support SNI so +**this module is no longer recommended**. + +This needs the following packages installed: + +* `pyOpenSSL`_ (tested with 19.0.0) +* `cryptography`_ (minimum 2.3, from pyopenssl) +* `idna`_ (minimum 2.1, from cryptography) + +However, pyOpenSSL depends on cryptography, so while we use all three directly here we +end up having relatively few packages required. + +You can install them with the following command: + +.. code-block:: bash + + $ python -m pip install pyopenssl cryptography idna + +To activate certificate checking, call +:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code +before you begin making HTTP requests. This can be done in a ``sitecustomize`` +module, or at any other time before your application begins using ``urllib3``, +like this: + +.. code-block:: python + + try: + import urllib3.contrib.pyopenssl + urllib3.contrib.pyopenssl.inject_into_urllib3() + except ImportError: + pass + +.. _pyopenssl: https://www.pyopenssl.org +.. _cryptography: https://cryptography.io +.. _idna: https://github.com/kjd/idna +""" + +from __future__ import annotations + +import OpenSSL.SSL +from cryptography import x509 +from cryptography.hazmat.primitives.serialization import load_pem_private_key +from cryptography.x509.oid import NameOID + +try: + from cryptography.x509 import UnsupportedExtension # type: ignore[attr-defined] +except ImportError: + # UnsupportedExtension is gone in cryptography >= 2.1.0 + class UnsupportedExtension(Exception): # type: ignore[no-redef] + pass + + +import logging +import ssl +import typing +from socket import socket as socket_cls + +from .. import util + +if typing.TYPE_CHECKING: + from OpenSSL.crypto import X509 + + +__all__ = ["inject_into_urllib3", "extract_from_urllib3"] + +# Map from urllib3 to PyOpenSSL compatible parameter-values. +_openssl_versions: dict[int, int] = { + util.ssl_.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined] + util.ssl_.PROTOCOL_TLS_CLIENT: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined] +} + +if hasattr(ssl, "PROTOCOL_TLSv1") and hasattr(OpenSSL.SSL, "TLSv1_METHOD"): + _openssl_versions[ssl.PROTOCOL_TLSv1] = OpenSSL.SSL.TLSv1_METHOD + +if hasattr(ssl, "PROTOCOL_TLSv1_1") and hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"): + _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD + +if hasattr(ssl, "PROTOCOL_TLSv1_2") and hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"): + _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD + + +_stdlib_to_openssl_verify = { + ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, + ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, + ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, +} +_openssl_to_stdlib_verify = {v: k for k, v in _stdlib_to_openssl_verify.items()} + +# The SSLvX values are the most likely to be missing in the future +# but we check them all just to be sure. +_OP_NO_SSLv2_OR_SSLv3: int = getattr(OpenSSL.SSL, "OP_NO_SSLv2", 0) | getattr( + OpenSSL.SSL, "OP_NO_SSLv3", 0 +) +_OP_NO_TLSv1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1", 0) +_OP_NO_TLSv1_1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_1", 0) +_OP_NO_TLSv1_2: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_2", 0) +_OP_NO_TLSv1_3: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_3", 0) + +_openssl_to_ssl_minimum_version: dict[int, int] = { + ssl.TLSVersion.MINIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.TLSv1: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1, + ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1, + ssl.TLSVersion.TLSv1_3: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 + ), + ssl.TLSVersion.MAXIMUM_SUPPORTED: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 + ), +} +_openssl_to_ssl_maximum_version: dict[int, int] = { + ssl.TLSVersion.MINIMUM_SUPPORTED: ( + _OP_NO_SSLv2_OR_SSLv3 + | _OP_NO_TLSv1 + | _OP_NO_TLSv1_1 + | _OP_NO_TLSv1_2 + | _OP_NO_TLSv1_3 + ), + ssl.TLSVersion.TLSv1: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3 + ), + ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3, + ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_3, + ssl.TLSVersion.TLSv1_3: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.MAXIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3, +} + +# OpenSSL will only write 16K at a time +SSL_WRITE_BLOCKSIZE = 16384 + +orig_util_SSLContext = util.ssl_.SSLContext + + +log = logging.getLogger(__name__) + + +def inject_into_urllib3() -> None: + "Monkey-patch urllib3 with PyOpenSSL-backed SSL-support." + + _validate_dependencies_met() + + util.SSLContext = PyOpenSSLContext # type: ignore[assignment] + util.ssl_.SSLContext = PyOpenSSLContext # type: ignore[assignment] + util.IS_PYOPENSSL = True + util.ssl_.IS_PYOPENSSL = True + + +def extract_from_urllib3() -> None: + "Undo monkey-patching by :func:`inject_into_urllib3`." + + util.SSLContext = orig_util_SSLContext + util.ssl_.SSLContext = orig_util_SSLContext + util.IS_PYOPENSSL = False + util.ssl_.IS_PYOPENSSL = False + + +def _validate_dependencies_met() -> None: + """ + Verifies that PyOpenSSL's package-level dependencies have been met. + Throws `ImportError` if they are not met. + """ + # Method added in `cryptography==1.1`; not available in older versions + from cryptography.x509.extensions import Extensions + + if getattr(Extensions, "get_extension_for_class", None) is None: + raise ImportError( + "'cryptography' module missing required functionality. " + "Try upgrading to v1.3.4 or newer." + ) + + # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509 + # attribute is only present on those versions. + from OpenSSL.crypto import X509 + + x509 = X509() + if getattr(x509, "_x509", None) is None: + raise ImportError( + "'pyOpenSSL' module missing required functionality. " + "Try upgrading to v0.14 or newer." + ) + + +def _dnsname_to_stdlib(name: str) -> str | None: + """ + Converts a dNSName SubjectAlternativeName field to the form used by the + standard library on the given Python version. + + Cryptography produces a dNSName as a unicode string that was idna-decoded + from ASCII bytes. We need to idna-encode that string to get it back, and + then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib + uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). + + If the name cannot be idna-encoded then we return None signalling that + the name given should be skipped. + """ + + def idna_encode(name: str) -> bytes | None: + """ + Borrowed wholesale from the Python Cryptography Project. It turns out + that we can't just safely call `idna.encode`: it can explode for + wildcard names. This avoids that problem. + """ + import idna + + try: + for prefix in ["*.", "."]: + if name.startswith(prefix): + name = name[len(prefix) :] + return prefix.encode("ascii") + idna.encode(name) + return idna.encode(name) + except idna.core.IDNAError: + return None + + # Don't send IPv6 addresses through the IDNA encoder. + if ":" in name: + return name + + encoded_name = idna_encode(name) + if encoded_name is None: + return None + return encoded_name.decode("utf-8") + + +def get_subj_alt_name(peer_cert: X509) -> list[tuple[str, str]]: + """ + Given an PyOpenSSL certificate, provides all the subject alternative names. + """ + cert = peer_cert.to_cryptography() + + # We want to find the SAN extension. Ask Cryptography to locate it (it's + # faster than looping in Python) + try: + ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value + except x509.ExtensionNotFound: + # No such extension, return the empty list. + return [] + except ( + x509.DuplicateExtension, + UnsupportedExtension, + x509.UnsupportedGeneralNameType, + UnicodeError, + ) as e: + # A problem has been found with the quality of the certificate. Assume + # no SAN field is present. + log.warning( + "A problem was encountered with the certificate that prevented " + "urllib3 from finding the SubjectAlternativeName field. This can " + "affect certificate validation. The error was %s", + e, + ) + return [] + + # We want to return dNSName and iPAddress fields. We need to cast the IPs + # back to strings because the match_hostname function wants them as + # strings. + # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 + # decoded. This is pretty frustrating, but that's what the standard library + # does with certificates, and so we need to attempt to do the same. + # We also want to skip over names which cannot be idna encoded. + names = [ + ("DNS", name) + for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) + if name is not None + ] + names.extend( + ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress) + ) + + return names + + +def _get_common_name(peer_cert: X509) -> str | None: + """ + Given a pyOpenSSL certificate, return the subject's common name. + """ + cert = peer_cert.to_cryptography() + names = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME) + return typing.cast(str, names[0].value) if names else None + + +class WrappedSocket: + """API-compatibility wrapper for Python OpenSSL's Connection-class.""" + + def __init__( + self, + connection: OpenSSL.SSL.Connection, + socket: socket_cls, + suppress_ragged_eofs: bool = True, + ) -> None: + self.connection = connection + self.socket = socket + self.suppress_ragged_eofs = suppress_ragged_eofs + self._io_refs = 0 + self._closed = False + + def fileno(self) -> int: + return self.socket.fileno() + + # Copy-pasted from Python 3.5 source code + def _decref_socketios(self) -> None: + if self._io_refs > 0: + self._io_refs -= 1 + if self._closed: + self.close() + + def recv(self, *args: typing.Any, **kwargs: typing.Any) -> bytes: + try: + data = self.connection.recv(*args, **kwargs) + except OpenSSL.SSL.SysCallError as e: + if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): + return b"" + else: + raise OSError(e.args[0], str(e)) from e + except OpenSSL.SSL.ZeroReturnError: + if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: + return b"" + else: + raise + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(self.socket, self.socket.gettimeout()): + raise TimeoutError("The read operation timed out") from e + else: + return self.recv(*args, **kwargs) + + # TLS 1.3 post-handshake authentication + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"read error: {e!r}") from e + else: + return data + + def recv_into(self, *args: typing.Any, **kwargs: typing.Any) -> int: + try: + return self.connection.recv_into(*args, **kwargs) + except OpenSSL.SSL.SysCallError as e: + if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): + return 0 + else: + raise OSError(e.args[0], str(e)) from e + except OpenSSL.SSL.ZeroReturnError: + if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: + return 0 + else: + raise + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(self.socket, self.socket.gettimeout()): + raise TimeoutError("The read operation timed out") from e + else: + return self.recv_into(*args, **kwargs) + + # TLS 1.3 post-handshake authentication + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"read error: {e!r}") from e + + def settimeout(self, timeout: float) -> None: + return self.socket.settimeout(timeout) + + def _send_until_done(self, data: bytes) -> int: + while True: + try: + return self.connection.send(data) + except OpenSSL.SSL.WantWriteError as e: + if not util.wait_for_write(self.socket, self.socket.gettimeout()): + raise TimeoutError() from e + continue + except OpenSSL.SSL.SysCallError as e: + raise OSError(e.args[0], str(e)) from e + + def sendall(self, data: bytes) -> None: + total_sent = 0 + while total_sent < len(data): + sent = self._send_until_done( + data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE] + ) + total_sent += sent + + def shutdown(self, how: int) -> None: + try: + self.connection.shutdown() + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"shutdown error: {e!r}") from e + + def close(self) -> None: + self._closed = True + if self._io_refs <= 0: + self._real_close() + + def _real_close(self) -> None: + try: + return self.connection.close() # type: ignore[no-any-return] + except OpenSSL.SSL.Error: + return + + @typing.overload + def getpeercert( + self, binary_form: typing.Literal[False] = False + ) -> dict[str, list[typing.Any]] | None: ... + + @typing.overload + def getpeercert(self, binary_form: typing.Literal[True]) -> bytes | None: ... + + def getpeercert( + self, binary_form: bool = False + ) -> dict[str, list[typing.Any]] | bytes | None: + x509 = self.connection.get_peer_certificate() + + if x509 is None: + return None + + if binary_form: + return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509) + + return { + "subject": ((("commonName", _get_common_name(x509)),),), # type: ignore[dict-item] + "subjectAltName": get_subj_alt_name(x509), + } + + def version(self) -> str: + return self.connection.get_protocol_version_name() + + def selected_alpn_protocol(self) -> str | None: + alpn_proto = self.connection.get_alpn_proto_negotiated() + return alpn_proto.decode() if alpn_proto else None + + +WrappedSocket.makefile = socket_cls.makefile # type: ignore[attr-defined] + + +class PyOpenSSLContext: + """ + I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible + for translating the interface of the standard library ``SSLContext`` object + to calls into PyOpenSSL. + """ + + def __init__(self, protocol: int) -> None: + self.protocol = _openssl_versions[protocol] + self._ctx = OpenSSL.SSL.Context(self.protocol) + self._options = 0 + self.check_hostname = False + self._minimum_version: int = ssl.TLSVersion.MINIMUM_SUPPORTED + self._maximum_version: int = ssl.TLSVersion.MAXIMUM_SUPPORTED + self._verify_flags: int = ssl.VERIFY_X509_TRUSTED_FIRST + + @property + def options(self) -> int: + return self._options + + @options.setter + def options(self, value: int) -> None: + self._options = value + self._set_ctx_options() + + @property + def verify_flags(self) -> int: + return self._verify_flags + + @verify_flags.setter + def verify_flags(self, value: int) -> None: + self._verify_flags = value + self._ctx.get_cert_store().set_flags(self._verify_flags) # type: ignore[union-attr] + + @property + def verify_mode(self) -> int: + return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()] + + @verify_mode.setter + def verify_mode(self, value: ssl.VerifyMode) -> None: + self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback) + + def set_default_verify_paths(self) -> None: + self._ctx.set_default_verify_paths() + + def set_ciphers(self, ciphers: bytes | str) -> None: + if isinstance(ciphers, str): + ciphers = ciphers.encode("utf-8") + self._ctx.set_cipher_list(ciphers) + + def load_verify_locations( + self, + cafile: str | None = None, + capath: str | None = None, + cadata: bytes | None = None, + ) -> None: + if cafile is not None: + cafile = cafile.encode("utf-8") # type: ignore[assignment] + if capath is not None: + capath = capath.encode("utf-8") # type: ignore[assignment] + try: + self._ctx.load_verify_locations(cafile, capath) + if cadata is not None: + self._ctx.load_verify_locations(cadata) + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"unable to load trusted certificates: {e!r}") from e + + def load_cert_chain( + self, + certfile: str, + keyfile: str | None = None, + password: str | bytes | None = None, + ) -> None: + try: + self._ctx.use_certificate_chain_file(certfile) + if password is not None: + if not isinstance(password, bytes): + password = password.encode("utf-8") + # pyOpenSSL added cryptography-key support in 24.3.0. + # Keep using the older password-callback path until 2026's + # versions because set_passwd_cb() became deprecated in 26.3.0. + if int(OpenSSL.__version__.split(".")[0]) >= 26: + with open(keyfile or certfile, "rb") as key_file: + key_data = key_file.read() + try: + private_key = load_pem_private_key(key_data, password) + except TypeError: + # Match SSLContext by ignoring passwords supplied + # for unencrypted keys. + # Incorrect passwords for encrypted keys raise + # ValueError instead. + private_key = load_pem_private_key(key_data, None) + # cryptography's loader returns a wider private-key union + # than pyOpenSSL accepts, so we add `type: ignore` here. + self._ctx.use_privatekey(private_key) # type: ignore[arg-type] + else: + self._ctx.set_passwd_cb(lambda *_: password) + self._ctx.use_privatekey_file(keyfile or certfile) + else: + self._ctx.use_privatekey_file(keyfile or certfile) + except (OpenSSL.SSL.Error, TypeError, ValueError) as e: + raise ssl.SSLError(f"Unable to load certificate chain: {e!r}") from e + + def set_alpn_protocols(self, protocols: list[bytes | str]) -> None: + protocols = [util.util.to_bytes(p, "ascii") for p in protocols] + return self._ctx.set_alpn_protos(protocols) # type: ignore[arg-type] + + def wrap_socket( + self, + sock: socket_cls, + server_side: bool = False, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + server_hostname: bytes | str | None = None, + ) -> WrappedSocket: + cnx = OpenSSL.SSL.Connection(self._ctx, sock) + + # If server_hostname is an IP, don't use it for SNI, per RFC6066 Section 3 + if server_hostname and not util.ssl_.is_ipaddress(server_hostname): + if isinstance(server_hostname, str): + server_hostname = server_hostname.encode("utf-8") + cnx.set_tlsext_host_name(server_hostname) + + cnx.set_connect_state() + + while True: + try: + cnx.do_handshake() + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(sock, sock.gettimeout()): + raise TimeoutError("select timed out") from e + continue + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"bad handshake: {e!r}") from e + break + + return WrappedSocket(cnx, sock) + + def _set_ctx_options(self) -> None: + self._ctx.set_options( + self._options + | _openssl_to_ssl_minimum_version[self._minimum_version] + | _openssl_to_ssl_maximum_version[self._maximum_version] + ) + + @property + def minimum_version(self) -> int: + return self._minimum_version + + @minimum_version.setter + def minimum_version(self, minimum_version: int) -> None: + self._minimum_version = minimum_version + self._set_ctx_options() + + @property + def maximum_version(self) -> int: + return self._maximum_version + + @maximum_version.setter + def maximum_version(self, maximum_version: int) -> None: + self._maximum_version = maximum_version + self._set_ctx_options() + + +def _verify_callback( + cnx: OpenSSL.SSL.Connection, + x509: X509, + err_no: int, + err_depth: int, + return_code: int, +) -> bool: + return err_no == 0 diff --git a/.venv/lib/python3.12/site-packages/urllib3/contrib/socks.py b/.venv/lib/python3.12/site-packages/urllib3/contrib/socks.py new file mode 100644 index 0000000000000000000000000000000000000000..67fceb080ad552d380fc1746c188af8c57aa59e6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/contrib/socks.py @@ -0,0 +1,226 @@ +""" +This module contains provisional support for SOCKS proxies from within +urllib3. This module supports SOCKS4, SOCKS4A (an extension of SOCKS4), and +SOCKS5. To enable its functionality, either install PySocks or install this +module with the ``socks`` extra. + +The SOCKS implementation supports the full range of urllib3 features. It also +supports the following SOCKS features: + +- SOCKS4A (``proxy_url='socks4a://...``) +- SOCKS4 (``proxy_url='socks4://...``) +- SOCKS5 with remote DNS (``proxy_url='socks5h://...``) +- SOCKS5 with local DNS (``proxy_url='socks5://...``) +- Usernames and passwords for the SOCKS proxy + +.. note:: + It is recommended to use ``socks5h://`` or ``socks4a://`` schemes in + your ``proxy_url`` to ensure that DNS resolution is done from the remote + server instead of client-side when connecting to a domain name. + +SOCKS4 supports IPv4 and domain names with the SOCKS4A extension. SOCKS5 +supports IPv4, IPv6, and domain names. + +When connecting to a SOCKS4 proxy the ``username`` portion of the ``proxy_url`` +will be sent as the ``userid`` section of the SOCKS request: + +.. code-block:: python + + proxy_url="socks4a://@proxy-host" + +When connecting to a SOCKS5 proxy the ``username`` and ``password`` portion +of the ``proxy_url`` will be sent as the username/password to authenticate +with the proxy: + +.. code-block:: python + + proxy_url="socks5h://:@proxy-host" + +""" + +from __future__ import annotations + +try: + import socks +except ImportError: + import warnings + + from ..exceptions import DependencyWarning + + warnings.warn( + ( + "SOCKS support in urllib3 requires the installation of optional " + "dependencies: specifically, PySocks. For more information, see " + "https://urllib3.readthedocs.io/en/latest/advanced-usage.html#socks-proxies" + ), + DependencyWarning, + ) + raise + +import typing +from socket import timeout as SocketTimeout + +from ..connection import HTTPConnection, HTTPSConnection +from ..connectionpool import HTTPConnectionPool, HTTPSConnectionPool +from ..exceptions import ConnectTimeoutError, NewConnectionError +from ..poolmanager import PoolManager +from ..util.url import parse_url + +try: + import ssl +except ImportError: + ssl = None # type: ignore[assignment] + + +class _TYPE_SOCKS_OPTIONS(typing.TypedDict): + socks_version: int + proxy_host: str | None + proxy_port: str | None + username: str | None + password: str | None + rdns: bool + + +class SOCKSConnection(HTTPConnection): + """ + A plain-text HTTP connection that connects via a SOCKS proxy. + """ + + def __init__( + self, + _socks_options: _TYPE_SOCKS_OPTIONS, + *args: typing.Any, + **kwargs: typing.Any, + ) -> None: + self._socks_options = _socks_options + super().__init__(*args, **kwargs) + + def _new_conn(self) -> socks.socksocket: + """ + Establish a new connection via the SOCKS proxy. + """ + extra_kw: dict[str, typing.Any] = {} + if self.source_address: + extra_kw["source_address"] = self.source_address + + if self.socket_options: + extra_kw["socket_options"] = self.socket_options + + try: + conn = socks.create_connection( + (self.host, self.port), + proxy_type=self._socks_options["socks_version"], + proxy_addr=self._socks_options["proxy_host"], + proxy_port=self._socks_options["proxy_port"], # type: ignore[arg-type] + proxy_username=self._socks_options["username"], + proxy_password=self._socks_options["password"], + proxy_rdns=self._socks_options["rdns"], + timeout=self.timeout, # type: ignore[arg-type] + **extra_kw, + ) + + except SocketTimeout as e: + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + + except socks.ProxyError as e: + # This is fragile as hell, but it seems to be the only way to raise + # useful errors here. + if e.socket_err: + error = e.socket_err + if isinstance(error, SocketTimeout): + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + else: + # Adding `from e` messes with coverage somehow, so it's omitted. + # See #2386. + raise NewConnectionError( + self, f"Failed to establish a new connection: {error}" + ) + else: # Defensive: see https://github.com/urllib3/urllib3/pull/3728#pullrequestreview-3816302703 + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + except OSError as e: # Defensive: PySocks should catch all these. + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + return conn + + +# We don't need to duplicate the Verified/Unverified distinction from +# urllib3/connection.py here because the HTTPSConnection will already have been +# correctly set to either the Verified or Unverified form by that module. This +# means the SOCKSHTTPSConnection will automatically be the correct type. +class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection): + pass + + +class SOCKSHTTPConnectionPool(HTTPConnectionPool): + ConnectionCls = SOCKSConnection + + +class SOCKSHTTPSConnectionPool(HTTPSConnectionPool): + ConnectionCls = SOCKSHTTPSConnection + + +class SOCKSProxyManager(PoolManager): + """ + A version of the urllib3 ProxyManager that routes connections via the + defined SOCKS proxy. + """ + + pool_classes_by_scheme = { + "http": SOCKSHTTPConnectionPool, + "https": SOCKSHTTPSConnectionPool, + } + + def __init__( + self, + proxy_url: str, + username: str | None = None, + password: str | None = None, + num_pools: int = 10, + headers: typing.Mapping[str, str] | None = None, + **connection_pool_kw: typing.Any, + ): + parsed = parse_url(proxy_url) + + if username is None and password is None: + username, password = parsed.auth_decoded + if parsed.scheme == "socks5": + socks_version = socks.PROXY_TYPE_SOCKS5 + rdns = False + elif parsed.scheme == "socks5h": + socks_version = socks.PROXY_TYPE_SOCKS5 + rdns = True + elif parsed.scheme == "socks4": + socks_version = socks.PROXY_TYPE_SOCKS4 + rdns = False + elif parsed.scheme == "socks4a": + socks_version = socks.PROXY_TYPE_SOCKS4 + rdns = True + else: + raise ValueError(f"Unable to determine SOCKS version from {proxy_url}") + + self.proxy_url = proxy_url + + socks_options = { + "socks_version": socks_version, + "proxy_host": parsed.host, + "proxy_port": parsed.port, + "username": username, + "password": password, + "rdns": rdns, + } + connection_pool_kw["_socks_options"] = socks_options + + super().__init__(num_pools, headers, **connection_pool_kw) + + self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme diff --git a/.venv/lib/python3.12/site-packages/urllib3/exceptions.py b/.venv/lib/python3.12/site-packages/urllib3/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..3d7e9b93d307ffe7d54868122227a165cc98383c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/exceptions.py @@ -0,0 +1,335 @@ +from __future__ import annotations + +import socket +import typing +import warnings +from email.errors import MessageDefect +from http.client import IncompleteRead as httplib_IncompleteRead + +if typing.TYPE_CHECKING: + from .connection import HTTPConnection + from .connectionpool import ConnectionPool + from .response import HTTPResponse + from .util.retry import Retry + +# Base Exceptions + + +class HTTPError(Exception): + """Base exception used by this module.""" + + +class HTTPWarning(Warning): + """Base warning used by this module.""" + + +_TYPE_REDUCE_RESULT = tuple[typing.Callable[..., object], tuple[object, ...]] + + +class PoolError(HTTPError): + """Base exception for errors caused within a pool.""" + + def __init__(self, pool: ConnectionPool, message: str) -> None: + self.pool = pool + self._message = message + super().__init__(f"{pool}: {message}") + + def __reduce__(self) -> _TYPE_REDUCE_RESULT: + # For pickling purposes. + return self.__class__, (None, self._message) + + +class RequestError(PoolError): + """Base exception for PoolErrors that have associated URLs.""" + + def __init__(self, pool: ConnectionPool, url: str | None, message: str) -> None: + self.url = url + super().__init__(pool, message) + + def __reduce__(self) -> _TYPE_REDUCE_RESULT: + # For pickling purposes. + return self.__class__, (None, self.url, self._message) + + +class SSLError(HTTPError): + """Raised when SSL certificate fails in an HTTPS connection.""" + + +class ProxyError(HTTPError): + """Raised when the connection to a proxy fails.""" + + # The original error is also available as __cause__. + original_error: Exception + + def __init__(self, message: str, error: Exception) -> None: + super().__init__(message, error) + self.original_error = error + + +class DecodeError(HTTPError): + """Raised when automatic decoding based on Content-Type fails.""" + + +class ProtocolError(HTTPError): + """Raised when something unexpected happens mid-request/response.""" + + +#: Renamed to ProtocolError but aliased for backwards compatibility. +ConnectionError = ProtocolError + + +# Leaf Exceptions + + +class MaxRetryError(RequestError): + """Raised when the maximum number of retries is exceeded. + + :param pool: The connection pool + :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool` + :param str url: The requested Url + :param reason: The underlying error + :type reason: :class:`Exception` + + """ + + def __init__( + self, pool: ConnectionPool, url: str | None, reason: Exception | None = None + ) -> None: + self.reason = reason + + message = f"Max retries exceeded with url: {url} (Caused by {reason!r})" + + super().__init__(pool, url, message) + + def __reduce__(self) -> _TYPE_REDUCE_RESULT: + # For pickling purposes. + return self.__class__, (None, self.url, self.reason) + + +class HostChangedError(RequestError): + """Raised when an existing pool gets a request for a foreign host.""" + + def __init__( + self, pool: ConnectionPool, url: str, retries: Retry | int = 3 + ) -> None: + message = f"Tried to open a foreign host with url: {url}" + super().__init__(pool, url, message) + self.retries = retries + + +class TimeoutStateError(HTTPError): + """Raised when passing an invalid state to a timeout""" + + +class TimeoutError(HTTPError): + """Raised when a socket timeout error occurs. + + Catching this error will catch both :exc:`ReadTimeoutErrors + ` and :exc:`ConnectTimeoutErrors `. + """ + + +class ReadTimeoutError(TimeoutError, RequestError): + """Raised when a socket timeout occurs while receiving data from a server""" + + +# This timeout error does not have a URL attached and needs to inherit from the +# base HTTPError +class ConnectTimeoutError(TimeoutError): + """Raised when a socket timeout occurs while connecting to a server""" + + +class NewConnectionError(ConnectTimeoutError, HTTPError): + """Raised when we fail to establish a new connection. Usually ECONNREFUSED.""" + + def __init__(self, conn: HTTPConnection, message: str) -> None: + self.conn = conn + self._message = message + super().__init__(f"{conn}: {message}") + + def __reduce__(self) -> _TYPE_REDUCE_RESULT: + # For pickling purposes. + return self.__class__, (None, self._message) + + @property + def pool(self) -> HTTPConnection: + warnings.warn( + "The 'pool' property is deprecated and will be removed " + "in urllib3 v3.0. Use 'conn' instead.", + FutureWarning, + stacklevel=2, + ) + + return self.conn + + +class NameResolutionError(NewConnectionError): + """Raised when host name resolution fails.""" + + def __init__(self, host: str, conn: HTTPConnection, reason: socket.gaierror): + message = f"Failed to resolve '{host}' ({reason})" + self._host = host + self._reason = reason + super().__init__(conn, message) + + def __reduce__(self) -> _TYPE_REDUCE_RESULT: + # For pickling purposes. + return self.__class__, (self._host, None, self._reason) + + +class EmptyPoolError(PoolError): + """Raised when a pool runs out of connections and no more are allowed.""" + + +class FullPoolError(PoolError): + """Raised when we try to add a connection to a full pool in blocking mode.""" + + +class ClosedPoolError(PoolError): + """Raised when a request enters a pool after the pool has been closed.""" + + +class LocationValueError(ValueError, HTTPError): + """Raised when there is something wrong with a given URL input.""" + + +class LocationParseError(LocationValueError): + """Raised when get_host or similar fails to parse the URL input.""" + + def __init__(self, location: str) -> None: + message = f"Failed to parse: {location}" + super().__init__(message) + + self.location = location + + +class URLSchemeUnknown(LocationValueError): + """Raised when a URL input has an unsupported scheme.""" + + def __init__(self, scheme: str): + message = f"Not supported URL scheme {scheme}" + super().__init__(message) + + self.scheme = scheme + + +class ResponseError(HTTPError): + """Used as a container for an error reason supplied in a MaxRetryError.""" + + GENERIC_ERROR = "too many error responses" + SPECIFIC_ERROR = "too many {status_code} error responses" + + +class SecurityWarning(HTTPWarning): + """Warned when performing security reducing actions""" + + +class InsecureRequestWarning(SecurityWarning): + """Warned when making an unverified HTTPS request.""" + + +class NotOpenSSLWarning(SecurityWarning): + """Warned when using unsupported SSL library""" + + +class SystemTimeWarning(SecurityWarning): + """Warned when system time is suspected to be wrong""" + + +class InsecurePlatformWarning(SecurityWarning): + """Warned when certain TLS/SSL configuration is not available on a platform.""" + + +class DependencyWarning(HTTPWarning): + """ + Warned when an attempt is made to import a module with missing optional + dependencies. + """ + + +class ResponseNotChunked(ProtocolError, ValueError): + """Response needs to be chunked in order to read it as chunks.""" + + +class BodyNotHttplibCompatible(HTTPError): + """ + Body should be :class:`http.client.HTTPResponse` like + (have an fp attribute which returns raw chunks) for read_chunked(). + """ + + +class IncompleteRead(HTTPError, httplib_IncompleteRead): + """ + Response length doesn't match expected Content-Length + + Subclass of :class:`http.client.IncompleteRead` to allow int value + for ``partial`` to avoid creating large objects on streamed reads. + """ + + partial: int # type: ignore[assignment] + expected: int + + def __init__(self, partial: int, expected: int) -> None: + self.partial = partial + self.expected = expected + + def __repr__(self) -> str: + return "IncompleteRead(%i bytes read, %i more expected)" % ( + self.partial, + self.expected, + ) + + +class InvalidChunkLength(HTTPError, httplib_IncompleteRead): + """Invalid chunk length in a chunked response.""" + + def __init__(self, response: HTTPResponse, length: bytes) -> None: + self.partial: int = response.tell() # type: ignore[assignment] + self.expected: int | None = response.length_remaining + self.response = response + self.length = length + + def __repr__(self) -> str: + return "InvalidChunkLength(got length %r, %i bytes read)" % ( + self.length, + self.partial, + ) + + +class InvalidHeader(HTTPError): + """The header provided was somehow invalid.""" + + +class ProxySchemeUnknown(AssertionError, URLSchemeUnknown): + """ProxyManager does not support the supplied scheme""" + + # TODO(t-8ch): Stop inheriting from AssertionError in v2.0. + + def __init__(self, scheme: str | None) -> None: + # 'localhost' is here because our URL parser parses + # localhost:8080 -> scheme=localhost, remove if we fix this. + if scheme == "localhost": + scheme = None + if scheme is None: + message = "Proxy URL had no scheme, should start with http:// or https://" + else: + message = f"Proxy URL had unsupported scheme {scheme}, should use http:// or https://" + super().__init__(message) + + +class ProxySchemeUnsupported(ValueError): + """Fetching HTTPS resources through HTTPS proxies is unsupported""" + + +class HeaderParsingError(HTTPError): + """Raised by assert_header_parsing, but we convert it to a log.warning statement.""" + + def __init__( + self, defects: list[MessageDefect], unparsed_data: bytes | str | None + ) -> None: + message = f"{defects or 'Unknown'}, unparsed data: {unparsed_data!r}" + super().__init__(message) + + +class UnrewindableBodyError(HTTPError): + """urllib3 encountered an error when trying to rewind a body""" diff --git a/.venv/lib/python3.12/site-packages/urllib3/fields.py b/.venv/lib/python3.12/site-packages/urllib3/fields.py new file mode 100644 index 0000000000000000000000000000000000000000..fe68e177324bc67f145091e464556a69b89bcda7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/fields.py @@ -0,0 +1,341 @@ +from __future__ import annotations + +import email.utils +import mimetypes +import typing + +_TYPE_FIELD_VALUE = typing.Union[str, bytes] +_TYPE_FIELD_VALUE_TUPLE = typing.Union[ + _TYPE_FIELD_VALUE, + tuple[str, _TYPE_FIELD_VALUE], + tuple[str, _TYPE_FIELD_VALUE, str], +] + + +def guess_content_type( + filename: str | None, default: str = "application/octet-stream" +) -> str: + """ + Guess the "Content-Type" of a file. + + :param filename: + The filename to guess the "Content-Type" of using :mod:`mimetypes`. + :param default: + If no "Content-Type" can be guessed, default to `default`. + """ + if filename: + return mimetypes.guess_type(filename)[0] or default + return default + + +def format_header_param_rfc2231(name: str, value: _TYPE_FIELD_VALUE) -> str: + """ + Helper function to format and quote a single header parameter using the + strategy defined in RFC 2231. + + Particularly useful for header parameters which might contain + non-ASCII values, like file names. This follows + `RFC 2388 Section 4.4 `_. + + :param name: + The name of the parameter, a string expected to be ASCII only. + :param value: + The value of the parameter, provided as ``bytes`` or `str``. + :returns: + An RFC-2231-formatted unicode string. + + .. deprecated:: 2.0.0 + Will be removed in urllib3 v3.0. This is not valid for + ``multipart/form-data`` header parameters. + """ + import warnings + + warnings.warn( + "'format_header_param_rfc2231' is insecure, deprecated and will be " + "removed in urllib3 v3.0. This is not valid for " + "multipart/form-data header parameters.", + FutureWarning, + stacklevel=2, + ) + + if isinstance(value, bytes): + value = value.decode("utf-8") + + if not any(ch in value for ch in '"\\\r\n'): + result = f'{name}="{value}"' + try: + result.encode("ascii") + except (UnicodeEncodeError, UnicodeDecodeError): + pass + else: + return result + + value = email.utils.encode_rfc2231(value, "utf-8") + value = f"{name}*={value}" + + return value + + +def format_multipart_header_param(name: str, value: _TYPE_FIELD_VALUE) -> str: + """ + Format and quote a single multipart header parameter. + + This follows the `WHATWG HTML Standard`_ as of 2021/06/10, matching + the behavior of current browser and curl versions. Values are + assumed to be UTF-8. The ``\\n``, ``\\r``, and ``"`` characters are + percent encoded. + + .. _WHATWG HTML Standard: + https://html.spec.whatwg.org/multipage/ + form-control-infrastructure.html#multipart-form-data + + :param name: + The name of the parameter, an ASCII-only ``str``. + :param value: + The value of the parameter, a ``str`` or UTF-8 encoded + ``bytes``. + :returns: + A string ``name="value"`` with the escaped value. + + .. versionchanged:: 2.0.0 + Matches the WHATWG HTML Standard as of 2021/06/10. Control + characters are no longer percent encoded. + + .. versionchanged:: 2.0.0 + Renamed from ``format_header_param_html5`` and + ``format_header_param``. The old names will be removed in + urllib3 v3.0. + """ + if isinstance(value, bytes): + value = value.decode("utf-8") + + # percent encode \n \r " + value = value.translate({10: "%0A", 13: "%0D", 34: "%22"}) + return f'{name}="{value}"' + + +def format_header_param_html5(name: str, value: _TYPE_FIELD_VALUE) -> str: + """ + .. deprecated:: 2.0.0 + Renamed to :func:`format_multipart_header_param`. Will be + removed in urllib3 v3.0. + """ + import warnings + + warnings.warn( + "'format_header_param_html5' has been renamed to " + "'format_multipart_header_param'. The old name will be " + "removed in urllib3 v3.0.", + FutureWarning, + stacklevel=2, + ) + return format_multipart_header_param(name, value) + + +def format_header_param(name: str, value: _TYPE_FIELD_VALUE) -> str: + """ + .. deprecated:: 2.0.0 + Renamed to :func:`format_multipart_header_param`. Will be + removed in urllib3 v3.0. + """ + import warnings + + warnings.warn( + "'format_header_param' has been renamed to " + "'format_multipart_header_param'. The old name will be " + "removed in urllib3 v3.0.", + FutureWarning, + stacklevel=2, + ) + return format_multipart_header_param(name, value) + + +class RequestField: + """ + A data container for request body parameters. + + :param name: + The name of this request field. Must be unicode. + :param data: + The data/value body. + :param filename: + An optional filename of the request field. Must be unicode. + :param headers: + An optional dict-like object of headers to initially use for the field. + + .. versionchanged:: 2.0.0 + The ``header_formatter`` parameter is deprecated and will + be removed in urllib3 v3.0. + """ + + def __init__( + self, + name: str, + data: _TYPE_FIELD_VALUE, + filename: str | None = None, + headers: typing.Mapping[str, str] | None = None, + header_formatter: typing.Callable[[str, _TYPE_FIELD_VALUE], str] | None = None, + ): + self._name = name + self._filename = filename + self.data = data + self.headers: dict[str, str | None] = {} + if headers: + self.headers = dict(headers) + + if header_formatter is not None: + import warnings + + warnings.warn( + "The 'header_formatter' parameter is deprecated and " + "will be removed in urllib3 v3.0.", + FutureWarning, + stacklevel=2, + ) + self.header_formatter = header_formatter + else: + self.header_formatter = format_multipart_header_param + + @classmethod + def from_tuples( + cls, + fieldname: str, + value: _TYPE_FIELD_VALUE_TUPLE, + header_formatter: typing.Callable[[str, _TYPE_FIELD_VALUE], str] | None = None, + ) -> RequestField: + """ + A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. + + Supports constructing :class:`~urllib3.fields.RequestField` from + parameter of key/value strings AND key/filetuple. A filetuple is a + (filename, data, MIME type) tuple where the MIME type is optional. + For example:: + + 'foo': 'bar', + 'fakefile': ('foofile.txt', 'contents of foofile'), + 'realfile': ('barfile.txt', open('realfile').read()), + 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), + 'nonamefile': 'contents of nonamefile field', + + Field names and filenames must be unicode. + """ + filename: str | None + content_type: str | None + data: _TYPE_FIELD_VALUE + + if isinstance(value, tuple): + if len(value) == 3: + filename, data, content_type = value + else: + filename, data = value + content_type = guess_content_type(filename) + else: + filename = None + content_type = None + data = value + + request_param = cls( + fieldname, data, filename=filename, header_formatter=header_formatter + ) + request_param.make_multipart(content_type=content_type) + + return request_param + + def _render_part(self, name: str, value: _TYPE_FIELD_VALUE) -> str: + """ + Override this method to change how each multipart header + parameter is formatted. By default, this calls + :func:`format_multipart_header_param`. + + :param name: + The name of the parameter, an ASCII-only ``str``. + :param value: + The value of the parameter, a ``str`` or UTF-8 encoded + ``bytes``. + + :meta public: + """ + return self.header_formatter(name, value) + + def _render_parts( + self, + header_parts: ( + dict[str, _TYPE_FIELD_VALUE | None] + | typing.Sequence[tuple[str, _TYPE_FIELD_VALUE | None]] + ), + ) -> str: + """ + Helper function to format and quote a single header. + + Useful for single headers that are composed of multiple items. E.g., + 'Content-Disposition' fields. + + :param header_parts: + A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format + as `k1="v1"; k2="v2"; ...`. + """ + iterable: typing.Iterable[tuple[str, _TYPE_FIELD_VALUE | None]] + + parts = [] + if isinstance(header_parts, dict): + iterable = header_parts.items() + else: + iterable = header_parts + + for name, value in iterable: + if value is not None: + parts.append(self._render_part(name, value)) + + return "; ".join(parts) + + def render_headers(self) -> str: + """ + Renders the headers for this request field. + """ + lines = [] + + sort_keys = ["Content-Disposition", "Content-Type", "Content-Location"] + for sort_key in sort_keys: + if self.headers.get(sort_key, False): + lines.append(f"{sort_key}: {self.headers[sort_key]}") + + for header_name, header_value in self.headers.items(): + if header_name not in sort_keys: + if header_value: + lines.append(f"{header_name}: {header_value}") + + lines.append("\r\n") + return "\r\n".join(lines) + + def make_multipart( + self, + content_disposition: str | None = None, + content_type: str | None = None, + content_location: str | None = None, + ) -> None: + """ + Makes this request field into a multipart request field. + + This method overrides "Content-Disposition", "Content-Type" and + "Content-Location" headers to the request parameter. + + :param content_disposition: + The 'Content-Disposition' of the request body. Defaults to 'form-data' + :param content_type: + The 'Content-Type' of the request body. + :param content_location: + The 'Content-Location' of the request body. + + """ + content_disposition = (content_disposition or "form-data") + "; ".join( + [ + "", + self._render_parts( + (("name", self._name), ("filename", self._filename)) + ), + ] + ) + + self.headers["Content-Disposition"] = content_disposition + self.headers["Content-Type"] = content_type + self.headers["Content-Location"] = content_location diff --git a/.venv/lib/python3.12/site-packages/urllib3/filepost.py b/.venv/lib/python3.12/site-packages/urllib3/filepost.py new file mode 100644 index 0000000000000000000000000000000000000000..14f70b05b4778f91137e4a9e7059d7514aa44d28 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/filepost.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import binascii +import codecs +import os +import typing +from io import BytesIO + +from .fields import _TYPE_FIELD_VALUE_TUPLE, RequestField + +writer = codecs.lookup("utf-8")[3] + +_TYPE_FIELDS_SEQUENCE = typing.Sequence[ + typing.Union[tuple[str, _TYPE_FIELD_VALUE_TUPLE], RequestField] +] +_TYPE_FIELDS = typing.Union[ + _TYPE_FIELDS_SEQUENCE, + typing.Mapping[str, _TYPE_FIELD_VALUE_TUPLE], +] + + +def choose_boundary() -> str: + """ + Our embarrassingly-simple replacement for mimetools.choose_boundary. + """ + return binascii.hexlify(os.urandom(16)).decode() + + +def iter_field_objects(fields: _TYPE_FIELDS) -> typing.Iterable[RequestField]: + """ + Iterate over fields. + + Supports list of (k, v) tuples and dicts, and lists of + :class:`~urllib3.fields.RequestField`. + + """ + iterable: typing.Iterable[RequestField | tuple[str, _TYPE_FIELD_VALUE_TUPLE]] + + if isinstance(fields, typing.Mapping): + iterable = fields.items() + else: + iterable = fields + + for field in iterable: + if isinstance(field, RequestField): + yield field + else: + yield RequestField.from_tuples(*field) + + +def encode_multipart_formdata( + fields: _TYPE_FIELDS, boundary: str | None = None +) -> tuple[bytes, str]: + """ + Encode a dictionary of ``fields`` using the multipart/form-data MIME format. + + :param fields: + Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). + Values are processed by :func:`urllib3.fields.RequestField.from_tuples`. + + :param boundary: + If not specified, then a random boundary will be generated using + :func:`urllib3.filepost.choose_boundary`. + """ + body = BytesIO() + if boundary is None: + boundary = choose_boundary() + + for field in iter_field_objects(fields): + body.write(f"--{boundary}\r\n".encode("latin-1")) + + writer(body).write(field.render_headers()) + data = field.data + + if isinstance(data, int): + data = str(data) # Backwards compatibility + + if isinstance(data, str): + writer(body).write(data) + else: + body.write(data) + + body.write(b"\r\n") + + body.write(f"--{boundary}--\r\n".encode("latin-1")) + + content_type = f"multipart/form-data; boundary={boundary}" + + return body.getvalue(), content_type diff --git a/.venv/lib/python3.12/site-packages/urllib3/http2/__init__.py b/.venv/lib/python3.12/site-packages/urllib3/http2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..133e1d8f237f6fddd557ae1c0e0cf738f7cc2748 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/http2/__init__.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from importlib.metadata import version + +__all__ = [ + "inject_into_urllib3", + "extract_from_urllib3", +] + +import typing + +orig_HTTPSConnection: typing.Any = None + + +def inject_into_urllib3() -> None: + # First check if h2 version is valid + h2_version = version("h2") + if not h2_version.startswith("4."): + raise ImportError( + "urllib3 v2 supports h2 version 4.x.x, currently " + f"the 'h2' module is compiled with {h2_version!r}. " + "See: https://github.com/urllib3/urllib3/issues/3290" + ) + + # Import here to avoid circular dependencies. + from .. import connection as urllib3_connection + from .. import util as urllib3_util + from ..connectionpool import HTTPSConnectionPool + from ..util import ssl_ as urllib3_util_ssl + from .connection import HTTP2Connection + + global orig_HTTPSConnection + orig_HTTPSConnection = urllib3_connection.HTTPSConnection + + HTTPSConnectionPool.ConnectionCls = HTTP2Connection + urllib3_connection.HTTPSConnection = HTTP2Connection # type: ignore[misc] + + # TODO: Offer 'http/1.1' as well, but for testing purposes this is handy. + urllib3_util.ALPN_PROTOCOLS = ["h2"] + urllib3_util_ssl.ALPN_PROTOCOLS = ["h2"] + + +def extract_from_urllib3() -> None: + from .. import connection as urllib3_connection + from .. import util as urllib3_util + from ..connectionpool import HTTPSConnectionPool + from ..util import ssl_ as urllib3_util_ssl + + HTTPSConnectionPool.ConnectionCls = orig_HTTPSConnection + urllib3_connection.HTTPSConnection = orig_HTTPSConnection # type: ignore[misc] + + urllib3_util.ALPN_PROTOCOLS = ["http/1.1"] + urllib3_util_ssl.ALPN_PROTOCOLS = ["http/1.1"] diff --git a/.venv/lib/python3.12/site-packages/urllib3/http2/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/http2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22344dadb73ab3dc024374111c82c0f115004110 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/http2/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/http2/__pycache__/probe.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/http2/__pycache__/probe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c63a0a8958fb2cd096d5b212f397478b2527ace Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/http2/__pycache__/probe.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/http2/connection.py b/.venv/lib/python3.12/site-packages/urllib3/http2/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab76d1f4880825e4604fb0b326a795d49b44a3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/http2/connection.py @@ -0,0 +1,357 @@ +from __future__ import annotations + +import logging +import re +import threading +import types +import typing + +import h2.config +import h2.connection +import h2.events + +from .._base_connection import _TYPE_BODY +from .._collections import HTTPHeaderDict +from ..connection import HTTPSConnection, _get_default_user_agent +from ..exceptions import ConnectionError +from ..response import BaseHTTPResponse + +orig_HTTPSConnection = HTTPSConnection + +T = typing.TypeVar("T") + +log = logging.getLogger(__name__) + +RE_IS_LEGAL_HEADER_NAME = re.compile(rb"^[!#$%&'*+\-.^_`|~0-9a-z]+$") +RE_IS_ILLEGAL_HEADER_VALUE = re.compile(rb"[\0\x00\x0a\x0d\r\n]|^[ \r\n\t]|[ \r\n\t]$") + + +def _is_legal_header_name(name: bytes) -> bool: + """ + "An implementation that validates fields according to the definitions in Sections + 5.1 and 5.5 of [HTTP] only needs an additional check that field names do not + include uppercase characters." (https://httpwg.org/specs/rfc9113.html#n-field-validity) + + `http.client._is_legal_header_name` does not validate the field name according to the + HTTP 1.1 spec, so we do that here, in addition to checking for uppercase characters. + + This does not allow for the `:` character in the header name, so should not + be used to validate pseudo-headers. + """ + return bool(RE_IS_LEGAL_HEADER_NAME.match(name)) + + +def _is_illegal_header_value(value: bytes) -> bool: + """ + "A field value MUST NOT contain the zero value (ASCII NUL, 0x00), line feed + (ASCII LF, 0x0a), or carriage return (ASCII CR, 0x0d) at any position. A field + value MUST NOT start or end with an ASCII whitespace character (ASCII SP or HTAB, + 0x20 or 0x09)." (https://httpwg.org/specs/rfc9113.html#n-field-validity) + """ + return bool(RE_IS_ILLEGAL_HEADER_VALUE.search(value)) + + +class _LockedObject(typing.Generic[T]): + """ + A wrapper class that hides a specific object behind a lock. + The goal here is to provide a simple way to protect access to an object + that cannot safely be simultaneously accessed from multiple threads. The + intended use of this class is simple: take hold of it with a context + manager, which returns the protected object. + """ + + __slots__ = ( + "lock", + "_obj", + ) + + def __init__(self, obj: T): + self.lock = threading.RLock() + self._obj = obj + + def __enter__(self) -> T: + self.lock.acquire() + return self._obj + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> None: + self.lock.release() + + +class HTTP2Connection(HTTPSConnection): + def __init__( + self, host: str, port: int | None = None, **kwargs: typing.Any + ) -> None: + self._h2_conn = self._new_h2_conn() + self._h2_stream: int | None = None + self._headers: list[tuple[bytes, bytes]] = [] + + if "proxy" in kwargs or "proxy_config" in kwargs: # Defensive: + raise NotImplementedError("Proxies aren't supported with HTTP/2") + + super().__init__(host, port, **kwargs) + + if self._tunnel_host is not None: + raise NotImplementedError("Tunneling isn't supported with HTTP/2") + + def _new_h2_conn(self) -> _LockedObject[h2.connection.H2Connection]: + config = h2.config.H2Configuration(client_side=True) + return _LockedObject(h2.connection.H2Connection(config=config)) + + def connect(self) -> None: + super().connect() + with self._h2_conn as conn: + conn.initiate_connection() + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + def putrequest( # type: ignore[override] + self, + method: str, + url: str, + **kwargs: typing.Any, + ) -> None: + """putrequest + This deviates from the HTTPConnection method signature since we never need to override + sending accept-encoding headers or the host header. + """ + if "skip_host" in kwargs: + raise NotImplementedError("`skip_host` isn't supported") + if "skip_accept_encoding" in kwargs: + raise NotImplementedError("`skip_accept_encoding` isn't supported") + + self._request_url = url or "/" + self._validate_path(url) # type: ignore[attr-defined] + + port = self.port if self.port is not None else 443 + if ":" in self.host: + authority = f"[{self.host}]:{port}" + else: + authority = f"{self.host}:{port}" + + self._headers.append((b":scheme", b"https")) + self._headers.append((b":method", method.encode())) + self._headers.append((b":authority", authority.encode())) + self._headers.append((b":path", url.encode())) + + with self._h2_conn as conn: + self._h2_stream = conn.get_next_available_stream_id() + + def putheader(self, header: str | bytes, *values: str | bytes) -> None: # type: ignore[override] + # TODO SKIPPABLE_HEADERS from urllib3 are ignored. + header = header.encode() if isinstance(header, str) else header + header = header.lower() # A lot of upstream code uses capitalized headers. + if not _is_legal_header_name(header): + raise ValueError(f"Illegal header name {str(header)}") + + for value in values: + value = value.encode() if isinstance(value, str) else value + if _is_illegal_header_value(value): + raise ValueError(f"Illegal header value {str(value)}") + self._headers.append((header, value)) + + def endheaders(self, message_body: typing.Any = None) -> None: # type: ignore[override] + if self._h2_stream is None: + raise ConnectionError("Must call `putrequest` first.") + + with self._h2_conn as conn: + conn.send_headers( + stream_id=self._h2_stream, + headers=self._headers, + end_stream=(message_body is None), + ) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + self._headers = [] # Reset headers for the next request. + + def send(self, data: typing.Any) -> None: + """Send data to the server. + `data` can be: `str`, `bytes`, an iterable, or file-like objects + that support a .read() method. + """ + if self._h2_stream is None: + raise ConnectionError("Must call `putrequest` first.") + + with self._h2_conn as conn: + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + if hasattr(data, "read"): # file-like objects + while True: + chunk = data.read(self.blocksize) + if not chunk: + break + if isinstance(chunk, str): + chunk = chunk.encode() + conn.send_data(self._h2_stream, chunk, end_stream=False) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + conn.end_stream(self._h2_stream) + return + + if isinstance(data, str): # str -> bytes + data = data.encode() + + try: + if isinstance(data, bytes): + conn.send_data(self._h2_stream, data, end_stream=True) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + else: + for chunk in data: + conn.send_data(self._h2_stream, chunk, end_stream=False) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + conn.end_stream(self._h2_stream) + except TypeError: + raise TypeError( + "`data` should be str, bytes, iterable, or file. got %r" + % type(data) + ) + + def set_tunnel( + self, + host: str, + port: int | None = None, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + raise NotImplementedError( + "HTTP/2 does not support setting up a tunnel through a proxy" + ) + + def getresponse( # type: ignore[override] + self, + ) -> HTTP2Response: + status = None + data = bytearray() + with self._h2_conn as conn: + end_stream = False + while not end_stream: + # TODO: Arbitrary read value. + if received_data := self.sock.recv(65535): + events = conn.receive_data(received_data) + for event in events: + if isinstance(event, h2.events.ResponseReceived): + headers = HTTPHeaderDict() + for header, value in event.headers: + if header == b":status": + status = int(value.decode()) + else: + headers.add( + header.decode("ascii"), value.decode("ascii") + ) + + elif isinstance(event, h2.events.DataReceived): + data += event.data + conn.acknowledge_received_data( + event.flow_controlled_length, event.stream_id + ) + + elif isinstance(event, h2.events.StreamEnded): + end_stream = True + + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + assert status is not None + return HTTP2Response( + status=status, + headers=headers, + request_url=self._request_url, + data=bytes(data), + ) + + def request( # type: ignore[override] + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + *, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + **kwargs: typing.Any, + ) -> None: + """Send an HTTP/2 request""" + if "chunked" in kwargs: + # TODO this is often present from upstream. + # raise NotImplementedError("`chunked` isn't supported with HTTP/2") + pass + + if self.sock is not None: + self.sock.settimeout(self.timeout) + + self.putrequest(method, url) + + headers = headers or {} + for k, v in headers.items(): + if k.lower() == "transfer-encoding" and v == "chunked": + continue + else: + self.putheader(k, v) + + if b"user-agent" not in dict(self._headers): + self.putheader(b"user-agent", _get_default_user_agent()) + + if body: + self.endheaders(message_body=body) + self.send(body) + else: + self.endheaders() + + def close(self) -> None: + with self._h2_conn as conn: + try: + conn.close_connection() + if data := conn.data_to_send(): + self.sock.sendall(data) + except Exception: + pass + + # Reset all our HTTP/2 connection state. + self._h2_conn = self._new_h2_conn() + self._h2_stream = None + self._headers = [] + + super().close() + + +class HTTP2Response(BaseHTTPResponse): + # TODO: This is a woefully incomplete response object, but works for non-streaming. + def __init__( + self, + status: int, + headers: HTTPHeaderDict, + request_url: str, + data: bytes, + decode_content: bool = False, # TODO: support decoding + ) -> None: + super().__init__( + status=status, + headers=headers, + # Following CPython, we map HTTP versions to major * 10 + minor integers + version=20, + version_string="HTTP/2", + # No reason phrase in HTTP/2 + reason=None, + decode_content=decode_content, + request_url=request_url, + ) + self._data = data + self.length_remaining = 0 + + @property + def data(self) -> bytes: + return self._data + + def get_redirect_location(self) -> None: + return None + + def close(self) -> None: + pass diff --git a/.venv/lib/python3.12/site-packages/urllib3/http2/probe.py b/.venv/lib/python3.12/site-packages/urllib3/http2/probe.py new file mode 100644 index 0000000000000000000000000000000000000000..9ea900764f0885eafaac9454523417d86e33df2d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/http2/probe.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import threading + + +class _HTTP2ProbeCache: + __slots__ = ( + "_lock", + "_cache_locks", + "_cache_values", + ) + + def __init__(self) -> None: + self._lock = threading.Lock() + self._cache_locks: dict[tuple[str, int], threading.RLock] = {} + self._cache_values: dict[tuple[str, int], bool | None] = {} + + def acquire_and_get(self, host: str, port: int) -> bool | None: + # By the end of this block we know that + # _cache_[values,locks] is available. + value = None + with self._lock: + key = (host, port) + try: + value = self._cache_values[key] + # If it's a known value we return right away. + if value is not None: + return value + except KeyError: + self._cache_locks[key] = threading.RLock() + self._cache_values[key] = None + + # If the value is unknown, we acquire the lock to signal + # to the requesting thread that the probe is in progress + # or that the current thread needs to return their findings. + key_lock = self._cache_locks[key] + key_lock.acquire() + try: + # If the by the time we get the lock the value has been + # updated we want to return the updated value. + value = self._cache_values[key] + + # In case an exception like KeyboardInterrupt is raised here. + except BaseException as e: # Defensive: + assert not isinstance(e, KeyError) # KeyError shouldn't be possible. + key_lock.release() + raise + + return value + + def set_and_release( + self, host: str, port: int, supports_http2: bool | None + ) -> None: + key = (host, port) + key_lock = self._cache_locks[key] + with key_lock: # Uses an RLock, so can be locked again from same thread. + if supports_http2 is None and self._cache_values[key] is not None: + raise ValueError( + "Cannot reset HTTP/2 support for origin after value has been set." + ) # Defensive: not expected in normal usage + + self._cache_values[key] = supports_http2 + key_lock.release() + + def _values(self) -> dict[tuple[str, int], bool | None]: + """This function is for testing purposes only. Gets the current state of the probe cache""" + with self._lock: + return {k: v for k, v in self._cache_values.items()} + + def _reset(self) -> None: + """This function is for testing purposes only. Reset the cache values""" + with self._lock: + self._cache_locks = {} + self._cache_values = {} + + +_HTTP2_PROBE_CACHE = _HTTP2ProbeCache() + +set_and_release = _HTTP2_PROBE_CACHE.set_and_release +acquire_and_get = _HTTP2_PROBE_CACHE.acquire_and_get +_values = _HTTP2_PROBE_CACHE._values +_reset = _HTTP2_PROBE_CACHE._reset + +__all__ = [ + "set_and_release", + "acquire_and_get", +] diff --git a/.venv/lib/python3.12/site-packages/urllib3/poolmanager.py b/.venv/lib/python3.12/site-packages/urllib3/poolmanager.py new file mode 100644 index 0000000000000000000000000000000000000000..df7cff936cc9e9cfff9e1e14acab91247998cb5f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/poolmanager.py @@ -0,0 +1,677 @@ +from __future__ import annotations + +import functools +import logging +import typing +import warnings +from types import TracebackType +from urllib.parse import urljoin + +from ._collections import HTTPHeaderDict, RecentlyUsedContainer +from ._request_methods import RequestMethods +from .connection import ProxyConfig +from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme +from .exceptions import ( + LocationValueError, + MaxRetryError, + ProxySchemeUnknown, + URLSchemeUnknown, +) +from .response import BaseHTTPResponse +from .util.connection import _TYPE_SOCKET_OPTIONS +from .util.proxy import connection_requires_http_tunnel +from .util.retry import Retry +from .util.timeout import Timeout +from .util.url import Url, parse_url + +if typing.TYPE_CHECKING: + import ssl + + from typing_extensions import Self + +__all__ = ["PoolManager", "ProxyManager", "proxy_from_url"] + + +log = logging.getLogger(__name__) + +SSL_KEYWORDS = ( + "key_file", + "cert_file", + "cert_reqs", + "ca_certs", + "ca_cert_data", + "ssl_version", + "ssl_minimum_version", + "ssl_maximum_version", + "ca_cert_dir", + "ssl_context", + "key_password", + "server_hostname", + "assert_hostname", + "assert_fingerprint", +) +# Default value for `blocksize` - a new parameter introduced to +# http.client.HTTPConnection & http.client.HTTPSConnection in Python 3.7 +_DEFAULT_BLOCKSIZE = 16384 + + +class PoolKey(typing.NamedTuple): + """ + All known keyword arguments that could be provided to the pool manager, its + pools, or the underlying connections. + + All custom key schemes should include the fields in this key at a minimum. + """ + + key_scheme: str + key_host: str + key_port: int | None + key_timeout: Timeout | float | int | None + key_retries: Retry | bool | int | None + key_block: bool | None + key_source_address: tuple[str, int] | None + key_key_file: str | None + key_key_password: str | None + key_cert_file: str | None + key_cert_reqs: str | None + key_ca_certs: str | None + key_ca_cert_data: str | bytes | None + key_ssl_version: int | str | None + key_ssl_minimum_version: ssl.TLSVersion | None + key_ssl_maximum_version: ssl.TLSVersion | None + key_ca_cert_dir: str | None + key_ssl_context: ssl.SSLContext | None + key_maxsize: int | None + key_headers: frozenset[tuple[str, str]] | None + key__proxy: Url | None + key__proxy_headers: frozenset[tuple[str, str]] | None + key__proxy_config: ProxyConfig | None + key_socket_options: _TYPE_SOCKET_OPTIONS | None + key__socks_options: frozenset[tuple[str, str]] | None + key_assert_hostname: bool | str | None + key_assert_fingerprint: str | None + key_server_hostname: str | None + key_blocksize: int | None + + +def _default_key_normalizer( + key_class: type[PoolKey], request_context: dict[str, typing.Any] +) -> PoolKey: + """ + Create a pool key out of a request context dictionary. + + According to RFC 3986, both the scheme and host are case-insensitive. + Therefore, this function normalizes both before constructing the pool + key for an HTTPS request. If you wish to change this behaviour, provide + alternate callables to ``key_fn_by_scheme``. + + :param key_class: + The class to use when constructing the key. This should be a namedtuple + with the ``scheme`` and ``host`` keys at a minimum. + :type key_class: namedtuple + :param request_context: + A dictionary-like object that contain the context for a request. + :type request_context: dict + + :return: A namedtuple that can be used as a connection pool key. + :rtype: PoolKey + """ + # Since we mutate the dictionary, make a copy first + context = request_context.copy() + context["scheme"] = context["scheme"].lower() + context["host"] = context["host"].lower() + + # These are both dictionaries and need to be transformed into frozensets + for key in ("headers", "_proxy_headers", "_socks_options"): + if key in context and context[key] is not None: + context[key] = frozenset(context[key].items()) + + # The socket_options key may be a list and needs to be transformed into a + # tuple. + socket_opts = context.get("socket_options") + if socket_opts is not None: + context["socket_options"] = tuple(socket_opts) + + # Map the kwargs to the names in the namedtuple - this is necessary since + # namedtuples can't have fields starting with '_'. + for key in list(context.keys()): + context["key_" + key] = context.pop(key) + + # Default to ``None`` for keys missing from the context + for field in key_class._fields: + if field not in context: + context[field] = None + + # Default key_blocksize to _DEFAULT_BLOCKSIZE if missing from the context + if context.get("key_blocksize") is None: + context["key_blocksize"] = _DEFAULT_BLOCKSIZE + + return key_class(**context) + + +#: A dictionary that maps a scheme to a callable that creates a pool key. +#: This can be used to alter the way pool keys are constructed, if desired. +#: Each PoolManager makes a copy of this dictionary so they can be configured +#: globally here, or individually on the instance. +key_fn_by_scheme = { + "http": functools.partial(_default_key_normalizer, PoolKey), + "https": functools.partial(_default_key_normalizer, PoolKey), +} + +pool_classes_by_scheme = {"http": HTTPConnectionPool, "https": HTTPSConnectionPool} + + +class PoolManager(RequestMethods): + """ + Allows for arbitrary requests while transparently keeping track of + necessary connection pools for you. + + :param num_pools: + Number of connection pools to cache before discarding the least + recently used pool. + + :param headers: + Headers to include with all requests, unless other headers are given + explicitly. + + :param \\**connection_pool_kw: + Additional parameters are used to create fresh + :class:`urllib3.connectionpool.ConnectionPool` instances. + + Example: + + .. code-block:: python + + import urllib3 + + http = urllib3.PoolManager(num_pools=2) + + resp1 = http.request("GET", "https://google.com/") + resp2 = http.request("GET", "https://google.com/mail") + resp3 = http.request("GET", "https://yahoo.com/") + + print(len(http.pools)) + # 2 + + """ + + proxy: Url | None = None + proxy_config: ProxyConfig | None = None + + def __init__( + self, + num_pools: int = 10, + headers: typing.Mapping[str, str] | None = None, + **connection_pool_kw: typing.Any, + ) -> None: + super().__init__(headers) + # PoolManager handles redirects itself in PoolManager.urlopen(). + # It always passes redirect=False to the underlying connection pool to + # suppress per-pool redirect handling. If the user supplied a non-Retry + # value (int/bool/etc) for retries and we let the pool normalize it + # while redirect=False, the resulting Retry object would have redirect + # handling disabled, which can interfere with PoolManager's own + # redirect logic. Normalize here so redirects remain governed solely by + # PoolManager logic. + if "retries" in connection_pool_kw: + retries = connection_pool_kw["retries"] + if not isinstance(retries, Retry): + retries = Retry.from_int(retries) + connection_pool_kw = connection_pool_kw.copy() + connection_pool_kw["retries"] = retries + self.connection_pool_kw = connection_pool_kw + + self.pools: RecentlyUsedContainer[PoolKey, HTTPConnectionPool] + self.pools = RecentlyUsedContainer(num_pools) + + # Locally set the pool classes and keys so other PoolManagers can + # override them. + self.pool_classes_by_scheme = pool_classes_by_scheme + self.key_fn_by_scheme = key_fn_by_scheme.copy() + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> typing.Literal[False]: + self.clear() + # Return False to re-raise any potential exceptions + return False + + def _new_pool( + self, + scheme: str, + host: str, + port: int, + request_context: dict[str, typing.Any] | None = None, + ) -> HTTPConnectionPool: + """ + Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and + any additional pool keyword arguments. + + If ``request_context`` is provided, it is provided as keyword arguments + to the pool class used. This method is used to actually create the + connection pools handed out by :meth:`connection_from_url` and + companion methods. It is intended to be overridden for customization. + """ + pool_cls: type[HTTPConnectionPool] = self.pool_classes_by_scheme[scheme] + if request_context is None: + request_context = self.connection_pool_kw.copy() + + # Default blocksize to _DEFAULT_BLOCKSIZE if missing or explicitly + # set to 'None' in the request_context. + if request_context.get("blocksize") is None: + request_context["blocksize"] = _DEFAULT_BLOCKSIZE + + # Although the context has everything necessary to create the pool, + # this function has historically only used the scheme, host, and port + # in the positional args. When an API change is acceptable these can + # be removed. + for key in ("scheme", "host", "port"): + request_context.pop(key, None) + + if scheme == "http": + for kw in SSL_KEYWORDS: + request_context.pop(kw, None) + + return pool_cls(host, port, **request_context) + + def clear(self) -> None: + """ + Empty our store of pools and direct them all to close. + + This will not affect in-flight connections, but they will not be + re-used after completion. + """ + self.pools.clear() + + def connection_from_host( + self, + host: str | None, + port: int | None = None, + scheme: str | None = "http", + pool_kwargs: dict[str, typing.Any] | None = None, + ) -> HTTPConnectionPool: + """ + Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme. + + If ``port`` isn't given, it will be derived from the ``scheme`` using + ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is + provided, it is merged with the instance's ``connection_pool_kw`` + variable and used to create the new connection pool, if one is + needed. + """ + + if not host: + raise LocationValueError("No host specified.") + + request_context = self._merge_pool_kwargs(pool_kwargs) + request_context["scheme"] = scheme or "http" + if port is None: + port = port_by_scheme.get(request_context["scheme"].lower(), 80) + request_context["port"] = port + request_context["host"] = host + + return self.connection_from_context(request_context) + + def connection_from_context( + self, request_context: dict[str, typing.Any] + ) -> HTTPConnectionPool: + """ + Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context. + + ``request_context`` must at least contain the ``scheme`` key and its + value must be a key in ``key_fn_by_scheme`` instance variable. + """ + if "strict" in request_context: + warnings.warn( + "The 'strict' parameter is no longer needed on Python 3+. " + "This will raise an error in urllib3 v3.0.", + FutureWarning, + ) + request_context.pop("strict") + + scheme = request_context["scheme"].lower() + pool_key_constructor = self.key_fn_by_scheme.get(scheme) + if not pool_key_constructor: + raise URLSchemeUnknown(scheme) + pool_key = pool_key_constructor(request_context) + + return self.connection_from_pool_key(pool_key, request_context=request_context) + + def connection_from_pool_key( + self, pool_key: PoolKey, request_context: dict[str, typing.Any] + ) -> HTTPConnectionPool: + """ + Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key. + + ``pool_key`` should be a namedtuple that only contains immutable + objects. At a minimum it must have the ``scheme``, ``host``, and + ``port`` fields. + """ + with self.pools.lock: + # If the scheme, host, or port doesn't match existing open + # connections, open a new ConnectionPool. + pool = self.pools.get(pool_key) + if pool: + return pool + + # Make a fresh ConnectionPool of the desired type + scheme = request_context["scheme"] + host = request_context["host"] + port = request_context["port"] + pool = self._new_pool(scheme, host, port, request_context=request_context) + self.pools[pool_key] = pool + + return pool + + def connection_from_url( + self, url: str, pool_kwargs: dict[str, typing.Any] | None = None + ) -> HTTPConnectionPool: + """ + Similar to :func:`urllib3.connectionpool.connection_from_url`. + + If ``pool_kwargs`` is not provided and a new pool needs to be + constructed, ``self.connection_pool_kw`` is used to initialize + the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs`` + is provided, it is used instead. Note that if a new pool does not + need to be created for the request, the provided ``pool_kwargs`` are + not used. + """ + u = parse_url(url) + return self.connection_from_host( + u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs + ) + + def _merge_pool_kwargs( + self, override: dict[str, typing.Any] | None + ) -> dict[str, typing.Any]: + """ + Merge a dictionary of override values for self.connection_pool_kw. + + This does not modify self.connection_pool_kw and returns a new dict. + Any keys in the override dictionary with a value of ``None`` are + removed from the merged dictionary. + """ + base_pool_kwargs = self.connection_pool_kw.copy() + if override: + for key, value in override.items(): + if value is None: + try: + del base_pool_kwargs[key] + except KeyError: + pass + else: + base_pool_kwargs[key] = value + return base_pool_kwargs + + def _proxy_requires_url_absolute_form(self, parsed_url: Url) -> bool: + """ + Indicates if the proxy requires the complete destination URL in the + request. Normally this is only needed when not using an HTTP CONNECT + tunnel. + """ + if self.proxy is None: + return False + + return not connection_requires_http_tunnel( + self.proxy, self.proxy_config, parsed_url.scheme + ) + + def urlopen( # type: ignore[override] + self, method: str, url: str, redirect: bool = True, **kw: typing.Any + ) -> BaseHTTPResponse: + """ + Same as :meth:`urllib3.HTTPConnectionPool.urlopen` + with custom cross-host redirect logic and only sends the request-uri + portion of the ``url``. + + The given ``url`` parameter must be absolute, such that an appropriate + :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it. + """ + u = parse_url(url) + + if u.scheme is None: + warnings.warn( + "URLs without a scheme (ie 'https://') are deprecated and will raise an error " + "in urllib3 v3.0. To avoid this FutureWarning ensure all URLs " + "start with 'https://' or 'http://'. Read more in this issue: " + "https://github.com/urllib3/urllib3/issues/2920", + category=FutureWarning, + stacklevel=2, + ) + + conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme) + + kw["assert_same_host"] = False + kw["redirect"] = False + + if "headers" not in kw: + kw["headers"] = self.headers + + if self._proxy_requires_url_absolute_form(u): + response = conn.urlopen(method, u._replace(fragment=None).url, **kw) + else: + response = conn.urlopen(method, u.request_uri, **kw) + + redirect_location = redirect and response.get_redirect_location() + if not redirect_location: + return response + + # Support relative URLs for redirecting. + redirect_location = urljoin(url, redirect_location) + + if response.status == 303: + # Change the method according to RFC 9110, Section 15.4.4. + method = "GET" + # And lose the body not to transfer anything sensitive. + kw["body"] = None + # The body is gone, so the state that describes it has to go too: + # there is nothing left to frame with chunked transfer encoding, + # and nothing left to rewind. + kw["chunked"] = False + kw["body_pos"] = None + kw["headers"] = HTTPHeaderDict(kw["headers"])._prepare_for_method_change() + + retries = kw.get("retries", response.retries) + if not isinstance(retries, Retry): + retries = Retry.from_int(retries, redirect=redirect) + + # Strip headers marked as unsafe to forward to the redirected location. + # Check remove_headers_on_redirect to avoid a potential network call within + # conn.is_same_host() which may use socket.gethostbyname() in the future. + if retries.remove_headers_on_redirect and not conn.is_same_host( + redirect_location + ): + new_headers = kw["headers"].copy() + for header in kw["headers"]: + if header.lower() in retries.remove_headers_on_redirect: + new_headers.pop(header, None) + kw["headers"] = new_headers + + try: + retries = retries.increment(method, url, response=response, _pool=conn) + except MaxRetryError: + if retries.raise_on_redirect: + response.drain_conn() + raise + return response + + kw["retries"] = retries + kw["redirect"] = redirect + + log.info("Redirecting %s -> %s", url, redirect_location) + + response.drain_conn() + return self.urlopen(method, redirect_location, **kw) + + +class ProxyManager(PoolManager): + """ + Behaves just like :class:`PoolManager`, but sends all requests through + the defined proxy, using the CONNECT method for HTTPS URLs. + + :param proxy_url: + The URL of the proxy to be used. + + :param proxy_headers: + A dictionary containing headers that will be sent to the proxy. In case + of HTTP they are being sent with each request, while in the + HTTPS/CONNECT case they are sent only once. Could be used for proxy + authentication. + + :param proxy_ssl_context: + The proxy SSL context is used to establish the TLS connection to the + proxy when using HTTPS proxies. + + :param use_forwarding_for_https: + (Defaults to False) If set to True will forward requests to the HTTPS + proxy to be made on behalf of the client instead of creating a TLS + tunnel via the CONNECT method. **Enabling this flag means that request + and response headers and content will be visible from the HTTPS proxy** + whereas tunneling keeps request and response headers and content + private. IP address, target hostname, SNI, and port are always visible + to an HTTPS proxy even when this flag is disabled. + + :param proxy_assert_hostname: + The hostname of the certificate to verify against. + + :param proxy_assert_fingerprint: + The fingerprint of the certificate to verify against. + + Example: + + .. code-block:: python + + import urllib3 + + proxy = urllib3.ProxyManager("https://localhost:3128/") + + resp1 = proxy.request("GET", "http://google.com/") + resp2 = proxy.request("GET", "http://httpbin.org/") + + # One pool was shared by both plain HTTP requests. + print(len(proxy.pools)) + # 1 + + resp3 = proxy.request("GET", "https://httpbin.org/") + resp4 = proxy.request("GET", "https://twitter.com/") + + # A separate pool was added for each HTTPS target. + print(len(proxy.pools)) + # 3 + + """ + + def __init__( + self, + proxy_url: str, + num_pools: int = 10, + headers: typing.Mapping[str, str] | None = None, + proxy_headers: typing.Mapping[str, str] | None = None, + proxy_ssl_context: ssl.SSLContext | None = None, + use_forwarding_for_https: bool = False, + proxy_assert_hostname: None | str | typing.Literal[False] = None, + proxy_assert_fingerprint: str | None = None, + **connection_pool_kw: typing.Any, + ) -> None: + if isinstance(proxy_url, HTTPConnectionPool): + str_proxy_url = f"{proxy_url.scheme}://{proxy_url.host}:{proxy_url.port}" + else: + str_proxy_url = proxy_url + proxy = parse_url(str_proxy_url) + + if proxy.scheme not in ("http", "https"): + raise ProxySchemeUnknown(proxy.scheme) + + # Keep the deprecated ssl_context fallback on the manager for + # compatibility, while passing only explicit proxy policy to connections. + self.proxy_ssl_context = proxy_ssl_context + if ( + use_forwarding_for_https + and proxy.scheme == "https" + and connection_pool_kw.get("ssl_context") is not None + ): + warnings.warn( + "Passing ssl_context when use_forwarding_for_https=True is deprecated " + "and will raise an error in urllib3 v3.0. " + "Use proxy_ssl_context to configure the TLS connection to the proxy.", + FutureWarning, + stacklevel=2, + ) + if self.proxy_ssl_context is None: + self.proxy_ssl_context = connection_pool_kw.get("ssl_context") + + if proxy.port is None: + port = port_by_scheme.get(proxy.scheme, 80) + proxy = proxy._replace(port=port) + + self.proxy = proxy + self.proxy_headers = proxy_headers or {} + self.proxy_config = ProxyConfig( + proxy_ssl_context, + use_forwarding_for_https, + proxy_assert_hostname, + proxy_assert_fingerprint, + ) + + connection_pool_kw["_proxy"] = self.proxy + connection_pool_kw["_proxy_headers"] = self.proxy_headers + connection_pool_kw["_proxy_config"] = self.proxy_config + + super().__init__(num_pools, headers, **connection_pool_kw) + + def connection_from_host( + self, + host: str | None, + port: int | None = None, + scheme: str | None = "http", + pool_kwargs: dict[str, typing.Any] | None = None, + ) -> HTTPConnectionPool: + if scheme == "https": + return super().connection_from_host( + host, port, scheme, pool_kwargs=pool_kwargs + ) + + return super().connection_from_host( + self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs # type: ignore[union-attr] + ) + + def _set_proxy_headers( + self, url: str, headers: typing.Mapping[str, str] | None = None + ) -> typing.Mapping[str, str]: + """ + Sets headers needed by proxies: specifically, the Accept and Host + headers. Only sets headers not provided by the user. + """ + headers_ = {"Accept": "*/*"} + + netloc = parse_url(url).netloc + if netloc: + headers_["Host"] = netloc + + if headers: + headers_.update(headers) + return headers_ + + def urlopen( # type: ignore[override] + self, method: str, url: str, redirect: bool = True, **kw: typing.Any + ) -> BaseHTTPResponse: + "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute." + u = parse_url(url) + if not connection_requires_http_tunnel(self.proxy, self.proxy_config, u.scheme): + # For connections using HTTP CONNECT, httplib sets the necessary + # headers on the CONNECT to the proxy. If we're not using CONNECT, + # we'll definitely need to set 'Host' at the very least. + headers = kw.get("headers", self.headers) + kw["headers"] = self._set_proxy_headers(url, headers) + + return super().urlopen(method, url, redirect=redirect, **kw) + + +def proxy_from_url(url: str, **kw: typing.Any) -> ProxyManager: + return ProxyManager(proxy_url=url, **kw) diff --git a/.venv/lib/python3.12/site-packages/urllib3/py.typed b/.venv/lib/python3.12/site-packages/urllib3/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..5f3ea3d919363f08ab03edbc85b6099bc4df5647 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/py.typed @@ -0,0 +1,2 @@ +# Instruct type checkers to look for inline type annotations in this package. +# See PEP 561. diff --git a/.venv/lib/python3.12/site-packages/urllib3/response.py b/.venv/lib/python3.12/site-packages/urllib3/response.py new file mode 100644 index 0000000000000000000000000000000000000000..ec7d30833075a56915ccd60f47407cfcee1a032d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/response.py @@ -0,0 +1,1526 @@ +from __future__ import annotations + +import collections +import io +import json as _json +import logging +import socket +import sys +import typing +import warnings +import zlib +from contextlib import contextmanager +from http.client import HTTPMessage as _HttplibHTTPMessage +from http.client import HTTPResponse as _HttplibHTTPResponse +from socket import timeout as SocketTimeout + +if typing.TYPE_CHECKING: + from ._base_connection import BaseHTTPConnection + +try: + try: + import brotlicffi as brotli # type: ignore[import-not-found] + except ImportError: + import brotli # type: ignore[import-not-found] +except ImportError: + brotli = None + +from . import util +from ._base_connection import _TYPE_BODY +from ._collections import HTTPHeaderDict +from .connection import BaseSSLError, HTTPConnection, HTTPException +from .exceptions import ( + BodyNotHttplibCompatible, + DecodeError, + DependencyWarning, + HTTPError, + IncompleteRead, + InvalidChunkLength, + InvalidHeader, + ProtocolError, + ReadTimeoutError, + ResponseNotChunked, + SSLError, +) +from .util.response import is_fp_closed, is_response_to_head +from .util.retry import Retry + +if typing.TYPE_CHECKING: + from .connectionpool import HTTPConnectionPool + +log = logging.getLogger(__name__) + +# Read in 64 KiB chunks +_READ_CHUNK_SIZE = 2**16 + +# Maximum length of a chunk-size line (and the trailing CRLF line) when reading a +# chunked-transfer-encoded response. Matches ``http.client._MAXLINE`` so urllib3's +# streaming path bounds these reads exactly like the stdlib ``.read()`` path does, +# preventing a malicious server from forcing unbounded buffering (memory exhaustion) +# via an unterminated chunk-size line. +_MAX_CHUNK_LINE_LENGTH = 2**16 + + +class ContentDecoder: + def decompress(self, data: bytes, max_length: int = -1) -> bytes: + raise NotImplementedError() + + @property + def has_unconsumed_tail(self) -> bool: + raise NotImplementedError() + + def flush(self) -> bytes: + raise NotImplementedError() + + +class DeflateDecoder(ContentDecoder): + def __init__(self) -> None: + self._first_try = True + self._first_try_data = b"" + self._unfed_data = b"" + self._obj = zlib.decompressobj() + + def decompress(self, data: bytes, max_length: int = -1) -> bytes: + data = self._unfed_data + data + self._unfed_data = b"" + # Data received after EOF cannot produce more output from this + # Deflate stream. + if self._obj.eof: + return b"" + if not data and not self._obj.unconsumed_tail: + return data + original_max_length = max_length + if original_max_length < 0: + max_length = 0 + elif original_max_length == 0: + # We should not pass 0 to the zlib decompressor because 0 is + # the default value that will make zlib decompress without a + # length limit. + # Data should be stored for subsequent calls. + self._unfed_data = data + return b"" + + # Subsequent calls always reuse `self._obj`. zlib requires + # passing the unconsumed tail if decompression is to continue. + if not self._first_try: + return self._obj.decompress( + self._obj.unconsumed_tail + data, max_length=max_length + ) + + # First call tries with RFC 1950 ZLIB format. + self._first_try_data += data + try: + decompressed = self._obj.decompress(data, max_length=max_length) + if decompressed: + self._first_try = False + self._first_try_data = b"" + return decompressed + # On failure, it falls back to RFC 1951 DEFLATE format. + except zlib.error: + self._first_try = False + self._obj = zlib.decompressobj(-zlib.MAX_WBITS) + try: + return self.decompress( + self._first_try_data, max_length=original_max_length + ) + finally: + self._first_try_data = b"" + + @property + def has_unconsumed_tail(self) -> bool: + return bool(self._unfed_data) or ( + bool(self._obj.unconsumed_tail) + and not self._first_try + and not self._obj.eof + ) + + def flush(self) -> bytes: + return self._obj.flush() + + +class GzipDecoderState: + FIRST_MEMBER = 0 + OTHER_MEMBERS = 1 + SWALLOW_DATA = 2 + + +class GzipDecoder(ContentDecoder): + def __init__(self) -> None: + self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) + self._state = GzipDecoderState.FIRST_MEMBER + self._unconsumed_tail = b"" + + def decompress(self, data: bytes, max_length: int = -1) -> bytes: + ret = bytearray() + if self._state == GzipDecoderState.SWALLOW_DATA: + return bytes(ret) + + if max_length == 0: + # We should not pass 0 to the zlib decompressor because 0 is + # the default value that will make zlib decompress without a + # length limit. + # Data should be stored for subsequent calls. + self._unconsumed_tail += data + return b"" + + # zlib requires passing the unconsumed tail to the subsequent + # call if decompression is to continue. + data = self._unconsumed_tail + data + if not data and self._obj.eof: + return bytes(ret) + + while True: + try: + ret += self._obj.decompress( + data, max_length=max(max_length - len(ret), 0) + ) + except zlib.error: + previous_state = self._state + # Ignore data after the first error + self._state = GzipDecoderState.SWALLOW_DATA + self._unconsumed_tail = b"" + if previous_state == GzipDecoderState.OTHER_MEMBERS: + # Allow trailing garbage acceptable in other gzip clients + return bytes(ret) + raise + + self._unconsumed_tail = data = ( + self._obj.unconsumed_tail or self._obj.unused_data + ) + if max_length > 0 and len(ret) >= max_length: + break + + if not data: + return bytes(ret) + # When the end of a gzip member is reached, a new decompressor + # must be created for unused (possibly future) data. + if self._obj.eof: + self._state = GzipDecoderState.OTHER_MEMBERS + self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) + + return bytes(ret) + + @property + def has_unconsumed_tail(self) -> bool: + return bool(self._unconsumed_tail) + + def flush(self) -> bytes: + return self._obj.flush() + + +if brotli is not None: + + class BrotliDecoder(ContentDecoder): + # Supports both 'brotlipy' and 'Brotli' packages + # since they share an import name. The top branches + # are for 'brotlipy' and bottom branches for 'Brotli' + def __init__(self) -> None: + self._obj = brotli.Decompressor() + if hasattr(self._obj, "decompress"): + setattr(self, "_decompress", self._obj.decompress) + else: + setattr(self, "_decompress", self._obj.process) + + # Requires Brotli >= 1.2.0 for `output_buffer_limit`. + def _decompress(self, data: bytes, output_buffer_limit: int = -1) -> bytes: + raise NotImplementedError() + + def decompress(self, data: bytes, max_length: int = -1) -> bytes: + try: + if max_length > 0: + return self._decompress(data, output_buffer_limit=max_length) + else: + return self._decompress(data) + except TypeError: + # Fallback for Brotli/brotlicffi/brotlipy versions without + # the `output_buffer_limit` parameter. + warnings.warn( + "Brotli >= 1.2.0 is required to prevent decompression bombs.", + DependencyWarning, + ) + return self._decompress(data) + + @property + def has_unconsumed_tail(self) -> bool: + try: + return not self._obj.can_accept_more_data() + except AttributeError: + return False + + def flush(self) -> bytes: + if hasattr(self._obj, "flush"): + return self._obj.flush() # type: ignore[no-any-return] + return b"" + + +try: + if sys.version_info >= (3, 14): + from compression import zstd + else: + from backports import zstd +except ImportError: + HAS_ZSTD = False +else: + HAS_ZSTD = True + + class ZstdDecoder(ContentDecoder): + def __init__(self) -> None: + self._obj = zstd.ZstdDecompressor() + + def decompress(self, data: bytes, max_length: int = -1) -> bytes: + if not data and not self.has_unconsumed_tail: + return b"" + if self._obj.eof: + data = self._obj.unused_data + data + self._obj = zstd.ZstdDecompressor() + part = self._obj.decompress(data, max_length=max_length) + length = len(part) + data_parts = [part] + # Every loop iteration is supposed to read data from a separate frame. + # The loop breaks when: + # - enough data is read; + # - no more unused data is available; + # - end of the last read frame has not been reached (i.e., + # more data has to be fed). + while ( + self._obj.eof + and self._obj.unused_data + and (max_length < 0 or length < max_length) + ): + unused_data = self._obj.unused_data + if not self._obj.needs_input: + self._obj = zstd.ZstdDecompressor() + part = self._obj.decompress( + unused_data, + max_length=(max_length - length) if max_length > 0 else -1, + ) + if part_length := len(part): + data_parts.append(part) + length += part_length + elif self._obj.needs_input: + break + return b"".join(data_parts) + + @property + def has_unconsumed_tail(self) -> bool: + return not (self._obj.needs_input or self._obj.eof) or bool( + self._obj.unused_data + ) + + def flush(self) -> bytes: + if not self._obj.eof: + raise DecodeError("Zstandard data is incomplete") + return b"" + + +class MultiDecoder(ContentDecoder): + """ + From RFC7231: + If one or more encodings have been applied to a representation, the + sender that applied the encodings MUST generate a Content-Encoding + header field that lists the content codings in the order in which + they were applied. + """ + + # Maximum allowed number of chained HTTP encodings in the + # Content-Encoding header. + max_decode_links = 5 + + def __init__(self, modes: str) -> None: + encodings = [m.strip() for m in modes.split(",")] + if len(encodings) > self.max_decode_links: + raise DecodeError( + "Too many content encodings in the chain: " + f"{len(encodings)} > {self.max_decode_links}" + ) + self._decoders = [_get_decoder(e) for e in encodings] + + def flush(self) -> bytes: + return self._decoders[0].flush() + + def decompress(self, data: bytes, max_length: int = -1) -> bytes: + if max_length <= 0: + for d in reversed(self._decoders): + data = d.decompress(data) + return data + + ret = bytearray() + # Every while loop iteration goes through all decoders once. + # It exits when enough data is read or no more data can be read. + # It is possible that the while loop iteration does not produce + # any data because we retrieve up to `max_length` from every + # decoder, and the amount of bytes may be insufficient for the + # next decoder to produce enough/any output. + while True: + any_data = False + for d in reversed(self._decoders): + data = d.decompress(data, max_length=max_length - len(ret)) + if data: + any_data = True + # We should not break when no data is returned because + # next decoders may produce data even with empty input. + ret += data + if not any_data or len(ret) >= max_length: + return bytes(ret) + data = b"" + + @property + def has_unconsumed_tail(self) -> bool: + return any(d.has_unconsumed_tail for d in self._decoders) + + +def _get_decoder(mode: str) -> ContentDecoder: + if "," in mode: + return MultiDecoder(mode) + + # According to RFC 9110 section 8.4.1.3, recipients should + # consider x-gzip equivalent to gzip + if mode in ("gzip", "x-gzip"): + return GzipDecoder() + + if brotli is not None and mode == "br": + return BrotliDecoder() + + if HAS_ZSTD and mode == "zstd": + return ZstdDecoder() + + return DeflateDecoder() + + +class BytesQueueBuffer: + """Memory-efficient bytes buffer + + To return decoded data in read() and still follow the BufferedIOBase API, we need a + buffer to always return the correct amount of bytes. + + This buffer should be filled using calls to put() + + Our maximum memory usage is determined by the sum of the size of: + + * self.buffer, which contains the full data + * the largest chunk that we will copy in get() + """ + + def __init__(self) -> None: + self.buffer: typing.Deque[bytes | memoryview[bytes]] = collections.deque() + self._size: int = 0 + + def __len__(self) -> int: + return self._size + + def put(self, data: bytes) -> None: + self.buffer.append(data) + self._size += len(data) + + def get(self, n: int) -> bytes: + if n == 0: + return b"" + elif not self.buffer: + raise RuntimeError("buffer is empty") + elif n < 0: + raise ValueError("n should be > 0") + + if len(self.buffer[0]) == n and isinstance(self.buffer[0], bytes): + self._size -= n + return self.buffer.popleft() + + fetched = 0 + ret = io.BytesIO() + while fetched < n: + remaining = n - fetched + chunk = self.buffer.popleft() + chunk_length = len(chunk) + if remaining < chunk_length: + chunk = memoryview(chunk) + left_chunk, right_chunk = chunk[:remaining], chunk[remaining:] + ret.write(left_chunk) + self.buffer.appendleft(right_chunk) + self._size -= remaining + break + else: + ret.write(chunk) + self._size -= chunk_length + fetched += chunk_length + + if not self.buffer: + break + + return ret.getvalue() + + def get_all(self) -> bytes: + buffer = self.buffer + if not buffer: + assert self._size == 0 + return b"" + if len(buffer) == 1: + result = buffer.pop() + if isinstance(result, memoryview): + result = result.tobytes() + else: + ret = io.BytesIO() + ret.writelines(buffer.popleft() for _ in range(len(buffer))) + result = ret.getvalue() + self._size = 0 + return result + + +class BaseHTTPResponse(io.IOBase): + CONTENT_DECODERS = ["gzip", "x-gzip", "deflate"] + if brotli is not None: + CONTENT_DECODERS += ["br"] + if HAS_ZSTD: + CONTENT_DECODERS += ["zstd"] + REDIRECT_STATUSES = [301, 302, 303, 307, 308] + + DECODER_ERROR_CLASSES: tuple[type[Exception], ...] = (IOError, zlib.error) + if brotli is not None: + DECODER_ERROR_CLASSES += (brotli.error,) + + if HAS_ZSTD: + DECODER_ERROR_CLASSES += (zstd.ZstdError,) + + def __init__( + self, + *, + headers: typing.Mapping[str, str] | typing.Mapping[bytes, bytes] | None = None, + status: int, + version: int, + version_string: str, + reason: str | None, + decode_content: bool, + request_url: str | None, + retries: Retry | None = None, + ) -> None: + if isinstance(headers, HTTPHeaderDict): + self.headers = headers + else: + self.headers = HTTPHeaderDict(headers) # type: ignore[arg-type] + self.status = status + self.version = version + self.version_string = version_string + self.reason = reason + self.decode_content = decode_content + self._has_decoded_content = False + self._request_url: str | None = request_url + self.retries = retries + + self.chunked = False + tr_enc = self.headers.get("transfer-encoding", "").lower() + # Don't incur the penalty of creating a list and then discarding it + encodings = (enc.strip() for enc in tr_enc.split(",")) + if "chunked" in encodings: + self.chunked = True + + self._decoder: ContentDecoder | None = None + # Distinguish an uninitialized decoder from a response needing no decoder. + self._decoder_initialized = False + self.length_remaining: int | None + + def get_redirect_location(self) -> str | None | typing.Literal[False]: + """ + Should we redirect and where to? + + :returns: Truthy redirect location string if we got a redirect status + code and valid location. ``None`` if redirect status and no + location. ``False`` if not a redirect status code. + """ + if self.status in self.REDIRECT_STATUSES: + return self.headers.get("location") + return False + + @property + def data(self) -> bytes: + raise NotImplementedError() + + def json(self) -> typing.Any: + """ + Deserializes the body of the HTTP response as a Python object. + + The body of the HTTP response must be encoded using UTF-8, as per + `RFC 8529 Section 8.1 `_. + + To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to + your custom decoder instead. + + If the body of the HTTP response is not decodable to UTF-8, a + `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a + valid JSON document, a `json.JSONDecodeError` will be raised. + + Read more :ref:`here `. + + :returns: The body of the HTTP response as a Python object. + """ + data = self.data.decode("utf-8") + return _json.loads(data) + + @property + def url(self) -> str | None: + raise NotImplementedError() + + @url.setter + def url(self, url: str | None) -> None: + raise NotImplementedError() + + @property + def connection(self) -> BaseHTTPConnection | None: + raise NotImplementedError() + + @property + def retries(self) -> Retry | None: + return self._retries + + @retries.setter + def retries(self, retries: Retry | None) -> None: + # Override the request_url if retries has a redirect location. + if retries is not None and retries.history: + self.url = retries.history[-1].redirect_location + self._retries = retries + + def stream( + self, amt: int | None = _READ_CHUNK_SIZE, decode_content: bool | None = None + ) -> typing.Iterator[bytes]: + raise NotImplementedError() + + def read( + self, + amt: int | None = None, + decode_content: bool | None = None, + cache_content: bool = False, + ) -> bytes: + raise NotImplementedError() + + def read1( + self, + amt: int | None = None, + decode_content: bool | None = None, + ) -> bytes: + raise NotImplementedError() + + def read_chunked( + self, + amt: int | None = None, + decode_content: bool | None = None, + ) -> typing.Iterator[bytes]: + raise NotImplementedError() + + def release_conn(self) -> None: + raise NotImplementedError() + + def drain_conn(self) -> None: + raise NotImplementedError() + + def shutdown(self) -> None: + raise NotImplementedError() + + def close(self) -> None: + raise NotImplementedError() + + def _init_decoder(self) -> None: + """ + Set-up the _decoder attribute if necessary. + """ + if self._decoder_initialized: + return + + if self._decoder is None: + # Note: content-encoding value should be case-insensitive, per RFC 7230 + # Section 3.2 + content_encoding = self.headers.get("content-encoding", "").lower() + if content_encoding in self.CONTENT_DECODERS: + self._decoder = _get_decoder(content_encoding) + elif "," in content_encoding: + encodings = [ + e.strip() + for e in content_encoding.split(",") + if e.strip() in self.CONTENT_DECODERS + ] + if encodings: + self._decoder = _get_decoder(content_encoding) + + self._decoder_initialized = True + + def _decode( + self, + data: bytes, + decode_content: bool | None, + flush_decoder: bool, + max_length: int | None = None, + ) -> bytes: + """ + Decode the data passed in and potentially flush the decoder. + """ + if not decode_content: + if self._has_decoded_content: + raise RuntimeError( + "Calling read(decode_content=False) is not supported after " + "read(decode_content=True) was called." + ) + return data + + if max_length is None or flush_decoder: + max_length = -1 + + try: + if self._decoder: + data = self._decoder.decompress(data, max_length=max_length) + self._has_decoded_content = True + except self.DECODER_ERROR_CLASSES as e: + content_encoding = self.headers.get("content-encoding", "").lower() + raise DecodeError( + "Received response with content-encoding: %s, but " + "failed to decode it." % content_encoding, + e, + ) from e + if flush_decoder: + data += self._flush_decoder() + + return data + + def _flush_decoder(self) -> bytes: + """ + Flushes the decoder. Should only be called if the decoder is actually + being used. + """ + if self._decoder: + return self._decoder.decompress(b"") + self._decoder.flush() + return b"" + + # Compatibility methods for `io` module + def readinto(self, b: bytearray | memoryview[int]) -> int: + temp = self.read(len(b)) + if len(temp) == 0: + return 0 + else: + b[: len(temp)] = temp + return len(temp) + + # Methods used by dependent libraries + def getheaders(self) -> HTTPHeaderDict: + return self.headers + + def getheader(self, name: str, default: str | None = None) -> str | None: + return self.headers.get(name, default) + + # Compatibility method for http.cookiejar + def info(self) -> HTTPHeaderDict: + return self.headers + + def geturl(self) -> str | None: + return self.url + + +class HTTPResponse(BaseHTTPResponse): + """ + HTTP Response container. + + Backwards-compatible with :class:`http.client.HTTPResponse` but the response ``body`` is + loaded and decoded on-demand when the ``data`` property is accessed. This + class is also compatible with the Python standard library's :mod:`io` + module, and can hence be treated as a readable object in the context of that + framework. + + Extra parameters for behaviour not present in :class:`http.client.HTTPResponse`: + + :param preload_content: + If True, the response's body will be preloaded during construction. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + + :param original_response: + When this HTTPResponse wrapper is generated from an :class:`http.client.HTTPResponse` + object, it's convenient to include the original for debug purposes. It's + otherwise unused. + + :param retries: + The retries contains the last :class:`~urllib3.util.retry.Retry` that + was used during the request. + + :param enforce_content_length: + Enforce content length checking. Body returned by server must match + value of Content-Length header, if present. Otherwise, raise error. + """ + + def __init__( + self, + body: _TYPE_BODY = "", + headers: typing.Mapping[str, str] | typing.Mapping[bytes, bytes] | None = None, + status: int = 0, + version: int = 0, + version_string: str = "HTTP/?", + reason: str | None = None, + preload_content: bool = True, + decode_content: bool = True, + original_response: _HttplibHTTPResponse | None = None, + pool: HTTPConnectionPool | None = None, + connection: HTTPConnection | None = None, + msg: _HttplibHTTPMessage | None = None, + retries: Retry | None = None, + enforce_content_length: bool = True, + request_method: str | None = None, + request_url: str | None = None, + auto_close: bool = True, + sock_shutdown: typing.Callable[[int], None] | None = None, + ) -> None: + super().__init__( + headers=headers, + status=status, + version=version, + version_string=version_string, + reason=reason, + decode_content=decode_content, + request_url=request_url, + retries=retries, + ) + + self.enforce_content_length = enforce_content_length + self.auto_close = auto_close + + self._body = None + self._uncached_read_occurred = False + self._fp: _HttplibHTTPResponse | None = None + self._original_response = original_response + self._fp_bytes_read = 0 + self.msg = msg + + if body and isinstance(body, (str, bytes)): + self._body = body + + self._pool = pool + self._connection = connection + + if hasattr(body, "read"): + self._fp = body # type: ignore[assignment] + self._sock_shutdown = sock_shutdown + + # Are we using the chunked-style of transfer encoding? + self.chunk_left: int | None = None + + # Determine length of response + self.length_remaining = self._init_length(request_method) + + # Used to return the correct amount of bytes for partial read()s + self._decoded_buffer = BytesQueueBuffer() + + # If requested, preload the body. + if preload_content and not self._body: + self._body = self.read(decode_content=decode_content) + + def release_conn(self) -> None: + if not self._pool or not self._connection: + return None + + self._pool._put_conn(self._connection) + self._connection = None + + def drain_conn(self) -> None: + """ + Read and discard any remaining HTTP response data in the response connection. + + Unread data in the HTTPResponse connection blocks the connection from being released back to the pool. + """ + try: + while self._raw_read(_READ_CHUNK_SIZE): + pass + except (HTTPError, OSError, BaseSSLError, HTTPException): + pass + if self._has_decoded_content: + # `_raw_read` skips decompression, so we should clean up the + # decoder to avoid keeping unnecessary data in memory. + self._decoded_buffer = BytesQueueBuffer() + self._decoder = None + + @property + def data(self) -> bytes: + # For backwards-compat with earlier urllib3 0.4 and earlier. + if self._body: + return self._body # type: ignore[return-value] + + if self._fp: + return self.read(cache_content=True) + + return None # type: ignore[return-value] + + @property + def connection(self) -> HTTPConnection | None: + return self._connection + + def isclosed(self) -> bool: + return is_fp_closed(self._fp) + + def tell(self) -> int: + """ + Obtain the number of bytes pulled over the wire so far. May differ from + the amount of content returned by :meth:`HTTPResponse.read` + if bytes are encoded on the wire (e.g, compressed). + """ + return self._fp_bytes_read + + def _init_length(self, request_method: str | None) -> int | None: + """ + Set initial length value for Response content if available. + """ + length: int | None + content_length: str | None = self.headers.get("content-length") + + if content_length is not None: + if self.chunked: + # This Response will fail with an IncompleteRead if it can't be + # received as chunked. This method falls back to attempt reading + # the response before raising an exception. + log.warning( + "Received response with both Content-Length and " + "Transfer-Encoding set. This is expressly forbidden " + "by RFC 7230 sec 3.3.2. Ignoring Content-Length and " + "attempting to process response as Transfer-Encoding: " + "chunked." + ) + return None + + try: + # RFC 7230 section 3.3.2 specifies multiple content lengths can + # be sent in a single Content-Length header + # (e.g. Content-Length: 42, 42). This line ensures the values + # are all valid ints and that as long as the `set` length is 1, + # all values are the same. Otherwise, the header is invalid. + lengths = {int(val) for val in content_length.split(",")} + if len(lengths) > 1: + raise InvalidHeader( + "Content-Length contained multiple " + "unmatching values (%s)" % content_length + ) + length = lengths.pop() + except ValueError: + length = None + else: + if length < 0: + length = None + + else: # if content_length is None + length = None + + # Convert status to int for comparison + # In some cases, httplib returns a status of "_UNKNOWN" + try: + status = int(self.status) + except ValueError: + status = 0 + + # Check for responses that shouldn't include a body + if status in (204, 304) or 100 <= status < 200 or request_method == "HEAD": + length = 0 + + return length + + @contextmanager + def _error_catcher(self) -> typing.Generator[None]: + """ + Catch low-level python exceptions, instead re-raising urllib3 + variants, so that low-level exceptions are not leaked in the + high-level api. + + On exit, release the connection back to the pool. + """ + clean_exit = False + + try: + try: + yield + + except SocketTimeout as e: + # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but + # there is yet no clean way to get at it from this context. + raise ReadTimeoutError(self._pool, None, "Read timed out.") from e # type: ignore[arg-type] + + except BaseSSLError as e: + # SSL errors related to framing/MAC get wrapped and reraised here + raise SSLError(e) from e + + except IncompleteRead as e: + if ( + e.expected is not None + and e.partial is not None + and e.expected == -e.partial + ): + arg = "Response may not contain content." + else: + arg = f"Connection broken: {e!r}" + raise ProtocolError(arg, e) from e + + except (HTTPException, OSError) as e: + raise ProtocolError(f"Connection broken: {e!r}", e) from e + + # If no exception is thrown, we should avoid cleaning up + # unnecessarily. + clean_exit = True + finally: + # If we didn't terminate cleanly, we need to throw away our + # connection. + if not clean_exit: + # The response may not be closed but we're not going to use it + # anymore so close it now to ensure that the connection is + # released back to the pool. + if self._original_response: + self._original_response.close() + + # Closing the response may not actually be sufficient to close + # everything, so if we have a hold of the connection close that + # too. + if self._connection: + self._connection.close() + + # If we hold the original response but it's closed now, we should + # return the connection back to the pool. + if self._original_response and self._original_response.isclosed(): + self.release_conn() + + def _fp_read( + self, + amt: int | None = None, + *, + read1: bool = False, + ) -> bytes: + """ + Read a response with the thought that reading the number of bytes + larger than can fit in a 32-bit int at a time via SSL in some + known cases leads to an overflow error that has to be prevented + if `amt` or `self.length_remaining` indicate that a problem may + happen. + + This happens to urllib3 injected with pyOpenSSL-backed SSL-support. + """ + assert self._fp + c_int_max = 2**31 - 1 + if ( + (amt and amt > c_int_max) + or ( + amt is None + and self.length_remaining + and self.length_remaining > c_int_max + ) + ) and util.IS_PYOPENSSL: + if read1: + return self._fp.read1(c_int_max) + buffer = io.BytesIO() + # Besides `max_chunk_amt` being a maximum chunk size, it + # affects memory overhead of reading a response by this + # method in CPython. + # `c_int_max` equal to 2 GiB - 1 byte is the actual maximum + # chunk size that does not lead to an overflow error, but + # 256 MiB is a compromise. + max_chunk_amt = 2**28 + while amt is None or amt != 0: + if amt is not None: + chunk_amt = min(amt, max_chunk_amt) + amt -= chunk_amt + else: + chunk_amt = max_chunk_amt + data = self._fp.read(chunk_amt) + if not data: + break + buffer.write(data) + del data # to reduce peak memory usage by `max_chunk_amt`. + return buffer.getvalue() + elif read1: + return self._fp.read1(amt) if amt is not None else self._fp.read1() + else: + # StringIO doesn't like amt=None + return self._fp.read(amt) if amt is not None else self._fp.read() + + def _raw_read( + self, + amt: int | None = None, + *, + read1: bool = False, + ) -> bytes: + """ + Reads `amt` of bytes from the socket. + """ + if self._fp is None: + return None # type: ignore[return-value] + + fp_closed = getattr(self._fp, "closed", False) + + with self._error_catcher(): + data = self._fp_read(amt, read1=read1) if not fp_closed else b"" + if amt is not None and amt != 0 and not data: + # Platform-specific: Buggy versions of Python. + # Close the connection when no data is returned + # + # This is redundant to what httplib/http.client _should_ + # already do. However, versions of python released before + # December 15, 2012 (http://bugs.python.org/issue16298) do + # not properly close the connection in all cases. There is + # no harm in redundantly calling close. + self._fp.close() + if ( + self.enforce_content_length + and self.length_remaining is not None + and self.length_remaining != 0 + ): + # This is an edge case that httplib failed to cover due + # to concerns of backward compatibility. We're + # addressing it here to make sure IncompleteRead is + # raised during streaming, so all calls with incorrect + # Content-Length are caught. + raise IncompleteRead(self._fp_bytes_read, self.length_remaining) + elif read1 and ( + (amt != 0 and not data) or self.length_remaining == len(data) + ): + # All data has been read, but `self._fp.read1` in + # CPython 3.12 and older doesn't always close + # `http.client.HTTPResponse`, so we close it here. + # See https://github.com/python/cpython/issues/113199 + self._fp.close() + + if data: + self._fp_bytes_read += len(data) + if self.length_remaining is not None: + self.length_remaining -= len(data) + return data + + def read( + self, + amt: int | None = None, + decode_content: bool | None = None, + cache_content: bool = False, + ) -> bytes: + """ + Similar to :meth:`http.client.HTTPResponse.read`, but with two additional + parameters: ``decode_content`` and ``cache_content``. + + :param amt: + How much of the content to read. If specified, caching is skipped + because it doesn't make sense to cache partial content as the full + response. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + + :param cache_content: + If True, will save the returned data such that the same result is + returned despite of the state of the underlying file object. This + is useful if you want the ``.data`` property to continue working + after having ``.read()`` the file object. (Overridden if ``amt`` is + set.) + """ + self._init_decoder() + if decode_content is None: + decode_content = self.decode_content + + if amt and amt < 0: + # Negative numbers and `None` should be treated the same. + amt = None + elif amt is not None: + cache_content = False + + if ( + self._decoder + and self._decoder.has_unconsumed_tail + and len(self._decoded_buffer) < amt + ): + decoded_data = self._decode( + b"", + decode_content, + flush_decoder=False, + max_length=amt - len(self._decoded_buffer), + ) + self._decoded_buffer.put(decoded_data) + if len(self._decoded_buffer) >= amt: + return self._decoded_buffer.get(amt) + + data = self._raw_read(amt) + if not cache_content: + self._uncached_read_occurred = True + + flush_decoder = amt is None or (amt != 0 and not data) + + if ( + not data + and len(self._decoded_buffer) == 0 + and not (self._decoder and self._decoder.has_unconsumed_tail) + ): + return data + + if amt is None: + data = self._decode(data, decode_content, flush_decoder) + # It's possible that there is buffered decoded data after a + # partial read. + if decode_content and len(self._decoded_buffer) > 0: + self._decoded_buffer.put(data) + data = self._decoded_buffer.get_all() + + if cache_content and not self._uncached_read_occurred: + self._body = data + else: + # do not waste memory on buffer when not decoding + if not decode_content: + if self._has_decoded_content: + raise RuntimeError( + "Calling read(decode_content=False) is not supported after " + "read(decode_content=True) was called." + ) + return data + + decoded_data = self._decode( + data, + decode_content, + flush_decoder, + max_length=amt - len(self._decoded_buffer), + ) + self._decoded_buffer.put(decoded_data) + + while len(self._decoded_buffer) < amt and data: + # TODO make sure to initially read enough data to get past the headers + # For example, the GZ file header takes 10 bytes, we don't want to read + # it one byte at a time + data = self._raw_read(amt) + decoded_data = self._decode( + data, + decode_content, + flush_decoder, + max_length=amt - len(self._decoded_buffer), + ) + self._decoded_buffer.put(decoded_data) + data = self._decoded_buffer.get(amt) + + return data + + def read1( + self, + amt: int | None = None, + decode_content: bool | None = None, + ) -> bytes: + """ + Similar to ``http.client.HTTPResponse.read1`` and documented + in :meth:`io.BufferedReader.read1`, but with an additional parameter: + ``decode_content``. + + :param amt: + How much of the content to read. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + """ + if decode_content is None: + decode_content = self.decode_content + if amt and amt < 0: + # Negative numbers and `None` should be treated the same. + amt = None + # try and respond without going to the network + if self._has_decoded_content: + if not decode_content: + raise RuntimeError( + "Calling read1(decode_content=False) is not supported after " + "read1(decode_content=True) was called." + ) + if ( + self._decoder + and self._decoder.has_unconsumed_tail + and (amt is None or len(self._decoded_buffer) < amt) + ): + decoded_data = self._decode( + b"", + decode_content, + flush_decoder=False, + max_length=( + amt - len(self._decoded_buffer) if amt is not None else None + ), + ) + self._decoded_buffer.put(decoded_data) + if len(self._decoded_buffer) > 0: + if amt is None: + return self._decoded_buffer.get_all() + return self._decoded_buffer.get(amt) + if amt == 0: + return b"" + + # FIXME, this method's type doesn't say returning None is possible + data = self._raw_read(amt, read1=True) + self._uncached_read_occurred = True + if not decode_content or data is None: + return data + + self._init_decoder() + while True: + flush_decoder = not data + decoded_data = self._decode( + data, decode_content, flush_decoder, max_length=amt + ) + self._decoded_buffer.put(decoded_data) + if decoded_data or flush_decoder: + break + data = self._raw_read(8192, read1=True) + + if amt is None: + return self._decoded_buffer.get_all() + return self._decoded_buffer.get(amt) + + def stream( + self, amt: int | None = _READ_CHUNK_SIZE, decode_content: bool | None = None + ) -> typing.Generator[bytes]: + """ + A generator wrapper for the read() method. A call will block until + ``amt`` bytes have been read from the connection or until the + connection is closed. + + :param amt: + How much of the content to read. The generator will return up to + much data per iteration, but may return less. This is particularly + likely when using compressed data. However, the empty string will + never be returned. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + """ + if amt == 0: + return + + if self.chunked and self.supports_chunked_reads(): + yield from self.read_chunked(amt, decode_content=decode_content) + else: + while ( + not is_fp_closed(self._fp) + or len(self._decoded_buffer) > 0 + or (self._decoder and self._decoder.has_unconsumed_tail) + ): + data = self.read(amt=amt, decode_content=decode_content) + + if data: + yield data + + # Overrides from io.IOBase + def readable(self) -> bool: + return True + + def shutdown(self) -> None: + if not self._sock_shutdown: + raise ValueError("Cannot shutdown socket as self._sock_shutdown is not set") + if self._connection is None: + raise RuntimeError( + "Cannot shutdown as connection has already been released to the pool" + ) + self._sock_shutdown(socket.SHUT_RD) + + def close(self) -> None: + self._sock_shutdown = None + + if not self.closed and self._fp: + self._fp.close() + + if self._connection: + self._connection.close() + + if not self.auto_close: + io.IOBase.close(self) + + @property + def closed(self) -> bool: + if not self.auto_close: + return io.IOBase.closed.__get__(self) # type: ignore[no-any-return] + elif self._fp is None: + return True + elif hasattr(self._fp, "isclosed"): + return self._fp.isclosed() + elif hasattr(self._fp, "closed"): + return self._fp.closed + else: + return True + + def fileno(self) -> int: + if self._fp is None: + raise OSError("HTTPResponse has no file to get a fileno from") + elif hasattr(self._fp, "fileno"): + return self._fp.fileno() + else: + raise OSError( + "The file-like object this HTTPResponse is wrapped " + "around has no file descriptor" + ) + + def flush(self) -> None: + if ( + self._fp is not None + and hasattr(self._fp, "flush") + and not getattr(self._fp, "closed", False) + ): + return self._fp.flush() + + def supports_chunked_reads(self) -> bool: + """ + Checks if the underlying file-like object looks like a + :class:`http.client.HTTPResponse` object. We do this by testing for + the fp attribute. If it is present we assume it returns raw chunks as + processed by read_chunked(). + """ + return hasattr(self._fp, "fp") + + def _update_chunk_length(self) -> None: + # First, we'll figure out length of a chunk and then + # we'll try to read it from socket. + if self.chunk_left is not None: + return None + line = self._fp.fp.readline(_MAX_CHUNK_LINE_LENGTH + 1) # type: ignore[union-attr] + if len(line) > _MAX_CHUNK_LINE_LENGTH: + self.close() + raise ProtocolError( + "Response chunk size line exceeded maximum allowed length" + ) from None + line = line.split(b";", 1)[0] + try: + self.chunk_left = int(line, 16) + except ValueError: + self.close() + if line: + # Invalid chunked protocol response, abort. + raise InvalidChunkLength(self, line) from None + else: + # Truncated at start of next chunk + raise ProtocolError("Response ended prematurely") from None + + def _handle_chunk(self, amt: int | None) -> bytes: + returned_chunk = None + if amt is None: + chunk = self._fp._safe_read(self.chunk_left) # type: ignore[union-attr] + returned_chunk = chunk + self._fp._safe_read(2) # type: ignore[union-attr] # Toss the CRLF at the end of the chunk. + self.chunk_left = None + elif self.chunk_left is not None and amt < self.chunk_left: + value = self._fp._safe_read(amt) # type: ignore[union-attr] + self.chunk_left = self.chunk_left - amt + returned_chunk = value + elif amt == self.chunk_left: + value = self._fp._safe_read(amt) # type: ignore[union-attr] + self._fp._safe_read(2) # type: ignore[union-attr] # Toss the CRLF at the end of the chunk. + self.chunk_left = None + returned_chunk = value + else: # amt > self.chunk_left + returned_chunk = self._fp._safe_read(self.chunk_left) # type: ignore[union-attr] + self._fp._safe_read(2) # type: ignore[union-attr] # Toss the CRLF at the end of the chunk. + self.chunk_left = None + return returned_chunk # type: ignore[no-any-return] + + def read_chunked( + self, amt: int | None = None, decode_content: bool | None = None + ) -> typing.Generator[bytes]: + """ + Similar to :meth:`HTTPResponse.read`, but with an additional + parameter: ``decode_content``. + + :param amt: + How much of the content to read. If specified, caching is skipped + because it doesn't make sense to cache partial content as the full + response. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + """ + self._init_decoder() + # FIXME: Rewrite this method and make it a class with a better structured logic. + if not self.chunked: + raise ResponseNotChunked( + "Response is not chunked. " + "Header 'transfer-encoding: chunked' is missing." + ) + if not self.supports_chunked_reads(): + raise BodyNotHttplibCompatible( + "Body should be http.client.HTTPResponse like. " + "It should have have an fp attribute which returns raw chunks." + ) + + with self._error_catcher(): + # Don't bother reading the body of a HEAD request. + if self._original_response and is_response_to_head(self._original_response): + self._original_response.close() + return None + + # If a response is already read and closed + # then return immediately. + if self._fp.fp is None: # type: ignore[union-attr] + return None + + if amt == 0: + return + elif amt and amt < 0: + # Negative numbers and `None` should be treated the same, + # but httplib handles only `None` correctly. + amt = None + + while True: + # First, check if any data is left in the decoder's buffer. + if self._decoder and self._decoder.has_unconsumed_tail: + chunk = b"" + else: + self._update_chunk_length() + self._uncached_read_occurred = True + if self.chunk_left == 0: + break + chunk = self._handle_chunk(amt) + decoded = self._decode( + chunk, + decode_content=decode_content, + flush_decoder=False, + max_length=amt, + ) + if decoded: + yield decoded + + if decode_content: + # On CPython and PyPy, we should never need to flush the + # decoder. However, on Jython we *might* need to, so + # lets defensively do it anyway. + decoded = self._flush_decoder() + if decoded: # Platform-specific: Jython. + yield decoded + + # Chunk content ends with \r\n: discard it. + while self._fp is not None: + line = self._fp.fp.readline(_MAX_CHUNK_LINE_LENGTH + 1) + if len(line) > _MAX_CHUNK_LINE_LENGTH: + raise ProtocolError( + "Response chunk trailer line exceeded maximum allowed length" + ) + if not line: + # Some sites may not end with '\r\n'. + break + if line == b"\r\n": + break + + # We read everything; close the "file". + if self._original_response: + self._original_response.close() + + @property + def url(self) -> str | None: + """ + Returns the URL that was the source of this response. + If the request that generated this response redirected, this method + will return the final redirect location. + """ + return self._request_url + + @url.setter + def url(self, url: str | None) -> None: + self._request_url = url + + def __iter__(self) -> typing.Iterator[bytes]: + buffer: list[bytes] = [] + for chunk in self.stream(decode_content=True): + if b"\n" in chunk: + chunks = chunk.split(b"\n") + yield b"".join(buffer) + chunks[0] + b"\n" + for x in chunks[1:-1]: + yield x + b"\n" + if chunks[-1]: + buffer = [chunks[-1]] + else: + buffer = [] + else: + buffer.append(chunk) + if buffer: + yield b"".join(buffer) diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__init__.py b/.venv/lib/python3.12/site-packages/urllib3/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..534126033c083203649022fa9b753a433f005556 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/util/__init__.py @@ -0,0 +1,42 @@ +# For backwards compatibility, provide imports that used to be here. +from __future__ import annotations + +from .connection import is_connection_dropped +from .request import SKIP_HEADER, SKIPPABLE_HEADERS, make_headers +from .response import is_fp_closed +from .retry import Retry +from .ssl_ import ( + ALPN_PROTOCOLS, + IS_PYOPENSSL, + SSLContext, + assert_fingerprint, + create_urllib3_context, + resolve_cert_reqs, + resolve_ssl_version, + ssl_wrap_socket, +) +from .timeout import Timeout +from .url import Url, parse_url +from .wait import wait_for_read, wait_for_write + +__all__ = ( + "IS_PYOPENSSL", + "SSLContext", + "ALPN_PROTOCOLS", + "Retry", + "Timeout", + "Url", + "assert_fingerprint", + "create_urllib3_context", + "is_connection_dropped", + "is_fp_closed", + "parse_url", + "make_headers", + "resolve_cert_reqs", + "resolve_ssl_version", + "ssl_wrap_socket", + "wait_for_read", + "wait_for_write", + "SKIP_HEADER", + "SKIPPABLE_HEADERS", +) diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0704351f6c39bc873eeadc83ca9f806a7cf21e6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/connection.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/connection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cad032f531139c8e9edb09a7e53de62affcf6d7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/connection.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/proxy.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/proxy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..344d7ed4ecf8d786bcfd6702946dbf3413d969f6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/proxy.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/request.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/request.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f0c69f096f88180e9b8afbb4c2cbdaef6e2456f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/request.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/response.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3e40cfcc67f537c030fb4b23d36ef9dc24632e1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/response.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/retry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/retry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54a4d915b52b2da7d986ad00fdfe71c930f96c00 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/retry.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/ssl_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/ssl_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c60b1822d4ffe32f95fe706eb4a42b82dc9b736a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/ssl_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dde711f7fcd2c65b3b6829988dafc7cf7691246 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/ssltransport.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/ssltransport.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a65e625972bb0b11dab0041aec95a8538814a05 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/ssltransport.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/timeout.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/timeout.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e43c60d02ad393125871a22994e5cdfe958bad6a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/timeout.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/url.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/url.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3cb64672d66f9eda4ffa8c4f5a4752b6459cad0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/url.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/util.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..162ddac2b51857ffea0f5408f2bd6c213db1d23d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/util.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/wait.cpython-312.pyc b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/wait.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b25e07c1f7f0cc28106f86b65ea355111d8394bf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/urllib3/util/__pycache__/wait.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/connection.py b/.venv/lib/python3.12/site-packages/urllib3/util/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..f92519ee9124e91e5da7d60ccc3f274312ed3514 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/util/connection.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import socket +import typing + +from ..exceptions import LocationParseError +from .timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT + +_TYPE_SOCKET_OPTIONS = list[tuple[int, int, typing.Union[int, bytes]]] + +if typing.TYPE_CHECKING: + from .._base_connection import BaseHTTPConnection + + +def is_connection_dropped(conn: BaseHTTPConnection) -> bool: # Platform-specific + """ + Returns True if the connection is dropped and should be closed. + :param conn: :class:`urllib3.connection.HTTPConnection` object. + """ + return not conn.is_connected + + +# This function is copied from socket.py in the Python 2.7 standard +# library test suite. Added to its signature is only `socket_options`. +# One additional modification is that we avoid binding to IPv6 servers +# discovered in DNS if the system doesn't have IPv6 functionality. +def create_connection( + address: tuple[str, int], + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + socket_options: _TYPE_SOCKET_OPTIONS | None = None, +) -> socket.socket: + """Connect to *address* and return the socket object. + + Convenience function. Connect to *address* (a 2-tuple ``(host, + port)``) and return the socket object. Passing the optional + *timeout* parameter will set the timeout on the socket instance + before attempting to connect. If no *timeout* is supplied, the + global default timeout setting returned by :func:`socket.getdefaulttimeout` + is used. If *source_address* is set it must be a tuple of (host, port) + for the socket to bind as a source address before making the connection. + An host of '' or port 0 tells the OS to use the default. + """ + + host, port = address + if host.startswith("["): + host = host.strip("[]") + err = None + + # Using the value from allowed_gai_family() in the context of getaddrinfo lets + # us select whether to work with IPv4 DNS records, IPv6 records, or both. + # The original create_connection function always returns all records. + family = allowed_gai_family() + + try: + host.encode("idna") + except UnicodeError: + raise LocationParseError(f"'{host}', label empty or too long") from None + + for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): + af, socktype, proto, canonname, sa = res + sock = None + try: + sock = socket.socket(af, socktype, proto) + + # If provided, set socket level options before connecting. + _set_socket_options(sock, socket_options) + + if timeout is not _DEFAULT_TIMEOUT: + sock.settimeout(timeout) + if source_address: + sock.bind(source_address) + sock.connect(sa) + # Break explicitly a reference cycle + err = None + return sock + + except OSError as _: + err = _ + if sock is not None: + sock.close() + + if err is not None: + try: + raise err + finally: + # Break explicitly a reference cycle + err = None + else: + raise OSError("getaddrinfo returns an empty list") + + +def _set_socket_options( + sock: socket.socket, options: _TYPE_SOCKET_OPTIONS | None +) -> None: + if options is None: + return + + for opt in options: + sock.setsockopt(*opt) + + +def allowed_gai_family() -> socket.AddressFamily: + """This function is designed to work in the context of + getaddrinfo, where family=socket.AF_UNSPEC is the default and + will perform a DNS search for both IPv6 and IPv4 records.""" + + family = socket.AF_INET + if HAS_IPV6: + family = socket.AF_UNSPEC + return family + + +def _has_ipv6(host: str) -> bool: + """Returns True if the system can bind an IPv6 address.""" + sock = None + has_ipv6 = False + + if socket.has_ipv6: + # has_ipv6 returns true if cPython was compiled with IPv6 support. + # It does not tell us if the system has IPv6 support enabled. To + # determine that we must bind to an IPv6 address. + # https://github.com/urllib3/urllib3/pull/611 + # https://bugs.python.org/issue658327 + try: + sock = socket.socket(socket.AF_INET6) + sock.bind((host, 0)) + has_ipv6 = True + except Exception: + pass + + if sock: + sock.close() + return has_ipv6 + + +HAS_IPV6 = _has_ipv6("::1") diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/proxy.py b/.venv/lib/python3.12/site-packages/urllib3/util/proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..908fc6621d0afbed16bde2c1957a5cf28d3a84d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/util/proxy.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import typing + +from .url import Url + +if typing.TYPE_CHECKING: + from ..connection import ProxyConfig + + +def connection_requires_http_tunnel( + proxy_url: Url | None = None, + proxy_config: ProxyConfig | None = None, + destination_scheme: str | None = None, +) -> bool: + """ + Returns True if the connection requires an HTTP CONNECT through the proxy. + + :param URL proxy_url: + URL of the proxy. + :param ProxyConfig proxy_config: + Proxy configuration from poolmanager.py + :param str destination_scheme: + The scheme of the destination. (i.e https, http, etc) + """ + # If we're not using a proxy, no way to use a tunnel. + if proxy_url is None: + return False + + # HTTP destinations never require tunneling, we always forward. + if destination_scheme == "http": + return False + + # Support for forwarding with HTTPS proxies and HTTPS destinations. + if ( + proxy_url.scheme == "https" + and proxy_config + and proxy_config.use_forwarding_for_https + ): + return False + + # Otherwise always use a tunnel. + return True diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/request.py b/.venv/lib/python3.12/site-packages/urllib3/util/request.py new file mode 100644 index 0000000000000000000000000000000000000000..8c6c7fbdcfd2bae3ba337d7edf17b9cb068c3c2d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/util/request.py @@ -0,0 +1,299 @@ +from __future__ import annotations + +import io +import sys +import typing +from base64 import b64encode +from enum import Enum + +from ..exceptions import UnrewindableBodyError +from .util import to_bytes + +if typing.TYPE_CHECKING: + from typing import Final + +# Pass as a value within ``headers`` to skip +# emitting some HTTP headers that are added automatically. +# The only headers that are supported are ``Accept-Encoding``, +# ``Host``, and ``User-Agent``. +SKIP_HEADER = "@@@SKIP_HEADER@@@" +SKIPPABLE_HEADERS = frozenset(["accept-encoding", "host", "user-agent"]) + +ACCEPT_ENCODING = "gzip,deflate" +try: + try: + import brotlicffi as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401 + except ImportError: + import brotli as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401 +except ImportError: + pass +else: + ACCEPT_ENCODING += ",br" + +try: + if sys.version_info >= (3, 14): + from compression import zstd as _unused_module_zstd # noqa: F401 + else: + from backports import zstd as _unused_module_zstd # noqa: F401 +except ImportError: + pass +else: + ACCEPT_ENCODING += ",zstd" + + +class _TYPE_FAILEDTELL(Enum): + token = 0 + + +_FAILEDTELL: Final[_TYPE_FAILEDTELL] = _TYPE_FAILEDTELL.token + +_TYPE_BODY_POSITION = typing.Union[int, _TYPE_FAILEDTELL] + +# When sending a request with these methods we aren't expecting +# a body so don't need to set an explicit 'Content-Length: 0' +# The reason we do this in the negative instead of tracking methods +# which 'should' have a body is because unknown methods should be +# treated as if they were 'POST' which *does* expect a body. +_METHODS_NOT_EXPECTING_BODY = {"GET", "HEAD", "DELETE", "TRACE", "OPTIONS", "CONNECT"} + + +def make_headers( + keep_alive: bool | None = None, + accept_encoding: bool | list[str] | str | None = None, + user_agent: str | None = None, + basic_auth: str | None = None, + proxy_basic_auth: str | None = None, + disable_cache: bool | None = None, + *, + basic_auth_encoding: str = "latin-1", + proxy_basic_auth_encoding: str = "latin-1", +) -> dict[str, str]: + """ + Shortcuts for generating request headers. + + :param keep_alive: + If ``True``, adds 'connection: keep-alive' header. + + :param accept_encoding: + Can be a boolean, list, or string. + ``True`` translates to 'gzip,deflate'. If the dependencies for + Brotli (either the ``brotli`` or ``brotlicffi`` package) and/or + Zstandard (the ``backports.zstd`` package for Python before 3.14) + algorithms are installed, then their encodings are + included in the string ('br' and 'zstd', respectively). + List will get joined by comma. + String will be used as provided. + + :param user_agent: + String representing the user-agent you want, such as + "python-urllib3/0.6" + + :param basic_auth: + Colon-separated username:password string for 'authorization: basic ...' + auth header. Basic authentication transmits Base64-encoded bytes, not + Unicode text, so the string is encoded with ``basic_auth_encoding`` + before Base64 encoding. + + Must contain decoded credentials (not percent-encoded). + For URLs parsed with :func:`parse_url`, use :attr:`Url.auth_decoded_joined` + to get the properly formatted string. + + :param basic_auth_encoding: + Text encoding used to encode ``basic_auth`` before Base64 encoding. + Defaults to "latin-1" for backward compatibility. Use "utf-8" only + when the peer expects UTF-8 Basic authentication credentials. + + Must contain decoded credentials (not percent-encoded). + For URLs parsed with :func:`parse_url`, use :attr:`Url.auth_decoded_joined` + to get the properly formatted string. + + :param proxy_basic_auth: + Colon-separated username:password string for 'proxy-authorization: basic ...' + auth header. Basic authentication transmits Base64-encoded bytes, not + Unicode text, so the string is encoded with ``proxy_basic_auth_encoding`` + before Base64 encoding. + + Must contain decoded credentials (not percent-encoded). + For URLs parsed with :func:`parse_url`, use :attr:`Url.auth_decoded_joined` + to get the properly formatted string. + + :param proxy_basic_auth_encoding: + Text encoding used to encode ``proxy_basic_auth`` before Base64 + encoding. Defaults to "latin-1" for backward compatibility. Use + "utf-8" only when the proxy expects UTF-8 Basic authentication + credentials. + + Must contain decoded credentials (not percent-encoded). + For URLs parsed with :func:`parse_url`, use :attr:`Url.auth_decoded_joined` + to get the properly formatted string. + + :param disable_cache: + If ``True``, adds 'cache-control: no-cache' header. + + Example: + + .. code-block:: python + + import urllib3 + + print(urllib3.util.make_headers(keep_alive=True, user_agent="Batman/1.0")) + # {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} + print(urllib3.util.make_headers(accept_encoding=True)) + # {'accept-encoding': 'gzip,deflate'} + """ + headers: dict[str, str] = {} + if accept_encoding: + if isinstance(accept_encoding, str): + pass + elif isinstance(accept_encoding, list): + accept_encoding = ",".join(accept_encoding) + else: + accept_encoding = ACCEPT_ENCODING + headers["accept-encoding"] = accept_encoding + + if user_agent: + headers["user-agent"] = user_agent + + if keep_alive: + headers["connection"] = "keep-alive" + + if basic_auth: + headers["authorization"] = ( + f"Basic {b64encode(basic_auth.encode(basic_auth_encoding)).decode()}" + ) + + if proxy_basic_auth: + headers["proxy-authorization"] = ( + f"Basic {b64encode(proxy_basic_auth.encode(proxy_basic_auth_encoding)).decode()}" + ) + + if disable_cache: + headers["cache-control"] = "no-cache" + + return headers + + +def set_file_position( + body: typing.Any, pos: _TYPE_BODY_POSITION | None +) -> _TYPE_BODY_POSITION | None: + """ + If a position is provided, move file to that point. + Otherwise, we'll attempt to record a position for future use. + """ + if pos is not None: + rewind_body(body, pos) + elif getattr(body, "tell", None) is not None: + try: + pos = body.tell() + except OSError: + # This differentiates from None, allowing us to catch + # a failed `tell()` later when trying to rewind the body. + pos = _FAILEDTELL + + return pos + + +def rewind_body(body: typing.IO[typing.AnyStr], body_pos: _TYPE_BODY_POSITION) -> None: + """ + Attempt to rewind body to a certain position. + Primarily used for request redirects and retries. + + :param body: + File-like object that supports seek. + + :param int pos: + Position to seek to in file. + """ + body_seek = getattr(body, "seek", None) + if body_seek is not None and isinstance(body_pos, int): + try: + body_seek(body_pos) + except OSError as e: + raise UnrewindableBodyError( + "An error occurred when rewinding request body for redirect/retry." + ) from e + elif body_pos is _FAILEDTELL: + raise UnrewindableBodyError( + "Unable to record file position for rewinding " + "request body during a redirect/retry." + ) + elif body_seek is None: + raise UnrewindableBodyError("body does not implement seek.") + else: + raise ValueError( + f"body_pos must be of type integer, instead it was {type(body_pos)}." + ) + + +class ChunksAndContentLength(typing.NamedTuple): + chunks: typing.Iterable[bytes] | None + content_length: int | None + + +def body_to_chunks( + body: typing.Any | None, method: str, blocksize: int +) -> ChunksAndContentLength: + """Takes the HTTP request method, body, and blocksize and + transforms them into an iterable of chunks to pass to + socket.sendall() and an optional 'Content-Length' header. + + A 'Content-Length' of 'None' indicates the length of the body + can't be determined so should use 'Transfer-Encoding: chunked' + for framing instead. + """ + + chunks: typing.Iterable[bytes] | None + content_length: int | None + + # No body, we need to make a recommendation on 'Content-Length' + # based on whether that request method is expected to have + # a body or not. + if body is None: + chunks = None + if method.upper() not in _METHODS_NOT_EXPECTING_BODY: + content_length = 0 + else: + content_length = None + + # Bytes or strings become bytes + elif isinstance(body, (str, bytes)): + chunks = (to_bytes(body),) + content_length = len(chunks[0]) + + # File-like object, TODO: use seek() and tell() for length? + elif hasattr(body, "read"): + + def chunk_readable() -> typing.Iterable[bytes]: + encode = isinstance(body, io.TextIOBase) + while True: + datablock = body.read(blocksize) + if not datablock: + break + if encode: + datablock = datablock.encode("utf-8") + yield datablock + + chunks = chunk_readable() + content_length = None + + # Otherwise we need to start checking via duck-typing. + else: + try: + # Check if the body implements the buffer API. + mv = memoryview(body) + except TypeError: + try: + # Check if the body is an iterable + chunks = iter(body) + content_length = None + except TypeError: + raise TypeError( + f"'body' must be a bytes-like object, file-like " + f"object, or iterable. Instead was {body!r}" + ) from None + else: + # Since it implements the buffer API can be passed directly to socket.sendall() + chunks = (body,) + content_length = mv.nbytes + + return ChunksAndContentLength(chunks=chunks, content_length=content_length) diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/response.py b/.venv/lib/python3.12/site-packages/urllib3/util/response.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4578696fa2e17a900c6890ec26d65e860b0b72 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/util/response.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import http.client as httplib +from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect + +from ..exceptions import HeaderParsingError + + +def is_fp_closed(obj: object) -> bool: + """ + Checks whether a given file-like object is closed. + + :param obj: + The file-like object to check. + """ + + try: + # Check `isclosed()` first, in case Python3 doesn't set `closed`. + # GH Issue #928 + return obj.isclosed() # type: ignore[no-any-return, attr-defined] + except AttributeError: + pass + + try: + # Check via the official file-like-object way. + return obj.closed # type: ignore[no-any-return, attr-defined] + except AttributeError: + pass + + try: + # Check if the object is a container for another file-like object that + # gets released on exhaustion (e.g. HTTPResponse). + return obj.fp is None # type: ignore[attr-defined] + except AttributeError: + pass + + raise ValueError("Unable to determine whether fp is closed.") + + +def assert_header_parsing(headers: httplib.HTTPMessage) -> None: + """ + Asserts whether all headers have been successfully parsed. + Extracts encountered errors from the result of parsing headers. + + Only works on Python 3. + + :param http.client.HTTPMessage headers: Headers to verify. + + :raises urllib3.exceptions.HeaderParsingError: + If parsing errors are found. + """ + + # This will fail silently if we pass in the wrong kind of parameter. + # To make debugging easier add an explicit check. + if not isinstance(headers, httplib.HTTPMessage): + raise TypeError(f"expected httplib.Message, got {type(headers)}.") + + unparsed_data = None + + # get_payload is actually email.message.Message.get_payload; + # we're only interested in the result if it's not a multipart message + if not headers.is_multipart(): + payload = headers.get_payload() + + if isinstance(payload, (bytes, str)): + unparsed_data = payload + + # httplib is assuming a response body is available + # when parsing headers even when httplib only sends + # header data to parse_headers() This results in + # defects on multipart responses in particular. + # See: https://github.com/urllib3/urllib3/issues/800 + + # So we ignore the following defects: + # - StartBoundaryNotFoundDefect: + # The claimed start boundary was never found. + # - MultipartInvariantViolationDefect: + # A message claimed to be a multipart but no subparts were found. + defects = [ + defect + for defect in headers.defects + if not isinstance( + defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect) + ) + ] + + if defects or unparsed_data: + raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data) + + +def is_response_to_head(response: httplib.HTTPResponse) -> bool: + """ + Checks whether the request of a response has been a HEAD-request. + + :param http.client.HTTPResponse response: + Response to check if the originating request + used 'HEAD' as a method. + """ + # FIXME: Can we do this somehow without accessing private httplib _method? + method_str = response._method # type: str # type: ignore[attr-defined] + return method_str.upper() == "HEAD" diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/retry.py b/.venv/lib/python3.12/site-packages/urllib3/util/retry.py new file mode 100644 index 0000000000000000000000000000000000000000..868f2930358c0bf8e544d7c9f0fae1c63f9d789e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/util/retry.py @@ -0,0 +1,569 @@ +from __future__ import annotations + +import email +import logging +import random +import re +import time +import typing +import warnings +from collections.abc import Collection +from itertools import takewhile +from types import TracebackType + +from ..exceptions import ( + ConnectTimeoutError, + InvalidHeader, + MaxRetryError, + ProtocolError, + ProxyError, + ReadTimeoutError, + ResponseError, +) +from .util import reraise + +if typing.TYPE_CHECKING: + from typing_extensions import Self + + from ..connectionpool import ConnectionPool + from ..response import BaseHTTPResponse + +log = logging.getLogger(__name__) + + +# Data structure for representing the metadata of requests that result in a retry. +class RequestHistory(typing.NamedTuple): + method: str | None + url: str | None + error: Exception | None + status: int | None + redirect_location: str | None + + +class Retry: + """Retry configuration. + + Each retry attempt will create a new Retry object with updated values, so + they can be safely reused. + + Retries can be defined as a default for a pool: + + .. code-block:: python + + retries = Retry(connect=5, read=2, redirect=5) + http = PoolManager(retries=retries) + response = http.request("GET", "https://example.com/") + + Or per-request (which overrides the default for the pool): + + .. code-block:: python + + response = http.request("GET", "https://example.com/", retries=Retry(10)) + + Retries can be disabled by passing ``False``: + + .. code-block:: python + + response = http.request("GET", "https://example.com/", retries=False) + + Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless + retries are disabled, in which case the causing exception will be raised. + + :param int total: + Total number of retries to allow. Takes precedence over other counts. + + Set to ``None`` to remove this constraint and fall back on other + counts. + + Set to ``0`` to fail on the first retry. + + Set to ``False`` to disable and imply ``raise_on_redirect=False``. + + :param int connect: + How many connection-related errors to retry on. + + These are errors raised before the request is sent to the remote server, + which we assume has not triggered the server to process the request. + + Set to ``0`` to fail on the first retry of this type. + + :param int read: + How many times to retry on read errors. + + These errors are raised after the request was sent to the server, so the + request may have side-effects. + + Set to ``0`` to fail on the first retry of this type. + + :param int redirect: + How many redirects to perform. Limit this to avoid infinite redirect + loops. + + A redirect is a HTTP response with a status code 301, 302, 303, 307 or + 308. + + Set to ``0`` to fail on the first retry of this type. + + Set to ``False`` to disable and imply ``raise_on_redirect=False``. + + :param int status: + How many times to retry on bad status codes. + + These are retries made on responses, where status code matches + ``status_forcelist``. + + Set to ``0`` to fail on the first retry of this type. + + :param int other: + How many times to retry on other errors. + + Other errors are errors that are not connect, read, redirect or status errors. + These errors might be raised after the request was sent to the server, so the + request might have side-effects. + + Set to ``0`` to fail on the first retry of this type. + + If ``total`` is not set, it's a good idea to set this to 0 to account + for unexpected edge cases and avoid infinite retry loops. + + :param Collection allowed_methods: + Set of uppercased HTTP method verbs that we should retry on. + + By default, we only retry on methods which are considered to be + idempotent (multiple requests with the same parameters end with the + same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`. + + Set to a ``None`` value to retry on any verb. + + :param Collection status_forcelist: + A set of integer HTTP status codes that we should force a retry on. + A retry is initiated if the request method is in ``allowed_methods`` + and the response status code is in ``status_forcelist``. + + By default, this is disabled with ``None``. + + :param float backoff_factor: + A backoff factor to apply between attempts after the second try + (most errors are resolved immediately by a second try without a + delay). urllib3 will sleep for:: + + {backoff factor} * (2 ** ({number of previous retries})) + + seconds. If `backoff_jitter` is non-zero, this sleep is extended by:: + + random.uniform(0, {backoff jitter}) + + seconds. For example, if the backoff_factor is 0.1, then :func:`Retry.sleep` will + sleep for [0.0s, 0.2s, 0.4s, 0.8s, ...] between retries. No backoff will ever + be longer than `backoff_max`. + + By default, backoff is disabled (factor set to 0). + + :param float backoff_max: + The maximum backoff time (in seconds) between retry attempts. + This value caps the computed backoff from `backoff_factor`. + + :param float backoff_jitter: + Random jitter amount (in seconds) added to the computed backoff. + Jitter is sampled uniformly from `0` to `backoff_jitter`. + + :param bool raise_on_redirect: Whether, if the number of redirects is + exhausted, to raise a MaxRetryError, or to return a response with a + response code in the 3xx range. + + :param bool raise_on_status: Similar meaning to ``raise_on_redirect``: + whether we should raise an exception, or return a response, + if status falls in ``status_forcelist`` range and retries have + been exhausted. + + :param tuple history: The history of the request encountered during + each call to :meth:`~Retry.increment`. The list is in the order + the requests occurred. Each list item is of class :class:`RequestHistory`. + + :param bool respect_retry_after_header: + Whether to respect Retry-After header on status codes defined as + :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not. + + :param Collection remove_headers_on_redirect: + Sequence of headers to remove from the request when a response + indicating a redirect is returned before firing off the redirected + request. + + :param int retry_after_max: Number of seconds to allow as the maximum for + Retry-After headers. Defaults to :attr:`Retry.DEFAULT_RETRY_AFTER_MAX`. + Any Retry-After headers larger than this value will be limited to this + value. + """ + + #: Default methods to be used for ``allowed_methods`` + DEFAULT_ALLOWED_METHODS = frozenset( + ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"] + ) + + #: Default status codes that trigger a retry when a Retry-After header is + #: present and ``respect_retry_after_header`` is enabled. + RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503]) + + #: Default headers to be used for ``remove_headers_on_redirect`` + DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset( + ["Cookie", "Authorization", "Proxy-Authorization"] + ) + + #: Default maximum backoff time. + DEFAULT_BACKOFF_MAX = 120 + + # This is undocumented in the RFC. Setting to 6 hours matches other popular libraries. + #: Default maximum allowed value for Retry-After headers in seconds + DEFAULT_RETRY_AFTER_MAX: typing.Final[int] = 21600 + + # Backward compatibility; assigned outside of the class. + DEFAULT: typing.ClassVar[Retry] + + def __init__( + self, + total: bool | int | None = 10, + connect: int | None = None, + read: int | None = None, + redirect: bool | int | None = None, + status: int | None = None, + other: int | None = None, + allowed_methods: typing.Collection[str] | None = DEFAULT_ALLOWED_METHODS, + status_forcelist: typing.Collection[int] | None = None, + backoff_factor: float = 0, + backoff_max: float = DEFAULT_BACKOFF_MAX, + raise_on_redirect: bool = True, + raise_on_status: bool = True, + history: tuple[RequestHistory, ...] | None = None, + respect_retry_after_header: bool = True, + remove_headers_on_redirect: typing.Collection[ + str + ] = DEFAULT_REMOVE_HEADERS_ON_REDIRECT, + backoff_jitter: float = 0.0, + retry_after_max: int = DEFAULT_RETRY_AFTER_MAX, + ) -> None: + self.total = total + self.connect = connect + self.read = read + self.status = status + self.other = other + + if redirect is False or total is False: + redirect = 0 + raise_on_redirect = False + + self.redirect = redirect + self.status_forcelist = status_forcelist or set() + if not allowed_methods and isinstance(allowed_methods, Collection): + warnings.warn( + "Using an empty collection for 'allowed_methods' option to " + "retry on any verb is deprecated and will skip retries for " + "all verbs in urllib3 v3.0. Instead use " + "Retry(..., allowed_methods=None).", + FutureWarning, + stacklevel=2, + ) + self.allowed_methods = allowed_methods + self.backoff_factor = backoff_factor + self.backoff_max = backoff_max + self.retry_after_max = retry_after_max + self.raise_on_redirect = raise_on_redirect + self.raise_on_status = raise_on_status + self.history = history or () + self.respect_retry_after_header = respect_retry_after_header + self.remove_headers_on_redirect = frozenset( + h.lower() for h in remove_headers_on_redirect + ) + self.backoff_jitter = backoff_jitter + + def new(self, **kw: typing.Any) -> Self: + params = dict( + total=self.total, + connect=self.connect, + read=self.read, + redirect=self.redirect, + status=self.status, + other=self.other, + allowed_methods=self.allowed_methods, + status_forcelist=self.status_forcelist, + backoff_factor=self.backoff_factor, + backoff_max=self.backoff_max, + retry_after_max=self.retry_after_max, + raise_on_redirect=self.raise_on_redirect, + raise_on_status=self.raise_on_status, + history=self.history, + remove_headers_on_redirect=self.remove_headers_on_redirect, + respect_retry_after_header=self.respect_retry_after_header, + backoff_jitter=self.backoff_jitter, + ) + + params.update(kw) + return type(self)(**params) # type: ignore[arg-type] + + @classmethod + def from_int( + cls, + retries: Retry | bool | int | None, + redirect: bool | int | None = True, + default: Retry | bool | int | None = None, + ) -> Retry: + """Backwards-compatibility for the old retries format.""" + if retries is None: + retries = default if default is not None else cls.DEFAULT + + if isinstance(retries, Retry): + return retries + + redirect = bool(redirect) and None + new_retries = cls(retries, redirect=redirect) + log.debug("Converted retries value: %r -> %r", retries, new_retries) + return new_retries + + def get_backoff_time(self) -> float: + """Formula for computing the current backoff + + :rtype: float + """ + # We want to consider only the last consecutive errors sequence (Ignore redirects). + consecutive_errors_len = len( + list( + takewhile(lambda x: x.redirect_location is None, reversed(self.history)) + ) + ) + if consecutive_errors_len <= 1: + return 0 + + backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1)) + if self.backoff_jitter != 0.0: + backoff_value += random.random() * self.backoff_jitter + return float(max(0, min(self.backoff_max, backoff_value))) + + def parse_retry_after(self, retry_after: str) -> float: + seconds: float + # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4 + if re.match(r"^\s*[0-9]+\s*$", retry_after): + seconds = int(retry_after) + else: + retry_date_tuple = email.utils.parsedate_tz(retry_after) + if retry_date_tuple is None: + raise InvalidHeader(f"Invalid Retry-After header: {retry_after}") + + retry_date = email.utils.mktime_tz(retry_date_tuple) + seconds = retry_date - time.time() + + seconds = max(seconds, 0) + + # Check the seconds do not exceed the specified maximum + if seconds > self.retry_after_max: + seconds = self.retry_after_max + + return seconds + + def get_retry_after(self, response: BaseHTTPResponse) -> float | None: + """Get the value of Retry-After in seconds.""" + + retry_after = response.headers.get("Retry-After") + + if retry_after is None: + return None + + return self.parse_retry_after(retry_after) + + def sleep_for_retry(self, response: BaseHTTPResponse) -> bool: + retry_after = self.get_retry_after(response) + if retry_after: + time.sleep(retry_after) + return True + + return False + + def _sleep_backoff(self) -> None: + backoff = self.get_backoff_time() + if backoff <= 0: + return + time.sleep(backoff) + + def sleep(self, response: BaseHTTPResponse | None = None) -> None: + """Sleep between retry attempts. + + This method will respect a server's ``Retry-After`` response header + and sleep the duration of the time requested. If that is not present, it + will use an exponential backoff. By default, the backoff factor is 0 and + this method will return immediately. + """ + + if self.respect_retry_after_header and response: + slept = self.sleep_for_retry(response) + if slept: + return + + self._sleep_backoff() + + def _is_connection_error(self, err: Exception) -> bool: + """Errors when we're fairly sure that the server did not receive the + request, so it should be safe to retry. + """ + if isinstance(err, ProxyError): + err = err.original_error + return isinstance(err, ConnectTimeoutError) + + def _is_read_error(self, err: Exception) -> bool: + """Errors that occur after the request has been started, so we should + assume that the server began processing it. + """ + return isinstance(err, (ReadTimeoutError, ProtocolError)) + + def _is_method_retryable(self, method: str) -> bool: + """Checks if a given HTTP method should be retried upon, depending if + it is included in the allowed_methods + """ + if self.allowed_methods and method.upper() not in self.allowed_methods: + return False + return True + + def is_retry( + self, method: str, status_code: int, has_retry_after: bool = False + ) -> bool: + """Is this method/status code retryable? (Based on allowlists and control + variables such as the number of total retries to allow, whether to + respect the Retry-After header, whether this header is present, and + whether the returned status code is on the list of status codes to + be retried upon on the presence of the aforementioned header) + """ + if not self._is_method_retryable(method): + return False + + if self.status_forcelist and status_code in self.status_forcelist: + return True + + return bool( + self.total + and self.respect_retry_after_header + and has_retry_after + and (status_code in self.RETRY_AFTER_STATUS_CODES) + ) + + def is_exhausted(self) -> bool: + """Are we out of retries?""" + retry_counts = [ + x + for x in ( + self.total, + self.connect, + self.read, + self.redirect, + self.status, + self.other, + ) + if x + ] + if not retry_counts: + return False + + return min(retry_counts) < 0 + + def increment( + self, + method: str | None = None, + url: str | None = None, + response: BaseHTTPResponse | None = None, + error: Exception | None = None, + _pool: ConnectionPool | None = None, + _stacktrace: TracebackType | None = None, + ) -> Self: + """Return a new Retry object with incremented retry counters. + + :param response: A response object, or None, if the server did not + return a response. + :type response: :class:`~urllib3.response.BaseHTTPResponse` + :param Exception error: An error encountered during the request, or + None if the response was received successfully. + + :return: A new ``Retry`` object. + """ + if self.total is False and error: + # Disabled, indicate to re-raise the error. + raise reraise(type(error), error, _stacktrace) + + total = self.total + if total is not None: + total -= 1 + + connect = self.connect + read = self.read + redirect = self.redirect + status_count = self.status + other = self.other + cause = "unknown" + status = None + redirect_location = None + + if error and self._is_connection_error(error): + # Connect retry? + if connect is False: + raise reraise(type(error), error, _stacktrace) + elif connect is not None: + connect -= 1 + + elif error and self._is_read_error(error): + # Read retry? + if read is False or method is None or not self._is_method_retryable(method): + raise reraise(type(error), error, _stacktrace) + elif read is not None: + read -= 1 + + elif error: + # Other retry? + if other is not None: + other -= 1 + + elif response and response.get_redirect_location(): + # Redirect retry? + if redirect is not None: + redirect -= 1 + cause = "too many redirects" + response_redirect_location = response.get_redirect_location() + if response_redirect_location: + redirect_location = response_redirect_location + status = response.status + + else: + # Incrementing because of a server error like a 500 in + # status_forcelist and the given method is in the allowed_methods + cause = ResponseError.GENERIC_ERROR + if response and response.status: + if status_count is not None: + status_count -= 1 + cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status) + status = response.status + + history = self.history + ( + RequestHistory(method, url, error, status, redirect_location), + ) + + new_retry = self.new( + total=total, + connect=connect, + read=read, + redirect=redirect, + status=status_count, + other=other, + history=history, + ) + + if new_retry.is_exhausted(): + reason = error or ResponseError(cause) + raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type] + + log.debug("Incremented Retry for (url='%s'): %r", url, new_retry) + + return new_retry + + def __repr__(self) -> str: + return ( + f"{type(self).__name__}(total={self.total}, connect={self.connect}, " + f"read={self.read}, redirect={self.redirect}, status={self.status})" + ) + + +# For backwards compatibility (equivalent to pre-v1.9): +Retry.DEFAULT = Retry(3) diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/ssl_.py b/.venv/lib/python3.12/site-packages/urllib3/util/ssl_.py new file mode 100644 index 0000000000000000000000000000000000000000..f6445a41dae75f4c2c461578dc0f455c2aa7b287 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/util/ssl_.py @@ -0,0 +1,481 @@ +from __future__ import annotations + +import hashlib +import hmac +import os +import socket +import sys +import typing +import warnings +from binascii import Error as BinasciiError +from binascii import unhexlify + +from ..exceptions import ProxySchemeUnsupported, SSLError +from .url import _BRACELESS_IPV6_ADDRZ_RE, _IPV4_RE + +SSLContext = None +SSLTransport = None +HAS_NEVER_CHECK_COMMON_NAME = False +IS_PYOPENSSL = False +ALPN_PROTOCOLS = ["http/1.1"] + +_TYPE_VERSION_INFO = tuple[int, int, int, str, int] + +# Maps the length of a digest to a possible hash function producing this digest +HASHFUNC_MAP = { + length: getattr(hashlib, algorithm, None) + for length, algorithm in ((32, "md5"), (40, "sha1"), (64, "sha256")) +} + + +def _is_has_never_check_common_name_reliable( + openssl_version: str, +) -> bool: + # As of May 2023, all released versions of LibreSSL fail to reject certificates with + # only common names, see https://github.com/urllib3/urllib3/pull/3024 + is_openssl = openssl_version.startswith("OpenSSL ") + + return is_openssl + + +if typing.TYPE_CHECKING: + from ssl import VerifyMode + from typing import TypedDict + + from .ssltransport import SSLTransport as SSLTransportType + + class _TYPE_PEER_CERT_RET_DICT(TypedDict, total=False): + subjectAltName: tuple[tuple[str, str], ...] + subject: tuple[tuple[tuple[str, str], ...], ...] + serialNumber: str + + +# Mapping from 'ssl.PROTOCOL_TLSX' to 'TLSVersion.X' +_SSL_VERSION_TO_TLS_VERSION: dict[int, int] = {} + +try: # Do we have ssl at all? + import ssl + from ssl import ( # type: ignore[assignment] + CERT_REQUIRED, + HAS_NEVER_CHECK_COMMON_NAME, + OP_NO_COMPRESSION, + OP_NO_TICKET, + OPENSSL_VERSION, + PROTOCOL_TLS, + PROTOCOL_TLS_CLIENT, + VERIFY_X509_PARTIAL_CHAIN, + VERIFY_X509_STRICT, + OP_NO_SSLv2, + OP_NO_SSLv3, + SSLContext, + TLSVersion, + ) + + PROTOCOL_SSLv23 = PROTOCOL_TLS + + # Setting SSLContext.hostname_checks_common_name = False didn't work with + # LibreSSL, check details in the used function. + if HAS_NEVER_CHECK_COMMON_NAME and not _is_has_never_check_common_name_reliable( + OPENSSL_VERSION, + ): # Defensive: + HAS_NEVER_CHECK_COMMON_NAME = False + + # Need to be careful here in case old TLS versions get + # removed in future 'ssl' module implementations. + for attr in ("TLSv1", "TLSv1_1", "TLSv1_2"): + try: + _SSL_VERSION_TO_TLS_VERSION[getattr(ssl, f"PROTOCOL_{attr}")] = getattr( + TLSVersion, attr + ) + except AttributeError: # Defensive: + continue + + from .ssltransport import SSLTransport # type: ignore[assignment] +except ImportError: + OP_NO_COMPRESSION = 0x20000 # type: ignore[assignment,misc] + OP_NO_TICKET = 0x4000 # type: ignore[assignment,misc] + OP_NO_SSLv2 = 0x1000000 # type: ignore[assignment,misc] + OP_NO_SSLv3 = 0x2000000 # type: ignore[assignment,misc] + PROTOCOL_SSLv23 = PROTOCOL_TLS = 2 # type: ignore[assignment,misc] + PROTOCOL_TLS_CLIENT = 16 # type: ignore[assignment,misc] + VERIFY_X509_PARTIAL_CHAIN = 0x80000 # type: ignore[assignment,misc] + VERIFY_X509_STRICT = 0x20 # type: ignore[assignment,misc] + + +_TYPE_PEER_CERT_RET = typing.Union["_TYPE_PEER_CERT_RET_DICT", bytes, None] + + +def assert_fingerprint(cert: bytes | None, fingerprint: str) -> None: + """ + Checks if given fingerprint matches the supplied certificate. + + :param cert: + Certificate as bytes object. + :param fingerprint: + Fingerprint as string of hexdigits, can be interspersed by colons. + """ + + if cert is None: + raise SSLError("No certificate for the peer.") + + fingerprint = fingerprint.replace(":", "").lower() + digest_length = len(fingerprint) + if digest_length not in HASHFUNC_MAP: + raise SSLError(f"Fingerprint of invalid length: {fingerprint}") + hashfunc = HASHFUNC_MAP.get(digest_length) + if hashfunc is None: + raise SSLError( + f"Hash function implementation unavailable for fingerprint length: {digest_length}" + ) + + # We need encode() here for py32; works on py2 and p33. + try: + fingerprint_bytes = unhexlify(fingerprint.encode()) + except BinasciiError as e: + raise SSLError(e) from e + + cert_digest = hashfunc(cert).digest() + + if not hmac.compare_digest(cert_digest, fingerprint_bytes): + raise SSLError( + f'Fingerprints did not match. Expected "{fingerprint}", got "{cert_digest.hex()}"' + ) + + +def resolve_cert_reqs(candidate: None | int | str) -> VerifyMode: + """ + Resolves the argument to a numeric constant, which can be passed to + the wrap_socket function/method from the ssl module. + Defaults to :data:`ssl.CERT_REQUIRED`. + If given a string it is assumed to be the name of the constant in the + :mod:`ssl` module or its abbreviation. + (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. + If it's neither `None` nor a string we assume it is already the numeric + constant which can directly be passed to wrap_socket. + """ + if candidate is None: + return CERT_REQUIRED + + if isinstance(candidate, str): + res = getattr(ssl, candidate, None) + if res is None: + res = getattr(ssl, "CERT_" + candidate) + return res # type: ignore[no-any-return] + + return candidate # type: ignore[return-value] + + +def resolve_ssl_version(candidate: None | int | str) -> int: + """ + like resolve_cert_reqs + """ + if candidate is None: + return PROTOCOL_TLS + + if isinstance(candidate, str): + res = getattr(ssl, candidate, None) + if res is None: + res = getattr(ssl, "PROTOCOL_" + candidate) + return typing.cast(int, res) + + return candidate + + +def create_urllib3_context( + ssl_version: int | None = None, + cert_reqs: int | None = None, + options: int | None = None, + ciphers: str | None = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + verify_flags: int | None = None, +) -> ssl.SSLContext: + """Creates and configures an :class:`ssl.SSLContext` instance for use with urllib3. + + :param ssl_version: + The desired protocol version to use. This will default to + PROTOCOL_SSLv23 which will negotiate the highest protocol that both + the server and your installation of OpenSSL support. + + This parameter is deprecated instead use 'ssl_minimum_version'. + :param ssl_minimum_version: + The minimum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value. + :param ssl_maximum_version: + The maximum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value. + Not recommended to set to anything other than 'ssl.TLSVersion.MAXIMUM_SUPPORTED' which is the + default value. + :param cert_reqs: + Whether to require the certificate verification. This defaults to + ``ssl.CERT_REQUIRED``. + :param options: + Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, + ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``. + :param ciphers: + Which cipher suites to allow the server to select. Defaults to either system configured + ciphers if OpenSSL 1.1.1+, otherwise uses a secure default set of ciphers. + :param verify_flags: + The flags for certificate verification operations. These default to + ``ssl.VERIFY_X509_PARTIAL_CHAIN`` and ``ssl.VERIFY_X509_STRICT`` for Python 3.13+. + :returns: + Constructed SSLContext object with specified options + :rtype: SSLContext + """ + if SSLContext is None: + raise TypeError("Can't create an SSLContext object without an ssl module") + + # This means 'ssl_version' was specified as an exact value. + if ssl_version not in (None, PROTOCOL_TLS, PROTOCOL_TLS_CLIENT): + # Disallow setting 'ssl_version' and 'ssl_minimum|maximum_version' + # to avoid conflicts. + if ssl_minimum_version is not None or ssl_maximum_version is not None: + raise ValueError( + "Can't specify both 'ssl_version' and either " + "'ssl_minimum_version' or 'ssl_maximum_version'" + ) + + # 'ssl_version' is deprecated and will be removed in the future. + else: + # Use 'ssl_minimum_version' and 'ssl_maximum_version' instead. + ssl_minimum_version = _SSL_VERSION_TO_TLS_VERSION.get( + ssl_version, TLSVersion.MINIMUM_SUPPORTED + ) + ssl_maximum_version = _SSL_VERSION_TO_TLS_VERSION.get( + ssl_version, TLSVersion.MAXIMUM_SUPPORTED + ) + + # This warning message is pushing users to use 'ssl_minimum_version' + # instead of both min/max. Best practice is to only set the minimum version and + # keep the maximum version to be it's default value: 'TLSVersion.MAXIMUM_SUPPORTED' + warnings.warn( + "'ssl_version' option is deprecated and will be " + "removed in urllib3 v3.0. Instead use 'ssl_minimum_version'", + category=FutureWarning, + stacklevel=2, + ) + + context = SSLContext(PROTOCOL_TLS_CLIENT) + if ssl_minimum_version is not None: + context.minimum_version = ssl_minimum_version + else: # pyOpenSSL defaults to 'MINIMUM_SUPPORTED' so explicitly set TLSv1.2 here + context.minimum_version = TLSVersion.TLSv1_2 + + if ssl_maximum_version is not None: + context.maximum_version = ssl_maximum_version + + # Unless we're given ciphers defer to either system ciphers in + # the case of OpenSSL 1.1.1+ or use our own secure default ciphers. + if ciphers: + context.set_ciphers(ciphers) + + # Setting the default here, as we may have no ssl module on import + cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs + + if options is None: + options = 0 + # SSLv2 is easily broken and is considered harmful and dangerous + options |= OP_NO_SSLv2 + # SSLv3 has several problems and is now dangerous + options |= OP_NO_SSLv3 + # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ + # (issue #309) + options |= OP_NO_COMPRESSION + # TLSv1.2 only. Unless set explicitly, do not request tickets. + # This may save some bandwidth on wire, and although the ticket is encrypted, + # there is a risk associated with it being on wire, + # if the server is not rotating its ticketing keys properly. + options |= OP_NO_TICKET + + context.options |= options + + if verify_flags is None: + verify_flags = 0 + # In Python 3.13+ ssl.create_default_context() sets VERIFY_X509_PARTIAL_CHAIN + # and VERIFY_X509_STRICT so we do the same + if sys.version_info >= (3, 13): + verify_flags |= VERIFY_X509_PARTIAL_CHAIN + verify_flags |= VERIFY_X509_STRICT + + context.verify_flags |= verify_flags + + # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is + # necessary for conditional client cert authentication with TLS 1.3. + # The attribute is None for OpenSSL <= 1.1.0 or does not exist when using + # an SSLContext created by pyOpenSSL. + if getattr(context, "post_handshake_auth", None) is not None: + context.post_handshake_auth = True + + # The order of the below lines setting verify_mode and check_hostname + # matter due to safe-guards SSLContext has to prevent an SSLContext with + # check_hostname=True, verify_mode=NONE/OPTIONAL. + # We always set 'check_hostname=False' for pyOpenSSL so we rely on our own + # 'ssl.match_hostname()' implementation. + if cert_reqs == ssl.CERT_REQUIRED and not IS_PYOPENSSL: + context.verify_mode = cert_reqs + context.check_hostname = True + else: + context.check_hostname = False + context.verify_mode = cert_reqs + + context.hostname_checks_common_name = False + + if "SSLKEYLOGFILE" in os.environ: + sslkeylogfile = os.path.expandvars(os.environ.get("SSLKEYLOGFILE")) + else: + sslkeylogfile = None + if sslkeylogfile: + context.keylog_filename = sslkeylogfile + + return context + + +@typing.overload +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = ..., + certfile: str | None = ..., + cert_reqs: int | None = ..., + ca_certs: str | None = ..., + server_hostname: str | None = ..., + ssl_version: int | None = ..., + ciphers: str | None = ..., + ssl_context: ssl.SSLContext | None = ..., + ca_cert_dir: str | None = ..., + key_password: str | None = ..., + ca_cert_data: None | str | bytes = ..., + tls_in_tls: typing.Literal[False] = ..., +) -> ssl.SSLSocket: ... + + +@typing.overload +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = ..., + certfile: str | None = ..., + cert_reqs: int | None = ..., + ca_certs: str | None = ..., + server_hostname: str | None = ..., + ssl_version: int | None = ..., + ciphers: str | None = ..., + ssl_context: ssl.SSLContext | None = ..., + ca_cert_dir: str | None = ..., + key_password: str | None = ..., + ca_cert_data: None | str | bytes = ..., + tls_in_tls: bool = ..., +) -> ssl.SSLSocket | SSLTransportType: ... + + +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = None, + certfile: str | None = None, + cert_reqs: int | None = None, + ca_certs: str | None = None, + server_hostname: str | None = None, + ssl_version: int | None = None, + ciphers: str | None = None, + ssl_context: ssl.SSLContext | None = None, + ca_cert_dir: str | None = None, + key_password: str | None = None, + ca_cert_data: None | str | bytes = None, + tls_in_tls: bool = False, +) -> ssl.SSLSocket | SSLTransportType: + """ + All arguments except for server_hostname, ssl_context, tls_in_tls, ca_cert_data and + ca_cert_dir have the same meaning as they do when using + :func:`ssl.create_default_context`, :meth:`ssl.SSLContext.load_cert_chain`, + :meth:`ssl.SSLContext.set_ciphers` and :meth:`ssl.SSLContext.wrap_socket`. + + :param server_hostname: + When SNI is supported, the expected hostname of the certificate + :param ssl_context: + A pre-made :class:`SSLContext` object. If none is provided, one will + be created using :func:`create_urllib3_context`. + :param ciphers: + A string of ciphers we wish the client to support. + :param ca_cert_dir: + A directory containing CA certificates in multiple separate files, as + supported by OpenSSL's -CApath flag or the capath argument to + SSLContext.load_verify_locations(). + :param key_password: + Optional password if the keyfile is encrypted. + :param ca_cert_data: + Optional string containing CA certificates in PEM format suitable for + passing as the cadata parameter to SSLContext.load_verify_locations() + :param tls_in_tls: + Use SSLTransport to wrap the existing socket. + """ + context = ssl_context + if context is None: + # Note: This branch of code and all the variables in it are only used in tests. + # We should consider deprecating and removing this code. + context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) + + if ca_certs or ca_cert_dir or ca_cert_data: + try: + context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) + except OSError as e: + raise SSLError(e) from e + + elif ssl_context is None and hasattr(context, "load_default_certs"): + # try to load OS default certs; works well on Windows. + context.load_default_certs() + + # Attempt to detect if we get the goofy behavior of the + # keyfile being encrypted and OpenSSL asking for the + # passphrase via the terminal and instead error out. + if keyfile and key_password is None and _is_key_file_encrypted(keyfile): + raise SSLError("Client private key is encrypted, password is required") + + if certfile: + if key_password is None: + context.load_cert_chain(certfile, keyfile) + else: + context.load_cert_chain(certfile, keyfile, key_password) + + context.set_alpn_protocols(ALPN_PROTOCOLS) + + ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname) + return ssl_sock + + +def is_ipaddress(hostname: str | bytes) -> bool: + """Detects whether the hostname given is an IPv4 or IPv6 address. + Also detects IPv6 addresses with Zone IDs. + + :param str hostname: Hostname to examine. + :return: True if the hostname is an IP address, False otherwise. + """ + if isinstance(hostname, bytes): + # IDN A-label bytes are ASCII compatible. + hostname = hostname.decode("ascii") + return bool(_IPV4_RE.match(hostname) or _BRACELESS_IPV6_ADDRZ_RE.match(hostname)) + + +def _is_key_file_encrypted(key_file: str) -> bool: + """Detects if a key file is encrypted or not.""" + with open(key_file) as f: + for line in f: + # Look for Proc-Type: 4,ENCRYPTED + if "ENCRYPTED" in line: + return True + + return False + + +def _ssl_wrap_socket_impl( + sock: socket.socket, + ssl_context: ssl.SSLContext, + tls_in_tls: bool, + server_hostname: str | None = None, +) -> ssl.SSLSocket | SSLTransportType: + if tls_in_tls: + if not SSLTransport: + # Import error, ssl is not available. + raise ProxySchemeUnsupported( + "TLS in TLS requires support for the 'ssl' module" + ) + + SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context) + return SSLTransport(sock, ssl_context, server_hostname) + + return ssl_context.wrap_socket(sock, server_hostname=server_hostname) diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/ssl_match_hostname.py b/.venv/lib/python3.12/site-packages/urllib3/util/ssl_match_hostname.py new file mode 100644 index 0000000000000000000000000000000000000000..94994f25ae1570211c0b98353790f669ef4585fa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/util/ssl_match_hostname.py @@ -0,0 +1,153 @@ +"""The match_hostname() function from Python 3.5, essential when using SSL.""" + +# Note: This file is under the PSF license as the code comes from the python +# stdlib. http://docs.python.org/3/license.html +# It is modified to remove commonName support. + +from __future__ import annotations + +import ipaddress +import re +import typing +from ipaddress import IPv4Address, IPv6Address + +if typing.TYPE_CHECKING: + from .ssl_ import _TYPE_PEER_CERT_RET_DICT + +__version__ = "3.5.0.1" + + +class CertificateError(ValueError): + pass + + +def _dnsname_match( + dn: typing.Any, hostname: str, max_wildcards: int = 1 +) -> typing.Match[str] | None | bool: + """Matching according to RFC 6125, section 6.4.3 + + http://tools.ietf.org/html/rfc6125#section-6.4.3 + """ + pats = [] + if not dn: + return False + + # Ported from python3-syntax: + # leftmost, *remainder = dn.split(r'.') + parts = dn.split(r".") + leftmost = parts[0] + remainder = parts[1:] + + wildcards = leftmost.count("*") + if wildcards > max_wildcards: + # Issue #17980: avoid denials of service by refusing more + # than one wildcard per fragment. A survey of established + # policy among SSL implementations showed it to be a + # reasonable choice. + raise CertificateError( + "too many wildcards in certificate DNS name: " + repr(dn) + ) + + # speed up common case w/o wildcards + if not wildcards: + return bool(dn.lower() == hostname.lower()) + + # RFC 6125, section 6.4.3, subitem 1. + # The client SHOULD NOT attempt to match a presented identifier in which + # the wildcard character comprises a label other than the left-most label. + if leftmost == "*": + # When '*' is a fragment by itself, it matches a non-empty dotless + # fragment. + pats.append("[^.]+") + elif leftmost.startswith("xn--") or hostname.startswith("xn--"): + # RFC 6125, section 6.4.3, subitem 3. + # The client SHOULD NOT attempt to match a presented identifier + # where the wildcard character is embedded within an A-label or + # U-label of an internationalized domain name. + pats.append(re.escape(leftmost)) + else: + # Otherwise, '*' matches any dotless string, e.g. www* + pats.append(re.escape(leftmost).replace(r"\*", "[^.]*")) + + # add the remaining fragments, ignore any wildcards + for frag in remainder: + pats.append(re.escape(frag)) + + pat = re.compile(r"\A" + r"\.".join(pats) + r"\Z", re.IGNORECASE) + return pat.match(hostname) + + +def _ipaddress_match(ipname: str, host_ip: IPv4Address | IPv6Address) -> bool: + """Exact matching of IP addresses. + + RFC 9110 section 4.3.5: "A reference identity of IP-ID contains the decoded + bytes of the IP address. An IP version 4 address is 4 octets, and an IP + version 6 address is 16 octets. [...] A reference identity of type IP-ID + matches if the address is identical to an iPAddress value of the + subjectAltName extension of the certificate." + """ + # OpenSSL may add a trailing newline to a subjectAltName's IP address + # Divergence from upstream: ipaddress can't handle byte str + ip = ipaddress.ip_address(ipname.rstrip()) + return bool(ip.packed == host_ip.packed) + + +def match_hostname( + cert: _TYPE_PEER_CERT_RET_DICT | None, + hostname: str, + hostname_checks_common_name: bool = False, +) -> None: + """Verify that *cert* (in decoded format as returned by + SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 + rules are followed, but IP addresses are not accepted for *hostname*. + + CertificateError is raised on failure. On success, the function + returns nothing. + """ + if not cert: + raise ValueError( + "empty or no certificate, match_hostname needs a " + "SSL socket or SSL context with either " + "CERT_OPTIONAL or CERT_REQUIRED" + ) + + try: + host_ip = ipaddress.ip_address(hostname) + except ValueError: + # Not an IP address (common case) + host_ip = None + dnsnames = [] + san: tuple[tuple[str, str], ...] = cert.get("subjectAltName", ()) + key: str + value: str + for key, value in san: + if key == "DNS": + if host_ip is None and _dnsname_match(value, hostname): + return + dnsnames.append(value) + elif key == "IP Address": + if host_ip is not None and _ipaddress_match(value, host_ip): + return + dnsnames.append(value) + + # We only check 'commonName' if it's enabled and we're not verifying + # an IP address. IP addresses aren't valid within 'commonName'. + if hostname_checks_common_name and host_ip is None and not dnsnames: + for sub in cert.get("subject", ()): + for key, value in sub: + if key == "commonName": + if _dnsname_match(value, hostname): + return + dnsnames.append( + value + ) # Defensive: for older PyPy and OpenSSL versions + + if len(dnsnames) > 1: + raise CertificateError( + "hostname %r " + "doesn't match either of %s" % (hostname, ", ".join(map(repr, dnsnames))) + ) + elif len(dnsnames) == 1: + raise CertificateError(f"hostname {hostname!r} doesn't match {dnsnames[0]!r}") + else: + raise CertificateError("no appropriate subjectAltName fields were found") diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/ssltransport.py b/.venv/lib/python3.12/site-packages/urllib3/util/ssltransport.py new file mode 100644 index 0000000000000000000000000000000000000000..6d59bc3bce2489c3a0aa5bcb83b737dcf33c033b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/util/ssltransport.py @@ -0,0 +1,271 @@ +from __future__ import annotations + +import io +import socket +import ssl +import typing + +from ..exceptions import ProxySchemeUnsupported + +if typing.TYPE_CHECKING: + from typing_extensions import Self + + from .ssl_ import _TYPE_PEER_CERT_RET, _TYPE_PEER_CERT_RET_DICT + + +_WriteBuffer = typing.Union[bytearray, memoryview] +_ReturnValue = typing.TypeVar("_ReturnValue") + +SSL_BLOCKSIZE = 16384 + + +class SSLTransport: + """ + The SSLTransport wraps an existing socket and establishes an SSL connection. + + Contrary to Python's implementation of SSLSocket, it allows you to chain + multiple TLS connections together. It's particularly useful if you need to + implement TLS within TLS. + + The class supports most of the socket API operations. + """ + + @staticmethod + def _validate_ssl_context_for_tls_in_tls(ssl_context: ssl.SSLContext) -> None: + """ + Raises a ProxySchemeUnsupported if the provided ssl_context can't be used + for TLS in TLS. + + The only requirement is that the ssl_context provides the 'wrap_bio' + methods. + """ + + if not hasattr(ssl_context, "wrap_bio"): + raise ProxySchemeUnsupported( + "TLS in TLS requires SSLContext.wrap_bio() which isn't " + "available on non-native SSLContext" + ) + + def __init__( + self, + socket: socket.socket, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + suppress_ragged_eofs: bool = True, + ) -> None: + """ + Create an SSLTransport around socket using the provided ssl_context. + """ + self.incoming = ssl.MemoryBIO() + self.outgoing = ssl.MemoryBIO() + + self.suppress_ragged_eofs = suppress_ragged_eofs + self.socket = socket + + self.sslobj = ssl_context.wrap_bio( + self.incoming, self.outgoing, server_hostname=server_hostname + ) + + # Perform initial handshake. + self._ssl_io_loop(self.sslobj.do_handshake) + + def __enter__(self) -> Self: + return self + + def __exit__(self, *_: typing.Any) -> None: + self.close() + + def fileno(self) -> int: + return self.socket.fileno() + + def read(self, len: int = 1024, buffer: typing.Any | None = None) -> int | bytes: + return self._wrap_ssl_read(len, buffer) + + def recv(self, buflen: int = 1024, flags: int = 0) -> int | bytes: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to recv") + return self._wrap_ssl_read(buflen) + + def recv_into( + self, + buffer: _WriteBuffer, + nbytes: int | None = None, + flags: int = 0, + ) -> None | int | bytes: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to recv_into") + if nbytes is None: + nbytes = len(buffer) + return self.read(nbytes, buffer) + + def sendall(self, data: bytes, flags: int = 0) -> None: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to sendall") + count = 0 + with memoryview(data) as view, view.cast("B") as byte_view: + amount = len(byte_view) + while count < amount: + v = self.send(byte_view[count:]) + count += v + + def send(self, data: bytes, flags: int = 0) -> int: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to send") + return self._ssl_io_loop(self.sslobj.write, data) + + def makefile( + self, + mode: str, + buffering: int | None = None, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> typing.BinaryIO | typing.TextIO | socket.SocketIO: + """ + Python's httpclient uses makefile and buffered io when reading HTTP + messages and we need to support it. + + This is unfortunately a copy and paste of socket.py makefile with small + changes to point to the socket directly. + """ + if not set(mode) <= {"r", "w", "b"}: + raise ValueError(f"invalid mode {mode!r} (only r, w, b allowed)") + + writing = "w" in mode + reading = "r" in mode or not writing + assert reading or writing + binary = "b" in mode + rawmode = "" + if reading: + rawmode += "r" + if writing: + rawmode += "w" + raw = socket.SocketIO(self, rawmode) # type: ignore[arg-type] + self.socket._io_refs += 1 # type: ignore[attr-defined] + if buffering is None: + buffering = -1 + if buffering < 0: + buffering = io.DEFAULT_BUFFER_SIZE + if buffering == 0: + if not binary: + raise ValueError("unbuffered streams must be binary") + return raw + buffer: typing.BinaryIO + if reading and writing: + buffer = io.BufferedRWPair(raw, raw, buffering) # type: ignore[assignment] + elif reading: + buffer = io.BufferedReader(raw, buffering) + else: + assert writing + buffer = io.BufferedWriter(raw, buffering) + if binary: + return buffer + text = io.TextIOWrapper(buffer, encoding, errors, newline) + text.mode = mode # type: ignore[misc] + return text + + def unwrap(self) -> None: + self._ssl_io_loop(self.sslobj.unwrap) + + def close(self) -> None: + self.socket.close() + + @typing.overload + def getpeercert( + self, binary_form: typing.Literal[False] = ... + ) -> _TYPE_PEER_CERT_RET_DICT | None: ... + + @typing.overload + def getpeercert(self, binary_form: typing.Literal[True]) -> bytes | None: ... + + def getpeercert(self, binary_form: bool = False) -> _TYPE_PEER_CERT_RET: + return self.sslobj.getpeercert(binary_form) # type: ignore[return-value] + + def version(self) -> str | None: + return self.sslobj.version() + + def cipher(self) -> tuple[str, str, int] | None: + return self.sslobj.cipher() + + def selected_alpn_protocol(self) -> str | None: + return self.sslobj.selected_alpn_protocol() + + def shared_ciphers(self) -> list[tuple[str, str, int]] | None: + return self.sslobj.shared_ciphers() + + def compression(self) -> str | None: + return self.sslobj.compression() + + def settimeout(self, value: float | None) -> None: + self.socket.settimeout(value) + + def gettimeout(self) -> float | None: + return self.socket.gettimeout() + + def _decref_socketios(self) -> None: + self.socket._decref_socketios() # type: ignore[attr-defined] + + def _wrap_ssl_read(self, len: int, buffer: bytearray | None = None) -> int | bytes: + try: + return self._ssl_io_loop(self.sslobj.read, len, buffer) + except ssl.SSLError as e: + if e.errno == ssl.SSL_ERROR_EOF and self.suppress_ragged_eofs: + return 0 # eof, return 0. + else: + raise + + # func is sslobj.do_handshake or sslobj.unwrap + @typing.overload + def _ssl_io_loop(self, func: typing.Callable[[], None]) -> None: ... + + # func is sslobj.write, arg1 is data + @typing.overload + def _ssl_io_loop(self, func: typing.Callable[[bytes], int], arg1: bytes) -> int: ... + + # func is sslobj.read, arg1 is len, arg2 is buffer + @typing.overload + def _ssl_io_loop( + self, + func: typing.Callable[[int, bytearray | None], bytes], + arg1: int, + arg2: bytearray | None, + ) -> bytes: ... + + def _ssl_io_loop( + self, + func: typing.Callable[..., _ReturnValue], + arg1: None | bytes | int = None, + arg2: bytearray | None = None, + ) -> _ReturnValue: + """Performs an I/O loop between incoming/outgoing and the socket.""" + should_loop = True + ret = None + + while should_loop: + errno = None + try: + if arg1 is None and arg2 is None: + ret = func() + elif arg2 is None: + ret = func(arg1) + else: + ret = func(arg1, arg2) + except ssl.SSLError as e: + if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): + # WANT_READ, and WANT_WRITE are expected, others are not. + raise e + errno = e.errno + + buf = self.outgoing.read() + self.socket.sendall(buf) + + if errno is None: + should_loop = False + elif errno == ssl.SSL_ERROR_WANT_READ: + buf = self.socket.recv(SSL_BLOCKSIZE) + if buf: + self.incoming.write(buf) + else: + self.incoming.write_eof() + return typing.cast(_ReturnValue, ret) diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/timeout.py b/.venv/lib/python3.12/site-packages/urllib3/util/timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb1be11d9cb06900dd82ecebd06aa6a7c5de916 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/util/timeout.py @@ -0,0 +1,275 @@ +from __future__ import annotations + +import time +import typing +from enum import Enum +from socket import getdefaulttimeout + +from ..exceptions import TimeoutStateError + +if typing.TYPE_CHECKING: + from typing import Final + + +class _TYPE_DEFAULT(Enum): + # This value should never be passed to socket.settimeout() so for safety we use a -1. + # socket.settimout() raises a ValueError for negative values. + token = -1 + + +_DEFAULT_TIMEOUT: Final[_TYPE_DEFAULT] = _TYPE_DEFAULT.token + +_TYPE_TIMEOUT = typing.Optional[typing.Union[float, _TYPE_DEFAULT]] + + +class Timeout: + """Timeout configuration. + + Timeouts can be defined as a default for a pool: + + .. code-block:: python + + import urllib3 + + timeout = urllib3.util.Timeout(connect=2.0, read=7.0) + + http = urllib3.PoolManager(timeout=timeout) + + resp = http.request("GET", "https://example.com/") + + print(resp.status) + + Or per-request (which overrides the default for the pool): + + .. code-block:: python + + response = http.request("GET", "https://example.com/", timeout=Timeout(10)) + + Timeouts can be disabled by setting all the parameters to ``None``: + + .. code-block:: python + + no_timeout = Timeout(connect=None, read=None) + response = http.request("GET", "https://example.com/", timeout=no_timeout) + + + :param total: + This combines the connect and read timeouts into one; the read timeout + will be set to the time leftover from the connect attempt. In the + event that both a connect timeout and a total are specified, or a read + timeout and a total are specified, the shorter timeout will be applied. + + Defaults to None. + + :type total: int, float, or None + + :param connect: + The maximum amount of time (in seconds) to wait for a connection + attempt to a server to succeed. Omitting the parameter will default the + connect timeout to the system default, probably `the global default + timeout in socket.py + `_. + None will set an infinite timeout for connection attempts. + + :type connect: int, float, or None + + :param read: + The maximum amount of time (in seconds) to wait between consecutive + read operations for a response from the server. Omitting the parameter + will default the read timeout to the system default, probably `the + global default timeout in socket.py + `_. + None will set an infinite timeout. + + :type read: int, float, or None + + .. note:: + + Many factors can affect the total amount of time for urllib3 to return + an HTTP response. + + For example, Python's DNS resolver does not obey the timeout specified + on the socket. Other factors that can affect total request time include + high CPU load, high swap, the program running at a low priority level, + or other behaviors. + + In addition, the read and total timeouts only measure the time between + read operations on the socket connecting the client and the server, + not the total amount of time for the request to return a complete + response. For most requests, the timeout is raised because the server + has not sent the first byte in the specified time. This is not always + the case; if a server streams one byte every fifteen seconds, a timeout + of 20 seconds will not trigger, even though the request will take + several minutes to complete. + """ + + #: A sentinel object representing the default timeout value + DEFAULT_TIMEOUT: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT + + def __init__( + self, + total: _TYPE_TIMEOUT = None, + connect: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + read: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + ) -> None: + self._connect = self._validate_timeout(connect, "connect") + self._read = self._validate_timeout(read, "read") + self.total = self._validate_timeout(total, "total") + self._start_connect: float | None = None + + def __repr__(self) -> str: + return f"{type(self).__name__}(connect={self._connect!r}, read={self._read!r}, total={self.total!r})" + + # __str__ provided for backwards compatibility + __str__ = __repr__ + + @staticmethod + def resolve_default_timeout(timeout: _TYPE_TIMEOUT) -> float | None: + return getdefaulttimeout() if timeout is _DEFAULT_TIMEOUT else timeout + + @classmethod + def _validate_timeout(cls, value: _TYPE_TIMEOUT, name: str) -> _TYPE_TIMEOUT: + """Check that a timeout attribute is valid. + + :param value: The timeout value to validate + :param name: The name of the timeout attribute to validate. This is + used to specify in error messages. + :return: The validated and casted version of the given value. + :raises ValueError: If it is a numeric value less than or equal to + zero, or the type is not an integer, float, or None. + """ + if value is None or value is _DEFAULT_TIMEOUT: + return value + + if isinstance(value, bool): + raise ValueError( + "Timeout cannot be a boolean value. It must " + "be an int, float or None." + ) + try: + float(value) + except (TypeError, ValueError): + raise ValueError( + "Timeout value %s was %s, but it must be an " + "int, float or None." % (name, value) + ) from None + + try: + if value <= 0: + raise ValueError( + "Attempted to set %s timeout to %s, but the " + "timeout cannot be set to a value less " + "than or equal to 0." % (name, value) + ) + except TypeError: + raise ValueError( + "Timeout value %s was %s, but it must be an " + "int, float or None." % (name, value) + ) from None + + return value + + @classmethod + def from_float(cls, timeout: _TYPE_TIMEOUT) -> Timeout: + """Create a new Timeout from a legacy timeout value. + + The timeout value used by httplib.py sets the same timeout on the + connect(), and recv() socket requests. This creates a :class:`Timeout` + object that sets the individual timeouts to the ``timeout`` value + passed to this function. + + :param timeout: The legacy timeout value. + :type timeout: integer, float, :attr:`urllib3.util.Timeout.DEFAULT_TIMEOUT`, or None + :return: Timeout object + :rtype: :class:`Timeout` + """ + return Timeout(read=timeout, connect=timeout) + + def clone(self) -> Timeout: + """Create a copy of the timeout object + + Timeout properties are stored per-pool but each request needs a fresh + Timeout object to ensure each one has its own start/stop configured. + + :return: a copy of the timeout object + :rtype: :class:`Timeout` + """ + # We can't use copy.deepcopy because that will also create a new object + # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to + # detect the user default. + return Timeout(connect=self._connect, read=self._read, total=self.total) + + def start_connect(self) -> float: + """Start the timeout clock, used during a connect() attempt + + :raises urllib3.exceptions.TimeoutStateError: if you attempt + to start a timer that has been started already. + """ + if self._start_connect is not None: + raise TimeoutStateError("Timeout timer has already been started.") + self._start_connect = time.monotonic() + return self._start_connect + + def get_connect_duration(self) -> float: + """Gets the time elapsed since the call to :meth:`start_connect`. + + :return: Elapsed time in seconds. + :rtype: float + :raises urllib3.exceptions.TimeoutStateError: if you attempt + to get duration for a timer that hasn't been started. + """ + if self._start_connect is None: + raise TimeoutStateError( + "Can't get connect duration for timer that has not started." + ) + return time.monotonic() - self._start_connect + + @property + def connect_timeout(self) -> _TYPE_TIMEOUT: + """Get the value to use when setting a connection timeout. + + This will be a positive float or integer, the value None + (never timeout), or the default system timeout. + + :return: Connect timeout. + :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None + """ + if self.total is None: + return self._connect + + if self._connect is None or self._connect is _DEFAULT_TIMEOUT: + return self.total + + return min(self._connect, self.total) # type: ignore[type-var] + + @property + def read_timeout(self) -> float | None: + """Get the value for the read timeout. + + This assumes some time has elapsed in the connection timeout and + computes the read timeout appropriately. + + If self.total is set, the read timeout is dependent on the amount of + time taken by the connect timeout. If the connection time has not been + established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be + raised. + + :return: Value to use for the read timeout. + :rtype: int, float or None + :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` + has not yet been called on this object. + """ + if ( + self.total is not None + and self.total is not _DEFAULT_TIMEOUT + and self._read is not None + and self._read is not _DEFAULT_TIMEOUT + ): + # In case the connect timeout has not yet been established. + if self._start_connect is None: + return self._read + return max(0, min(self.total - self.get_connect_duration(), self._read)) + elif self.total is not None and self.total is not _DEFAULT_TIMEOUT: + return max(0, self.total - self.get_connect_duration()) + else: + return self.resolve_default_timeout(self._read) diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/url.py b/.venv/lib/python3.12/site-packages/urllib3/util/url.py new file mode 100644 index 0000000000000000000000000000000000000000..8a9f7146842e2d2a5dacf08a21d56739d17d37ab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/util/url.py @@ -0,0 +1,577 @@ +from __future__ import annotations + +import re +import typing +from functools import partial +from urllib.parse import unquote as _unquote + +from ..exceptions import LocationParseError +from .util import to_str + +# We only want to normalize urls with an HTTP(S) scheme. +# urllib3 infers URLs without a scheme (None) to be http. +_NORMALIZABLE_SCHEMES = ("http", "https", None) + +# Almost all of these patterns were derived from the +# 'rfc3986' module: https://github.com/python-hyper/rfc3986 +_PERCENT_RE = re.compile(r"%[a-fA-F0-9]{2}") +_HOST_PERCENT_RE = re.compile(r"%[a-fA-F0-9]{2}|%") +_SCHEME_RE = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+-]*:|/)") +_HOST_INVALID_CHAR_RE = re.compile(r"[\x00-\x20\x7f]") +_URI_RE = re.compile( + r"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?" + r"(?://([^\\/?#]*))?" + r"([^?#]*)" + r"(?:\?([^#]*))?" + r"(?:#(.*))?$", + re.UNICODE | re.DOTALL, +) + +_IPV4_PAT = r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}" +_HEX_PAT = "[0-9A-Fa-f]{1,4}" +_LS32_PAT = "(?:{hex}:{hex}|{ipv4})".format(hex=_HEX_PAT, ipv4=_IPV4_PAT) +_subs = {"hex": _HEX_PAT, "ls32": _LS32_PAT} +_variations = [ + # 6( h16 ":" ) ls32 + "(?:%(hex)s:){6}%(ls32)s", + # "::" 5( h16 ":" ) ls32 + "::(?:%(hex)s:){5}%(ls32)s", + # [ h16 ] "::" 4( h16 ":" ) ls32 + "(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s", + # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + "(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s", + # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + "(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s", + # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + "(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s", + # [ *4( h16 ":" ) h16 ] "::" ls32 + "(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s", + # [ *5( h16 ":" ) h16 ] "::" h16 + "(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s", + # [ *6( h16 ":" ) h16 ] "::" + "(?:(?:%(hex)s:){0,6}%(hex)s)?::", +] + +_UNRESERVED_PAT = r"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._\-~" +_IPV6_PAT = "(?:" + "|".join([x % _subs for x in _variations]) + ")" +_ZONE_ID_PAT = "(?:%25|%)(?:[" + _UNRESERVED_PAT + "]|%[a-fA-F0-9]{2})+" +_IPV6_ADDRZ_PAT = r"\[" + _IPV6_PAT + r"(?:" + _ZONE_ID_PAT + r")?\]" +_REG_NAME_PAT = r"(?:[^\[\]%:/?#]|%[a-fA-F0-9]{2})*" +_TARGET_RE = re.compile(r"^(/[^?#]*)(?:\?([^#]*))?(?:#.*)?$") + +_IPV4_RE = re.compile( + r"^(?:0[xX][0-9a-fA-F]+|[0-9]+)(?:\.(?:0[xX][0-9a-fA-F]+|[0-9]+)){0,3}$" +) +_IPV6_RE = re.compile("^" + _IPV6_PAT + "$") +_IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT + "$") +_BRACELESS_IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT[2:-2] + "$") +_ZONE_ID_RE = re.compile("(" + _ZONE_ID_PAT + r")\]$") + +_HOST_PORT_PAT = ("^(%s|%s|%s)(?::0*?(|0|[1-9][0-9]{0,4}))?$") % ( + _REG_NAME_PAT, + _IPV4_PAT, + _IPV6_ADDRZ_PAT, +) +_HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL) + +_UNRESERVED_CHARS = set( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~" +) +_SUB_DELIM_CHARS = set("!$&'()*+,;=") +_USERINFO_CHARS = _UNRESERVED_CHARS | _SUB_DELIM_CHARS | {":"} +_PATH_CHARS = _USERINFO_CHARS | {"@", "/"} +_QUERY_CHARS = _FRAGMENT_CHARS = _PATH_CHARS | {"?"} + + +class Url( + typing.NamedTuple( + "Url", + [ + ("scheme", typing.Optional[str]), + ("auth", typing.Optional[str]), + ("host", typing.Optional[str]), + ("port", typing.Optional[int]), + ("path", typing.Optional[str]), + ("query", typing.Optional[str]), + ("fragment", typing.Optional[str]), + ], + ) +): + """ + Data structure for representing an HTTP URL. Used as a return value for + :func:`parse_url`. Both the scheme and host are normalized as they are + both case-insensitive according to RFC 3986. + + :param auth: User information as defined in RFC 3986 3.2.1. This + component is kept percent-encoded. Use :attr:`auth_decoded` or + :attr:`auth_decoded_joined` to get the decoded form. + """ + + def __new__( # type: ignore[no-untyped-def] + cls, + scheme: str | None = None, + auth: str | None = None, + host: str | None = None, + port: int | None = None, + path: str | None = None, + query: str | None = None, + fragment: str | None = None, + ): + if path and not path.startswith("/"): + path = "/" + path + if scheme is not None: + scheme = scheme.lower() + return super().__new__(cls, scheme, auth, host, port, path, query, fragment) + + @property + def auth_decoded(self) -> tuple[None, None] | tuple[str, str | None]: + """ + User information with %-escapes decoded as UTF-8, returned as a + ``(username, password)`` tuple. + + Both values are ``None`` if ``auth`` is ``None``. + ``password`` is ``None`` if not present in the auth component. + """ + if self.auth is None: + return None, None + username, sep, password = self.auth.partition(":") + return ( + _unquote(username, encoding="utf-8"), + _unquote(password, encoding="utf-8") if sep else None, + ) + + @property + def auth_decoded_joined(self) -> str | None: + """ + User information with %-escapes decoded as UTF-8, as a string + prepared for encoding into an 'authorization: basic ...' header. + + This property does not choose the encoding used for an + 'authorization: basic ...' header. Use the ``basic_auth_encoding`` or + ``proxy_basic_auth_encoding`` parameters of + :func:`urllib3.util.make_headers` when converting the returned string + into Basic authentication bytes. + + This is a convenience property that joins the username and + password with a colon, if both are present. + If only the username is present, a trailing colon is still + appended. + If ``auth`` is ``None``, this returns ``None``. + """ + username, password = self.auth_decoded + if username is None: + return None + return f"{username}:{password or ''}" + + @property + def hostname(self) -> str | None: + """For backwards-compatibility with urlparse. We're nice like that.""" + return self.host + + @property + def request_uri(self) -> str: + """Absolute path including the query string.""" + uri = self.path or "/" + + if self.query is not None: + uri += "?" + self.query + + return uri + + @property + def authority(self) -> str | None: + """ + Authority component as defined in RFC 3986 3.2. + This includes userinfo (auth), host and port. + + i.e. + userinfo@host:port + """ + userinfo = self.auth + netloc = self.netloc + if netloc is None or userinfo is None: + return netloc + else: + return f"{userinfo}@{netloc}" + + @property + def netloc(self) -> str | None: + """ + Network location including host and port. + + If you need the equivalent of urllib.parse's ``netloc``, + use the ``authority`` property instead. + """ + if self.host is None: + return None + if self.port is not None: + return f"{self.host}:{self.port}" + return self.host + + @property + def url(self) -> str: + """ + Convert self into a url + + This function should more or less round-trip with :func:`.parse_url`. The + returned url may not be exactly the same as the url inputted to + :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls + with a blank port will have : removed). + + Example: + + .. code-block:: python + + import urllib3 + + U = urllib3.util.parse_url("https://google.com/mail/") + + print(U.url) + # "https://google.com/mail/" + + print( urllib3.util.Url("https", "username:password", + "host.com", 80, "/path", "query", "fragment" + ).url + ) + # "https://username:password@host.com:80/path?query#fragment" + """ + scheme, auth, host, port, path, query, fragment = self + url = "" + + # We use "is not None" we want things to happen with empty strings (or 0 port) + if scheme is not None: + url += scheme + "://" + if auth is not None: + url += auth + "@" + if host is not None: + url += host + if port is not None: + url += ":" + str(port) + if path is not None: + url += path + if query is not None: + url += "?" + query + if fragment is not None: + url += "#" + fragment + + return url + + def __str__(self) -> str: + return self.url + + +@typing.overload +def _encode_invalid_chars( + component: str, allowed_chars: typing.Container[str] +) -> str: # Abstract + ... + + +@typing.overload +def _encode_invalid_chars( + component: None, allowed_chars: typing.Container[str] +) -> None: # Abstract + ... + + +def _encode_invalid_chars( + component: str | None, allowed_chars: typing.Container[str] +) -> str | None: + """Percent-encodes a URI component without reapplying + onto an already percent-encoded component. + """ + if component is None: + return component + + component = to_str(component) + + # Fast path: an ASCII component that consists only of allowed characters + # and contains no '%' needs neither encoding nor percent-normalization. + # Components containing '%' always take the general path below because + # how '%' is treated depends on whether the whole component is already + # percent-encoded. + if ( + "%" not in component + and component.isascii() + and all(map(allowed_chars.__contains__, component)) + ): + return component + + # Normalize existing percent-encoded bytes. + # Try to see if the component we're encoding is already percent-encoded + # so we can skip all '%' characters but still encode all others. + component, percent_encodings = _PERCENT_RE.subn( + lambda match: match.group(0).upper(), component + ) + + uri_bytes = component.encode("utf-8", "surrogatepass") + is_percent_encoded = percent_encodings == uri_bytes.count(b"%") + encoded_component = bytearray() + + # Iterating over bytes yields integers; 0x25 is '%'. + for byte_ord in uri_bytes: + if (is_percent_encoded and byte_ord == 0x25) or ( + byte_ord < 128 and chr(byte_ord) in allowed_chars + ): + encoded_component.append(byte_ord) + else: + encoded_component += b"%%%02X" % byte_ord + + return encoded_component.decode() + + +def _remove_path_dot_segments(path: str) -> str: + # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code + segments = path.split("/") # Turn the path into a list of segments + output = [] # Initialize the variable to use to store output + + for segment in segments: + # '.' is the current directory, so ignore it, it is superfluous + if segment == ".": + continue + # Anything other than '..', should be appended to the output + if segment != "..": + output.append(segment) + # In this case segment == '..', if we can, we should pop the last + # element + elif output: + output.pop() + + # If the path starts with '/' and the output is empty or the first string + # is non-empty + if path.startswith("/") and (not output or output[0]): + output.insert(0, "") + + # If the path starts with '/.' or '/..' ensure we add one more empty + # string to add a trailing '/' + if path.endswith(("/.", "/..")): + output.append("") + + return "/".join(output) + + +@typing.overload +def _normalize_host(host: None, scheme: str | None) -> None: ... + + +@typing.overload +def _normalize_host(host: str, scheme: str | None) -> str: ... + + +def _normalize_host(host: str | None, scheme: str | None) -> str | None: + if host: + invalid_host_char = _HOST_INVALID_CHAR_RE.search(host) + if invalid_host_char: + raise LocationParseError( + f"Host {host!r} contains invalid character " + f"{invalid_host_char.group()!r}" + ) + if scheme in _NORMALIZABLE_SCHEMES: + is_ipv6 = _IPV6_ADDRZ_RE.match(host) + if is_ipv6: + # IPv6 hosts of the form 'a::b%zone' are encoded in a URL as + # such per RFC 6874: 'a::b%25zone'. Unquote the ZoneID + # separator as necessary to return a valid RFC 4007 scoped IP. + match = _ZONE_ID_RE.search(host) + if match: + start, end = match.span(1) + zone_id = host[start:end] + + if zone_id.startswith("%25") and zone_id != "%25": + zone_id = zone_id[3:] + else: + zone_id = zone_id[1:] + zone_id = _PERCENT_RE.sub( + partial(_normalize_zone_id_percent_encoding, error_host=host), + zone_id, + ) + zone_id = _encode_invalid_chars(zone_id, _UNRESERVED_CHARS) + return f"{host[:start].lower()}%{zone_id}{host[end:]}" + else: + return host.lower() + elif not _IPV4_RE.match(host): + if "%" in host: + host = _HOST_PERCENT_RE.sub(_normalize_host_percent_encoding, host) + return to_str( + b".".join([_idna_encode(label) for label in host.split(".")]), + "ascii", + ) + return host + + +def _decode_percent_encoding(match: re.Match[str], *, error_host: str) -> str: + percent_encoded_octet = match.group(0) + decoded_octet = chr(int(percent_encoded_octet[1:], 16)) + # Keep this narrower than _HOST_INVALID_CHAR_RE because "%20" is valid + # percent-encoding and remains encoded. + if decoded_octet < "\x20" or decoded_octet == "\x7f": + raise LocationParseError( + f"Host {error_host!r} contains invalid percent-encoded " + f"control character {percent_encoded_octet!r}" + ) + return decoded_octet + + +def _normalize_host_percent_encoding(match: re.Match[str]) -> str: + # Reject invalid percent encodings + if match.group(0) == "%": + raise LocationParseError(f"{match.string!r} is not a valid host") + decoded_octet = _decode_percent_encoding(match, error_host=match.string) + if decoded_octet in _UNRESERVED_CHARS: + return decoded_octet + return match.group(0).upper() + + +def _normalize_zone_id_percent_encoding( + match: re.Match[str], *, error_host: str +) -> str: + _decode_percent_encoding(match, error_host=error_host) + return match.group(0).upper() + + +def _idna_encode(name: str) -> bytes: + if not name.isascii(): + try: + import idna + except ImportError: + raise LocationParseError( + "Unable to parse URL without the 'idna' module" + ) from None + + try: + return idna.encode(name.lower(), strict=True, std3_rules=True) + except idna.IDNAError: + raise LocationParseError( + f"Name '{name}' is not a valid IDNA label" + ) from None + + return _PERCENT_RE.sub(lambda match: match.group(0).upper(), name.lower()).encode( + "ascii" + ) + + +def _encode_target(target: str) -> str: + """Percent-encodes a request target so that there are no invalid characters + + Pre-condition for this function is that 'target' must start with '/'. + If that is the case then _TARGET_RE will always produce a match. + """ + match = _TARGET_RE.match(target) + if not match: # Defensive: + raise LocationParseError(f"{target!r} is not a valid request URI") + + path, query = match.groups() + encoded_target = _encode_invalid_chars(path, _PATH_CHARS) + if query is not None: + query = _encode_invalid_chars(query, _QUERY_CHARS) + encoded_target += "?" + query + return encoded_target + + +def parse_url(url: str) -> Url: + """ + Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is + performed to parse incomplete urls. Fields not provided will be None. + This parser is RFC 3986 and RFC 6874 compliant. + + The parser logic and helper functions are based heavily on + work done in the ``rfc3986`` module. + + :param str url: URL to parse into a :class:`.Url` namedtuple. + + Partly backwards-compatible with :mod:`urllib.parse`. + + Example: + + .. code-block:: python + + import urllib3 + + print( urllib3.util.parse_url('http://google.com/mail/')) + # Url(scheme='http', host='google.com', port=None, path='/mail/', ...) + + print( urllib3.util.parse_url('google.com:80')) + # Url(scheme=None, host='google.com', port=80, path=None, ...) + + print( urllib3.util.parse_url('/foo?bar')) + # Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) + """ + if not url: + # Empty + return Url() + + if not _SCHEME_RE.search(url): + url = "//" + url + + scheme: str | None + authority: str | None + auth: str | None + host: str | None + port: str | None + port_int: int | None + path: str | None + query: str | None + fragment: str | None + + scheme, authority, path, query, fragment = _URI_RE.match(url).groups() # type: ignore[union-attr] + normalize_uri = scheme is None or scheme.lower() in _NORMALIZABLE_SCHEMES + + if scheme: + scheme = scheme.lower() + + if authority: + auth, _, host_port = authority.rpartition("@") + auth = auth or None + host_port_match = _HOST_PORT_RE.fullmatch(host_port) + if not host_port_match: + invalid_host_char = _HOST_INVALID_CHAR_RE.search(host_port) + if invalid_host_char: + raise LocationParseError( + f"Host {host_port!r} contains invalid character " + f"{invalid_host_char.group()!r}" + ) + raise LocationParseError(f"{host_port!r} is not a valid host or port") + host, port = host_port_match.groups() + if auth and normalize_uri: + auth = _encode_invalid_chars(auth, _USERINFO_CHARS) + if port == "": + port = None + else: + auth, host, port = None, None, None + + if port is not None: + port_int = int(port) + if not (0 <= port_int <= 65535): + raise LocationParseError(url) + else: + port_int = None + + host = _normalize_host(host, scheme) + + if normalize_uri and path: + path = _remove_path_dot_segments(path) + path = _encode_invalid_chars(path, _PATH_CHARS) + if normalize_uri and query: + query = _encode_invalid_chars(query, _QUERY_CHARS) + if normalize_uri and fragment: + fragment = _encode_invalid_chars(fragment, _FRAGMENT_CHARS) + + # For the sake of backwards compatibility we put empty + # string values for path if there are any defined values + # beyond the path in the URL. + # TODO: Remove this when we break backwards compatibility. + if not path: + if query is not None or fragment is not None: + path = "" + else: + path = None + + return Url( + scheme=scheme, + auth=auth, + host=host, + port=port_int, + path=path, + query=query, + fragment=fragment, + ) diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/util.py b/.venv/lib/python3.12/site-packages/urllib3/util/util.py new file mode 100644 index 0000000000000000000000000000000000000000..35c77e4025842f548565334a3c04cba90f9283d6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/util/util.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import typing +from types import TracebackType + + +def to_bytes( + x: str | bytes, encoding: str | None = None, errors: str | None = None +) -> bytes: + if isinstance(x, bytes): + return x + elif not isinstance(x, str): + raise TypeError(f"not expecting type {type(x).__name__}") + if encoding or errors: + return x.encode(encoding or "utf-8", errors=errors or "strict") + return x.encode() + + +def to_str( + x: str | bytes, encoding: str | None = None, errors: str | None = None +) -> str: + if isinstance(x, str): + return x + elif not isinstance(x, bytes): + raise TypeError(f"not expecting type {type(x).__name__}") + if encoding or errors: + return x.decode(encoding or "utf-8", errors=errors or "strict") + return x.decode() + + +def reraise( + tp: type[BaseException] | None, + value: BaseException, + tb: TracebackType | None = None, +) -> typing.NoReturn: + try: + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + finally: + value = None # type: ignore[assignment] + tb = None diff --git a/.venv/lib/python3.12/site-packages/urllib3/util/wait.py b/.venv/lib/python3.12/site-packages/urllib3/util/wait.py new file mode 100644 index 0000000000000000000000000000000000000000..aeca0c7ad5b232eeb1ad9c43d315bd1d74eaed9a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/urllib3/util/wait.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import select +import socket +from functools import partial + +__all__ = ["wait_for_read", "wait_for_write"] + + +# How should we wait on sockets? +# +# There are two types of APIs you can use for waiting on sockets: the fancy +# modern stateful APIs like epoll/kqueue, and the older stateless APIs like +# select/poll. The stateful APIs are more efficient when you have a lots of +# sockets to keep track of, because you can set them up once and then use them +# lots of times. But we only ever want to wait on a single socket at a time +# and don't want to keep track of state, so the stateless APIs are actually +# more efficient. So we want to use select() or poll(). +# +# Now, how do we choose between select() and poll()? On traditional Unixes, +# select() has a strange calling convention that makes it slow, or fail +# altogether, for high-numbered file descriptors. The point of poll() is to fix +# that, so on Unixes, we prefer poll(). +# +# On Windows, there is no poll() (or at least Python doesn't provide a wrapper +# for it), but that's OK, because on Windows, select() doesn't have this +# strange calling convention; plain select() works fine. +# +# So: on Windows we use select(), and everywhere else we use poll(). We also +# fall back to select() in case poll() is somehow broken or missing. + + +def select_wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + if not read and not write: + raise RuntimeError("must specify at least one of read=True, write=True") + rcheck = [] + wcheck = [] + if read: + rcheck.append(sock) + if write: + wcheck.append(sock) + # When doing a non-blocking connect, most systems signal success by + # marking the socket writable. Windows, though, signals success by marked + # it as "exceptional". We paper over the difference by checking the write + # sockets for both conditions. (The stdlib selectors module does the same + # thing.) + fn = partial(select.select, rcheck, wcheck, wcheck) + rready, wready, xready = fn(timeout) + return bool(rready or wready or xready) + + +def poll_wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + if not read and not write: + raise RuntimeError("must specify at least one of read=True, write=True") + mask = 0 + if read: + mask |= select.POLLIN + if write: + mask |= select.POLLOUT + poll_obj = select.poll() + poll_obj.register(sock, mask) + + # For some reason, poll() takes timeout in milliseconds + def do_poll(t: float | None) -> list[tuple[int, int]]: + if t is not None: + t *= 1000 + return poll_obj.poll(t) + + return bool(do_poll(timeout)) + + +def _have_working_poll() -> bool: + # Apparently some systems have a select.poll that fails as soon as you try + # to use it, either due to strange configuration or broken monkeypatching + # from libraries like eventlet/greenlet. + try: + poll_obj = select.poll() + poll_obj.poll(0) + except (AttributeError, OSError): + return False + else: + return True + + +def wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + # We delay choosing which implementation to use until the first time we're + # called. We could do it at import time, but then we might make the wrong + # decision if someone goes wild with monkeypatching select.poll after + # we're imported. + global wait_for_socket + if _have_working_poll(): + wait_for_socket = poll_wait_for_socket + elif hasattr(select, "select"): + wait_for_socket = select_wait_for_socket + return wait_for_socket(sock, read, write, timeout) + + +def wait_for_read(sock: socket.socket, timeout: float | None = None) -> bool: + """Waits for reading to be available on a given socket. + Returns True if the socket is readable, or False if the timeout expired. + """ + return wait_for_socket(sock, read=True, timeout=timeout) + + +def wait_for_write(sock: socket.socket, timeout: float | None = None) -> bool: + """Waits for writing to be available on a given socket. + Returns True if the socket is readable, or False if the timeout expired. + """ + return wait_for_socket(sock, write=True, timeout=timeout) diff --git a/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/METADATA b/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..e9b937da36468912d186169cb09fda8cdf82d421 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/METADATA @@ -0,0 +1,589 @@ +Metadata-Version: 2.5 +Name: wcwidth +Version: 0.8.5 +Summary: Measures the displayed width of unicode strings in a terminal +Project-URL: Homepage, https://github.com/jquast/wcwidth +Author-email: Jeff Quast +License-Expression: MIT +License-File: LICENSE +Keywords: cjk,combining,console,eastasian,emoji,emulator,terminal,unicode,wcswidth,wcwidth,xterm +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Natural Language :: English +Classifier: Operating System :: POSIX +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 +Classifier: Topic :: Software Development :: Internationalization +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Localization +Classifier: Topic :: Terminals +Classifier: Typing :: Typed +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst + +|pypi_downloads| |codecov| |license| + +============ +Introduction +============ + +This Python library is mainly for CLI/TUI programs that carefully produce output for Terminals. + +See page libwcwidth_ about the portable C11 library. + +Installation +------------ + +The stable version of this package is maintained on pypi, install or upgrade, using pip:: + + pip install --upgrade wcwidth + +Problem +------- + +All Python string-formatting functions, `textwrap.wrap()`_, `str.ljust()`_, `str.rjust()`_, and +`str.center()`_ **incorrectly** measure the displayed width of a string as equal to the number of +their codepoints. + +Some examples of **incorrect results**: + +.. code-block:: python + + >>> # result consumes 16 total cells, 11 expected, + >>> 'コンニチハ'.rjust(11, 'X') + 'XXXXXXコンニチハ' + + >>> # combining acute accent: result consumes 5 total cells, 6 expected, + >>> 'cafe\u0301'.center(6, 'X') + 'caféX' + +Solution +-------- + +The lowest-level functions in this library are derived from POSIX.1-2001 and POSIX.1-2008 +`wcwidth(3)`_ and `wcswidth(3)`_, which this library precisely copies by interface as `wcwidth()`_ +and `wcswidth()`_. These functions return -1 when C0 and C1 control codes are present. + +An easy-to-use `width()`_ function is provided as a wrapper of `wcswidth()`_ that is also capable of +measuring most terminal control codes and sequences, like colors, bold, tabstops, and horizontal +cursor movement. `width()`_ argument ``term_program`` may provide more accurate terminal measurement +Corrections_ as a wrapper of `wcstwidth()`_. + +Text-justification is solved by the sequence-aware functions `ljust()`_, `rjust()`_, `center()`_, +and the grapheme-aware function `wrap()`_, serving as drop-in replacements to python standard +functions. + +The `clip()`_ function extracts substrings by their displayed column positions, and +`strip_sequences()`_ removes terminal escape sequences from text altogether. + +The iterator functions `iter_graphemes()`_ and `iter_sequences()`_ allow for careful navigation of +grapheme and terminal control sequence boundaries as required by editors or REPLs with cursor +control. `iter_graphemes_reverse()`_ and `grapheme_boundary_before()`_ are necessary for backward +cursor control over complex unicode. + +Discrepancies +------------- + +You may find that support *varies* for complex unicode sequences or codepoints. + +This library may be considered to presume the terminal is enabled for DEC Private Mode 2027 +("Grapheme Clustering") by default, which may require to be enabled by a TUI application but +is often the default mode for those terminals that support it. + +This library does support any specific "legacy width" measurement by API, but it does provide +Corrections_ for those terminals without grapheme support. + +See also: + +- `terminal-unicode-core.tex`_ (2021) +- `Grapheme Clusters and Terminal Emulators`_ (2023) +- `State of Terminal Emulators in 2025`_ +- `Perfecting Terminal Character Width Using Correction Tables`_ (2026) + +The `jquast/ucs-detect`_ project publishes automatic results of compliance to our standard for Wide +character, Languages, grapheme clustering, complex or combining scripts, emojis, zero-width joiner, +variations, and regional indicator (flags) as a `General Tabulated Summary`_ by terminal emulator +software and version. The results of the ucs-detect project create our correction tables. + +======== +Overview +======== + +A brief overview, through examples, for all of the public API functions. + +Full API Documentation at https://wcwidth.readthedocs.io/en/latest/api.html + +wcwidth() +--------- + +Measures width of a single codepoint, + +.. code-block:: python + + >>> # '♀' narrow emoji + >>> wcwidth.wcwidth('\u2640') + 1 + +Use function `wcwidth()`_ to determine the length of a *single unicode character*. + +See specification_ of character measurements. Note that ``-1`` is returned for control codes. + +wcswidth() +---------- + +Measures width of a string, returns -1 for control codes. + +.. code-block:: python + + >>> # '♀️' emoji w/vs-16 + >>> wcwidth.wcswidth('\u2640\ufe0f') + 2 + +Use function `wcswidth()`_ to determine the length of many, a *string of unicode characters*. + +See specification_ of character measurements. Note that ``-1`` is returned if control codes occurs +anywhere in the string. + +wcstwidth() +----------- + +Same behavior as `wcswidth()`_ with automatic terminal-specific Corrections_, reading +``TERM_PROGRAM`` or ``TERM`` when ``True`` (default), or caller can provide terminal query +XTVERSION_ or ENQ_ response: + +.. code-block:: python + + >>> # '♀️' emoji w/vs-16, uncorrected: + >>> wcwidth.wcswidth('\u2640\ufe0f') + 2 + >>> # corrected, + >>> wcwidth.wcstwidth('\u2640\ufe0f', term_program='vte') + 1 + +width() +------- + +Use function `width()`_ to measure a string with improved handling of ``control_codes`` and +measurement Corrections_ through ``term_program``: + +.. code-block:: python + + >>> # same support as wcswidth(), eg. regional indicator flag: + >>> wcwidth.width('\U0001F1FF\U0001F1FC') + 2 + >>> # set term_program=True to use wcstwidth() + >>> wcwidth.width('\U0001F1FF\U0001F1FC', term_program=True) + 1 + >>> # or set term_program for measurement of a specific terminal + >>> wcwidth.width('\U0001F1FF\U0001F1FC', term_program='contour') + 2 + >>> # but also supports sequences, like SGR colored text, "WARN", followed by reset + >>> wcwidth.width('\x1b[38;2;255;150;100mWARN\x1b[0m') + 4 + >>> # tabs are measured as though the string begins at a tabstop, + >>> wcwidth.width('\t', tabsize=4) + 4 + >>> # or, all control characters can be ignored (including tab) + >>> wcwidth.width('\t\n\a\r', control_codes='ignore') + 0 + >>> # sequences with "indeterminate" effects like Home + Clear are zero-width + >>> wcwidth.width('\x1b[H\x1b[2J') + 0 + >>> # horizontal cursor movements are parsed, + >>> wcwidth.width('hello\b\b\b\b\bworld') + 5 + >>> wcwidth.width('hello\x1b[5Dworld') + 5 + >>> # or ignored, + >>> wcwidth.width('hello\x1b[5Dworld', control_codes='ignore') + 10 + >>> # Measure width of text using kitty text sizing protocol (OSC 66), + >>> width('\x1b]66;w=2;XY\x07') + 2 + >>> # Scaled text sizing: each grapheme occupies 'scale' cells + >>> width('\x1b]66;s=2;ABC\x07') + 6 + +Use ``control_codes='ignore'`` when the input is known not to contain any control characters or +terminal sequences for slightly improved performance. Note that TAB (``'\t'``) is a control +character and is also ignored, you may want to use `str.expandtabs()`_, first. + +Use ``control_codes='strict'`` when input is known to contain some control sequences, such as +SGR color, bold, hyperlinks and cursor movement. Any sequence that cannot be accurately parsed +for horizontal measurement, such as clearing the screen, vertical, or absolute cursor movement will +raise ``ValueError``: + +.. code-block:: python + + >>> # or, raise ValueError for "indeterminate" effects using control_codes='strict' + >>> wcwidth.width('\n', control_codes='strict') + Traceback (most recent call last): + ... + ValueError: Vertical movement character 0xa at position 0 + + + >>> wcwidth.width('\x1b[H\x1b[2J', control_codes='strict') + Traceback (most recent call last): + ... + ValueError: Indeterminate cursor sequence at position 0, '\x1b[H' + + + >>> # cursor left movement beyond string start raises in strict mode, + >>> wcwidth.width('a\x1b[5Da', control_codes='strict') + Traceback (most recent call last): + ... + ValueError: Cursor left movement at position 1 would move 5 cells left from column 1, exceeding string start + +iter_sequences() +---------------- + +Iterates through text, segmented by terminal sequence, + +.. code-block:: python + + >>> list(wcwidth.iter_sequences('hello')) + [('hello', False)] + >>> list(wcwidth.iter_sequences('\x1b[31mred\x1b[0m')) + [('\x1b[31m', True), ('red', False), ('\x1b[0m', True)] + +Use `iter_sequences()`_ to split text into segments of plain text and escape sequences. Each tuple +contains the segment string and a boolean indicating whether it is an escape sequence (``True``) or +text (``False``). + +iter_graphemes() +---------------- + +Use `iter_graphemes()`_ to iterate over *grapheme clusters* of a string. + +.. code-block:: python + + >>> from wcwidth import iter_graphemes + >>> # ok + Regional Indicator 'Z', 'W' (Zimbabwe) + >>> list(wcwidth.iter_graphemes('ok\U0001F1FF\U0001F1FC')) + ['o', 'k', '🇿🇼'] + + >>> # cafe + combining acute accent + >>> list(wcwidth.iter_graphemes('cafe\u0301')) + ['c', 'a', 'f', 'é'] + + >>> # ok + Emoji Man + ZWJ + Woman + ZWJ + Girl + >>> list(wcwidth.iter_graphemes('ok\U0001F468\u200D\U0001F469\u200D\U0001F467')) + ['o', 'k', '👨\u200d👩\u200d👧'] + +A grapheme cluster is what a user perceives as a single character, even if it is composed of +multiple Unicode codepoints. This function implements `Unicode Standard Annex #29`_ grapheme cluster +boundary rules. + +ljust() +------- + +Use `ljust()`_ as replacement of `str.ljust()`_: + +.. code-block:: python + + >>> 'コンニチハ'.ljust(11, '*') # don't do this + 'コンニチハ******' + >>> wcwidth.ljust('コンニチハ', 11, '*') # do this! + 'コンニチハ*' + +rjust() +------- + +Use `rjust()`_ as replacement of `str.rjust()`_: + +.. code-block:: python + + >>> 'コンニチハ'.rjust(11, '*') # don't do this + '******コンニチハ' + >>> wcwidth.rjust('コンニチハ', 11, '*') # do this! + '*コンニチハ' + +center() +-------- + +Use `center()`_ as replacement of `str.center()`_: + +.. code-block:: python + + >>> 'cafe\u0301'.center(6, '*') # don't do this + 'café*' + >>> wcwidth.center('cafe\u0301', 6, '*') + '*café*' # do this! + +wrap() +------ + +Use function `wrap()`_ to wrap text containing terminal sequences, Unicode grapheme +clusters, and wide characters to a given display width. + +.. code-block:: python + + >>> from wcwidth import wrap + >>> # Basic wrapping + >>> wrap('hello world', 5) + ['hello', 'world'] + + >>> # Wrapping CJK text (each character is 2 cells wide) + >>> wrap('コンニチハ', 4) + ['コン', 'ニチ', 'ハ'] + + >>> # Text with ANSI color sequences - SGR codes are propagated by default + >>> # Each line ends with reset, next line starts with restored style + >>> wrap('\x1b[1;31mhello world\x1b[0m', 5) + ['\x1b[1;31mhello\x1b[0m', '\x1b[1;31mworld\x1b[0m'] + +clip() +------ + +Use `clip()`_ to extract a substring by column positions, preserving terminal sequences. + +.. code-block:: python + + >>> from wcwidth import clip + >>> # Wide characters split to Narrow boundaries using fillchar=' ' + >>> clip('中文字', 0, 3) + '中 ' + >>> clip('中文字', 1, 5, fillchar='.') + '.文.' + + >>> # 'end' defaults to -1, meaning "to the end of the line" + >>> clip('中文字', 1) + ' 文字' + >>> clip('\x1b[1;31mHello world\x1b[0m', 6) + '\x1b[1;31mworld\x1b[0m' + + >>> # SGR codes are propagated by default - result begins with active style + >>> # and ends with reset if styles are active + >>> clip('\x1b[1;31mHello world\x1b[0m', 6, 11) + '\x1b[1;31mworld\x1b[0m' + + >>> # Disable SGR propagation to preserve sequence order outside of clip boundary + >>> clip('\x1b[31m中文\x1b[32m', 0, 3, propagate_sgr=False) + '\x1b[31m中 \x1b[32m' + + >>> # Cursor-left overwrites previous text (painter's algorithm) + >>> clip('hello\x1b[2DXY', 0, 5) + 'helXY' + >>> # Carriage return resets to column 0, overwriting earlier cells + >>> clip('abc\rXY', 0, 5) + 'XYc' + + >>> # even OSC 8 hyperlink text may be clipped, 'Click This link' -> 'is link' ! + >>> clip('\x1b]8;;http://example.com\x07Click This link\x1b]8;;\x07', 8, 15) + '\x1b]8;;http://example.com\x07is link\x1b]8;;\x07' + + >>> # and OSC 66 kitty text sizing, supporting width and scale, 'Look' -> '...ook' + >>> clip('\x1b]66;w=4:s=4;Look\x07', 1, 16, fillchar='.') + '...\x1b]66;s=4:w=3;ook\x07' + +Use ``overtyping=False`` when the input is known not to contain any cursor movement characters +(``\b``, ``\r``, ``CSI C``, ``CSI D``, ``CSI G``) for improved performance. When +``overtyping=None`` (default), a slower "Painter's algorithm" may be used after testing for the +presence of these characters. ``overtyping`` has no effect when ``control_codes='ignore'``. + +strip_sequences() +----------------- + +Use `strip_sequences()`_ to remove all terminal escape sequences from text. + +.. code-block:: python + + >>> from wcwidth import strip_sequences + >>> strip_sequences('\x1b[31mred\x1b[0m') + 'red' + +.. _ambiguous_width: + +Ambiguous Width +--------------- + +Some Unicode characters have "East Asian Ambiguous" (A) width. These characters display as 1 cell by +default, matching Western terminal contexts, but many CJK (Chinese, Japanese, Korean) environments +may have a preference for 2 cells. This is often found as boolean option, "Ambiguous width as wide" +in Terminal Emulator software preferences. + +The ``ambiguous_width`` parameter is available on all width-measuring functions: `wcwidth()`_, +`wcswidth()`_, `width()`_, `ljust()`_, `rjust()`_, `center()`_, `wrap()`_, and `clip()`_. + +By default, wcwidth treats ambiguous characters as narrow (width 1). For CJK environments where your +terminal is configured to display ambiguous characters as double-width, pass ``ambiguous_width=2``: + +.. code-block:: python + + >>> # CIRCLED DIGIT ONE - ambiguous width + >>> wcwidth.width('\u2460') + 1 + >>> wcwidth.width('\u2460', ambiguous_width=2) + 2 + +**Terminal Detection** + +The most reliable method to detect whether a terminal profile is set for "Ambiguous width as wide" +mode is to display an ambiguous character surrounded by a pair of Cursor Position Report (CPR) +queries with a terminal in cooked or raw mode, and to parse the responses for their ``(y, x)`` +locations and measure the difference ``x``. + +This code should also be careful to check whether it is attached to a terminal and be careful of +possible timeout, slow network, or non-response when working with "dumb terminals" like a CI build. + +`jquast/blessed`_ library provides such a helping `Terminal.detect_ambiguous_width()`_ method: + +.. code-block:: python + + >>> import blessed, functools + >>> # Detect terminal ambiguous width as wide (2) or narrow (1) + >>> ambiguous_width = blessed.Terminal().detect_ambiguous_width() + >>> # Define a new 'width' function with this argument + >>> awidth = functools.partial(wcwidth.width, ambiguous_width=ambiguous_width) + >>> # result depends on attached terminal mode + >>> awidth('\u2460') + 1 + +Corrections +----------- + +Corrections may be automatically applied depending on the detected or given terminal software name +beginning with wcwidth release 0.8.0. This allows to correct widths for terminal software that +differs from the python wcwidth specification_. These corrections are sourced from the +`jquast/ucs-detect`_ project. + +The ``term_program`` parameter is available on all width-measuring functions: `wcstwidth()`_, +`width()`_, `ljust()`_, `rjust()`_, `center()`_, `wrap()`_, and `clip()`_. + +`wcstwidth()`_ defaults to ``term_program=True``, auto-detecting the terminal from the +``TERM_PROGRAM`` or ``TERM`` environment variable. All other functions default to +``term_program=False``, disabling corrections. Use ``term_program=True`` for automatic +detection by environment values of ``TERM`` and ``TERM_PROGRAM``. + +.. code-block:: python + + # VTE terminals (Gnome Terminal Et al.) still render trigrams as narrow (1 cell), but their + # definition was changed to wide in Unicode 16 (September 2024). + >>> wcwidth.wcswidth('\u2630') + 2 + >>> wcwidth.wcstwidth('\u2630', term_program='vte') + 1 + + # account for Alacritty non-support of emoji ZWJ: + # man + ZWJ + woman + ZWJ + girl + ZWJ + boy + >>> family = '\U0001F468\u200D\U0001F469\u200D\U0001F467\u200D\U0001F466' + >>> wcwidth.wcswidth(family) + 2 + >>> wcwidth.wcstwidth(family, term_program='alacritty') + 8 + +Only detectable_ terminals are included: those that identify themselves by XTVERSION_, ENQ_, any +``TERM_PROGRAM`` or a unique ``TERM`` environment value. For the most accurate correction tables, +query the terminal's software version via XTVERSION_ (``CSI > q``) using a higher-level interactive +terminal library like `jquast/blessed`_: + +.. code-block:: python + + >>> import blessed, wcwidth + >>> term = blessed.Terminal() + >>> sw_ver = term.get_software_version() + >>> print(sw_ver) + SoftwareVersion(name='VTE', version='7600') + >>> wcwidth.width('\u2630', term_program=sw_ver.name) + 1 + +This is important because ``TERM_PROGRAM`` is not forwarded for remote hosts, like SSH, and many +terminals may only be identified using XTVERSION_ or ENQ_. Use `list_term_programs()`_ to see all +recognized names: + +.. BEGIN_LIST_TERM_PROGRAMS +.. code-block:: python + + >>> wcwidth.list_term_programs() + ('absolutetelnet/ssh', 'alacritty', 'apple_terminal', 'bobcat', 'contour', + 'extraterm', 'foot', 'ghostty', 'hyper', 'iterm.app', 'iterm2', 'kitty', + 'konsole', 'mintty', 'mlterm', 'pterm', 'putty', 'rio', 'rxvt', + 'rxvt-unicode-256color', 'st', 'st-256color', 'tabby', 'terminology', + 'urxvt', 'vscode', 'vte', 'warp', 'warpterminal', 'wezterm', 'xterm', + 'xterm-ghostty', 'xterm-kitty', 'xterm.js') + +.. END_LIST_TERM_PROGRAMS + +``term_program=False`` (the default for `width()`_, `ljust()`_, `rjust()`_, `center()`_, +`wrap()`_, and `clip()`_) disables terminal corrections. + +For automatic tests and other purposes that require cross-environment consistency, set static values +or unset ``TERM`` and ``TERM_PROGRAM`` environment values, such as in ``conftest.py`` with pytest: + +.. code-block:: python + + @pytest.fixture(autouse=True) + def _clear_term_program(): + """unset TERM/TERM_PROGRAM before each test.""" + saved_term = os.environ.pop('TERM', None) + saved_tprog = os.environ.pop('TERM_PROGRAM', None) + yield + if saved_term is not None: + os.environ['TERM'] = saved_term + if saved_tprog is not None: + os.environ['TERM_PROGRAM'] = saved_tprog + +================== +More documentation +================== + +Developer documentation, for building and contributing to this project, at +https://wcwidth.readthedocs.io/en/latest/developing.html + +Projects using wcwidth, and implementations in other languages, at +https://wcwidth.readthedocs.io/en/latest/related.html + +.. _`specification`: https://wcwidth.readthedocs.io/en/latest/specs.html +.. _`jquast/blessed`: https://github.com/jquast/blessed +.. _`wcwidth(3)`: https://man7.org/linux/man-pages/man3/wcwidth.3.html +.. _`wcswidth(3)`: https://man7.org/linux/man-pages/man3/wcswidth.3.html +.. _`jquast/ucs-detect`: https://github.com/jquast/ucs-detect +.. _`textwrap.wrap()`: https://docs.python.org/3/library/textwrap.html#textwrap.wrap +.. _`str.ljust()`: https://docs.python.org/3/library/stdtypes.html#str.ljust +.. _`str.rjust()`: https://docs.python.org/3/library/stdtypes.html#str.rjust +.. _`str.center()`: https://docs.python.org/3/library/stdtypes.html#str.center +.. _`str.expandtabs()`: https://docs.python.org/3/library/stdtypes.html#str.expandtabs +.. _`General Tabulated Summary`: https://ucs-detect.readthedocs.io/results.html#tabulated-results +.. _`wcwidth()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.wcwidth +.. _`wcswidth()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.wcswidth +.. _`wcstwidth()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.wcstwidth +.. _`width()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.width +.. _`iter_graphemes()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.iter_graphemes +.. _`iter_graphemes_reverse()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.iter_graphemes_reverse +.. _`grapheme_boundary_before()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.grapheme_boundary_before +.. _`ljust()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.ljust +.. _`rjust()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.rjust +.. _`center()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.center +.. _`wrap()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.wrap +.. _`clip()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.clip +.. _`strip_sequences()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.strip_sequences +.. _`iter_sequences()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.iter_sequences +.. _`list_term_programs()`: https://wcwidth.readthedocs.io/en/latest/api.html#wcwidth.list_term_programs +.. _`Unicode Standard Annex #29`: https://www.unicode.org/reports/tr29/ +.. _`Terminal.detect_ambiguous_width()`: https://blessed.readthedocs.io/en/latest/api/terminal.html#blessed.terminal.Terminal.detect_ambiguous_width +.. _`Grapheme Clusters and Terminal Emulators`: https://mitchellh.com/writing/grapheme-clusters-in-terminals +.. _`terminal-unicode-core.tex`: https://github.com/contour-terminal/terminal-unicode-core/blob/master/spec/terminal-unicode-core.tex +.. _`State of Terminal Emulators in 2025`: https://www.jeffquast.com/post/state-of-terminal-emulation-2025/ +.. _`Perfecting Terminal Character Width Using Correction Tables`: https://www.jeffquast.com/post/perfecting-terminal-character-width-using-correction-tables/ +.. _XTVERSION: https://vtdn.dev/docs/dcs/xtversion/ +.. _ENQ: https://documentation.help/PuTTY/config-answerback.html +.. _detectable: https://ucs-detect.readthedocs.io/results.html#terminal-identification +.. _libwcwidth: https://wcwidth.readthedocs.io/en/latest/libwcwidth.html +.. |pypi_downloads| image:: https://img.shields.io/pypi/dm/wcwidth.svg?logo=pypi + :alt: Downloads + :target: https://pypi.org/project/wcwidth/ +.. |codecov| image:: https://codecov.io/gh/jquast/wcwidth/branch/master/graph/badge.svg + :alt: codecov.io Code Coverage + :target: https://app.codecov.io/gh/jquast/wcwidth/ +.. |license| image:: https://img.shields.io/pypi/l/wcwidth.svg + :target: https://pypi.org/project/wcwidth/ + :alt: MIT License + diff --git a/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/RECORD b/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d1a694d0e7512d9612ceac639361e6dc5ec239c3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/RECORD @@ -0,0 +1,102 @@ +wcwidth-0.8.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +wcwidth-0.8.5.dist-info/METADATA,sha256=bMUs3XZJ_GDUaMYouKpzEKAJojDjRDPQ_VLLbrou6dk,23578 +wcwidth-0.8.5.dist-info/RECORD,, +wcwidth-0.8.5.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87 +wcwidth-0.8.5.dist-info/licenses/LICENSE,sha256=cLmKlaIUTrcK-AF_qMbZXOJH5AhnQ26LxknhN_4T0ho,1322 +wcwidth/__init__.py,sha256=jf1pT4ISSiC_YE0hzvUrPXq0E3DYo0bAN3k51Q0KWFg,3025 +wcwidth/__pycache__/__init__.cpython-312.pyc,, +wcwidth/__pycache__/_clip.cpython-312.pyc,, +wcwidth/__pycache__/_constants.cpython-312.pyc,, +wcwidth/__pycache__/_wcswidth.cpython-312.pyc,, +wcwidth/__pycache__/_wcwidth.cpython-312.pyc,, +wcwidth/__pycache__/_width.cpython-312.pyc,, +wcwidth/__pycache__/align.cpython-312.pyc,, +wcwidth/__pycache__/bisearch.cpython-312.pyc,, +wcwidth/__pycache__/control_codes.cpython-312.pyc,, +wcwidth/__pycache__/escape_sequences.cpython-312.pyc,, +wcwidth/__pycache__/grapheme.cpython-312.pyc,, +wcwidth/__pycache__/hyperlink.cpython-312.pyc,, +wcwidth/__pycache__/sgr_state.cpython-312.pyc,, +wcwidth/__pycache__/table_ambiguous.cpython-312.pyc,, +wcwidth/__pycache__/table_grapheme.cpython-312.pyc,, +wcwidth/__pycache__/table_mc.cpython-312.pyc,, +wcwidth/__pycache__/table_overrides.cpython-312.pyc,, +wcwidth/__pycache__/table_term_programs.cpython-312.pyc,, +wcwidth/__pycache__/table_vs15.cpython-312.pyc,, +wcwidth/__pycache__/table_vs16.cpython-312.pyc,, +wcwidth/__pycache__/table_wide.cpython-312.pyc,, +wcwidth/__pycache__/table_zero.cpython-312.pyc,, +wcwidth/__pycache__/text_sizing.cpython-312.pyc,, +wcwidth/__pycache__/textwrap.cpython-312.pyc,, +wcwidth/__pycache__/unicode_versions.cpython-312.pyc,, +wcwidth/__pycache__/wcwidth.cpython-312.pyc,, +wcwidth/_clip.py,sha256=2jaW1DD08UoAOg9h-mpvWZLDZbSuqzZ7V3x47JhwpBQ,35912 +wcwidth/_constants.py,sha256=BEJfBbzkGXusg3u7QMB-EOBw2iH8HdOcKL4PYFJCWmg,6414 +wcwidth/_wcswidth.py,sha256=hmiGdfqmGSAe2v7FcFUGwidHDgLEB8rNbGvbX93LkF0,17637 +wcwidth/_wcwidth.py,sha256=2Q4BYg1LrLIxzBVYTNIMNvNr0QhIlNk8XibuwG_A5og,6757 +wcwidth/_width.py,sha256=iwklobxIKVBSLAmOXXt9nPfPtEEMHH769v28F9tbWxc,22820 +wcwidth/align.py,sha256=9xOfKCn9FiCa6EI20fln23m5uFZ6JWiC3JY-pvF0NJc,6588 +wcwidth/bisearch.py,sha256=Y_FdvYTzFXD2pa5cppUegD5SXfy-B8HC4A9rrJOdb40,813 +wcwidth/control_codes.py,sha256=NGkPsXNA_MSNH_G1xQjvDgX4mSj-kp1TLfLP-GIUz08,1579 +wcwidth/escape_sequences.py,sha256=ukt0p_sUZmIWhscHGGP48pqcWDR8u2VNg5e2hTyViHE,8222 +wcwidth/grapheme.py,sha256=0FwdyLE_MCq0Vt7Xd6xb839h4aRqrK2Fng01aaJcggg,13222 +wcwidth/hyperlink.py,sha256=jWrkBEVKDWpfWQrulpQA9Vtdkuv0tpnzPuSS05gtPSE,4449 +wcwidth/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +wcwidth/sgr_state.py,sha256=meFC3xY6jBPicD_43koussHLbIhg3l_gpmlbyconYsI,13073 +wcwidth/table_ambiguous.py,sha256=di2N-92K1qcb9QAV6J1N1NvFs9JwVg4cPJATD9qYZX0,11867 +wcwidth/table_grapheme.py,sha256=MXbO48fHgxFZIofNWkRQnUgZnZi99GcxBYxml03w7W0,146562 +wcwidth/table_grapheme_overrides/__init__.py,sha256=8BFwbTUhAkLonMfR-ArWw3oaFo-Mfu0QL6imuprskNY,1231 +wcwidth/table_grapheme_overrides/__pycache__/__init__.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_058c7585.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_2148ff29.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_244dc88b.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_336a71a1.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_33ac73f2.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_3a1895d5.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_59180a0d.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_65c6beb5.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_78f828e8.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_8c2ae14d.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_900356bf.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_97904ece.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_a5880eeb.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_b6d33cf4.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_c57c295b.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_cf02297d.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_e18ac6a7.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_e2b75ee3.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_fb5fd79b.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_known_fdc99132.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/__pycache__/_registry.cpython-312.pyc,, +wcwidth/table_grapheme_overrides/_known_058c7585.py,sha256=9k37DibKndhN6iqQWXbR7IOa_SiJ05KDVZhrW3mBzOo,70405 +wcwidth/table_grapheme_overrides/_known_2148ff29.py,sha256=Qax5c6GdKN5u78EGl0JSQA3kgw4mZ8jbaic9v-rYekI,32859 +wcwidth/table_grapheme_overrides/_known_244dc88b.py,sha256=LE9rkmY2cu327E-hikZ9q6on3kMleOIn1NZCdQG07qw,1977 +wcwidth/table_grapheme_overrides/_known_336a71a1.py,sha256=lqwoTZlUZ5ucCOX_-WDPMQyOefAT8YoBb4ATEicOffA,73690 +wcwidth/table_grapheme_overrides/_known_33ac73f2.py,sha256=LGENu5d3BYauiJtKjcaHj5Ky_PhDQ8YR15uQowEhSsM,51607 +wcwidth/table_grapheme_overrides/_known_3a1895d5.py,sha256=Tb03sh2wv4AyqJZ7ACsASGrpxYGqyOvqebP9csj1WL4,28356 +wcwidth/table_grapheme_overrides/_known_59180a0d.py,sha256=shiDEhtkga0HaUn5JxcPL9EP98JqNnB808wJUWkd5SI,69393 +wcwidth/table_grapheme_overrides/_known_65c6beb5.py,sha256=8BmrrvBrMqqWYKFgqVFyfea4UtHSixP8HsOq8fAaImU,72065 +wcwidth/table_grapheme_overrides/_known_78f828e8.py,sha256=3qL7BCld1bylScC47_jRMMfqcLkeXljRXQwwAJq-bDs,29457 +wcwidth/table_grapheme_overrides/_known_8c2ae14d.py,sha256=GtNXikIImV0uA2RYaLMaRYAntlmEGRwg3eB638jTdwM,72055 +wcwidth/table_grapheme_overrides/_known_900356bf.py,sha256=HW_cZDAFaSVeVY1NwTjht9BG53OOL8WdrQBmARDiNBs,2579 +wcwidth/table_grapheme_overrides/_known_97904ece.py,sha256=oIh4nDC_B61_2gZNt9VjBIHTqyPhKPsGNMuila2BgME,68622 +wcwidth/table_grapheme_overrides/_known_a5880eeb.py,sha256=EEhYMSMVvWhd4CMwT46E43mZMxLY8wxmc5L5fJqUyAE,68676 +wcwidth/table_grapheme_overrides/_known_b6d33cf4.py,sha256=IHTeDfm1h5zo4-V5oDmzam5slRDAoORZ9vdTxW-RP3A,78876 +wcwidth/table_grapheme_overrides/_known_c57c295b.py,sha256=n-OtNEYp-L16PINwwfBmzm0yAYsmCGYu_O2bedIH6Nc,141315 +wcwidth/table_grapheme_overrides/_known_cf02297d.py,sha256=iUeiFKK1CSxngp4UiGqh30qv3VPZfz17QPwrGQapCeE,32688 +wcwidth/table_grapheme_overrides/_known_e18ac6a7.py,sha256=0Cqr4Zc4ji7bOcUBdwXNMpEJR2uznRZEEXU6lluPsig,145380 +wcwidth/table_grapheme_overrides/_known_e2b75ee3.py,sha256=E-WeOp26MUshW3Wwu2AgNgXP46hmCG-7Et3eRnO6frg,765 +wcwidth/table_grapheme_overrides/_known_fb5fd79b.py,sha256=UTUgBjEKeDM0k_sioxyCJCPbjviKvUJjwzRWvU-2ZbU,76258 +wcwidth/table_grapheme_overrides/_known_fdc99132.py,sha256=2DPjZLKsj8v333GuMZ-yX1Lt6RsFrjI8hPqwEJfjlHI,70400 +wcwidth/table_grapheme_overrides/_registry.py,sha256=7coxGOT8hlBWZTrHr3yN1TEalB0tUzrFZUS0FLg3AYI,785 +wcwidth/table_mc.py,sha256=8IQjaptDghloUhZy7DTHnDNvIkw1LBew64Kvv82x-mE,14198 +wcwidth/table_overrides.py,sha256=TIGCq2lLwvpWGKcrp9eu_guOio6rC75UCjmKXnWntrQ,47858 +wcwidth/table_term_programs.py,sha256=ifuBqk7YUlghnWQ75P-6N54mriYD8OVZMvNdbkR31W4,1070 +wcwidth/table_vs15.py,sha256=mvVcXGgBtnikwRASb4AyMJrIYQZAscp0vk6go1heR4s,5170 +wcwidth/table_vs16.py,sha256=FjceLbmW_W5grGOQX52egyNCm3F0LHZbg6Sl11GasMY,6857 +wcwidth/table_wide.py,sha256=oWffoXc4-5ObgVcZP8nRH3Cx4e0DheGm-u4HyNWtUIU,9159 +wcwidth/table_zero.py,sha256=A9YQUcafKG_nesylWDvjcfpnT4bP9hpqvcV_oaUVbMY,26107 +wcwidth/text_sizing.py,sha256=oENDrgoO7darRw1CHD6gOfmuqq4yVVGxvkADPbjFuNU,7946 +wcwidth/textwrap.py,sha256=9Up5PHss6fVt2rrxPPg7Pk8gs4S6bPu6YE3yIlqNFyY,29568 +wcwidth/unicode_versions.py,sha256=BQT1UMDnfdGzyBxAig18GIjPri7jGarFxF51UEBDm7A,508 +wcwidth/wcwidth.py,sha256=WX66lOPtigH_axqcvU0JMTFd950jxV4MGrZEBHoGkEs,2858 diff --git a/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..39dc805011177e5b2a77e7afb5ec7187aeb3e34d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.32.4 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a44c0757243a785b0b73c21a38c45f44a4a2c32f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth-0.8.5.dist-info/licenses/LICENSE @@ -0,0 +1,27 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jeff Quast + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Markus Kuhn -- 2007-05-26 (Unicode 5.0) + +Permission to use, copy, modify, and distribute this software +for any purpose and without fee is hereby granted. The author +disclaims all warranties with regard to this software. diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__init__.py b/.venv/lib/python3.12/site-packages/wcwidth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cf0b87aa965f1e0e37aaa16441bd04cd6026ba94 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/__init__.py @@ -0,0 +1,74 @@ +""" +Python 'wcwidth' module. + +https://github.com/jquast/wcwidth +""" + +# re-export common and outermost functions & definitions, even a few private +# ones, some for convenience, others for legacy, only the items in __all__ are +# documented as public API + +__lazy_modules__ = [ + "wcwidth._clip", + "wcwidth._wcswidth", + "wcwidth._wcwidth", + "wcwidth._width", + "wcwidth.align", + "wcwidth.bisearch", + "wcwidth.escape_sequences", + "wcwidth.grapheme", + "wcwidth.hyperlink", + "wcwidth.sgr_state", + "wcwidth.table_ambiguous", + "wcwidth.table_vs16", + "wcwidth.table_wide", + "wcwidth.table_zero", + "wcwidth.text_sizing", + "wcwidth.textwrap", + "wcwidth.unicode_versions", +] + +# local +from ._clip import clip +from .align import ljust, rjust, center +from ._width import width +from .bisearch import bisearch as _bisearch +from .grapheme import iter_graphemes, iter_graphemes_reverse, grapheme_boundary_before +from .textwrap import SequenceTextWrapper, wrap +from ._wcswidth import wcswidth, wcstwidth +from .hyperlink import Hyperlink, HyperlinkParams +from .sgr_state import propagate_sgr +from ._constants import list_term_programs +from .table_vs16 import VS16_NARROW_TO_WIDE +from .table_wide import WIDE_EASTASIAN +from .table_zero import ZERO_WIDTH +from .text_sizing import TextSizing, TextSizingParams +from .table_ambiguous import AMBIGUOUS_EASTASIAN +from .escape_sequences import iter_sequences, strip_sequences +from .unicode_versions import list_versions + +# Import order matters for legacy API compatibility (releases before 0.7.0). +# +# The first release put every function in a single 'wcwidth.py' file, and while the top-level +# 'from wcwidth import wcswidth' was always preferred, the deeper +# 'from wcwidth.wcwidth import wcswidth' form was always possible too. Both keep working. +# +# Below 3.15 the legacy submodule is pre-imported so sys.modules['wcwidth.wcwidth'] is populated +# during package initialization; a later ``import wcwidth.wcwidth`` would otherwise trigger on-disk +# file discovery and rebind that name from the function to the module object. On 3.15+ +# __lazy_modules__ covers every submodule and the shim loads on demand. +if __import__('sys').version_info < (3, 15): + from . import wcwidth as _wcwidth_module # isort:skip +from ._wcwidth import wcwidth, _wcmatch_version, _wcversion_value # isort:skip # pylint: disable=wrong-import-position + + +# The __all__ attribute defines the items exported from statement, +# 'from wcwidth import *', but also to say, "This is the public API". +__all__ = ('wcwidth', 'wcswidth', 'wcstwidth', 'width', 'iter_sequences', 'iter_graphemes', + 'iter_graphemes_reverse', 'grapheme_boundary_before', + 'ljust', 'rjust', 'center', 'wrap', 'clip', 'strip_sequences', + 'list_versions', 'list_term_programs', 'propagate_sgr', + 'Hyperlink', 'HyperlinkParams', 'TextSizing', 'TextSizingParams') + +# Version is stamped by code generation (bin/update-tables.py) from pyproject.toml. +__version__ = '0.8.5' diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcc7f4441264702ee28c7e36150cc655e0d631b0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_clip.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_clip.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71be3f3964c82c4ab1761fd836a9acb82c19668f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_clip.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_constants.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7163caa60cd7f057bb84f06d8f8b73bf3ceeaa2c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_constants.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_wcswidth.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_wcswidth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9df5f5a10f2cca96cad9cab0fa025dcd6779647 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_wcswidth.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_wcwidth.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_wcwidth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..081eee8ade9c0f1d0da3f474a9e2b4814f38afed Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_wcwidth.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_width.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_width.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f7d4f34e3b1cf384cb5c0f5c9a92c331181b65d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/_width.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/align.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/align.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1edec990048bb5e74e2adba71795e900a69aceb2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/align.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/bisearch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/bisearch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afe6d3fee6fe2069141666c4c873c1bfb96150b1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/bisearch.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/control_codes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/control_codes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b21a79d6abdf76d98d76a53db6474ccce8ebc1b7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/control_codes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/escape_sequences.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/escape_sequences.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..410d7a3740c30085099a55eb350ef28789e559d1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/escape_sequences.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/grapheme.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/grapheme.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84cf3d90cd813bed4a787f6e4569f4dfe3a2b02a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/grapheme.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/hyperlink.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/hyperlink.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bff372c15e9c422f56bb0b793ba0aeecf4287ef Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/hyperlink.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/sgr_state.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/sgr_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44eef8dff3f95f3c2bfd41377979f7dd9292ac87 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/sgr_state.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_ambiguous.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_ambiguous.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..885780af0fe37af88cf3c7aff4da7afe0ed9451a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_ambiguous.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_grapheme.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_grapheme.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d551186d1d796191add68925ea3f8b8bc436a205 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_grapheme.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_mc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_mc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d76481b0ff164034699d26dd2e904cbd11020a8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_mc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6402ae01f50b30774d1349699ac68dc4ef115217 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_overrides.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_term_programs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_term_programs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d967e0b5188df8573ada2b7c03029f690c3f0e83 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_term_programs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_vs15.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_vs15.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e8c109eabe463db0cd88d2d1c4dd7448c51d3af Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_vs15.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_vs16.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_vs16.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b21e0a7acd3d39dce2beb9f94085f95639f13ac Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_vs16.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_wide.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_wide.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edc8e20ef61f1d0f0a488607ed3b7c2355c9b6e7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_wide.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_zero.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_zero.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a769b940dc1af1d8bb75b97272c2d1b090cc7f3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/table_zero.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/text_sizing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/text_sizing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b851f07e4e020419fda6aae86a0ca650042535b8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/text_sizing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/textwrap.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/textwrap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..590b4ba57b4559c977475d2950a180c7b35e052f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/textwrap.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/unicode_versions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/unicode_versions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b85d2514282d1bf31fb9fa645939a99291194f4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/unicode_versions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/wcwidth.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/wcwidth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2081807bb93a20b1845388ff7777e71707157407 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/__pycache__/wcwidth.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/_clip.py b/.venv/lib/python3.12/site-packages/wcwidth/_clip.py new file mode 100644 index 0000000000000000000000000000000000000000..a70b61ade052a7d205ab0dd95e068207a315e64a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/_clip.py @@ -0,0 +1,907 @@ +"""This is a python implementation of clip().""" +from __future__ import annotations + +# std imports +import sys +import enum +from itertools import islice + +from typing import Literal, Callable, Optional, NamedTuple + +# local +from ._width import width +from .grapheme import iter_graphemes +from .hyperlink import Hyperlink, HyperlinkParams +from .sgr_state import (_SGR_PATTERN, + _SGR_STATE_DEFAULT, + _SGRState, + _sgr_state_update, + _sgr_state_is_active, + _sgr_state_to_sequence) +from ._constants import _clamp_ambiguous_width +from .text_sizing import TextSizing, TextSizingParams +from .escape_sequences import (_SEQUENCE_CLASSIFY, + _HORIZONTAL_CURSOR_MOVEMENT, + INDETERMINATE_EFFECT_SEQUENCE) + + +class _HyperlinkAction(enum.Enum): + """Outcome of processing an OSC 8 hyperlink unit.""" + + NO_CLOSE = enum.auto() # open sequence without matching close + EMPTY = enum.auto() # hyperlink with no visible inner text + OUTSIDE = enum.auto() # hyperlink entirely outside the clip window + VISIBLE = enum.auto() # hyperlink overlaps the clip window + + +class _HyperlinkResult(NamedTuple): + """ + Result of processing an OSC 8 hyperlink. + + Only the fields relevant to each action are populated. + """ + + action: _HyperlinkAction + close_end: int = 0 + inner_width: int = 0 + open_seq: str = '' + clipped_inner: str = '' + close_seq: str = '' + clipped_width: int = 0 + hl_col_end: int = 0 + + +def _apply_sgr_wrap(result: str, captured_style: Optional[_SGRState], + end_style: Optional[_SGRState] = None) -> str: + """ + Apply SGR prefix/suffix around *result*. + + If an SGR state was captured at the first visible character, prefix the result with the + corresponding SGR sequence, and suffix with a reset if any styles remain active at the end + of the clipped region. + + *end_style* is the style in effect after the final SGR sequence emitted within the clip window, + or ``None`` when no such sequence was emitted, the style at the first visible character is still + in effect. This matches :func:`wcwidth.propagate_sgr`, which decides the trailing reset by SGR + state at the end of each line. + """ + if captured_style is not None: + if prefix := _sgr_state_to_sequence(captured_style): + result = prefix + result + if _sgr_state_is_active(captured_style if end_style is None else end_style): + result += '\x1b[0m' + return result + + +def _process_hyperlink( + text: str, + start: int, + end: int, + fillchar: str, + tabsize: int, + ambiguous_width: int, + term_program: bool | str, + control_codes: Literal['parse', 'strict', 'ignore'], + *, + params: HyperlinkParams, + match_end: int, + col: int, +) -> _HyperlinkResult: + """ + Process an OSC 8 hyperlink unit. + + Finds the matching close sequence, measures the inner text width, and determines whether the + hyperlink is empty, outside the clip window, or visible (requiring inner-text clipping). + """ + # pylint: disable=too-many-locals,too-many-positional-arguments,too-many-arguments + close_start, close_end = Hyperlink.find_close(text, match_end) + if (close_start, close_end) == (-1, -1): + return _HyperlinkResult(_HyperlinkAction.NO_CLOSE) + inner_text = text[match_end:close_start] + inner_width = width( + inner_text, control_codes=control_codes, + tabsize=tabsize, ambiguous_width=ambiguous_width, + term_program=term_program, + ) + + if inner_width == 0: + return _HyperlinkResult(_HyperlinkAction.EMPTY, close_end=close_end) + + hl_col_end = col + inner_width + + if hl_col_end <= start or col >= end: + return _HyperlinkResult(_HyperlinkAction.OUTSIDE, close_end=close_end, + inner_width=inner_width) + + inner_clip_start = max(0, start - col) + inner_clip_end = end - col + + clipped_inner = clip( + inner_text, inner_clip_start, inner_clip_end, + fillchar=fillchar, tabsize=tabsize, + ambiguous_width=ambiguous_width, + term_program=term_program, + propagate_sgr=False, + control_codes=control_codes, + ) + + clipped_width = width( + clipped_inner, control_codes=control_codes, + tabsize=tabsize, ambiguous_width=ambiguous_width, + term_program=term_program, + ) + + return _HyperlinkResult( + _HyperlinkAction.VISIBLE, + close_end=close_end, + inner_width=inner_width, + open_seq=params.make_open(), + clipped_inner=clipped_inner, + close_seq=params.make_close(), + clipped_width=clipped_width, + hl_col_end=hl_col_end, + ) + + +def _reconstruct_painter( + cells: dict[int, tuple[str, int]], + sequences: list[tuple[int, int, str]], + start: int, + end: int, + fillchar: str, +) -> str: + """ + Reconstruct the output string from painter's algorithm state. + + Walks columns left-to-right, interleaving escape sequences and cell content, filling gaps with + *fillchar*. + """ + # pylint: disable=too-many-locals + # Group and sort sequences by column, preserving insertion order within each. + seqs_by_col: dict[int, list[tuple[int, str]]] = {} + for col_pos, order, seq_text in sequences: + seqs_by_col.setdefault(col_pos, []).append((order, seq_text)) + for entries in seqs_by_col.values(): + entries.sort() + + max_cell_col = max(cells.keys()) if cells else -1 + max_seq_col = max(seqs_by_col.keys()) if seqs_by_col else -1 + max_col = max(max_cell_col, max_seq_col) + + parts: list[str] = [] + walk_col = 0 + col_limit = min(max_col, end) + while walk_col <= col_limit: + # Emit any sequences anchored at this column. + for _, seq_text in seqs_by_col.get(walk_col, ()): + parts.append(seq_text) + + if walk_col >= end: + walk_col += 1 + continue + + if walk_col in cells: + cell_text, cell_w = cells[walk_col] + parts.append(cell_text) + walk_col += cell_w or 1 + else: + if start <= walk_col <= max_cell_col: + parts.append(fillchar) + walk_col += 1 + + # Emit sequences anchored beyond the visible region. + for c in sorted(seqs_by_col.keys()): + if c > col_limit: + for _, seq_text in seqs_by_col[c]: + parts.append(seq_text) + + return ''.join(parts) + + +def _clip_simple( + text: str, + start: int, + end: int, + *, + propagate_sgr: bool, + ambiguous_width: int, + term_program: bool | str, + fillchar: str, + tabsize: int, + strict: bool, + control_codes: Literal['parse', 'strict', 'ignore'], +) -> tuple[str, Optional[_SGRState], Optional[_SGRState]]: + """ + Clip text without cursor movement (simple append-to-output path). + + Returns ``(result, captured_style, end_style)``. The caller applies SGR wrapping. + """ + # pylint: disable=too-complex,too-many-locals,too-many-branches,too-many-statements + # pylint: disable=too-many-nested-blocks + # code length and complexity traded for performance, to allow this to be used as a "hot path" + + output: list[str] = [] + col = 0 + idx = 0 + # captured_style is a frozen snapshot of current_style taken at the first + # visible character emitted within the clip window (start, end). It stays + # None until that point. current_style, by contrast, is continuously + # updated by SGR sequences throughout the scan. The snapshot is what the + # caller uses to wrap the result in the correct SGR state. + # + # When propagate_sgr is False, current_style (and therefore captured_style) + # remain None, and SGR sequences pass through as literal text. + captured_style: Optional[_SGRState] = None + # end_style is the state after the last SGR sequence emitted *within* the + # clip window; it decides the trailing reset. None until such a sequence + # is emitted, meaning captured_style is still in effect at the end. + end_style: Optional[_SGRState] = None + current_style = _SGR_STATE_DEFAULT if propagate_sgr else None + + while idx < len(text): + char = text[idx] + + # Early exit: past visible region. + if col >= end and char not in '\r\x08\t\x1b': + if captured_style is not None: + break + # propagate_sgr is always False here: with propagate_sgr=True, + # captured_style is set on the first visible emission in the + # clip window and we would have broken above. The skip-ahead + # optimization is only needed (and safe) when SGR tracking is off. + next_esc = text.find('\x1b', idx + 1) + if next_esc == -1: + break + idx = next_esc + continue + + if char == '\x1b': + m = _SEQUENCE_CLASSIFY.match(text, idx) + if not m: + output.append(char) + idx += 1 + continue + + # SGR: update current_style. Sequences before the first visible + # emission are folded into the prefix synthesized by + # _apply_sgr_wrap(); those inside the clip window are emitted at + # their original position; those at or beyond *end* are dropped. + if m.group('sgr_params') is not None and propagate_sgr and current_style is not None: + current_style = _sgr_state_update(current_style, m.group()) + if captured_style is not None and col < end: + output.append(m.group()) + end_style = current_style + idx = m.end() + continue + + # OSC 8 hyperlink. + if hl_state := HyperlinkParams.parse(m.group()): + r = _process_hyperlink( + text, start, end, fillchar, tabsize, ambiguous_width, + term_program, + control_codes, + params=hl_state, match_end=m.end(), col=col, + ) + if r.action is _HyperlinkAction.NO_CLOSE: + output.append(m.group()) + idx = m.end() + elif r.action is _HyperlinkAction.EMPTY: + idx = r.close_end + elif r.action is _HyperlinkAction.OUTSIDE: + col += r.inner_width + idx = r.close_end + else: + output.append(r.open_seq) + output.append(r.clipped_inner) + output.append(r.close_seq) + if propagate_sgr and captured_style is None: + captured_style = current_style + # Inner text is clipped with propagate_sgr=False, so any SGR + # sequences it emits are verbatim: fold them into our state. + if propagate_sgr and current_style is not None: + for sgr_m in _SGR_PATTERN.finditer(r.clipped_inner): + current_style = _sgr_state_update(current_style, sgr_m.group()) + end_style = current_style + col += r.inner_width + idx = r.close_end + continue + + # OSC 66 Text Sizing. + if (ts_meta := m.group('ts_meta')) is not None: + ts_text = m.group('ts_text') or '' + ts_term = m.group('ts_term') + assert ts_term is not None + ts = TextSizing( + TextSizingParams.from_params(ts_meta, control_codes=control_codes), + ts_text, ts_term) + ts_width = ts.display_width(ambiguous_width) + + if col >= start and col + ts_width <= end: + output.append(ts.make_sequence()) + if propagate_sgr and captured_style is None: + captured_style = current_style + col += ts_width + elif col < end and col + ts_width > start: + ts_parts: list[str] = [] + + def _ts_write(s: str, _w: int, _col: int) -> None: + ts_parts.append(s) + col = _text_sizing_clip( + ts, col, start, end, fillchar, ambiguous_width, + term_program, + _ts_write) + output.extend(ts_parts) + if propagate_sgr and captured_style is None: + captured_style = current_style + else: + col += ts_width + idx = m.end() + continue + + # Indeterminate-effect sequences: raise in strict mode. + seq = m.group() + if strict and INDETERMINATE_EFFECT_SEQUENCE.match(seq): + raise ValueError( + f"Indeterminate cursor sequence at position {idx}, " + f"{seq!r}" + ) + + # Any other recognized sequence: preserve as-is. + output.append(seq) + idx = m.end() + continue + + if char == '\t': + # Expand tab, filling clip window with spaces. + if tabsize > 0: + next_tab = col + (tabsize - (col % tabsize)) + while col < next_tab: + if start <= col < end: + output.append(' ') + if propagate_sgr and captured_style is None: + captured_style = current_style + col += 1 + else: + output.append('\t') + idx += 1 + continue + + grapheme = next(iter_graphemes(text, start=idx)) + grapheme_w = width(grapheme, ambiguous_width=ambiguous_width, + term_program=term_program) + + # Emit grapheme or fillchar depending on visibility within clip window. + if grapheme_w == 0: + if start <= col < end: + output.append(grapheme) + elif col >= start and col + grapheme_w <= end: + output.append(grapheme) + if propagate_sgr and captured_style is None: + captured_style = current_style + elif col < end and col + grapheme_w > start: + output.append(fillchar * (min(end, col + grapheme_w) - max(start, col))) + if propagate_sgr and captured_style is None: + captured_style = current_style + + col += grapheme_w + idx += len(grapheme) + + return ''.join(output), captured_style, end_style + + +def _text_sizing_clip( + ts: TextSizing, + col: int, + start: int, + end: int, + fillchar: str, + ambiguous_width: int, + term_program: bool | str, + write_cells: Callable[[str, int, int], None], +) -> int: + """ + Emit tokens for a text-sizing (OSC 66) sequence, clipped to (start, end). + + Calls *write_cells(text, width, col)* for each emitted cell or sequence. Returns new column + position. + """ + # pylint: disable=too-many-locals,too-many-branches,too-many-positional-arguments,too-complex + ts_width = ts.display_width(ambiguous_width) + + # Fully visible: emit entire sequence + if col >= start and col + ts_width <= end: + write_cells(ts.make_sequence(), ts_width, col) + return col + ts_width + # Fully outside: just advance column + if col >= end or col + ts_width <= start: + return col + ts_width + + # Partial overlap: decompose + rel_start = max(0, start - col) + rel_end = min(end, col + ts_width) - col + scale = ts.params.scale + + units: list[tuple[str, int]] = [] + if ts.params.width > 0: + for g in islice(iter_graphemes(ts.text), ts.params.width): + units.append((g, scale)) + for _ in range(ts.params.width - len(units)): + units.append(('', scale)) + else: + for g in iter_graphemes(ts.text): + units.append( + (g, width(g, ambiguous_width=ambiguous_width, + term_program=term_program) * scale)) + + pending_units: list[tuple[str, int]] = [] + + def flush(flush_col: int) -> None: + if not pending_units: + return + texts = [u[0] for u in pending_units] + total_w = sum(u[1] for u in pending_units) + params = TextSizingParams( + scale, + len(texts) if ts.params.width > 0 else 0, + ts.params.numerator, ts.params.denominator, + ts.params.vertical_align, ts.params.horizontal_align) + write_cells( + TextSizing(params, ''.join(texts), ts.terminator).make_sequence(), + total_w, + flush_col) + pending_units.clear() + + flush_col_pos = col + rel_start + unit_pos = 0 + for unit_text, unit_w in units: + unit_end = unit_pos + unit_w + if unit_end <= rel_start: + unit_pos = unit_end + continue + if unit_pos >= rel_end: + break + + overlap = min(unit_end, rel_end) - max(unit_pos, rel_start) + if overlap == unit_w and unit_w > 0: + if not pending_units: + flush_col_pos = col + max(unit_pos, rel_start) + pending_units.append((unit_text, unit_w)) + else: + flush(flush_col_pos) + abs_start = col + max(unit_pos, rel_start) + for i in range(overlap): + write_cells(fillchar, 1, abs_start + i) + unit_pos = unit_end + + flush(flush_col_pos) + return col + ts_width + + +def _clip_painter( + text: str, + start: int, + end: int, + *, + propagate_sgr: bool, + ambiguous_width: int, + term_program: bool | str, + fillchar: str, + tabsize: int, + strict: bool, + control_codes: Literal['parse', 'strict', 'ignore'], +) -> tuple[str, Optional[_SGRState], Optional[_SGRState]]: + """ + Clip text with cursor movement (painter's algorithm path). + + Returns ``(result, captured_style, end_style)``. The caller applies SGR wrapping. + """ + # pylint: disable=too-complex,too-many-locals,too-many-branches + # pylint: disable=too-many-statements,too-many-nested-blocks + # code length and complexity traded for performance, to allow this to be used as a "hot path" + + cells: dict[int, tuple[str, int]] = {} + hyperlink_cells: set[int] = set() + sequences: list[tuple[int, int, str]] = [] + seq_order = 0 + + col = 0 + idx = 0 + # captured_style is a frozen snapshot of current_style taken at the first + # visible character emitted within the clip window (start, end); it stays + # None until that point. current_style is continuously updated by SGR + # sequences throughout the scan. + # + # When propagate_sgr is False, current_style (and therefore captured_style) + # remain None, and SGR sequences pass through as literal text. + captured_style: Optional[_SGRState] = None + # end_style is the state after the last SGR sequence emitted *within* the + # clip window; it decides the trailing reset. None until such a sequence + # is emitted, meaning captured_style is still in effect at the end. + end_style: Optional[_SGRState] = None + current_style = _SGR_STATE_DEFAULT if propagate_sgr else None + # Next movement at or after the scan position, -1 when none is left. + next_movement: Optional[int] = None + + def _write_cells(s: str, w: int, write_col: int, + is_hyperlink: bool = False) -> None: + """Write *w* cells of text *s* at *write_col*, handling wide-char splitting.""" + nonlocal captured_style, seq_order + if w == 0: + # Zero-width: a cell here would be overwritten by the next write. + if s: + sequences.append((write_col, seq_order, s)) + seq_order += 1 + if propagate_sgr and captured_style is None: + captured_style = current_style + return + for offset in range(w): + src_col = write_col + offset + if src_col > 0 and cells.get(src_col - 1, ('', 0))[1] == 2: + cells[src_col - 1] = (fillchar, 1) + hyperlink_cells.discard(src_col - 1) + if cells.get(src_col, ('', 0))[1] == 2: + cells[src_col + 1] = (fillchar, 1) + hyperlink_cells.discard(src_col + 1) + cells.pop(src_col, None) + hyperlink_cells.discard(src_col) + cells[write_col] = (s, w) + if is_hyperlink: + for offset in range(w): + hyperlink_cells.add(write_col + offset) + if propagate_sgr and captured_style is None: + captured_style = current_style + + while idx < len(text): + char = text[idx] + + # Early exit: past visible region. + if col >= end and char not in '\r\x08\t\x1b': + # Movement right-of the window can still rewinds back into it. + if next_movement is None or 0 <= next_movement < idx: + # Any match starts with one of these, and rfind is far cheaper. + if max(text.rfind('\x08'), text.rfind('\r'), text.rfind('\x1b')) < idx: + next_movement = -1 + else: + found = _HORIZONTAL_CURSOR_MOVEMENT.search(text, idx) + next_movement = -1 if found is None else found.end() + if next_movement < 0: + if captured_style is not None: + break + next_esc = text.find('\x1b', idx + 1) + if next_esc == -1: + break + idx = next_esc + continue + + if char == '\x1b': + m = _SEQUENCE_CLASSIFY.match(text, idx) + if not m: + # Record lone ESC as a zero-width sequence at current column. + sequences.append((col, seq_order, char)) + seq_order += 1 + idx += 1 + continue + + # SGR: update current_style. Sequences before the first visible + # emission are folded into the prefix synthesized by + # _apply_sgr_wrap(); those inside the clip window are emitted at + # their original position; those at or beyond *end* are dropped. + if m.group('sgr_params') is not None and propagate_sgr and current_style is not None: + current_style = _sgr_state_update(current_style, m.group()) + if captured_style is not None and col < end: + sequences.append((col, seq_order, m.group())) + seq_order += 1 + end_style = current_style + idx = m.end() + continue + + # OSC 8 hyperlink. + if hl_state := HyperlinkParams.parse(m.group()): + r = _process_hyperlink( + text, start, end, fillchar, tabsize, ambiguous_width, + term_program, + control_codes, + params=hl_state, match_end=m.end(), col=col, + ) + if r.action is _HyperlinkAction.NO_CLOSE: + sequences.append((col, seq_order, m.group())) + seq_order += 1 + idx = m.end() + elif r.action is _HyperlinkAction.EMPTY: + idx = r.close_end + elif r.action is _HyperlinkAction.OUTSIDE: + col += r.inner_width + idx = r.close_end + else: + sequences.append((col, seq_order, r.open_seq)) + seq_order += 1 + _write_cells(r.clipped_inner, r.clipped_width, col, + is_hyperlink=True) + col += r.clipped_width + sequences.append((col, seq_order, r.close_seq)) + seq_order += 1 + # Inner text is clipped with propagate_sgr=False, so any SGR + # sequences it emits are verbatim: fold them into our state. + if propagate_sgr and current_style is not None: + for sgr_m in _SGR_PATTERN.finditer(r.clipped_inner): + current_style = _sgr_state_update(current_style, sgr_m.group()) + end_style = current_style + col = r.hl_col_end + idx = r.close_end + continue + + # OSC 66 Text Sizing. + if (ts_meta := m.group('ts_meta')) is not None: + ts_text = m.group('ts_text') or '' + ts_term = m.group('ts_term') + assert ts_term is not None + ts = TextSizing( + TextSizingParams.from_params(ts_meta, control_codes=control_codes), + ts_text, ts_term) + col = _text_sizing_clip( + ts, col, start, end, fillchar, ambiguous_width, + term_program, + _write_cells) + idx = m.end() + continue + + # Indeterminate-effect sequences: raise in strict mode. + seq = m.group() + if strict and INDETERMINATE_EFFECT_SEQUENCE.match(seq): + raise ValueError( + f"Indeterminate cursor sequence at position {idx}, " + f"{seq!r}" + ) + + # Horizontal Position Absolute (CSI n G). + if (hpa_n := m.group('hpa_n')) is not None: + col = int(hpa_n) - 1 if hpa_n else 0 + idx = m.end() + continue + + # Cursor Forward (CSI n C). + if (cforward_n := m.group('cforward_n')) is not None: + n_forward = int(cforward_n) if cforward_n else 1 + move_end = col + n_forward + if col < end and move_end > start: + for i in range(max(col, start), min(move_end, end)): + _write_cells(fillchar, 1, i) + col = move_end + idx = m.end() + continue + + # Cursor Backward (CSI n D). + if (cbackward_n := m.group('cbackward_n')) is not None: + n_backward = int(cbackward_n) if cbackward_n else 1 + if strict and n_backward > col: + raise ValueError( + f"Cursor left movement at position {idx} would move " + f"{n_backward} cells left from column {col}, " + f"exceeding string start" + ) + col -= n_backward + if col < 0: + col = 0 + idx = m.end() + continue + + # Any other recognized sequence: preserve as-is. + sequences.append((col, seq_order, m.group())) + seq_order += 1 + idx = m.end() + continue + + # Carriage return. + if char == '\r': + col = 0 + idx += 1 + continue + + # Backspace. + if char == '\x08': + if col > 0: + col -= 1 + idx += 1 + continue + + # Tab expansion. + if char == '\t': + if tabsize > 0: + next_tab = col + (tabsize - (col % tabsize)) + for fill_col in range(max(col, start), min(next_tab, end)): + _write_cells(' ', 1, fill_col) + col = next_tab + else: + sequences.append((col, seq_order, '\t')) + seq_order += 1 + idx += 1 + continue + + # Grapheme cluster. + grapheme = next(iter_graphemes(text, start=idx)) + grapheme_w = width(grapheme, ambiguous_width=ambiguous_width, + term_program=term_program) + + # Emit grapheme or fillchar depending on visibility within clip window. + if grapheme_w == 0: + if start <= col < end: + sequences.append((col, seq_order, grapheme)) + seq_order += 1 + elif col >= start and col + grapheme_w <= end: + _write_cells(grapheme, grapheme_w, col) + elif col < end and col + grapheme_w > start: + clip_start = max(start, col) + for offset in range(min(end, col + grapheme_w) - clip_start): + _write_cells(fillchar, 1, clip_start + offset) + + col += grapheme_w + idx += len(grapheme) + + return (_reconstruct_painter(cells, sequences, start, end, fillchar), + captured_style, end_style) + + +def clip( + text: str, + start: int = 0, + end: int = -1, + *, + fillchar: str = ' ', + tabsize: int = 8, + ambiguous_width: int = 1, + propagate_sgr: bool = True, + control_codes: Literal['parse', 'strict', 'ignore'] = 'parse', + overtyping: Optional[bool] = None, + term_program: bool | str = False, +) -> str: + r""" + Clip text to display columns (start, end) while preserving all terminal sequences. + + This function extracts a substring using visible column positions. Terminal escape sequences + are preserved in output. If a wide character (width of 2) is + split at a boundary, it is replaced with ``fillchar``. + + TAB characters (``\t``) are expanded to spaces up to the next tab stop, controlled by the + ``tabsize`` parameter. When cursor movement is detected, a "painter's algorithm" is used unless + ``overtyping=False`` is set. Cursor movement control codes are parsed for their effects instead + of ignored. For these operations, it is assumed that ``text`` begins at column 0. + + For text containing **OSC 8 hyperlinks**, the visible text inside a hyperlink is clipped to the + requested column range and the hyperlink sequence is rebuilt:: + + >>> clip('\x1b]8;;http://example.com\x07Click This link\x1b]8;;\x07', 6, 10) + '\x1b]8;;http://example.com\x07This\x1b]8;;\x07' + + :param text: String to clip, may contain terminal escape sequences. + :param start: Absolute starting column (inclusive, 0-indexed), default ``0``. + :param end: Absolute ending column (exclusive). The default value, ``-1``, + signifies "to the end of the line", clipping only from *start* without + requiring the caller to measure the display width of *text*. + :param fillchar: Character to use when a wide character must be split at + a boundary (default space). Must have display width of 1. + :param tabsize: Tab stop width (default 8). Set to 0 to pass tabs through + as zero-width (preserved in output but don't advance column position). + :param ambiguous_width: Width to use for East Asian Ambiguous (A) + characters. Default is ``1`` (narrow). Set to ``2`` for CJK contexts. + :param propagate_sgr: If True (default), SGR (terminal styling) sequences + are propagated, matching :func:`propagate_sgr`. The result begins with + any style active at the start position, retains any style changes + occurring within the clipped region at their original position, and + ends with a reset sequence if styles are active at the end position. + :param control_codes: How to handle control characters and sequences: + + - ``'parse'`` (default): Track horizontal cursor movement and clip + hyperlink text. Cursor overwrite is always allowed, with best effort + results; indeterminate sequences (home, clear, reset, etc.) are + preserved as zero-width. + - ``'strict'``: Like ``parse``, but raises :exc:`ValueError` on + sequences with indeterminate effects (cursor home, clear screen, + reset, vertical movement, etc.) matching :func:`width` behavior. + Also raises on out-of-bounds horizontal cursor movement. + - ``'ignore'``: All control characters are treated as zero-width. + Cursor movement is not tracked (fastest path). + + :param overtyping: Whether to use the painter's algorithm for cursor + movement (``\b`` backspace, ``\r`` carriage return, and CSI cursor + left/right/position sequences). When ``None`` (default), auto-detects + by scanning for these characters in *text*. Set to ``False`` for improved + performance when the caller knows *text* contains no cursor movement + characters. Set to ``True`` to force the painter's algorithm (useful + for testing). Has no effect when ``control_codes='ignore'``. + :param term_program: Terminal software identifier for table correction. + ``False`` (default) disables override lookup. ``True`` reads the + ``TERM_PROGRAM`` or ``TERM`` environment variable for auto-detection. + Accepts a canonical terminal name matching :func:`list_term_programs`, + such as from XTVERSION_, ENQ_, or ``TERM_PROGRAM``. + + .. versionadded:: 0.8.0 + + :returns: Substring of ``text`` spanning display columns (start, end), + with all terminal sequences preserved and wide characters at boundaries + replaced with ``fillchar``. + + :raises ValueError: If ``end`` is negative and not ``-1``, or if + ``control_codes='strict'`` and an indeterminate-effect sequence or + out-of-bounds cursor movement is encountered. + + SGR (terminal styling) sequences are propagated by default. The result + begins with any active style and ends with a reset:: + + >>> clip('\x1b[1;34mHello world\x1b[0m', 6, 11) + '\x1b[1;34mworld\x1b[0m' + >>> clip('\x1b[1mbold\x1b[m normal', 1, 9) + '\x1b[1mold\x1b[m norm' + + Set ``propagate_sgr=False`` to disable this behavior. + + .. versionadded:: 0.3.0 + + .. versionchanged:: 0.5.0 + Added ``propagate_sgr`` parameter (default True). + + .. versionchanged:: 0.7.0 + Added ``control_codes`` parameter (default 'parse'). + OSC 8 hyperlink-aware clipping. OSC 66 text sizing protocol support. + Added ``overtyping`` parameter (default None, auto-detect). + + .. versionchanged:: 0.8.4 + ``start`` now defaults to ``0`` and ``end`` to ``-1``, meaning "to the + end of the line":: + + >>> clip('\x1b[1;34mHello world\x1b[0m', 6) + '\x1b[1;34mworld\x1b[0m' + + Example:: + + >>> clip('hello world', 0, 5) + 'hello' + >>> clip('中文字', 0, 3) # Wide char split at column 3 + '中 ' + >>> clip('a\tb', 0, 10) # Tab expanded to spaces + 'a b' + """ + start = max(start, 0) + if end < 0: + if end != -1: + raise ValueError( + f"end must be -1 (to end of line) or non-negative, got {end}") + # Unbounded: clip only from *start*, to the end of the line. + end = sys.maxsize + if end <= start: + return '' + + # Fast path: printable ASCII only. + if text.isascii() and text.isprintable(): + return text[start:end] + + ambiguous_width = _clamp_ambiguous_width(ambiguous_width) + + # No escape sequences => no SGR tracking needed. + has_esc = '\x1b' in text + if propagate_sgr and not has_esc: + propagate_sgr = False + + # Determine whether painter's algorithm is needed. + if overtyping is None: + # Auto-detect: scan for cursor movement characters. + overtyping = ( + control_codes != 'ignore' and + ('\x08' in text or '\r' in text or + (has_esc and bool(_HORIZONTAL_CURSOR_MOVEMENT.search(text)))) + ) + elif overtyping and control_codes == 'ignore': + overtyping = False # control_codes='ignore' overrides + fn_clip = _clip_painter if overtyping else _clip_simple + + return _apply_sgr_wrap(*fn_clip( + text=text, + start=start, + end=end, + propagate_sgr=propagate_sgr, + ambiguous_width=ambiguous_width, + term_program=term_program, + fillchar=fillchar, + tabsize=tabsize, + strict=(control_codes == 'strict'), + control_codes=control_codes, + )) diff --git a/.venv/lib/python3.12/site-packages/wcwidth/_constants.py b/.venv/lib/python3.12/site-packages/wcwidth/_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..b3cc1fe142cf04f17de4e0d436b6d58a969d8be6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/_constants.py @@ -0,0 +1,177 @@ +"""Shared data tables and constants for wcwidth.py, _wcwidth.py, and _wcswidth.py.""" +from __future__ import annotations + +# std imports +import os +from operator import index as _index +from functools import lru_cache + +from typing import Tuple, NamedTuple + +# local +from .table_mc import CATEGORY_MC +from .table_wide import WIDE_EASTASIAN +from .table_zero import ZERO_WIDTH +from .table_grapheme import (ISC_VIRAMA, + EXTENDED_PICTOGRAPHIC, + ISC_INVISIBLE_STACKER, + GRAPHEME_REGIONAL_INDICATOR) +from .table_ambiguous import AMBIGUOUS_EASTASIAN +from .table_overrides import (SFZ_OVERRIDES, + SRI_OVERRIDES, + VS15_OVERRIDES, + VS16_OVERRIDES, + WIDE_OVERRIDES, + NARROW_OVERRIDES) +from .unicode_versions import list_versions +from .table_term_programs import ALIASES, KNOWN_TERMINALS + +_RangeTuple = Tuple[Tuple[int, int], ...] + + +__all__ = ( + "_REGIONAL_INDICATOR_SET", + "_ISC_VIRAMA_SET", + "_LATEST_VERSION", + "_CATEGORY_MC_TABLE", + "_EMOJI_ZWJ_SET", + "_FITZPATRICK_RANGE", + "_ZERO_WIDTH_TABLE", + "_WIDE_EASTASIAN_TABLE", + "_AMBIGUOUS_TABLE", + "resolve_terminal", + "get_term_overrides", + "list_term_programs", +) + +_REGIONAL_INDICATOR_SET = frozenset( + range(GRAPHEME_REGIONAL_INDICATOR[0][0], GRAPHEME_REGIONAL_INDICATOR[0][1] + 1) +) +_ISC_VIRAMA_SET = frozenset( + cp for lo, hi in (*ISC_VIRAMA, *ISC_INVISIBLE_STACKER) + for cp in range(lo, hi + 1) +) +# pylint: disable=invalid-name +_LATEST_VERSION = list_versions()[-1] +_CATEGORY_MC_TABLE = CATEGORY_MC[_LATEST_VERSION] +_EMOJI_ZWJ_SET = frozenset( + cp for lo, hi in EXTENDED_PICTOGRAPHIC for cp in range(lo, hi + 1) +) | _REGIONAL_INDICATOR_SET +_FITZPATRICK_RANGE = (0x1F3FB, 0x1F3FF) + +_ZERO_WIDTH_TABLE = ZERO_WIDTH[_LATEST_VERSION] +_WIDE_EASTASIAN_TABLE = WIDE_EASTASIAN[_LATEST_VERSION] +_AMBIGUOUS_TABLE = AMBIGUOUS_EASTASIAN[_LATEST_VERSION] + + +def list_term_programs() -> tuple[str, ...]: + """ + Return all recognized values for the ``term_program`` argument. + + Includes canonical terminal names and their TERM/TERM_PROGRAM aliases. + + .. versionadded:: 0.8.0 + """ + return tuple(sorted(KNOWN_TERMINALS | ALIASES.keys())) + + +def _merge_ranges(*tuples: _RangeTuple) -> _RangeTuple: + """Merge multiple sorted range tuples into one sorted, non-overlapping tuple.""" + all_ranges: list[tuple[int, int]] = [] + for t in tuples: + all_ranges.extend(t) + if not all_ranges: + return () + all_ranges.sort(key=lambda r: r[0]) + merged = [all_ranges[0]] + for lo, hi in all_ranges[1:]: + _, prev_hi = merged[-1] + if lo <= prev_hi: + merged[-1] = (merged[-1][0], max(prev_hi, hi)) + else: + merged.append((lo, hi)) + return tuple(merged) + + +class TerminalOverrides(NamedTuple): + """Pre-merged override range tuples for a single terminal.""" + + narrower: _RangeTuple + vs16_narrower: _RangeTuple + vs15_wider: _RangeTuple + zeroer: _RangeTuple + narrow_wider: _RangeTuple + narrow_zeroer: _RangeTuple + + +_EMPTY_OVERRIDES = TerminalOverrides((), (), (), (), (), ()) + + +@lru_cache(maxsize=32) +def get_term_overrides(term_canonical: str) -> TerminalOverrides: + """Return a TerminalOverrides, with all empty tuples when there are no overrides.""" + # wide, sri, sfz: all narrow characters Unicode expects wide (no 'wider' data exists) + narrower = _merge_ranges( + WIDE_OVERRIDES.get(term_canonical, {}).get('narrower', ()), + SRI_OVERRIDES.get(term_canonical, {}).get('narrower', ()), + SFZ_OVERRIDES.get(term_canonical, {}).get('narrower', ()), + ) + vs16_narrower = VS16_OVERRIDES.get(term_canonical, {}).get('narrower', ()) + vs15_wider = VS15_OVERRIDES.get(term_canonical, {}).get('wider', ()) + zeroer = _merge_ranges( + WIDE_OVERRIDES.get(term_canonical, {}).get('zeroer', ()), + SRI_OVERRIDES.get(term_canonical, {}).get('zeroer', ()), + SFZ_OVERRIDES.get(term_canonical, {}).get('zeroer', ()), + ) + narrow_wider = NARROW_OVERRIDES.get(term_canonical, {}).get('wider', ()) + narrow_zeroer = NARROW_OVERRIDES.get(term_canonical, {}).get('narrow_zeroer', ()) + # vs15_narrower intentionally excluded: no known terminal narrows VS15 + # vs16_wider intentionally excluded: any 'wider' entries in emoji_vs16_results + # ucs-detect YAML are from the vs16n baseline test (base char without VS16), + # not actual VS16 correction data. + + if not (narrower or vs16_narrower or vs15_wider or zeroer + or narrow_wider or narrow_zeroer): + return _EMPTY_OVERRIDES + return TerminalOverrides(narrower, vs16_narrower, vs15_wider, zeroer, + narrow_wider, narrow_zeroer) + + +@lru_cache(maxsize=32) +def resolve_terminal(term_program: bool | str = False) -> str | None: + """ + Resolve a terminal identifier to its canonical name. + + :param term_program: Terminal identifier. ``False`` (default) disables override lookup. + ``True`` reads the ``TERM_PROGRAM`` environment variable, falling back to ``TERM``. + A string value is used directly (canonical name, alias, XTVERSION/ENQ result, etc.). + :returns: Canonical terminal name if recognized, ``None`` otherwise. + + The auto-detection path (``term_program=True``) reads environment variables at call time + and caches the result. The environment is assumed immutable for the process lifetime; + callers that change ``TERM`` or ``TERM_PROGRAM`` mid-process must call + :func:`resolve_terminal.cache_clear` afterward. + """ + if term_program is False: + return None + if term_program is True: + term_program = os.environ.get('TERM_PROGRAM', '') or os.environ.get('TERM', '') + if not term_program: + return None + key = term_program.strip().lower() + canonical = ALIASES.get(key, key) + if canonical not in KNOWN_TERMINALS: + return None + return canonical + + +def _clamp_ambiguous_width(ambiguous_width: int) -> int: + """Clamp *ambiguous_width* to 1 or 2.""" + # this operator.index() rejects bool/float and overall this is faster than + # combining min() and max(). + value = _index(ambiguous_width) + if value < 1: + return 1 + if value > 2: + return 2 + return value diff --git a/.venv/lib/python3.12/site-packages/wcwidth/_wcswidth.py b/.venv/lib/python3.12/site-packages/wcwidth/_wcswidth.py new file mode 100644 index 0000000000000000000000000000000000000000..666409281eee43c88b03045efa9bff13da76cf75 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/_wcswidth.py @@ -0,0 +1,446 @@ +"""This is a python implementation of wcswidth().""" + +from __future__ import annotations + +from typing import Optional + +__lazy_modules__ = [ + "wcwidth._constants", + "wcwidth._wcwidth", + "wcwidth.bisearch", + "wcwidth.table_grapheme", + "wcwidth.table_vs16", +] +# local +from . import table_grapheme_overrides +from ._wcwidth import wcwidth +from .bisearch import bisearch +from ._constants import (_EMOJI_ZWJ_SET, + _ISC_VIRAMA_SET, + _CATEGORY_MC_TABLE, + _FITZPATRICK_RANGE, + _REGIONAL_INDICATOR_SET, + resolve_terminal, + get_term_overrides, + _clamp_ambiguous_width) +from .table_vs15 import VS15_WIDE_TO_NARROW +from .table_vs16 import VS16_NARROW_TO_WIDE +from .table_grapheme import GRAPHEME_EXTEND + + +def _scan_zwj_cluster_end(text: str, start: int, end: int) -> int: + """ + Scan forward from *start* (base character) to end of a ZWJ grapheme cluster. + + Follows the UAX #29 GB11 pattern (ExtPict Extend* ZWJ x ExtPict) chained repeatedly until no + more ZWJ joins are found. + """ + idx = start + 1 + # Skip Extend characters (Fitzpatrick modifiers, etc.) before first ZWJ + while idx < end and bisearch(ord(text[idx]), GRAPHEME_EXTEND): + idx += 1 + # Follow ZWJ chains + while idx < end: + if ord(text[idx]) != 0x200D: + break + idx += 1 + # GB11: \p{ExtPict} Extend* ZWJ × \p{ExtPict} + # Extend modifiers (VS16, Fitzpatrick skin tones, etc.) attach to + # the ExtPict *before* the ZWJ. After ZWJ the next codepoint is + # always an ExtPict directly, no Extend skip needed. + if idx < end and ord(text[idx]) in _EMOJI_ZWJ_SET: + idx += 1 + # Skip trailing Extend (VS16, etc.) after ExtPict before next ZWJ + while idx < end and bisearch(ord(text[idx]), GRAPHEME_EXTEND): + idx += 1 + continue + break + return idx + + +def wcswidth( + pwcs: str, + n: Optional[int] = None, + unicode_version: str = 'auto', + ambiguous_width: int = 1, +) -> int: + """ + Given a unicode string, return its printable length on a terminal. + + See :ref:`Specification` for details of cell measurement. + + This implementation differs from Markus Khun's original POSIX C implementation, in that this + ``wcswidth()`` processes graphemes strings yielded by :func:`wcwidth.iter_graphemes` defined by + `Unicode Standard Annex #29`_. POSIX wcswidth(3) is not grapheme-aware and does not measure many + kinds of Emojis or complex scripts correctly. + + :param pwcs: Measure width of given unicode string. + :param n: When ``n`` is None (default), return the length of the entire + string, otherwise only the first ``n`` characters are measured. + :param unicode_version: Ignored. Retained for backwards compatibility. + + .. deprecated:: 0.3.0 + Only the latest Unicode version is now shipped. + + :param ambiguous_width: Width to use for East Asian Ambiguous (A) + characters. Default is ``1`` (narrow). Set to ``2`` for CJK contexts. + :returns: The width, in cells, needed to display the first ``n`` characters + of the unicode string ``pwcs``. Returns ``-1`` for C0 and C1 control + characters! + + .. _`Unicode Standard Annex #29`: https://www.unicode.org/reports/tr29/ + """ + # pylint: disable=unused-argument,too-many-locals,too-many-statements,redefined-variable-type + # pylint: disable=too-complex,too-many-branches,duplicate-code,too-many-nested-blocks + + # Fast path: pure ASCII printable strings are always width == length + if n is None and pwcs.isascii() and pwcs.isprintable(): + return len(pwcs) + + ambiguous_width = _clamp_ambiguous_width(ambiguous_width) + + _wcwidth = wcwidth if ambiguous_width == 1 else lambda c: wcwidth(c, 'auto', ambiguous_width) + + end = len(pwcs) if n is None else min(n, len(pwcs)) + total_width = 0 + idx = 0 + + last_measured_idx = -2 # -2 sentinel blocks VS16/VS15 (no base available) + last_measured_ucs = -1 + last_measured_w = 0 + prev_was_virama = False + cluster_width = 0 + vs16_nw_table = VS16_NARROW_TO_WIDE['9.0.0'] + vs15_wn_table = VS15_WIDE_TO_NARROW['9.0.0'] + _bisearch = bisearch + + while idx < end: + char = pwcs[idx] + ucs = ord(char) + + # 5. ZWJ (U+200D): consumed without contributing width. + # Virama codepoints are treated as zero-width combining marks (Mn). When a + # virama+consonant sequence forms a conjunct, its width is capped at 2 cells. + + # ZWJ (U+200D) + if ucs == 0x200D: + if prev_was_virama: + idx += 1 + elif idx + 1 < end: + last_measured_w = 0 + prev_was_virama = False + idx += 2 + else: + prev_was_virama = False + idx += 1 + continue + + # 6. VS16 (U+FE0F): converts preceding narrow character to wide. + if ucs == 0xFE0F and last_measured_idx >= 0: + if _bisearch(last_measured_ucs, vs16_nw_table): + cluster_width = 2 + last_measured_idx = -2 + idx += 1 + continue + + # VS15 (U+FE0E): text variation selector, requests narrow presentation. + if ucs == 0xFE0E and last_measured_idx >= 0: + if bisearch(last_measured_ucs, vs15_wn_table) and last_measured_w == 2: + total_width -= 1 + last_measured_idx = -2 + idx += 1 + continue + + # 7. Regional Indicator & Fitzpatrick (both above BMP) + if ucs > 0xFFFF: + if ucs in _REGIONAL_INDICATOR_SET: + ri_before = 0 + j = idx - 1 + while j >= 0 and ord(pwcs[j]) in _REGIONAL_INDICATOR_SET: + ri_before += 1 + j -= 1 + if ri_before % 2 == 1: + last_measured_ucs = ucs + idx += 1 + continue + elif (_FITZPATRICK_RANGE[0] <= ucs <= _FITZPATRICK_RANGE[1] + and last_measured_ucs in _EMOJI_ZWJ_SET): + idx += 1 + continue + + # 8. Normal character: measure with wcwidth + w = _wcwidth(char) + if w < 0: + return -1 + if w > 0: + if prev_was_virama: + cluster_width = 2 + elif cluster_width: + total_width += cluster_width + cluster_width = w + else: + cluster_width = w + + last_measured_idx = idx + last_measured_ucs = ucs + last_measured_w = w + prev_was_virama = False + elif ucs in _ISC_VIRAMA_SET: + prev_was_virama = True + elif last_measured_idx >= 0 and _bisearch(ucs, _CATEGORY_MC_TABLE): + cluster_width = 2 + last_measured_idx = -2 + prev_was_virama = False + else: + prev_was_virama = False + idx += 1 + + if cluster_width: + total_width += cluster_width + return total_width + + +def wcstwidth( + pwcs: str, + n: Optional[int] = None, + unicode_version: str = 'auto', + ambiguous_width: int = 1, + term_program: bool | str = True, +) -> int: + """ + Given a unicode string, return its printable length on a terminal given by ``term_program``. + + See :ref:`Specification` for details of cell measurement. + + Unlike :func:`wcswidth`, this function applies per-terminal correction tables for + emoji presentation and grapheme clusters. + + :param pwcs: Measure width of given unicode string. + :param n: When ``n`` is None (default), return the length of the entire + string, otherwise only the first ``n`` characters are measured. + :param unicode_version: Ignored. Retained for backwards compatibility. + :param ambiguous_width: Width to use for East Asian Ambiguous (A) + characters. Default is ``1`` (narrow). Set to ``2`` for CJK contexts. + :param term_program: Terminal software identifier for table correction. + ``True`` (default) reads the ``TERM_PROGRAM`` or ``TERM`` environment + variable for auto-detection. ``False`` disables override lookup. + Accepts a canonical terminal name matching :func:`list_term_programs`, + such as from XTVERSION_, ENQ_, or ``TERM_PROGRAM``. + + .. versionadded:: 0.8.0 + :returns: The width, in cells, needed to display the first ``n`` characters + of the unicode string ``pwcs``. Returns ``-1`` for C0 and C1 control + characters! + """ + # pylint: disable=unused-argument,too-many-locals,too-many-statements,redefined-variable-type + # pylint: disable=too-complex,too-many-branches,duplicate-code,too-many-nested-blocks + # This function intentionally keeps all logic inline for performance. + + # Fast path: pure ASCII printable strings are always width == length + if n is None and pwcs.isascii() and pwcs.isprintable(): + return len(pwcs) + + ambiguous_width = _clamp_ambiguous_width(ambiguous_width) + + # Resolve terminal software for override lookup + term_canonical = resolve_terminal(term_program) + + # Skip override lookup when no terminal detected (avoids lru_cache call overhead). + # Extract locals for hot-loop performance (NamedTuple attribute access is slow). + if term_canonical: + overrides = get_term_overrides(term_canonical) + _narrower = overrides.narrower + _vs16_narrower = overrides.vs16_narrower + _vs15_wider = overrides.vs15_wider + _zeroer = overrides.zeroer + _narrow_wider = overrides.narrow_wider + _narrow_zeroer = overrides.narrow_zeroer + _grapheme_overrides = table_grapheme_overrides.get(term_canonical) + else: + _narrower = () + _vs16_narrower = () + _vs15_wider = () + _zeroer = () + _narrow_wider = () + _narrow_zeroer = () + _grapheme_overrides = {} + + # Select wcwidth call pattern for best lru_cache performance + _wcwidth = wcwidth if ambiguous_width == 1 else lambda c: wcwidth(c, 'auto', ambiguous_width) + + end = len(pwcs) if n is None else min(n, len(pwcs)) + total_width = 0 + idx = 0 + + # grapheme-clustering state and local re-binding for performance. + # Widths accumulate in cluster_width and flush at boundaries. A cluster is a base character + # plus combining marks, deferring the flush lets grapheme overrides replace the measured width + # retrospectively. + last_measured_idx = -2 # -2 sentinel blocks VS16/VS15 (no base available) + last_measured_ucs = -1 + last_measured_w = 0 + prev_was_virama = False + cluster_start = -1 + total_before_cluster = 0 + cluster_width = 0 + vs16_nw_table = VS16_NARROW_TO_WIDE['9.0.0'] + vs15_wn_table = VS15_WIDE_TO_NARROW['9.0.0'] + _bisearch = bisearch + + while idx < end: + char = pwcs[idx] + ucs = ord(char) + + # + # Much of the logic below matches width(); it is repeated here for performance, with + # matching index reference numbers (starting at #5). + # + # 5. ZWJ (U+200D): consumed without contributing width. + # Virama codepoints are treated as zero-width combining marks (Mn). When a + # virama+consonant sequence forms a conjunct, its width is capped at 2 cells + # matching behavior of popular terminals (PR #224) + + # ZWJ (U+200D) + if ucs == 0x200D: + if prev_was_virama: + idx += 1 + elif idx + 1 < end: + # Check for terminal grapheme override when base char is ExtPict/RI + if (_grapheme_overrides + and last_measured_idx >= 0 + and last_measured_ucs in _EMOJI_ZWJ_SET): + cluster_end = _scan_zwj_cluster_end(pwcs, last_measured_idx, end) + cluster = pwcs[last_measured_idx:cluster_end] + override_w = _grapheme_overrides.get(cluster) + if override_w is not None: + total_width += (override_w - last_measured_w) + last_measured_idx = -2 + last_measured_ucs = -1 + last_measured_w = 0 + prev_was_virama = False + cluster_start = -1 + idx = cluster_end + continue + # No override; ZWJ breaks VS adjacency. + # VS16 already set last_measured_idx = -2, blocking further VS16. + last_measured_w = 0 + prev_was_virama = False + idx += 2 + else: + prev_was_virama = False + idx += 1 + continue + + # 6. VS16 (U+FE0F): converts preceding narrow character to wide. + if ucs == 0xFE0F and last_measured_idx >= 0: + if _vs16_narrower and _bisearch(last_measured_ucs, _vs16_narrower): + pass + elif _bisearch(last_measured_ucs, vs16_nw_table): + cluster_width = 2 + last_measured_idx = -2 + idx += 1 + continue + + # VS15 (U+FE0E): text variation selector, requests narrow presentation. + if ucs == 0xFE0E and last_measured_idx >= 0: + base_ucs = last_measured_ucs + vs15_narrow = bisearch(base_ucs, vs15_wn_table) + if _vs15_wider and bisearch(base_ucs, _vs15_wider): + vs15_narrow = False + if vs15_narrow and last_measured_w == 2: + total_width -= 1 + last_measured_idx = -2 + idx += 1 + continue + + # 7. Regional Indicator & Fitzpatrick (both above BMP) + if ucs > 0xFFFF: + if ucs in _REGIONAL_INDICATOR_SET: + ri_before = 0 + j = idx - 1 + while j >= 0 and ord(pwcs[j]) in _REGIONAL_INDICATOR_SET: + ri_before += 1 + j -= 1 + if ri_before % 2 == 1: + last_measured_ucs = ucs + idx += 1 + continue + elif (_FITZPATRICK_RANGE[0] <= ucs <= _FITZPATRICK_RANGE[1] + and last_measured_ucs in _EMOJI_ZWJ_SET): + idx += 1 + continue + + # 8. Normal character: measure with wcwidth + w = _wcwidth(char) + if w < 0: + # C0/C1 control character + return -1 + # Apply single-codepoint terminal overrides (pre-merged tuples) + if w == 2 and _narrower and bisearch(ucs, _narrower): + w = 1 + elif w == 2 and _zeroer and bisearch(ucs, _zeroer): + w = 0 + if w == 1 and _narrow_wider and bisearch(ucs, _narrow_wider): + w = 2 + elif w == 1 and _narrow_zeroer and bisearch(ucs, _narrow_zeroer): + w = 0 + if w > 0: + # virama+consonant extends current cluster; otherwise start new + if prev_was_virama: + cluster_width = 2 + elif cluster_width: + # flush previous cluster, check for grapheme overrides + flushed = False + if _grapheme_overrides and cluster_start >= 0: + # Two-phase override lookup: candidate (cluster+current) catches Lo+Lo pairs + # where both chars bear width (Thai KO KAI + SARA AM). cluster_text (cluster + # alone) catches C+Mc clusters where the override key is shorter. + candidate = pwcs[cluster_start:idx + 1] + override_w = _grapheme_overrides.get(candidate) + if override_w is not None: + total_width = total_before_cluster + override_w + flushed = True + cluster_width = 0 + else: + cluster_text = pwcs[cluster_start:idx] + override_w = _grapheme_overrides.get(cluster_text) + if override_w is not None: + total_width = total_before_cluster + override_w + else: + total_width += cluster_width + else: + total_width += cluster_width + if not flushed: + cluster_width = w + cluster_start = idx + total_before_cluster = total_width + else: + cluster_width = w + cluster_start = idx + total_before_cluster = total_width + last_measured_idx = idx + last_measured_ucs = ucs + last_measured_w = w + prev_was_virama = False + elif ucs in _ISC_VIRAMA_SET: + prev_was_virama = True + elif last_measured_idx >= 0 and _bisearch(ucs, _CATEGORY_MC_TABLE): + # Spacing Combining Mark (Mc) following a base character + cluster_width = 2 + last_measured_idx = -2 + prev_was_virama = False + else: + prev_was_virama = False + idx += 1 + + if cluster_width: + if _grapheme_overrides and cluster_start >= 0: + cluster_text = pwcs[cluster_start:end] + override_w = _grapheme_overrides.get(cluster_text) + if override_w is not None: + total_width = total_before_cluster + override_w + else: + total_width += cluster_width + else: + total_width += cluster_width + return total_width diff --git a/.venv/lib/python3.12/site-packages/wcwidth/_wcwidth.py b/.venv/lib/python3.12/site-packages/wcwidth/_wcwidth.py new file mode 100644 index 0000000000000000000000000000000000000000..82a39556cf459d506e283eed65f15e768ad7ea17 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/_wcwidth.py @@ -0,0 +1,168 @@ +""" +This is a python implementation of wcwidth() and wcswidth(). + +https://github.com/jquast/wcwidth + +Derived from Markus Kuhn's C code, + +This is an implementation of wcwidth() and wcswidth() (defined in +IEEE Std 1002.1-2001) for Unicode. + +http://www.opengroup.org/onlinepubs/007904975/functions/wcwidth.html +http://www.opengroup.org/onlinepubs/007904975/functions/wcswidth.html + +In fixed-width output devices, Latin characters all occupy a single +"cell" position of equal width, whereas ideographic CJK characters +occupy two such cells. Interoperability between terminal-line +applications and (teletype-style) character terminals using the +UTF-8 encoding requires agreement on which character should advance +the cursor by how many cell positions. No established formal +standards exist at present on which Unicode character shall occupy +how many cell positions on character terminals. These routines are +a first attempt of defining such behavior based on simple rules +applied to data provided by the Unicode Consortium. + +For some graphical characters, the Unicode standard explicitly +defines a character-cell width via the definition of the East Asian +FullWidth (F), Wide (W), Half-width (H), and Narrow (Na) classes. +In all these cases, there is no ambiguity about which width a +terminal shall use. For characters in the East Asian Ambiguous (A) +class, the width choice depends purely on a preference of backward +compatibility with either historic CJK or Western practice. +Choosing single-width for these characters is easy to justify as +the appropriate long-term solution, as the CJK practice of +displaying these characters as double-width comes from historic +implementation simplicity (8-bit encoded characters were displayed +single-width and 16-bit ones double-width, even for Greek, +Cyrillic, etc.) and not any typographic considerations. + +Much less clear is the choice of width for the Not East Asian +(Neutral) class. Existing practice does not dictate a width for any +of these characters. It would nevertheless make sense +typographically to allocate two character cells to characters such +as for instance EM SPACE or VOLUME INTEGRAL, which cannot be +represented adequately with a single-width glyph. The following +routines at present merely assign a single-cell width to all +neutral characters, in the interest of simplicity. This is not +entirely satisfactory and should be reconsidered before +establishing a formal standard in this area. At the moment, the +decision which Not East Asian (Neutral) characters should be +represented by double-width glyphs cannot yet be answered by +applying a simple rule from the Unicode database content. Setting +up a proper standard for the behavior of UTF-8 character terminals +will require a careful analysis not only of each Unicode character, +but also of each presentation form, something the author of these +routines has avoided to do so far. + +http://www.unicode.org/unicode/reports/tr11/ + +Latest version: http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c +""" + +from __future__ import annotations + +# std imports +from functools import lru_cache + +__lazy_modules__ = [ + "wcwidth.bisearch", + "wcwidth._constants", +] +# local +from .bisearch import bisearch +from ._constants import (_LATEST_VERSION, + _AMBIGUOUS_TABLE, + _ZERO_WIDTH_TABLE, + _WIDE_EASTASIAN_TABLE, + _clamp_ambiguous_width) + + +@lru_cache(maxsize=128) +def _wcversion_value(ver_string: str) -> tuple[int, ...]: # pragma: no cover + """ + Integer-mapped value of given dotted version string. + + .. deprecated:: 0.3.0 + + This function is no longer used internally by wcwidth but is retained + for API compatibility with external tools. + + :param ver_string: Unicode version string, of form ``n.n.n``. + :returns: tuple of digit tuples, ``tuple(int, [...])``. + """ + retval = tuple(map(int, (ver_string.split('.')))) + return retval + + +@lru_cache(maxsize=8) +def _wcmatch_version(given_version: str) -> str: # pylint: disable=unused-argument + """ + Return the supported Unicode version level. + + .. deprecated:: 0.3.0 + This function now always returns the latest version. + + This function is no longer used internally by wcwidth but is retained + for API compatibility with external tools. + + :param given_version: Ignored. Any value is accepted for compatibility. + :returns: The latest unicode version string. + """ + return _LATEST_VERSION + + +# maxsize=1024: western scripts need ~64 unique codepoints per session, but +# CJK sessions may use ~2000 of ~3500 common hanzi/kanji. 1024 accommodates +# heavy CJK use. Performance floor at 32; bisearch is ~100ns per miss. + +@lru_cache(maxsize=1024) +def wcwidth(wc: str, unicode_version: str = 'auto', ambiguous_width: int = 1) -> int: # pylint: disable=unused-argument + r""" + Given one Unicode codepoint, return its printable length on a terminal. + + :param wc: A single Unicode character. + :param unicode_version: Ignored. Retained for backwards compatibility. + + .. deprecated:: 0.3.0 + Only the latest Unicode version is now shipped. + + :param ambiguous_width: Width to use for East Asian Ambiguous (A) + characters. Default is ``1`` (narrow). Set to ``2`` for CJK contexts + where ambiguous characters display as double-width. See + :ref:`ambiguous_width` for details. + :returns: The width, in cells, necessary to display the character of + Unicode string character, ``wc``. Returns 0 if the ``wc`` argument has + no printable effect on a terminal (such as NUL '\0'), -1 if ``wc`` is + not printable, or has an indeterminate effect on the terminal, such as + a control character. Otherwise, the number of column positions the + character occupies on a graphic terminal (1 or 2) is returned. + + See :ref:`Specification` for details of cell measurement. + """ + ucs = ord(wc) if wc else 0 + + # small optimization: early return of 1 for printable ASCII, this provides + # approximately 40% performance improvement for mostly-ascii documents, with + # less than 1% impact to others. + if 32 <= ucs < 0x7f: + return 1 + + ambiguous_width = _clamp_ambiguous_width(ambiguous_width) + + # C0/C1 control characters are -1 for compatibility with POSIX-like calls + if ucs and ucs < 32 or 0x07F <= ucs < 0x0A0: + return -1 + + # Zero width + if bisearch(ucs, _ZERO_WIDTH_TABLE): + return 0 + + # Wide (F/W categories) + if bisearch(ucs, _WIDE_EASTASIAN_TABLE): + return 2 + + # Ambiguous width (A category) - only when ambiguous_width=2 + if ambiguous_width == 2 and bisearch(ucs, _AMBIGUOUS_TABLE): + return 2 + + return 1 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/_width.py b/.venv/lib/python3.12/site-packages/wcwidth/_width.py new file mode 100644 index 0000000000000000000000000000000000000000..783c49bc26f7332af3aaa9d8ade345e65403ffe1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/_width.py @@ -0,0 +1,518 @@ +"""This is a high-level width() supporting terminal output.""" + +from __future__ import annotations + +from typing import Literal + +__lazy_modules__ = [ + "wcwidth._constants", + "wcwidth._wcswidth", + "wcwidth._wcwidth", + "wcwidth.bisearch", + "wcwidth.control_codes", + "wcwidth.escape_sequences", + "wcwidth.table_grapheme", + "wcwidth.table_vs16", + "wcwidth.text_sizing", +] +# local +from . import table_grapheme_overrides +from ._wcwidth import wcwidth +from .bisearch import bisearch +from ._wcswidth import wcswidth, wcstwidth, _scan_zwj_cluster_end +from ._constants import (_EMOJI_ZWJ_SET, + _ISC_VIRAMA_SET, + _CATEGORY_MC_TABLE, + _FITZPATRICK_RANGE, + _REGIONAL_INDICATOR_SET, + resolve_terminal, + get_term_overrides, + _clamp_ambiguous_width) +from .table_vs15 import VS15_WIDE_TO_NARROW +from .table_vs16 import VS16_NARROW_TO_WIDE +from .text_sizing import TextSizing, TextSizingParams +from .control_codes import ILLEGAL_CTRL, VERTICAL_CTRL, HORIZONTAL_CTRL, ZERO_WIDTH_CTRL +from .escape_sequences import (_SEQUENCE_CLASSIFY, + TEXT_SIZING_PATTERN, + CURSOR_MOVEMENT_SEQUENCE, + INDETERMINATE_EFFECT_SEQUENCE, + strip_sequences) + +# In 'parse' mode, strings longer than this are checked for cursor-movement +# controls (BS, TAB, CR, cursor sequences); when absent, mode downgrades to +# 'ignore' to skip character-by-character parsing. The detection scan cost is +# negligible for long strings but wasted on short ones like labels or headings. +_WIDTH_FAST_PATH_MIN_LEN = 20 + +# Translation table to strip C0/C1 control characters for fast 'ignore' mode. +_CONTROL_CHAR_TABLE = str.maketrans('', '', ( + ''.join(chr(c) for c in range(0x00, 0x20)) + # C0: NUL through US (including tab) + '\x7f' + # DEL + ''.join(chr(c) for c in range(0x80, 0xa0)) # C1: U+0080-U+009F +)) + + +def _width_ignored_codes(text: str, ambiguous_width: int = 1, + term_program: bool | str = False) -> int: + """ + Fast path for width() with control_codes='ignore'. + + Strips escape sequences and control characters, then measures remaining text. + """ + if term_program is False: + return wcswidth( + strip_sequences(text).translate(_CONTROL_CHAR_TABLE), + ambiguous_width=ambiguous_width, + ) + return wcstwidth( + strip_sequences(text).translate(_CONTROL_CHAR_TABLE), + ambiguous_width=ambiguous_width, + term_program=term_program, + ) + + +def width( + text: str, + *, + control_codes: Literal['parse', 'strict', 'ignore'] = 'parse', + tabsize: int = 8, + ambiguous_width: int = 1, + term_program: bool | str = False, +) -> int: + r""" + Return printable width of text containing many kinds of control codes and sequences. + + Unlike :func:`wcswidth`, this function handles most control characters and many popular terminal + output sequences. Never returns -1. + + :param text: String to measure. + :param control_codes: How to handle control characters and sequences: + + - ``'parse'`` (default): Track horizontal cursor movement like BS ``\b``, CR ``\r``, TAB + ``\t``, cursor left and right movement sequences. Vertical movement (LF, VT, FF) and + indeterminate terminal sequences are zero-width. OSC 66 Kitty Text Sizing protocol, OSC 8 + Hyperlink, and many other kinds of output sequences are parsed for displayed measurements. + - ``'strict'``: Like parse, but raises :exc:`ValueError` on control characters with + indeterminate results of the screen or cursor, like clear or vertical movement. Generally, + these should be handled with a virtual terminal emulator (like 'pyte'). + - ``'ignore'``: All C0 and C1 control characters and escape sequences are measured as + width 0. This is the fastest measurement for text already filtered or known not to contain + any kinds of control codes or sequences. TAB ``\t`` is zero-width; to ensure + tab expansion, pre-process text using :func:`str.expandtabs`. + + :param tabsize: Tab stop width for ``'parse'`` and ``'strict'`` modes. Default is 8. Must be + positive. Has no effect when ``control_codes='ignore'``. + :param ambiguous_width: Width to use for East Asian Ambiguous (A) characters. Default is ``1`` + (narrow). Set to ``2`` for CJK contexts. + :param term_program: Terminal software identifier for table correction. + ``False`` (default) disables override lookup. ``True`` reads the + ``TERM_PROGRAM`` or ``TERM`` environment variable for auto-detection. + Accepts a canonical terminal name matching :func:`list_term_programs`, + such as from XTVERSION_, ENQ_, or ``TERM_PROGRAM``. + + .. versionadded:: 0.8.0 + :returns: Maximum cursor position reached, "extent", accounting for cursor movement sequences + present in ``text`` according to given parameters. This represents the rightmost column the + cursor reaches. Always a non-negative integer. + :raises ValueError: If ``control_codes='strict'`` and control characters with indeterminate + effects, such as vertical movement or clear sequences are encountered, or on unexpected + C0 or C1 control code. Also raised when ``control_codes`` is not one of the valid values. + + .. versionadded:: 0.3.0 + + .. versionchanged:: 0.7.0 + Expanded strict-mode to raise :exc:`ValueError` when cursor-left movement + (CSI D) would move beyond the beginning of the string. Previously, cursor-left + was silently clamped to column 0 in all modes. + + Support horizontal cursor sequences (``cub``, ``cuf``, ``hpa``). Cursor-left (``cub``) or + backspace (``\b``) now overwrites text. ``column_address`` (``hpa``) and carriage return + (``\r``) are now parsed, and some values conditionally raise ``ValueError`` when + ``control_codes='parse'``. + + Examples:: + + >>> width('hello') + 5 + >>> width('コンニチハ') + 10 + >>> width('\x1b[31mred\x1b[0m') + 3 + >>> width('\x1b[31mred\x1b[0m', control_codes='ignore') # same result (ignored) + 3 + >>> width('123\b4') # backspace overwrites previous cell (outputs '124') + 3 + >>> width('abc\t') # tab caused cursor to move to column 8 + 8 + >>> width('1\x1b[10C') # '1' + cursor right 10, cursor ends on column 11 + 11 + >>> width('1\x1b[10C', control_codes='ignore') # faster but wrong in this case + 1 + """ + # pylint: disable=too-complex,too-many-branches,too-many-statements,too-many-locals,redefined-variable-type,too-many-nested-blocks + # This could be split into sub-functions (#1, #3 and #6 especially), but this function is a + # hot path, so the steps stay inline and the pylint complexity rules are disabled. + + # Fast path for ASCII printable (no tabs, escapes, or control chars) + if text.isascii() and text.isprintable(): + return len(text) + + ambiguous_width = _clamp_ambiguous_width(ambiguous_width) + + # Fast parse: if no horizontal cursor movements are possible, switch to 'ignore' mode. + # Only check longer strings - the detection overhead hurts short string performance. + if control_codes == 'parse' and len(text) > _WIDTH_FAST_PATH_MIN_LEN: + # Check for cursor-affecting control characters + if '\b' not in text and '\t' not in text and '\r' not in text: + # Check for escape sequences, if none contain cursor movement or + # text sizing, downgrade to 'ignore' + if '\x1b' not in text or ( + not CURSOR_MOVEMENT_SEQUENCE.search(text) + and not TEXT_SIZING_PATTERN.search(text) + ): + control_codes = 'ignore' + + # Fast path for ignore mode, useful if you know the text is already free of control codes + if control_codes == 'ignore': + return _width_ignored_codes(text, ambiguous_width, term_program=term_program) + + # Resolve terminal software for override lookup + term_canonical = resolve_terminal(term_program) + + # Skip override lookup when no terminal detected (avoids lru_cache call overhead). + # Extract locals for hot-loop performance (NamedTuple attribute access is slow). + if term_canonical: + overrides = get_term_overrides(term_canonical) + _narrower = overrides.narrower + _vs16_narrower = overrides.vs16_narrower + _vs15_wider = overrides.vs15_wider + _zeroer = overrides.zeroer + _narrow_wider = overrides.narrow_wider + _narrow_zeroer = overrides.narrow_zeroer + _grapheme_overrides = table_grapheme_overrides.get(term_canonical) + else: + _narrower = () + _vs16_narrower = () + _vs15_wider = () + _zeroer = () + _narrow_wider = () + _narrow_zeroer = () + _grapheme_overrides = {} + + strict = control_codes == 'strict' + # Track absolute positions: tab stops need modulo on absolute column, CR resets to 0. + # Initialize max_extent to 0 so backward movement (CR, BS) won't yield negative width. + current_col = 0 + max_extent = 0 + idx = 0 + text_len = len(text) + + # Select wcwidth call pattern for best lru_cache performance: + # - ambiguous_width=1 (default): single-arg calls share cache with direct wcwidth() calls + # - ambiguous_width=2: full positional args needed (results differ, separate cache is correct) + _wcwidth = wcwidth if ambiguous_width == 1 else lambda c: wcwidth(c, 'auto', ambiguous_width) + + # grapheme-clustering state and local re-binding for performance. + # Widths accumulate in cluster_width and flush at boundaries (see _wcswidth.py) + last_measured_idx = -2 # -2 sentinel blocks VS16/VS15 (no base available) + last_measured_ucs = -1 + last_measured_w = 0 + prev_was_virama = False + _max_extent_before = 0 + cluster_start = -1 + col_before_cluster = 0 + max_extent_before_cluster = 0 + cluster_width = 0 + vs16_nw_table = VS16_NARROW_TO_WIDE['9.0.0'] + vs15_wn_table = VS15_WIDE_TO_NARROW['9.0.0'] + _bisearch = bisearch + + while idx < text_len: + char = text[idx] + + # 1. ESC sequences + if char == '\x1b': + # Flush pending cluster before processing escape sequence + if cluster_width: + current_col += cluster_width + if current_col > max_extent: + max_extent = current_col + cluster_width = 0 + m = _SEQUENCE_CLASSIFY.match(text, idx) + if not m: + # 1a. Errant ESC or unknown sequence: only the first character is zero-width + idx += 1 + else: + seq = m.group() + if strict and INDETERMINATE_EFFECT_SEQUENCE.match(seq): + raise ValueError(f"Indeterminate cursor sequence at position {idx}, {seq!r}") + + # 2b. horizontal position absolute (before forward/backward to + # avoid other_seq match in _SEQUENCE_CLASSIFY) + if (hpa_n := m.group('hpa_n')) is not None: + target_col = int(hpa_n) if hpa_n else 1 + if strict: + raise ValueError( + f"Indeterminate horizontal position at position {idx}, " + f"{seq!r} (absolute column unknown)" + ) + current_col = target_col - 1 # HPA is 1-indexed, convert to 0-indexed + # 2c. cursor forward, backward + elif (cforward_n := m.group('cforward_n')) is not None: + current_col += int(cforward_n) if cforward_n else 1 + elif (cbackward_n := m.group('cbackward_n')) is not None: + n_backward = int(cbackward_n) if cbackward_n else 1 + if strict and n_backward > current_col: + raise ValueError( + f"Cursor left movement at position {idx} would move " + f"{n_backward} cells left from column {current_col}, " + f"exceeding string start" + ) + current_col -= n_backward + if current_col < 0: + current_col = 0 + # 2d. OSC 66 Text Sizing: positive display width + elif (ts_meta := m.group('ts_meta')) is not None: + ts_text = m.group('ts_text') or '' + ts_term = m.group('ts_term') + assert ts_term is not None + text_size = TextSizing( + TextSizingParams.from_params(ts_meta, control_codes=control_codes), + ts_text, ts_term) + current_col += text_size.display_width(ambiguous_width) + # 2e. SGR and other zero-width sequences: no column advance + idx = m.end() + # Escape sequences break VS16 adjacency: reset last-measured state + last_measured_idx = -2 + last_measured_ucs = -1 + cluster_start = -1 + if current_col > max_extent: + max_extent = current_col + continue + + # 2. Vertical or Illegal control characters zero width or error when 'strict' + if char in ILLEGAL_CTRL: + if strict: + raise ValueError(f"Illegal control character {ord(char):#x} at position {idx}") + if cluster_width: + current_col += cluster_width + if current_col > max_extent: + max_extent = current_col + cluster_width = 0 + idx += 1 + last_measured_idx = -2 + last_measured_ucs = -1 + cluster_start = -1 + continue + + if char in VERTICAL_CTRL: + if strict: + raise ValueError(f"Vertical movement character {ord(char):#x} at position {idx}") + if cluster_width: + current_col += cluster_width + if current_col > max_extent: + max_extent = current_col + cluster_width = 0 + idx += 1 + last_measured_idx = -2 + last_measured_ucs = -1 + cluster_start = -1 + continue + + # 3. Horizontal movement characters + if char in HORIZONTAL_CTRL: + if cluster_width: + current_col += cluster_width + if current_col > max_extent: + max_extent = current_col + cluster_width = 0 + if char == '\t' and tabsize > 0: + current_col += tabsize - (current_col % tabsize) + elif char == '\b': + if current_col > 0: + current_col -= 1 + elif char == '\r': + if strict: + raise ValueError( + f"Horizontal movement character \\r at position {idx}: " + "indeterminate starting column" + ) + current_col = 0 + if current_col > max_extent: + max_extent = current_col + idx += 1 + last_measured_idx = -2 + last_measured_ucs = -1 + cluster_start = -1 + continue + + # 4. Zero-width control characters + if char in ZERO_WIDTH_CTRL: + if cluster_width: + current_col += cluster_width + if current_col > max_extent: + max_extent = current_col + cluster_width = 0 + idx += 1 + last_measured_idx = -2 + last_measured_ucs = -1 + cluster_start = -1 + continue + + # 5. Inline grapheme-clustering: ZWJ, Virama, VS16, Regional Indicators, + # Fitzpatrick, Mc, wcwidth + ucs = ord(char) + + # ZWJ (U+200D) + if ucs == 0x200D: + if prev_was_virama: + idx += 1 + elif idx + 1 < text_len: + # Check for terminal grapheme override when base char is ExtPict/RI + if (_grapheme_overrides + and last_measured_idx >= 0 + and last_measured_ucs in _EMOJI_ZWJ_SET): + cluster_end = _scan_zwj_cluster_end(text, last_measured_idx, text_len) + cluster = text[last_measured_idx:cluster_end] + override_w = _grapheme_overrides.get(cluster) + if override_w is not None: + current_col += (override_w - last_measured_w) + max_extent = max(max_extent, current_col) + last_measured_idx = -2 + last_measured_ucs = -1 + last_measured_w = 0 + prev_was_virama = False + cluster_start = -1 + idx = cluster_end + continue + # No override; ZWJ breaks VS adjacency. + # VS16 already set last_measured_idx = -2, blocking further VS16. + last_measured_w = 0 + prev_was_virama = False + idx += 2 + else: + prev_was_virama = False + idx += 1 + continue + + # 6. VS16 (U+FE0F): converts preceding narrow character to wide. + if ucs == 0xFE0F and last_measured_idx >= 0: + if _vs16_narrower and _bisearch(last_measured_ucs, _vs16_narrower): + pass + elif _bisearch(last_measured_ucs, vs16_nw_table): + cluster_width = 2 + last_measured_idx = -2 + idx += 1 + continue + + # VS15 (U+FE0E): text variation selector, requests narrow presentation. + if ucs == 0xFE0E and last_measured_idx >= 0: + base_ucs = last_measured_ucs + vs15_narrow = bisearch(base_ucs, vs15_wn_table) + if _vs15_wider and bisearch(base_ucs, _vs15_wider): + vs15_narrow = False + if vs15_narrow and last_measured_w == 2: + current_col -= 1 + max_extent = max(_max_extent_before, current_col) + last_measured_idx = -2 + idx += 1 + continue + + # 7. Regional Indicator & Fitzpatrick (both above BMP) + if ucs > 0xFFFF: + if ucs in _REGIONAL_INDICATOR_SET: + ri_before = 0 + j = idx - 1 + while j >= 0 and ord(text[j]) in _REGIONAL_INDICATOR_SET: + ri_before += 1 + j -= 1 + if ri_before % 2 == 1: + last_measured_ucs = ucs + idx += 1 + continue + elif (_FITZPATRICK_RANGE[0] <= ucs <= _FITZPATRICK_RANGE[1] + and last_measured_ucs in _EMOJI_ZWJ_SET): + idx += 1 + continue + + # 8. Normal character: measure with wcwidth + w = _wcwidth(char) + # Apply single-codepoint terminal overrides (pre-merged tuples) + if w == 2 and _narrower and bisearch(ucs, _narrower): + w = 1 + elif w == 2 and _zeroer and bisearch(ucs, _zeroer): + w = 0 + if w == 1 and _narrow_wider and bisearch(ucs, _narrow_wider): + w = 2 + elif w == 1 and _narrow_zeroer and bisearch(ucs, _narrow_zeroer): + w = 0 + if w > 0: + # virama+consonant extends current cluster; otherwise start new + if prev_was_virama: + cluster_width = 2 + elif cluster_width: + # flush previous cluster, check for grapheme overrides + flushed = False + if _grapheme_overrides and cluster_start >= 0: + # Two-phase override lookup (see _wcswidth.py) + candidate = text[cluster_start:idx + 1] + override_w = _grapheme_overrides.get(candidate) + if override_w is not None: + current_col = col_before_cluster + override_w + max_extent = max(max_extent_before_cluster, current_col) + flushed = True + cluster_width = 0 + else: + cluster_text = text[cluster_start:idx] + override_w = _grapheme_overrides.get(cluster_text) + if override_w is not None: + current_col = col_before_cluster + override_w + max_extent = max(max_extent_before_cluster, current_col) + else: + current_col += cluster_width + else: + current_col += cluster_width + if current_col > max_extent: + max_extent = current_col + if not flushed: + cluster_width = w + cluster_start = idx + col_before_cluster = current_col + max_extent_before_cluster = max_extent + else: + cluster_width = w + cluster_start = idx + col_before_cluster = current_col + max_extent_before_cluster = max_extent + last_measured_idx = idx + last_measured_ucs = ucs + last_measured_w = w + _max_extent_before = max_extent + prev_was_virama = False + elif ucs in _ISC_VIRAMA_SET: + prev_was_virama = True + elif last_measured_idx >= 0 and _bisearch(ucs, _CATEGORY_MC_TABLE): + # Spacing Combining Mark (Mc) following a base character + cluster_width = 2 + last_measured_idx = -2 + prev_was_virama = False + else: + prev_was_virama = False + idx += 1 + + if cluster_width: + if _grapheme_overrides and cluster_start >= 0: + cluster_text = text[cluster_start:text_len] + override_w = _grapheme_overrides.get(cluster_text) + if override_w is not None: + current_col = col_before_cluster + override_w + max_extent = max(max_extent_before_cluster, current_col) + else: + current_col += cluster_width + if current_col > max_extent: + max_extent = current_col + else: + current_col += cluster_width + if current_col > max_extent: + max_extent = current_col + return max_extent diff --git a/.venv/lib/python3.12/site-packages/wcwidth/align.py b/.venv/lib/python3.12/site-packages/wcwidth/align.py new file mode 100644 index 0000000000000000000000000000000000000000..ac0343c8636079878e5affaeb219a316731ed4f1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/align.py @@ -0,0 +1,165 @@ +"""Python grapheme, emoji, and sequence-aware ljust, rjust, center().""" +from __future__ import annotations + +from typing import Literal + +# local +from ._width import width + + +def ljust( + text: str, + dest_width: int, + fillchar: str = ' ', + *, + control_codes: Literal['parse', 'strict', 'ignore'] = 'parse', + ambiguous_width: int = 1, + term_program: bool | str = False, +) -> str: + r""" + Return text left-justified in a string of given display width. + + :param text: String to justify, may contain terminal sequences. + :param dest_width: Total display width of result in terminal cells. + :param fillchar: Single character for padding (default space). Must have + display width of 1. Unicode characters like ``'·'`` are acceptable. + The width is not validated. + :param control_codes: How to handle control sequences when measuring. + Passed to :func:`width` for measurement. + :param ambiguous_width: Width to use for East Asian Ambiguous (A) + characters. Default is ``1`` (narrow). Set to ``2`` for CJK contexts. + :param term_program: Terminal software identifier for table correction. + ``False`` (default) disables override lookup. ``True`` reads the + ``TERM_PROGRAM`` or ``TERM`` environment variable for auto-detection. + Accepts a canonical terminal name matching :func:`list_term_programs`, + such as from XTVERSION_, ENQ_, or ``TERM_PROGRAM``. + + .. versionadded:: 0.8.0 + :returns: Text padded on the right to reach ``dest_width``. + + .. versionadded:: 0.3.0 + + Example:: + + >>> ljust('hi', 5) + 'hi ' + >>> ljust('\x1b[31mhi\x1b[0m', 5) + '\x1b[31mhi\x1b[0m ' + >>> ljust('\U0001F468\u200D\U0001F469\u200D\U0001F467', 6) + '👨‍👩‍👧 ' + """ + if text.isascii() and text.isprintable(): + text_width = len(text) + else: + text_width = width(text, control_codes=control_codes, ambiguous_width=ambiguous_width, + term_program=term_program) + padding_cells = max(0, dest_width - text_width) + return text + fillchar * padding_cells + + +def rjust( + text: str, + dest_width: int, + fillchar: str = ' ', + *, + control_codes: Literal['parse', 'strict', 'ignore'] = 'parse', + ambiguous_width: int = 1, + term_program: bool | str = False, +) -> str: + r""" + Return text right-justified in a string of given display width. + + :param text: String to justify, may contain terminal sequences. + :param dest_width: Total display width of result in terminal cells. + :param fillchar: Single character for padding (default space). Must have + display width of 1. Unicode characters like ``'·'`` are acceptable. + The width is not validated. + :param control_codes: How to handle control sequences when measuring. + Passed to :func:`width` for measurement. + :param ambiguous_width: Width to use for East Asian Ambiguous (A) + characters. Default is ``1`` (narrow). Set to ``2`` for CJK contexts. + :param term_program: Terminal software identifier for table correction. + ``False`` (default) disables override lookup. ``True`` reads the + ``TERM_PROGRAM`` or ``TERM`` environment variable for auto-detection. + Accepts a canonical terminal name matching :func:`list_term_programs`, + such as from XTVERSION_, ENQ_, or ``TERM_PROGRAM``. + + .. versionadded:: 0.8.0 + :returns: Text padded on the left to reach ``dest_width``. + + .. versionadded:: 0.3.0 + + Example:: + + >>> rjust('hi', 5) + ' hi' + >>> rjust('\x1b[31mhi\x1b[0m', 5) + ' \x1b[31mhi\x1b[0m' + >>> rjust('\U0001F468\u200D\U0001F469\u200D\U0001F467', 6) + ' 👨‍👩‍👧' + """ + if text.isascii() and text.isprintable(): + text_width = len(text) + else: + text_width = width(text, control_codes=control_codes, ambiguous_width=ambiguous_width, + term_program=term_program) + padding_cells = max(0, dest_width - text_width) + return fillchar * padding_cells + text + + +def center( + text: str, + dest_width: int, + fillchar: str = ' ', + *, + control_codes: Literal['parse', 'strict', 'ignore'] = 'parse', + ambiguous_width: int = 1, + term_program: bool | str = False, +) -> str: + r""" + Return text centered in a string of given display width. + + :param text: String to center, may contain terminal sequences. + :param dest_width: Total display width of result in terminal cells. + :param fillchar: Single character for padding (default space). Must have + display width of 1. Unicode characters like ``'·'`` are acceptable. + The width is not validated. + :param control_codes: How to handle control sequences when measuring. + Passed to :func:`width` for measurement. + :param ambiguous_width: Width to use for East Asian Ambiguous (A) + characters. Default is ``1`` (narrow). Set to ``2`` for CJK contexts. + :param term_program: Terminal software identifier for table correction. + ``False`` (default) disables override lookup. ``True`` reads the + ``TERM_PROGRAM`` or ``TERM`` environment variable for auto-detection. + Accepts a canonical terminal name matching :func:`list_term_programs`, + such as from XTVERSION_, ENQ_, or ``TERM_PROGRAM``. + + .. versionadded:: 0.8.0 + :returns: Text padded on both sides to reach ``dest_width``. + + For odd-width padding, the extra cell fills in the same cell position as + Python's :meth:`str.center` behavior (the left side when ``dest_width`` is + odd, the right side when ``dest_width`` is even). + See `the eccentric str.center `_. + + .. versionadded:: 0.3.0 + + Example:: + + >>> center('hi', 6) + ' hi ' + >>> center('\x1b[31mhi\x1b[0m', 6) + ' \x1b[31mhi\x1b[0m ' + >>> center('\U0001F468\u200D\U0001F469\u200D\U0001F467', 6) + ' 👨‍👩‍👧 ' + """ + if text.isascii() and text.isprintable(): + text_width = len(text) + else: + text_width = width(text, control_codes=control_codes, ambiguous_width=ambiguous_width, + term_program=term_program) + total_padding = max(0, dest_width - text_width) + # matching https://jazcap53.github.io/pythons-eccentric-strcenter.html + left_pad = total_padding // 2 + (total_padding & dest_width & 1) + right_pad = total_padding - left_pad + return fillchar * left_pad + text + fillchar * right_pad diff --git a/.venv/lib/python3.12/site-packages/wcwidth/bisearch.py b/.venv/lib/python3.12/site-packages/wcwidth/bisearch.py new file mode 100644 index 0000000000000000000000000000000000000000..e95c51b8dc9362f65ee9bec03070e2362f5958c3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/bisearch.py @@ -0,0 +1,30 @@ +"""Binary search function for Unicode interval tables.""" + +from __future__ import annotations + + +def bisearch(ucs: int, table: tuple[tuple[int, int], ...]) -> int: + """ + Binary search in interval table. + + :param ucs: Ordinal value of unicode character. + :param table: Tuple of starting and ending ranges of ordinal values, in form of ``((start, end), + ...)``. + :returns: 1 if ordinal value ucs is found within lookup table, else 0. + """ + lbound = 0 + ubound = len(table) - 1 + + if ucs < table[0][0] or ucs > table[ubound][1]: + return 0 + + while ubound >= lbound: + mid = (lbound + ubound) // 2 + if ucs > table[mid][1]: + lbound = mid + 1 + elif ucs < table[mid][0]: + ubound = mid - 1 + else: + return 1 + + return 0 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/control_codes.py b/.venv/lib/python3.12/site-packages/wcwidth/control_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6fff76386241c07f760391aa320fd4dddb068b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/control_codes.py @@ -0,0 +1,46 @@ +""" +Control character sets for terminal handling. + +This module provides the control character sets used by the width() function to handle terminal +control characters. +""" + +# Illegal C0/C1 control characters. +# These raise ValueError in 'strict' mode. +ILLEGAL_CTRL = frozenset( + chr(c) for c in ( + list(range(0x01, 0x07)) + # SOH, STX, ETX (^C), EOT (^D), ENQ, ACK + list(range(0x10, 0x1b)) + # DLE through SUB (^Z) + list(range(0x1c, 0x20)) + # FS, GS, RS, US + [0x7f] + # DEL + list(range(0x80, 0xa0)) # C1 control characters + ) +) + +# Vertical movement control characters. +# These raise ValueError in 'strict' mode (indeterminate horizontal position). +VERTICAL_CTRL = frozenset({ + '\x0a', # LF (line feed) + '\x0b', # VT (vertical tab) + '\x0c', # FF (form feed) +}) + +# Horizontal movement control characters. +# These affect cursor position and are tracked in 'strict' and 'parse' modes. +HORIZONTAL_CTRL = frozenset({ + '\x08', # BS (backspace) - cursor left 1 + '\x09', # HT (horizontal tab) - advance to next tab stop + '\x0d', # CR (carriage return) - cursor to column 0 +}) + +# Terminal-valid zero-width control characters. +# These are allowed in all modes (zero-width, no movement). +ZERO_WIDTH_CTRL = frozenset({ + '\x00', # NUL + '\x07', # BEL (bell) + '\x0e', # SO (shift out) + '\x0f', # SI (shift in) +}) + +# All control characters that need special handling (not regular printable). +ALL_CTRL = ILLEGAL_CTRL | VERTICAL_CTRL | HORIZONTAL_CTRL | ZERO_WIDTH_CTRL | {'\x1b'} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/escape_sequences.py b/.venv/lib/python3.12/site-packages/wcwidth/escape_sequences.py new file mode 100644 index 0000000000000000000000000000000000000000..b6fc1f639e680f54c7e1fefa9b91de0c93caaf47 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/escape_sequences.py @@ -0,0 +1,208 @@ +r""" +Terminal escape sequence patterns. + +This module provides regex patterns for matching terminal escape sequences. All patterns match +sequences that begin with ESC (``\x1b``). Before calling re.match with these patterns, callers +should first check that the character at the current position is ESC for optimal performance. +""" + +# std imports +import re + +import typing + +# local +from .sgr_state import _SGR_PATTERN + +# Text Sizing Protocol (OSC 66), https://sw.kovidgoyal.net/kitty/text-sizing-protocol/ +TEXT_SIZING_PATTERN = re.compile( + r'\x1b\]66;([^;\x07\x1b]*)(?:;([^\x07\x1b]*))?(\x07|\x1b\\)' +) + +# Zero-width escape sequences (SGR, OSC, CSI, etc.). This table, like INDETERMINATE_EFFECT_SEQUENCE, +# originated from the 'blessed' library. +ZERO_WIDTH_PATTERN = re.compile( + # CSI sequences + r'\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]|' + # OSC sequences; OSC 66 text sizing gets special handling in width() and clip() and has positive + # width, despite the ZERO_WIDTH_PATTERN name. + r'\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|' + # APC sequences + r'\x1b_[^\x1b\x07]*(?:\x07|\x1b\\)|' + # DCS sequences + r'\x1bP[^\x1b\x07]*(?:\x07|\x1b\\)|' + # PM sequences + r'\x1b\^[^\x1b\x07]*(?:\x07|\x1b\\)|' + # Character set designation (subset of nF, handled separately for clarity). + # The final byte is (?s:.) so a newline terminates it like any other byte. + r'\x1b[()](?s:.)|' + # nF sequences: ESC + one or more intermediate bytes (0x20-0x2F) + final byte (0x30-0x7E) + r'\x1b[\x20-\x2f]+[\x30-\x7e]|' + # Fe sequences (C1 controls) + r'\x1b[\x40-\x5f]|' + # Fp sequences (private use) + r'\x1b[\x30-\x3f]|' + # Fs sequences (independent functions) + r'\x1b[\x60-\x7e]' +) + +# TEXT_SIZING_PATTERN with named groups, shared by the two patterns below. +_TEXT_SIZING_NAMED = (r'\x1b\]66;(?P[^;\x07\x1b]*)' + r'(?:;(?P[^\x07\x1b]*))?(?P\x07|\x1b\\)') + +# One alternation: a separate OSC 66 pass would splice the text around each removal. +_STRIP_WITH_TEXT_SIZING = re.compile(_TEXT_SIZING_NAMED + '|' + ZERO_WIDTH_PATTERN.pattern) + + +def _strip_repl(match: "re.Match[str]") -> str: + """Keep the inner text of an OSC 66 match, drop every other sequence.""" + return match.group('ts_text') or '' + + +# Cursor right movement: CSI [n] C, parameter may be parsed by width() +CURSOR_RIGHT_SEQUENCE = re.compile(r'\x1b\[(\d*)C') + +# Cursor left movement: CSI [n] D, parameter may be parsed by width() +CURSOR_LEFT_SEQUENCE = re.compile(r'\x1b\[(\d*)D') + +# Horizontal position absolute: CSI [n] G, parameter may be parsed by width() +CURSOR_HPA_SEQUENCE = re.compile(r'\x1b\[(\d*)G') + +# Combined cursor movement: single regex for fast-path detection of any +# horizontal cursor movement (left, right, hpa). Avoids two separate search() +# calls in hot-path width() and clip() pre-checks. +CURSOR_MOVEMENT_SEQUENCE = re.compile(r'\x1b\[(\d*)[CDG]') + +# Combined horizontal cursor movement: matches BS, CR, and CSI C/D/G cursor sequences +# in a single regex pass. Used by clip() to decide between the simple append path +# and the painter's algorithm. +_HORIZONTAL_CURSOR_MOVEMENT = re.compile(r'[\x08\r]|\x1b\[(\d*)[CDG]') + +# Combined pattern: a single regex that matches any zero-width escape sequence +# and classifies it via named groups, aprox 2x faster than redundant re.matches +# in clip() and width(). +_SEQUENCE_CLASSIFY = re.compile( + _SGR_PATTERN.pattern.replace('(', '(?P', 1) + + '|' + CURSOR_HPA_SEQUENCE.pattern.replace('(', '(?P', 1) + + '|' + CURSOR_RIGHT_SEQUENCE.pattern.replace('(', '(?P', 1) + + '|' + CURSOR_LEFT_SEQUENCE.pattern.replace('(', '(?P', 1) + + '|' + _TEXT_SIZING_NAMED + + '|' + r'(?P(?:' + ZERO_WIDTH_PATTERN.pattern + '))' +) + +# Indeterminate effect sequences - raise ValueError in 'strict' mode. The effects of these sequences +# are likely to be undesirable, moving the cursor vertically or to any unknown position, and +# otherwise not managed by the 'width' method of this library. +# +# This table was created initially with code generation by extraction of termcap library with +# techniques used at 'blessed' library runtime for 'xterm', 'alacritty', 'kitty', ghostty', +# 'screen', 'tmux', and others. Then, these common capabilities were merged into the list below. +INDETERMINATE_EFFECT_SEQUENCE = re.compile( + '|'.join(f'(?:{_pattern})' for _pattern in ( + r'\x1b\[\d+;\d+r', # change_scroll_region + r'\x1b\[\d*K', # erase_in_line (clr_eol, clr_bol) + r'\x1b\[\d*J', # erase_in_display (clr_eos, erase_display) + r'\x1b\[\d+;\d+H', # cursor_address + r'\x1b\[\d*H', # cursor_home + r'\x1b\[\d*A', # cursor_up + r'\x1b\[\d*B', # cursor_down + r'\x1b\[\d*P', # delete_character + r'\x1b\[\d*M', # delete_line + r'\x1b\[\d*L', # insert_line + r'\x1b\[\d*@', # insert_character + r'\x1b\[\d+X', # erase_chars + r'\x1b\[\d*S', # scroll_up (parm_index) + r'\x1b\[\d*T', # scroll_down (parm_rindex) + r'\x1b\[\d*d', # row_address + r'\x1b\[\?1049[hl]', # alternate screen buffer + r'\x1b\[\?47[hl]', # alternate screen (legacy) + r'\x1b8', # restore_cursor + r'\x1bD', # scroll_forward (index) + r'\x1bM', # scroll_reverse (reverse index) + r'\x1bc', # full_reset (RIS) + )) +) + + +def iter_sequences(text: str) -> typing.Iterator[typing.Tuple[str, bool]]: + r""" + Iterate through text, yielding segments with sequence identification. + + This generator yields tuples of ``(segment, is_sequence)`` for each part + of the input text, where ``is_sequence`` is ``True`` if the segment is + a recognized terminal escape sequence. + + :param text: String to iterate through. + :returns: Iterator of (segment, is_sequence) tuples. + + .. versionadded:: 0.3.0 + + Example:: + + >>> list(iter_sequences('hello')) + [('hello', False)] + >>> list(iter_sequences('\x1b[31mred')) + [('\x1b[31m', True), ('red', False)] + >>> list(iter_sequences('\x1b[1m\x1b[31m')) + [('\x1b[1m', True), ('\x1b[31m', True)] + """ + idx = 0 + text_len = len(text) + segment_start = 0 + + while idx < text_len: + char = text[idx] + + if char == '\x1b': + # Yield any accumulated non-sequence text + if idx > segment_start: + yield (text[segment_start:idx], False) + + # Try to match an escape sequence + match = ZERO_WIDTH_PATTERN.match(text, idx) + if match: + yield (match.group(), True) + idx = match.end() + else: + # Lone ESC or unrecognized - yield as sequence anyway + yield (char, True) + idx += 1 + segment_start = idx + else: + idx += 1 + + # Yield any remaining text + if segment_start < text_len: + yield (text[segment_start:], False) + + +def strip_sequences(text: str) -> str: + r""" + Return text with all terminal escape sequences removed. + + Unknown or incomplete ESC sequences are preserved. + + :param text: String that may contain terminal escape sequences. + :returns: The input text with all escape sequences stripped. + + .. versionadded:: 0.3.0 + + .. versionchanged:: 0.7.0 + Inner text of OSC 66 (Text sizing protocol) is preserved. + + Example:: + + >>> strip_sequences('\x1b[31mred\x1b[0m') + 'red' + >>> strip_sequences('hello') + 'hello' + >>> strip_sequences('\x1b[1m\x1b[31mbold red\x1b[0m text') + 'bold red text' + >>> strip_sequences('\x1b]66;s=2;hello\x07') + 'hello' + >>> strip_sequences('\x1b]8;id=34;https://example.com\x1b\\[view]\x1b]8;;\x1b\\') + '[view]' + """ + if '\x1b]66;' in text: + return _STRIP_WITH_TEXT_SIZING.sub(_strip_repl, text) + return ZERO_WIDTH_PATTERN.sub('', text) diff --git a/.venv/lib/python3.12/site-packages/wcwidth/grapheme.py b/.venv/lib/python3.12/site-packages/wcwidth/grapheme.py new file mode 100644 index 0000000000000000000000000000000000000000..7fab3342bd5ef9abf32476ecc4ccda41bff321d3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/grapheme.py @@ -0,0 +1,425 @@ +""" +Grapheme cluster segmentation following Unicode Standard Annex #29. + +This module provides pure-Python implementation of the grapheme cluster boundary algorithm as +defined in UAX #29: Unicode Text Segmentation. + +https://www.unicode.org/reports/tr29/ +""" + +from __future__ import annotations + +# std imports +from enum import IntEnum +from functools import lru_cache + +from typing import TYPE_CHECKING, Optional, NamedTuple + +__lazy_modules__ = [ + "wcwidth.bisearch", + "wcwidth.table_grapheme", +] +# local +from .bisearch import bisearch as _bisearch +from .table_grapheme import (GRAPHEME_L, + GRAPHEME_T, + GRAPHEME_V, + GRAPHEME_LV, + INCB_EXTEND, + INCB_LINKER, + GRAPHEME_LVT, + INCB_CONSONANT, + GRAPHEME_EXTEND, + GRAPHEME_CONTROL, + GRAPHEME_PREPEND, + GRAPHEME_SPACINGMARK, + EXTENDED_PICTOGRAPHIC, + GRAPHEME_REGIONAL_INDICATOR) + +if TYPE_CHECKING: # pragma: no cover + # std imports + from collections.abc import Iterator + +# Maximum backward scan distance when finding grapheme cluster boundaries. +# Covers all known Unicode grapheme clusters with margin; longer sequences are pathological. +MAX_GRAPHEME_SCAN = 32 + + +class GCB(IntEnum): + """Grapheme Cluster Break property values.""" + + OTHER = 0 + CR = 1 + LF = 2 + CONTROL = 3 + EXTEND = 4 + ZWJ = 5 + REGIONAL_INDICATOR = 6 + PREPEND = 7 + SPACING_MARK = 8 + L = 9 + V = 10 + T = 11 + LV = 12 + LVT = 13 + + +# All lru_cache sizes in this file use maxsize=1024, chosen by benchmarking UDHR data (500+ +# languages) and considering typical process-long sessions: western scripts need ~64 unique +# codepoints, and CJK can reach ~2000. +@lru_cache(maxsize=1024) +def _grapheme_cluster_break(ucs: int) -> GCB: + # pylint: disable=too-many-branches,too-complex + """Return the Grapheme_Cluster_Break property for a codepoint.""" + # Single codepoint matches + if ucs == 0x000d: + return GCB.CR + if ucs == 0x000a: + return GCB.LF + if ucs == 0x200d: + return GCB.ZWJ + # Matching by codepoint ranges, requiring binary search + if _bisearch(ucs, GRAPHEME_CONTROL): + return GCB.CONTROL + if _bisearch(ucs, GRAPHEME_EXTEND): + return GCB.EXTEND + if _bisearch(ucs, GRAPHEME_REGIONAL_INDICATOR): + return GCB.REGIONAL_INDICATOR + if _bisearch(ucs, GRAPHEME_PREPEND): + return GCB.PREPEND + if _bisearch(ucs, GRAPHEME_SPACINGMARK): + return GCB.SPACING_MARK + if _bisearch(ucs, GRAPHEME_L): + return GCB.L + if _bisearch(ucs, GRAPHEME_V): + return GCB.V + if _bisearch(ucs, GRAPHEME_T): + return GCB.T + if _bisearch(ucs, GRAPHEME_LV): + return GCB.LV + if _bisearch(ucs, GRAPHEME_LVT): + return GCB.LVT + return GCB.OTHER + + +@lru_cache(maxsize=1024) +def _is_extended_pictographic(ucs: int) -> bool: + """Check if codepoint has Extended_Pictographic property.""" + return bool(_bisearch(ucs, EXTENDED_PICTOGRAPHIC)) + + +@lru_cache(maxsize=1024) +def _is_incb_linker(ucs: int) -> bool: + """Check if codepoint has InCB=Linker property.""" + return bool(_bisearch(ucs, INCB_LINKER)) + + +@lru_cache(maxsize=1024) +def _is_incb_consonant(ucs: int) -> bool: + """Check if codepoint has InCB=Consonant property.""" + return bool(_bisearch(ucs, INCB_CONSONANT)) + + +@lru_cache(maxsize=1024) +def _is_incb_extend(ucs: int) -> bool: + """Check if codepoint has InCB=Extend property.""" + return bool(_bisearch(ucs, INCB_EXTEND)) + + +class BreakResult(NamedTuple): + """Result of grapheme cluster break decision.""" + + should_break: bool + ri_count: int + + +@lru_cache(maxsize=1024) +def _simple_break_check(prev_gcb: GCB, curr_gcb: GCB) -> Optional[BreakResult]: + """ + Check simple GCB-pair-based break rules (cacheable). + + Returns BreakResult for rules that can be determined from GCB properties alone, or None if + complex lookback rules (GB9c, GB11) need to be checked. + """ + # GB3: CR x LF + if prev_gcb == GCB.CR and curr_gcb == GCB.LF: + return BreakResult(should_break=False, ri_count=0) + + # GB4: (Control|CR|LF) ÷ + if prev_gcb in (GCB.CONTROL, GCB.CR, GCB.LF): + return BreakResult(should_break=True, ri_count=0) + + # GB5: ÷ (Control|CR|LF) + if curr_gcb in (GCB.CONTROL, GCB.CR, GCB.LF): + return BreakResult(should_break=True, ri_count=0) + + # GB6: L x (L|V|LV|LVT) + if prev_gcb == GCB.L and curr_gcb in (GCB.L, GCB.V, GCB.LV, GCB.LVT): + return BreakResult(should_break=False, ri_count=0) + + # GB7: (LV|V) x (V|T) + if prev_gcb in (GCB.LV, GCB.V) and curr_gcb in (GCB.V, GCB.T): + return BreakResult(should_break=False, ri_count=0) + + # GB8: (LVT|T) x T + if prev_gcb in (GCB.LVT, GCB.T) and curr_gcb == GCB.T: + return BreakResult(should_break=False, ri_count=0) + + # GB9: x (Extend|ZWJ) - but ZWJ needs GB11 check, so only handle Extend here + if curr_gcb == GCB.EXTEND: + return BreakResult(should_break=False, ri_count=0) + + # GB9a: x SpacingMark + if curr_gcb == GCB.SPACING_MARK: + return BreakResult(should_break=False, ri_count=0) + + # GB9b: Prepend x + if prev_gcb == GCB.PREPEND: + return BreakResult(should_break=False, ri_count=0) + + # GB9c and GB11 need lookback - return None to signal complex check needed + # GB12/13 (RI pairs) need ri_count state - also handled in main function + return None + + +def _should_break( + prev_gcb: GCB, + curr_gcb: GCB, + text: str, + curr_idx: int, + ri_count: int, +) -> BreakResult: + # pylint: disable=too-many-branches,too-complex + """ + Determine if there should be a grapheme cluster break between prev and curr. + + Implements UAX #29 grapheme cluster boundary rules. + """ + # Try cached simple rules first + result = _simple_break_check(prev_gcb, curr_gcb) + if result is not None: + return result + + # GB9: x ZWJ (not cached because GB11 needs lookback when prev is ZWJ) + if curr_gcb == GCB.ZWJ: + return BreakResult(should_break=False, ri_count=0) + + # GB9c: Indic conjunct cluster + # \p{InCB=Linker} \p{InCB=Extend}* x \p{InCB=Consonant} + curr_ucs = ord(text[curr_idx]) + if _is_incb_consonant(curr_ucs): + i = curr_idx - 1 + while i >= 0 and _is_incb_extend(ord(text[i])): + i -= 1 + if i >= 0 and _is_incb_linker(ord(text[i])): + return BreakResult(should_break=False, ri_count=0) + + # GB11: ExtPict Extend* ZWJ x ExtPict + if prev_gcb == GCB.ZWJ and _is_extended_pictographic(curr_ucs): + i = curr_idx - 2 # Skip the ZWJ at curr_idx - 1 + while i >= 0: + prev_ucs = ord(text[i]) + prev_prop = _grapheme_cluster_break(prev_ucs) + if prev_prop == GCB.EXTEND: + i -= 1 + elif _is_extended_pictographic(prev_ucs): + return BreakResult(should_break=False, ri_count=0) + else: + break + + # GB12/GB13: RI x RI (pair matching) + if prev_gcb == GCB.REGIONAL_INDICATOR and curr_gcb == GCB.REGIONAL_INDICATOR: + if ri_count % 2 == 1: + return BreakResult(should_break=False, ri_count=ri_count + 1) + return BreakResult(should_break=True, ri_count=1) + + # GB999: Any ÷ Any + ri_count = 1 if curr_gcb == GCB.REGIONAL_INDICATOR else 0 + return BreakResult(should_break=True, ri_count=ri_count) + + +def _iter_graphemes_python( + unistr: str, + start: int = 0, + end: int | None = None, +) -> Iterator[str]: + r""" + Iterate over grapheme clusters by UAX #29 extended grapheme cluster rules. + + Grapheme clusters are "user-perceived characters" - what a user would + consider a single character, which may consist of multiple Unicode + codepoints (e.g., a base character with combining marks, emoji sequences). + + :param unistr: The Unicode string to segment. + :param start: Starting index (default 0). + :param end: Ending index (default len(unistr)). + :yields: Grapheme cluster substrings. + + Example:: + + >>> list(iter_graphemes('cafe\u0301')) + ['c', 'a', 'f', 'é'] + >>> list(iter_graphemes('ok\U0001F468\u200D\U0001F469\u200D\U0001F467')) + ['o', 'k', '👨\u200d👩\u200d👧'] + >>> list(iter_graphemes('ok\U0001F1FA\U0001F1F8')) + ['o', 'k', '🇺🇸'] + + .. versionadded:: 0.3.0 + """ + if not unistr: + return + + length = len(unistr) + + if end is None: + end = length + + if start >= end or start >= length: + return + + end = min(end, length) + + # Track state for grapheme cluster boundaries + cluster_start = start + ri_count = 0 + + # Get GCB for first character + prev_gcb = _grapheme_cluster_break(ord(unistr[start])) + + # Handle Regional Indicator count initialization + if prev_gcb == GCB.REGIONAL_INDICATOR: + ri_count = 1 + + for idx in range(start + 1, end): + curr_gcb = _grapheme_cluster_break(ord(unistr[idx])) + + result = _should_break(prev_gcb, curr_gcb, unistr, idx, ri_count) + ri_count = result.ri_count + + if result.should_break: + yield unistr[cluster_start:idx] + cluster_start = idx + + prev_gcb = curr_gcb + + # Yield the final cluster + yield unistr[cluster_start:end] + + +def _find_cluster_start(text: str, pos: int) -> int: + """ + Find the start of the grapheme cluster containing the character before pos. + + Scans backwards from pos to find a safe starting point, then iterates forward using standard + break rules to find the actual cluster boundary. + + :param text: The Unicode string. + :param pos: Position to search before (exclusive). + :returns: Start position of the grapheme cluster. + """ + target_cp = ord(text[pos - 1]) + + # GB3: CR x LF - LF after CR is part of same cluster + if target_cp == 0x0A and pos >= 2 and text[pos - 2] == '\r': + return pos - 2 + + # Fast path: ASCII (except LF) starts its own cluster + if target_cp < 0x80: + # GB9b: Check for preceding PREPEND (rare: Arabic/Brahmic) + if pos >= 2 and target_cp >= 0x20: + prev_cp = ord(text[pos - 2]) + if prev_cp >= 0x80 and _grapheme_cluster_break(prev_cp) == GCB.PREPEND: + return _find_cluster_start(text, pos - 1) + return pos - 1 + + # Scan backward to find a safe starting point + safe_start = pos - 1 + while safe_start > 0 and (pos - safe_start) < MAX_GRAPHEME_SCAN: + cp = ord(text[safe_start]) + if 0x20 <= cp < 0x80: # ASCII always starts a cluster + break + if _grapheme_cluster_break(cp) == GCB.CONTROL: # GB4 + break + safe_start -= 1 + + # Verify forward to find the actual cluster boundary + cluster_start = safe_start + left_gcb = _grapheme_cluster_break(ord(text[safe_start])) + ri_count = 1 if left_gcb == GCB.REGIONAL_INDICATOR else 0 + + for i in range(safe_start + 1, pos): + right_gcb = _grapheme_cluster_break(ord(text[i])) + result = _should_break(left_gcb, right_gcb, text, i, ri_count) + ri_count = result.ri_count + if result.should_break: + cluster_start = i + left_gcb = right_gcb + + return cluster_start + + +def grapheme_boundary_before(unistr: str, pos: int) -> int: + r""" + Find the grapheme cluster boundary immediately before a position. + + :param unistr: The Unicode string to search. + :param pos: Position in the string (0 < pos <= len(unistr)). + :returns: Start index of the grapheme cluster containing the character at pos-1. + + Example:: + + >>> grapheme_boundary_before('Hello \U0001F44B\U0001F3FB', 8) + 6 + >>> grapheme_boundary_before('a\r\nb', 3) + 1 + + .. versionadded:: 0.3.6 + """ + if pos <= 0: + return 0 + return _find_cluster_start(unistr, min(pos, len(unistr))) + + +def iter_graphemes_reverse( + unistr: str, + start: int = 0, + end: Optional[int] = None, +) -> Iterator[str]: + r""" + Iterate over grapheme clusters in reverse order (last to first). + + :param unistr: The Unicode string to segment. + :param start: Starting index (default 0). + :param end: Ending index (default len(unistr)). + :yields: Grapheme cluster substrings in reverse order. + + Example:: + + >>> list(iter_graphemes_reverse('cafe\u0301')) + ['e\u0301', 'f', 'a', 'c'] + + .. versionadded:: 0.3.6 + """ + if not unistr: + return + + length = len(unistr) + + end = length if end is None else min(end, length) + start = max(start, 0) + + if start >= end or start >= length: + return + + pos = end + while pos > start: + cluster_start = _find_cluster_start(unistr, pos) + # Don't yield partial graphemes that extend before start + if cluster_start < start: + break + yield unistr[cluster_start:pos] + pos = cluster_start + + +# Bind iter_graphemes at module level to avoid per-call dispatch overhead. +iter_graphemes = _iter_graphemes_python diff --git a/.venv/lib/python3.12/site-packages/wcwidth/hyperlink.py b/.venv/lib/python3.12/site-packages/wcwidth/hyperlink.py new file mode 100644 index 0000000000000000000000000000000000000000..4278b9f8c18dbf333da7cf86f0ada38df8fc45bc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/hyperlink.py @@ -0,0 +1,142 @@ +""" +OSC 8 hyperlink parsing and measurement. + +.. versionadded:: 0.7.0 +""" + +from __future__ import annotations + +# std imports +import re + +import typing + +# local +from ._width import width as _width +from .escape_sequences import _SEQUENCE_CLASSIFY + +HYPERLINK_OPEN_RE = re.compile(r'\x1b]8;([^;]*);([^\x07\x1b]*)(\x07|\x1b\\)') +HYPERLINK_CLOSE_RE = re.compile(r'\x1b]8;;(\x07|\x1b\\)') + + +class HyperlinkParams(typing.NamedTuple): + r""" + Parsed parameters from an OSC 8 hyperlink open sequence. + + :param url: The hyperlink URL. + :param params: Colon-separated metadata string (often empty). + :param terminator: Sequence terminator (``\x07`` or ``\x1b\\``). + """ + + url: str + params: str = '' + terminator: str = '\x07' + + @classmethod + def parse(cls, seq: str) -> HyperlinkParams | None: + r""" + Parse an OSC 8 open sequence string. + + Returns ``None`` if *seq* is not a valid OSC 8 open. + + Example:: + + >>> HyperlinkParams.parse('\x1b]8;;http://example.com\x07') + HyperlinkParams(url='http://example.com', params='', terminator='\x07') + """ + m = HYPERLINK_OPEN_RE.match(seq) + if m is None: + return None + return cls(url=m.group(2), params=m.group(1), terminator=m.group(3)) + + def make_open(self) -> str: + """Generate the OSC 8 open escape sequence.""" + return f'\x1b]8;{self.params};{self.url}{self.terminator}' + + def make_close(self) -> str: + """Generate the OSC 8 close escape sequence.""" + return f'\x1b]8;;{self.terminator}' + + +class Hyperlink(typing.NamedTuple): + """ + A complete OSC 8 hyperlink with target and inner text. + + :param params: Parsed open sequence parameters. + :param text: Inner text between the open and close sequences. + """ + + params: HyperlinkParams + text: str + + @classmethod + def find_close(cls, text: str, open_end: int) -> tuple[int, int]: + """ + Find the matching OSC 8 close sequence. + + Searches 'text' starting at 'open_end', the position just past the open + sequence. Returns position of close sequence ``(close_start, + close_end)`` or ``(-1, -1)`` if not found. + + Per the OSC 8 specification, terminal emulators treat hyperlinks as a + state attribute. A close sequence closes + the current hyperlink regardless of how many open sequences preceded it. + """ + m = HYPERLINK_CLOSE_RE.search(text, open_end) + if m is None: + return (-1, -1) + return (m.start(), m.end()) + + def display_width( + self, + *, + control_codes: typing.Literal['parse', 'strict', 'ignore'] = 'parse', + tabsize: int = 8, + ambiguous_width: int = 1, + ) -> int: + r""" + Measure the display width of the hyperlink's inner text. + + Delegates to :func:`wcwidth.width` with the given parameters. + + Example:: + + >>> hl = Hyperlink.parse('\x1b]8;;http://example.com\x07Hello\x1b]8;;\x07', 0) + >>> hl.display_width() + 5 + """ + return _width( + self.text, + control_codes=control_codes, + tabsize=tabsize, + ambiguous_width=ambiguous_width, + ) + + @classmethod + def parse(cls, text: str, start: int = 0) -> Hyperlink | None: + r""" + Parse a complete OSC 8 hyperlink unit from *text* at position *start*. + + Locates the open sequence, finds the matching close, and returns a + ``Hyperlink`` containing the parsed parameters and inner text. Returns + ``None`` if the text at *start* is not a complete OSC 8 hyperlink. + + Example:: + + >>> Hyperlink.parse('\x1b]8;;http://example.com\x07Hello\x1b]8;;\x07') + Hyperlink(params=HyperlinkParams(url='http://example.com', ...), text='Hello') + """ + m = _SEQUENCE_CLASSIFY.match(text, start) + if m is None: + return None + params = HyperlinkParams.parse(m.group()) + if params is None: + return None + close_start, close_end = cls.find_close(text, m.end()) + if (close_start, close_end) == (-1, -1): + return None + return cls(params=params, text=text[m.end():close_start]) + + def make_sequence(self) -> str: + """Rebuild the complete OSC 8 hyperlink escape sequence.""" + return self.params.make_open() + self.text + self.params.make_close() diff --git a/.venv/lib/python3.12/site-packages/wcwidth/py.typed b/.venv/lib/python3.12/site-packages/wcwidth/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/sgr_state.py b/.venv/lib/python3.12/site-packages/wcwidth/sgr_state.py new file mode 100644 index 0000000000000000000000000000000000000000..dce06d871fba2f3408dff11a0da078e279c11a91 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/sgr_state.py @@ -0,0 +1,355 @@ +""" +SGR (Select Graphic Rendition) state tracking for terminal escape sequences. + +This module provides functions for tracking and propagating terminal styling (bold, italic, colors, +etc.) via public API propagate_sgr(), and its dependent functions, cut() and wrap(). It only has +attributes necessary to perform its functions, eg 'RED' and 'BLUE' attributes are not defined. +""" + +from __future__ import annotations + +# std imports +import re +from enum import IntEnum + +from typing import TYPE_CHECKING, Iterator, NamedTuple + +if TYPE_CHECKING: # pragma: no cover + from typing import Sequence + + +class _SGR(IntEnum): + """ + SGR (Select Graphic Rendition) parameter codes. + + References: + - https://invisible-island.net/xterm/ctlseqs/ctlseqs.html + - https://github.com/tehmaze/ansi/tree/master/ansi/colour + """ + + RESET = 0 + BOLD = 1 + DIM = 2 + ITALIC = 3 + UNDERLINE = 4 + BLINK = 5 + RAPID_BLINK = 6 + INVERSE = 7 + HIDDEN = 8 + STRIKETHROUGH = 9 + DOUBLE_UNDERLINE = 21 + BOLD_DIM_OFF = 22 + ITALIC_OFF = 23 + UNDERLINE_OFF = 24 + BLINK_OFF = 25 + INVERSE_OFF = 27 + HIDDEN_OFF = 28 + STRIKETHROUGH_OFF = 29 + FG_BLACK = 30 + FG_WHITE = 37 + FG_EXTENDED = 38 + FG_DEFAULT = 39 + BG_BLACK = 40 + BG_WHITE = 47 + BG_EXTENDED = 48 + BG_DEFAULT = 49 + FG_BRIGHT_BLACK = 90 + FG_BRIGHT_WHITE = 97 + BG_BRIGHT_BLACK = 100 + BG_BRIGHT_WHITE = 107 + + +# SGR sequence pattern: CSI followed by params (digits, semicolons, colons) ending with 'm' +# Colons are used in ITU T.416 (ISO 8613-6) extended color format: 38:2::R:G:B +# This colon format is less common than semicolon (38;2;R;G;B) but supported by kitty, +# iTerm2, and newer VTE-based terminals. +_SGR_PATTERN = re.compile(r'\x1b\[([\d;:]*)m') + +# Fast path: quick check if any SGR sequence exists +_SGR_QUICK_CHECK = re.compile(r'\x1b\[[\d;:]*m') + +# Reset sequence +_SGR_RESET = '\x1b[0m' + + +class _SGRState(NamedTuple): + """ + Track active SGR terminal attributes by category (immutable). + + :param bold: Bold attribute (SGR 1). + :param dim: Dim/faint attribute (SGR 2). + :param italic: Italic attribute (SGR 3). + :param underline: Underline attribute (SGR 4). + :param blink: Slow blink attribute (SGR 5). + :param rapid_blink: Rapid blink attribute (SGR 6). + :param inverse: Inverse/reverse attribute (SGR 7). + :param hidden: Hidden/invisible attribute (SGR 8). + :param strikethrough: Strikethrough attribute (SGR 9). + :param double_underline: Double underline attribute (SGR 21). + :param foreground: Foreground color as tuple of SGR params, or None for default. + :param background: Background color as tuple of SGR params, or None for default. + """ + + bold: bool = False + dim: bool = False + italic: bool = False + underline: bool = False + blink: bool = False + rapid_blink: bool = False + inverse: bool = False + hidden: bool = False + strikethrough: bool = False + double_underline: bool = False + foreground: tuple[int, ...] | None = None + background: tuple[int, ...] | None = None + + +# Default state with no attributes set +_SGR_STATE_DEFAULT = _SGRState() + + +def _sgr_state_is_active(state: _SGRState) -> bool: + """ + Return True if any attributes are set. + + :param state: The SGR state to check. + :returns: True if any attribute differs from default. + """ + return (state.bold or state.dim or state.italic or state.underline + or state.blink or state.rapid_blink or state.inverse or state.hidden + or state.strikethrough or state.double_underline + or state.foreground is not None or state.background is not None) + + +def _color_params_to_str(color: tuple[int, ...]) -> str: + """ + Join color parameters, preserving the ITU T.416 colon form where it was used. + + ``38:2::R:G:B`` carries a colour space element that the legacy + ``38;2;R;G;B`` form has no slot for, so joining it with ``;`` would shift R, G and B + one position and leave a trailing parameter. + + :param color: Color parameters as parsed by :func:`_parse_sgr_params`. + :returns: Parameter string for embedding in an SGR sequence. + """ + if len(color) > 5 and color[1] == 2: + return ':'.join(str(p) for p in color) + return ';'.join(str(p) for p in color) + + +def _sgr_state_to_sequence(state: _SGRState) -> str: + """ + Generate minimal SGR sequence to restore this state from reset. + + :param state: The SGR state to convert. + :returns: SGR escape sequence string, or empty string if no attributes set. + """ + if not _sgr_state_is_active(state): + return '' + + # Map boolean attributes to their SGR codes + bool_attrs = [ + (state.bold, '1'), (state.dim, '2'), (state.italic, '3'), + (state.underline, '4'), (state.blink, '5'), (state.rapid_blink, '6'), + (state.inverse, '7'), (state.hidden, '8'), (state.strikethrough, '9'), + (state.double_underline, '21'), + ] + params = [code for active, code in bool_attrs if active] + + # Add color params (already formatted as tuples) + if state.foreground is not None: + params.append(_color_params_to_str(state.foreground)) + if state.background is not None: + params.append(_color_params_to_str(state.background)) + + return f'\x1b[{";".join(params)}m' + + +def _parse_sgr_params(sequence: str) -> list[int | tuple[int, ...]]: + r""" + Parse SGR sequence and return list of parameter values. + + Handles compound sequences like ``\x1b[1;31;4m`` -> [1, 31, 4]. + Empty params (e.g., ``\x1b[m``) are treated as [0] (reset). + Colon-separated extended colors like ``\x1b[38:2::255:0:0m`` are returned + as tuples: [(38, 2, 255, 0, 0)]. + + :param sequence: SGR escape sequence string. + :returns: List of integer parameters or tuples for colon-separated colors. + """ + match = _SGR_PATTERN.match(sequence) + if not match: + return [] + params_str = match.group(1) + if not params_str: + return [0] # \x1b[m is equivalent to \x1b[0m + result: list[int | tuple[int, ...]] = [] + for param in params_str.split(';'): + if ':' in param: + # Colon-separated extended color (ITU T.416 format) + # e.g., "38:2::255:0:0" or "38:2:1:255:0:0" (with colorspace) + parts = [int(p) if p else 0 for p in param.split(':')] + result.append(tuple(parts)) + else: + result.append(int(param) if param else 0) + return result + + +def _parse_extended_color( + params: Iterator[int | tuple[int, ...]], base: int +) -> tuple[int, ...] | None: + """ + Parse extended color (256-color or RGB) from parameter iterator. + + :param params: Iterator of remaining SGR parameters (semicolon-separated format). + :param base: Base code (38 for foreground, 48 for background). + :returns: Color tuple like (38, 5, N) or (38, 2, R, G, B), or None if malformed. + """ + try: + mode = next(params) + if isinstance(mode, tuple): + return None # Unexpected tuple, colon format handled separately + if mode == 5: # 256-color + n = next(params) + if isinstance(n, tuple): + return None + return (int(base), 5, n) + if mode == 2: # RGB + r, g, b = next(params), next(params), next(params) + if isinstance(r, tuple) or isinstance(g, tuple) or isinstance(b, tuple): + return None + return (int(base), 2, r, g, b) + except StopIteration: + pass + return None + + +def _sgr_state_update(state: _SGRState, sequence: str) -> _SGRState: + # pylint: disable=too-many-branches,too-complex,too-many-statements + # NOTE: When minimum Python version is 3.10+, this can be simplified using match/case. + """ + Parse SGR sequence and return new state with updates applied. + + :param state: Current SGR state. + :param sequence: SGR escape sequence string. + :returns: New SGRState with updates applied. + """ + params_list = _parse_sgr_params(sequence) + params = iter(params_list) + for p in params: + # Handle colon-separated extended colors (ITU T.416 format) + if isinstance(p, tuple): + if len(p) >= 2 and p[0] == _SGR.FG_EXTENDED: + # Foreground: (38, 2, [colorspace,] R, G, B) or (38, 5, N) + state = state._replace(foreground=p) + elif len(p) >= 2 and p[0] == _SGR.BG_EXTENDED: + # Background: (48, 2, [colorspace,] R, G, B) or (48, 5, N) + state = state._replace(background=p) + continue + if p == _SGR.RESET: + state = _SGR_STATE_DEFAULT + # Attribute ON codes + elif p == _SGR.BOLD: + state = state._replace(bold=True) + elif p == _SGR.DIM: + state = state._replace(dim=True) + elif p == _SGR.ITALIC: + state = state._replace(italic=True) + elif p == _SGR.UNDERLINE: + state = state._replace(underline=True) + elif p == _SGR.BLINK: + state = state._replace(blink=True) + elif p == _SGR.RAPID_BLINK: + state = state._replace(rapid_blink=True) + elif p == _SGR.INVERSE: + state = state._replace(inverse=True) + elif p == _SGR.HIDDEN: + state = state._replace(hidden=True) + elif p == _SGR.STRIKETHROUGH: + state = state._replace(strikethrough=True) + elif p == _SGR.DOUBLE_UNDERLINE: + state = state._replace(double_underline=True) + # Attribute OFF codes + elif p == _SGR.BOLD_DIM_OFF: + state = state._replace(bold=False, dim=False) + elif p == _SGR.ITALIC_OFF: + state = state._replace(italic=False) + elif p == _SGR.UNDERLINE_OFF: + state = state._replace(underline=False, double_underline=False) + elif p == _SGR.BLINK_OFF: + state = state._replace(blink=False, rapid_blink=False) + elif p == _SGR.INVERSE_OFF: + state = state._replace(inverse=False) + elif p == _SGR.HIDDEN_OFF: + state = state._replace(hidden=False) + elif p == _SGR.STRIKETHROUGH_OFF: + state = state._replace(strikethrough=False) + # Basic colors (30-37, 40-47 standard; 90-97, 100-107 bright) + elif (_SGR.FG_BLACK <= p <= _SGR.FG_WHITE + or _SGR.FG_BRIGHT_BLACK <= p <= _SGR.FG_BRIGHT_WHITE): + state = state._replace(foreground=(p,)) + elif (_SGR.BG_BLACK <= p <= _SGR.BG_WHITE + or _SGR.BG_BRIGHT_BLACK <= p <= _SGR.BG_BRIGHT_WHITE): + state = state._replace(background=(p,)) + elif p == _SGR.FG_DEFAULT: + state = state._replace(foreground=None) + elif p == _SGR.BG_DEFAULT: + state = state._replace(background=None) + # Extended colors (semicolon-separated format) + elif p == _SGR.FG_EXTENDED: + if color := _parse_extended_color(params, _SGR.FG_EXTENDED): + state = state._replace(foreground=color) + elif p == _SGR.BG_EXTENDED: + if color := _parse_extended_color(params, _SGR.BG_EXTENDED): + state = state._replace(background=color) + return state + + +def propagate_sgr(lines: Sequence[str]) -> list[str]: + r""" + Propagate SGR codes across wrapped lines. + + When text with SGR styling is wrapped across multiple lines, each line + needs to be self-contained for proper display. This function: + + - Ends each line with ``\x1b[0m`` if styles are active (prevents bleeding) + - Starts each subsequent line with the active style restored + + :param lines: List of text lines, possibly containing SGR sequences. + :returns: List of lines with SGR codes propagated. + + Example:: + + >>> propagate_sgr(['\x1b[31mhello', 'world\x1b[0m']) + ['\x1b[31mhello\x1b[0m', '\x1b[31mworld\x1b[0m'] + + This is useful in cases of making special editors and viewers, and is used for the + default modes (propagate_sgr=True) of :func:`wcwidth.wrap` and :func:`wcwidth.clip`. + + When wrapping and clipping text containing SGR sequences, maybe a previous line enabled the BLUE + color--if we are viewing *only* the line following, we would want the carry over the BLUE color, + and all lines with sequences should end with terminating reset (``\x1b[0m``). + """ + # Fast path: check if any line contains SGR sequences + if not any(_SGR_QUICK_CHECK.search(line) for line in lines) or not lines: + return list(lines) + + result: list[str] = [] + state = _SGR_STATE_DEFAULT + + for line in lines: + # Prefix with restoration sequence if state is active + prefix = _sgr_state_to_sequence(state) + + # Update state by processing all SGR sequences in this line + for match in _SGR_PATTERN.finditer(line): + state = _sgr_state_update(state, match.group()) + + # Build output line + output_line = prefix + line if prefix else line + if _sgr_state_is_active(state): + output_line = output_line + _SGR_RESET + + result.append(output_line) + + return result diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_ambiguous.py b/.venv/lib/python3.12/site-packages/wcwidth/table_ambiguous.py new file mode 100644 index 0000000000000000000000000000000000000000..366ac3ba83768b5e9273eed55b44ca65888f2f21 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_ambiguous.py @@ -0,0 +1,189 @@ +""" +Exports AMBIGUOUS_EASTASIAN table keyed by supporting unicode version level. + +This code generated by python wcwidth project. +""" +# pylint: disable=duplicate-code +AMBIGUOUS_EASTASIAN = { + '18.0.0': ( + # Source: EastAsianWidth-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x000a1, 0x000a1,), # Inverted Exclamation Mark + (0x000a4, 0x000a4,), # Currency Sign + (0x000a7, 0x000a8,), # Section Sign ..Diaeresis + (0x000aa, 0x000aa,), # Feminine Ordinal Indicator + (0x000ad, 0x000ae,), # Soft Hyphen ..Registered Sign + (0x000b0, 0x000b4,), # Degree Sign ..Acute Accent + (0x000b6, 0x000ba,), # Pilcrow Sign ..Masculine Ordinal Indica + (0x000bc, 0x000bf,), # Vulgar Fraction One Quar..Inverted Question Mark + (0x000c6, 0x000c6,), # Latin Capital Letter Ae + (0x000d0, 0x000d0,), # Latin Capital Letter Eth + (0x000d7, 0x000d8,), # Multiplication Sign ..Latin Capital Letter O W + (0x000de, 0x000e1,), # Latin Capital Letter Tho..Latin Small Letter A Wit + (0x000e6, 0x000e6,), # Latin Small Letter Ae + (0x000e8, 0x000ea,), # Latin Small Letter E Wit..Latin Small Letter E Wit + (0x000ec, 0x000ed,), # Latin Small Letter I Wit..Latin Small Letter I Wit + (0x000f0, 0x000f0,), # Latin Small Letter Eth + (0x000f2, 0x000f3,), # Latin Small Letter O Wit..Latin Small Letter O Wit + (0x000f7, 0x000fa,), # Division Sign ..Latin Small Letter U Wit + (0x000fc, 0x000fc,), # Latin Small Letter U With Diaeresis + (0x000fe, 0x000fe,), # Latin Small Letter Thorn + (0x00101, 0x00101,), # Latin Small Letter A With Macron + (0x00111, 0x00111,), # Latin Small Letter D With Stroke + (0x00113, 0x00113,), # Latin Small Letter E With Macron + (0x0011b, 0x0011b,), # Latin Small Letter E With Caron + (0x00126, 0x00127,), # Latin Capital Letter H W..Latin Small Letter H Wit + (0x0012b, 0x0012b,), # Latin Small Letter I With Macron + (0x00131, 0x00133,), # Latin Small Letter Dotle..Latin Small Ligature Ij + (0x00138, 0x00138,), # Latin Small Letter Kra + (0x0013f, 0x00142,), # Latin Capital Letter L W..Latin Small Letter L Wit + (0x00144, 0x00144,), # Latin Small Letter N With Acute + (0x00148, 0x0014b,), # Latin Small Letter N Wit..Latin Small Letter Eng + (0x0014d, 0x0014d,), # Latin Small Letter O With Macron + (0x00152, 0x00153,), # Latin Capital Ligature O..Latin Small Ligature Oe + (0x00166, 0x00167,), # Latin Capital Letter T W..Latin Small Letter T Wit + (0x0016b, 0x0016b,), # Latin Small Letter U With Macron + (0x001ce, 0x001ce,), # Latin Small Letter A With Caron + (0x001d0, 0x001d0,), # Latin Small Letter I With Caron + (0x001d2, 0x001d2,), # Latin Small Letter O With Caron + (0x001d4, 0x001d4,), # Latin Small Letter U With Caron + (0x001d6, 0x001d6,), # Latin Small Letter U With Diaeresis And Macron + (0x001d8, 0x001d8,), # Latin Small Letter U With Diaeresis And Acute + (0x001da, 0x001da,), # Latin Small Letter U With Diaeresis And Caron + (0x001dc, 0x001dc,), # Latin Small Letter U With Diaeresis And Grave + (0x00251, 0x00251,), # Latin Small Letter Alpha + (0x00261, 0x00261,), # Latin Small Letter Script G + (0x002c4, 0x002c4,), # Modifier Letter Up Arrowhead + (0x002c7, 0x002c7,), # Caron + (0x002c9, 0x002cb,), # Modifier Letter Macron ..Modifier Letter Grave Ac + (0x002cd, 0x002cd,), # Modifier Letter Low Macron + (0x002d0, 0x002d0,), # Modifier Letter Triangular Colon + (0x002d8, 0x002db,), # Breve ..Ogonek + (0x002dd, 0x002dd,), # Double Acute Accent + (0x002df, 0x002df,), # Modifier Letter Cross Accent + (0x00391, 0x003a1,), # Greek Capital Letter Alp..Greek Capital Letter Rho + (0x003a3, 0x003a9,), # Greek Capital Letter Sig..Greek Capital Letter Ome + (0x003b1, 0x003c1,), # Greek Small Letter Alpha..Greek Small Letter Rho + (0x003c3, 0x003c9,), # Greek Small Letter Sigma..Greek Small Letter Omega + (0x00401, 0x00401,), # Cyrillic Capital Letter Io + (0x00410, 0x0044f,), # Cyrillic Capital Letter ..Cyrillic Small Letter Ya + (0x00451, 0x00451,), # Cyrillic Small Letter Io + (0x02010, 0x02010,), # Hyphen + (0x02013, 0x02016,), # En Dash ..Double Vertical Line + (0x02018, 0x02019,), # Left Single Quotation Ma..Right Single Quotation M + (0x0201c, 0x0201d,), # Left Double Quotation Ma..Right Double Quotation M + (0x02020, 0x02022,), # Dagger ..Bullet + (0x02024, 0x02027,), # One Dot Leader ..Hyphenation Point + (0x02030, 0x02030,), # Per Mille Sign + (0x02032, 0x02033,), # Prime ..Double Prime + (0x02035, 0x02035,), # Reversed Prime + (0x0203b, 0x0203b,), # Reference Mark + (0x0203e, 0x0203e,), # Overline + (0x02074, 0x02074,), # Superscript Four + (0x0207f, 0x0207f,), # Superscript Latin Small Letter N + (0x02081, 0x02084,), # Subscript One ..Subscript Four + (0x020ac, 0x020ac,), # Euro Sign + (0x02103, 0x02103,), # Degree Celsius + (0x02105, 0x02105,), # Care Of + (0x02109, 0x02109,), # Degree Fahrenheit + (0x02113, 0x02113,), # Script Small L + (0x02116, 0x02116,), # Numero Sign + (0x02121, 0x02122,), # Telephone Sign ..Trade Mark Sign + (0x02126, 0x02126,), # Ohm Sign + (0x0212b, 0x0212b,), # Angstrom Sign + (0x02153, 0x02154,), # Vulgar Fraction One Thir..Vulgar Fraction Two Thir + (0x0215b, 0x0215e,), # Vulgar Fraction One Eigh..Vulgar Fraction Seven Ei + (0x02160, 0x0216b,), # Roman Numeral One ..Roman Numeral Twelve + (0x02170, 0x02179,), # Small Roman Numeral One ..Small Roman Numeral Ten + (0x02189, 0x02189,), # Vulgar Fraction Zero Thirds + (0x02190, 0x02199,), # Leftwards Arrow ..South West Arrow + (0x021b8, 0x021b9,), # North West Arrow To Long..Leftwards Arrow To Bar O + (0x021d2, 0x021d2,), # Rightwards Double Arrow + (0x021d4, 0x021d4,), # Left Right Double Arrow + (0x021e7, 0x021e7,), # Upwards White Arrow + (0x02200, 0x02200,), # For All + (0x02202, 0x02203,), # Partial Differential ..There Exists + (0x02207, 0x02208,), # Nabla ..Element Of + (0x0220b, 0x0220b,), # Contains As Member + (0x0220f, 0x0220f,), # N-ary Product + (0x02211, 0x02211,), # N-ary Summation + (0x02215, 0x02215,), # Division Slash + (0x0221a, 0x0221a,), # Square Root + (0x0221d, 0x02220,), # Proportional To ..Angle + (0x02223, 0x02223,), # Divides + (0x02225, 0x02225,), # Parallel To + (0x02227, 0x0222c,), # Logical And ..Double Integral + (0x0222e, 0x0222e,), # Contour Integral + (0x02234, 0x02237,), # Therefore ..Proportion + (0x0223c, 0x0223d,), # Tilde Operator ..Reversed Tilde + (0x02248, 0x02248,), # Almost Equal To + (0x0224c, 0x0224c,), # All Equal To + (0x02252, 0x02252,), # Approximately Equal To Or The Image Of + (0x02260, 0x02261,), # Not Equal To ..Identical To + (0x02264, 0x02267,), # Less-than Or Equal To ..Greater-than Over Equal + (0x0226a, 0x0226b,), # Much Less-than ..Much Greater-than + (0x0226e, 0x0226f,), # Not Less-than ..Not Greater-than + (0x02282, 0x02283,), # Subset Of ..Superset Of + (0x02286, 0x02287,), # Subset Of Or Equal To ..Superset Of Or Equal To + (0x02295, 0x02295,), # Circled Plus + (0x02299, 0x02299,), # Circled Dot Operator + (0x022a5, 0x022a5,), # Up Tack + (0x022bf, 0x022bf,), # Right Triangle + (0x02312, 0x02312,), # Arc + (0x02460, 0x024e9,), # Circled Digit One ..Circled Latin Small Lett + (0x024eb, 0x0254b,), # Negative Circled Number ..Box Drawings Heavy Verti + (0x02550, 0x02573,), # Box Drawings Double Hori..Box Drawings Light Diago + (0x02580, 0x0258f,), # Upper Half Block ..Left One Eighth Block + (0x02592, 0x02595,), # Medium Shade ..Right One Eighth Block + (0x025a0, 0x025a1,), # Black Square ..White Square + (0x025a3, 0x025a9,), # White Square Containing ..Square With Diagonal Cro + (0x025b2, 0x025b3,), # Black Up-pointing Triang..White Up-pointing Triang + (0x025b6, 0x025b7,), # Black Right-pointing Tri..White Right-pointing Tri + (0x025bc, 0x025bd,), # Black Down-pointing Tria..White Down-pointing Tria + (0x025c0, 0x025c1,), # Black Left-pointing Tria..White Left-pointing Tria + (0x025c6, 0x025c8,), # Black Diamond ..White Diamond Containing + (0x025cb, 0x025cb,), # White Circle + (0x025ce, 0x025d1,), # Bullseye ..Circle With Right Half B + (0x025e2, 0x025e5,), # Black Lower Right Triang..Black Upper Right Triang + (0x025ef, 0x025ef,), # Large Circle + (0x02605, 0x02606,), # Black Star ..White Star + (0x02609, 0x02609,), # Sun + (0x0260e, 0x0260f,), # Black Telephone ..White Telephone + (0x0261c, 0x0261c,), # White Left Pointing Index + (0x0261e, 0x0261e,), # White Right Pointing Index + (0x02640, 0x02640,), # Female Sign + (0x02642, 0x02642,), # Male Sign + (0x02660, 0x02661,), # Black Spade Suit ..White Heart Suit + (0x02663, 0x02665,), # Black Club Suit ..Black Heart Suit + (0x02667, 0x0266a,), # White Club Suit ..Eighth Note + (0x0266c, 0x0266d,), # Beamed Sixteenth Notes ..Music Flat Sign + (0x0266f, 0x0266f,), # Music Sharp Sign + (0x0269e, 0x0269f,), # Three Lines Converging R..Three Lines Converging L + (0x026bf, 0x026bf,), # Squared Key + (0x026c6, 0x026cd,), # Rain ..Disabled Car + (0x026cf, 0x026d3,), # Pick ..Chains + (0x026d5, 0x026e1,), # Alternate One-way Left W..Restricted Left Entry-2 + (0x026e3, 0x026e3,), # Heavy Circle With Stroke And Two Dots Above + (0x026e8, 0x026e9,), # Black Cross On Shield ..Shinto Shrine + (0x026eb, 0x026f1,), # Castle ..Umbrella On Ground + (0x026f4, 0x026f4,), # Ferry + (0x026f6, 0x026f9,), # Square Four Corners ..Person With Ball + (0x026fb, 0x026fc,), # Japanese Bank Symbol ..Headstone Graveyard Symb + (0x026fe, 0x026ff,), # Cup On Black Square ..White Flag With Horizont + (0x0273d, 0x0273d,), # Heavy Teardrop-spoked Asterisk + (0x02776, 0x0277f,), # Dingbat Negative Circled..Dingbat Negative Circled + (0x02b56, 0x02b59,), # Heavy Oval With Oval Ins..Heavy Circled Saltire + (0x03248, 0x0324f,), # Circled Number Ten On Bl..Circled Number Eighty On + (0x0e000, 0x0f8ff,), # (nil) + (0x0fffd, 0x0fffd,), # Replacement Character + (0x1f100, 0x1f10a,), # Digit Zero Full Stop ..Digit Nine Comma + (0x1f110, 0x1f12d,), # Parenthesized Latin Capi..Circled Cd + (0x1f130, 0x1f169,), # Squared Latin Capital Le..Negative Circled Latin C + (0x1f170, 0x1f18d,), # Negative Squared Latin C..Negative Squared Sa + (0x1f18f, 0x1f190,), # Negative Squared Wc ..Square Dj + (0x1f19b, 0x1f1ac,), # Squared Three D ..Squared Vod + (0xf0000, 0xffffd,), # (nil) + (0x100000, 0x10fffd,), # (nil) + ), +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme.py new file mode 100644 index 0000000000000000000000000000000000000000..093d3a965b6068d81ba3a95a6704abbc2398158a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme.py @@ -0,0 +1,2365 @@ +""" +Exports grapheme cluster break property tables for Unicode version 18.0.0. + +This module provides lookup tables for Unicode grapheme cluster break properties as defined in UAX +#29: Unicode Text Segmentation. + +This code generated by python wcwidth project. +""" +# pylint: disable=duplicate-code + +GRAPHEME_CR = ( + # Source: GraphemeBreakProperty-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x0000d, 0x0000d,), # Carriage Return +) + +GRAPHEME_LF = ( + # Source: GraphemeBreakProperty-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x0000a, 0x0000a,), # Line Feed +) + +GRAPHEME_CONTROL = ( + # Source: GraphemeBreakProperty-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x00000, 0x00009,), # Null ..Character Tabulation + (0x0000b, 0x0000c,), # Line Tabulation ..Form Feed + (0x0000e, 0x0001f,), # Shift Out ..Information Separator On + (0x0007f, 0x0009f,), # Delete ..Application Program Comm + (0x000ad, 0x000ad,), # Soft Hyphen + (0x0061c, 0x0061c,), # Arabic Letter Mark + (0x0180e, 0x0180e,), # Mongolian Vowel Separator + (0x0200b, 0x0200b,), # Zero Width Space + (0x0200e, 0x0200f,), # Left-to-right Mark ..Right-to-left Mark + (0x02028, 0x0202e,), # Line Separator ..Right-to-left Override + (0x02060, 0x0206f,), # Word Joiner ..Nominal Digit Shapes + (0x0feff, 0x0feff,), # Zero Width No-break Space + (0x0fff0, 0x0fffb,), # (nil) ..Interlinear Annotation T + (0x13430, 0x1343f,), # Egyptian Hieroglyph Vert..Egyptian Hieroglyph End + (0x1bca0, 0x1bca3,), # Shorthand Format Letter ..Shorthand Format Up Step + (0x1d173, 0x1d17a,), # Musical Symbol Begin Bea..Musical Symbol End Phras + (0xe0000, 0xe001f,), # (nil) + (0xe0080, 0xe00ff,), # (nil) + (0xe01f0, 0xe0fff,), # (nil) +) + +GRAPHEME_EXTEND = ( + # Source: GraphemeBreakProperty-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x00300, 0x0036f,), # Combining Grave Accent ..Combining Latin Small Le + (0x00483, 0x00489,), # Combining Cyrillic Titlo..Combining Cyrillic Milli + (0x00591, 0x005bd,), # Hebrew Accent Etnahta ..Hebrew Point Meteg + (0x005bf, 0x005bf,), # Hebrew Point Rafe + (0x005c1, 0x005c2,), # Hebrew Point Shin Dot ..Hebrew Point Sin Dot + (0x005c4, 0x005c5,), # Hebrew Mark Upper Dot ..Hebrew Mark Lower Dot + (0x005c7, 0x005c9,), # Hebrew Point Qamats Qata..Hebrew Point Dagesh Haza + (0x00610, 0x0061a,), # Arabic Sign Sallallahou ..Arabic Small Kasra + (0x0064b, 0x0065f,), # Arabic Fathatan ..Arabic Wavy Hamza Below + (0x00670, 0x00670,), # Arabic Letter Superscript Alef + (0x006d6, 0x006dc,), # Arabic Small High Ligatu..Arabic Small High Seen + (0x006df, 0x006e4,), # Arabic Small High Rounde..Arabic Small High Madda + (0x006e7, 0x006e8,), # Arabic Small High Yeh ..Arabic Small High Noon + (0x006ea, 0x006ed,), # Arabic Empty Centre Low ..Arabic Small Low Meem + (0x00711, 0x00711,), # Syriac Letter Superscript Alaph + (0x00730, 0x0074a,), # Syriac Pthaha Above ..Syriac Barrekh + (0x007a6, 0x007b0,), # Thaana Abafili ..Thaana Sukun + (0x007eb, 0x007f3,), # Nko Combining Short High..Nko Combining Double Dot + (0x007fd, 0x007fd,), # Nko Dantayalan + (0x00816, 0x00819,), # Samaritan Mark In ..Samaritan Mark Dagesh + (0x0081b, 0x00823,), # Samaritan Mark Epentheti..Samaritan Vowel Sign A + (0x00825, 0x00827,), # Samaritan Vowel Sign Sho..Samaritan Vowel Sign U + (0x00829, 0x0082d,), # Samaritan Vowel Sign Lon..Samaritan Mark Nequdaa + (0x00859, 0x0085b,), # Mandaic Affrication Mark..Mandaic Gemination Mark + (0x00897, 0x0089f,), # Arabic Pepet ..Arabic Half Madda Over M + (0x008ca, 0x008e1,), # Arabic Small High Farsi ..Arabic Small High Sign S + (0x008e3, 0x00902,), # Arabic Turned Damma Belo..Devanagari Sign Anusvara + (0x0093a, 0x0093a,), # Devanagari Vowel Sign Oe + (0x0093c, 0x0093c,), # Devanagari Sign Nukta + (0x00941, 0x00948,), # Devanagari Vowel Sign U ..Devanagari Vowel Sign Ai + (0x0094d, 0x0094d,), # Devanagari Sign Virama + (0x00951, 0x00957,), # Devanagari Stress Sign U..Devanagari Vowel Sign Uu + (0x00962, 0x00963,), # Devanagari Vowel Sign Vo..Devanagari Vowel Sign Vo + (0x00981, 0x00981,), # Bengali Sign Candrabindu + (0x009bc, 0x009bc,), # Bengali Sign Nukta + (0x009be, 0x009be,), # Bengali Vowel Sign Aa + (0x009c1, 0x009c4,), # Bengali Vowel Sign U ..Bengali Vowel Sign Vocal + (0x009cd, 0x009cd,), # Bengali Sign Virama + (0x009d7, 0x009d7,), # Bengali Au Length Mark + (0x009e2, 0x009e3,), # Bengali Vowel Sign Vocal..Bengali Vowel Sign Vocal + (0x009fe, 0x009fe,), # Bengali Sandhi Mark + (0x00a01, 0x00a02,), # Gurmukhi Sign Adak Bindi..Gurmukhi Sign Bindi + (0x00a3c, 0x00a3c,), # Gurmukhi Sign Nukta + (0x00a41, 0x00a42,), # Gurmukhi Vowel Sign U ..Gurmukhi Vowel Sign Uu + (0x00a47, 0x00a48,), # Gurmukhi Vowel Sign Ee ..Gurmukhi Vowel Sign Ai + (0x00a4b, 0x00a4d,), # Gurmukhi Vowel Sign Oo ..Gurmukhi Sign Virama + (0x00a51, 0x00a51,), # Gurmukhi Sign Udaat + (0x00a70, 0x00a71,), # Gurmukhi Tippi ..Gurmukhi Addak + (0x00a75, 0x00a75,), # Gurmukhi Sign Yakash + (0x00a81, 0x00a82,), # Gujarati Sign Candrabind..Gujarati Sign Anusvara + (0x00abc, 0x00abc,), # Gujarati Sign Nukta + (0x00ac1, 0x00ac5,), # Gujarati Vowel Sign U ..Gujarati Vowel Sign Cand + (0x00ac7, 0x00ac8,), # Gujarati Vowel Sign E ..Gujarati Vowel Sign Ai + (0x00acd, 0x00acd,), # Gujarati Sign Virama + (0x00ae2, 0x00ae3,), # Gujarati Vowel Sign Voca..Gujarati Vowel Sign Voca + (0x00afa, 0x00aff,), # Gujarati Sign Sukun ..Gujarati Sign Two-circle + (0x00b01, 0x00b01,), # Oriya Sign Candrabindu + (0x00b3c, 0x00b3c,), # Oriya Sign Nukta + (0x00b3e, 0x00b3f,), # Oriya Vowel Sign Aa ..Oriya Vowel Sign I + (0x00b41, 0x00b44,), # Oriya Vowel Sign U ..Oriya Vowel Sign Vocalic + (0x00b4d, 0x00b4d,), # Oriya Sign Virama + (0x00b53, 0x00b57,), # Oriya Sign Dot Above ..Oriya Au Length Mark + (0x00b62, 0x00b63,), # Oriya Vowel Sign Vocalic..Oriya Vowel Sign Vocalic + (0x00b82, 0x00b82,), # Tamil Sign Anusvara + (0x00bbe, 0x00bbe,), # Tamil Vowel Sign Aa + (0x00bc0, 0x00bc0,), # Tamil Vowel Sign Ii + (0x00bcd, 0x00bcd,), # Tamil Sign Virama + (0x00bd7, 0x00bd7,), # Tamil Au Length Mark + (0x00c00, 0x00c00,), # Telugu Sign Combining Candrabindu Above + (0x00c04, 0x00c04,), # Telugu Sign Combining Anusvara Above + (0x00c3c, 0x00c3c,), # Telugu Sign Nukta + (0x00c3e, 0x00c40,), # Telugu Vowel Sign Aa ..Telugu Vowel Sign Ii + (0x00c46, 0x00c48,), # Telugu Vowel Sign E ..Telugu Vowel Sign Ai + (0x00c4a, 0x00c4d,), # Telugu Vowel Sign O ..Telugu Sign Virama + (0x00c55, 0x00c56,), # Telugu Length Mark ..Telugu Ai Length Mark + (0x00c62, 0x00c63,), # Telugu Vowel Sign Vocali..Telugu Vowel Sign Vocali + (0x00c81, 0x00c81,), # Kannada Sign Candrabindu + (0x00cbc, 0x00cbc,), # Kannada Sign Nukta + (0x00cbf, 0x00cc0,), # Kannada Vowel Sign I ..Kannada Vowel Sign Ii + (0x00cc2, 0x00cc2,), # Kannada Vowel Sign Uu + (0x00cc6, 0x00cc8,), # Kannada Vowel Sign E ..Kannada Vowel Sign Ai + (0x00cca, 0x00ccd,), # Kannada Vowel Sign O ..Kannada Sign Virama + (0x00cd5, 0x00cd6,), # Kannada Length Mark ..Kannada Ai Length Mark + (0x00ce2, 0x00ce3,), # Kannada Vowel Sign Vocal..Kannada Vowel Sign Vocal + (0x00d00, 0x00d01,), # Malayalam Sign Combining..Malayalam Sign Candrabin + (0x00d3b, 0x00d3c,), # Malayalam Sign Vertical ..Malayalam Sign Circular + (0x00d3e, 0x00d3e,), # Malayalam Vowel Sign Aa + (0x00d41, 0x00d44,), # Malayalam Vowel Sign U ..Malayalam Vowel Sign Voc + (0x00d4d, 0x00d4d,), # Malayalam Sign Virama + (0x00d57, 0x00d57,), # Malayalam Au Length Mark + (0x00d62, 0x00d63,), # Malayalam Vowel Sign Voc..Malayalam Vowel Sign Voc + (0x00d81, 0x00d81,), # Sinhala Sign Candrabindu + (0x00dca, 0x00dca,), # Sinhala Sign Al-lakuna + (0x00dcf, 0x00dcf,), # Sinhala Vowel Sign Aela-pilla + (0x00dd2, 0x00dd4,), # Sinhala Vowel Sign Ketti..Sinhala Vowel Sign Ketti + (0x00dd6, 0x00dd6,), # Sinhala Vowel Sign Diga Paa-pilla + (0x00ddf, 0x00ddf,), # Sinhala Vowel Sign Gayanukitta + (0x00e31, 0x00e31,), # Thai Character Mai Han-akat + (0x00e34, 0x00e3a,), # Thai Character Sara I ..Thai Character Phinthu + (0x00e47, 0x00e4e,), # Thai Character Maitaikhu..Thai Character Yamakkan + (0x00eb1, 0x00eb1,), # Lao Vowel Sign Mai Kan + (0x00eb4, 0x00ebc,), # Lao Vowel Sign I ..Lao Semivowel Sign Lo + (0x00ec8, 0x00ece,), # Lao Tone Mai Ek ..Lao Yamakkan + (0x00f18, 0x00f19,), # Tibetan Astrological Sig..Tibetan Astrological Sig + (0x00f35, 0x00f35,), # Tibetan Mark Ngas Bzung Nyi Zla + (0x00f37, 0x00f37,), # Tibetan Mark Ngas Bzung Sgor Rtags + (0x00f39, 0x00f39,), # Tibetan Mark Tsa -phru + (0x00f71, 0x00f7e,), # Tibetan Vowel Sign Aa ..Tibetan Sign Rjes Su Nga + (0x00f80, 0x00f84,), # Tibetan Vowel Sign Rever..Tibetan Mark Halanta + (0x00f86, 0x00f87,), # Tibetan Sign Lci Rtags ..Tibetan Sign Yang Rtags + (0x00f8d, 0x00f97,), # Tibetan Subjoined Sign L..Tibetan Subjoined Letter + (0x00f99, 0x00fbc,), # Tibetan Subjoined Letter..Tibetan Subjoined Letter + (0x00fc6, 0x00fc6,), # Tibetan Symbol Padma Gdan + (0x0102d, 0x01030,), # Myanmar Vowel Sign I ..Myanmar Vowel Sign Uu + (0x01032, 0x01037,), # Myanmar Vowel Sign Ai ..Myanmar Sign Dot Below + (0x01039, 0x0103a,), # Myanmar Sign Virama ..Myanmar Sign Asat + (0x0103d, 0x0103e,), # Myanmar Consonant Sign M..Myanmar Consonant Sign M + (0x01058, 0x01059,), # Myanmar Vowel Sign Vocal..Myanmar Vowel Sign Vocal + (0x0105e, 0x01060,), # Myanmar Consonant Sign M..Myanmar Consonant Sign M + (0x01071, 0x01074,), # Myanmar Vowel Sign Geba ..Myanmar Vowel Sign Kayah + (0x01082, 0x01082,), # Myanmar Consonant Sign Shan Medial Wa + (0x01085, 0x01086,), # Myanmar Vowel Sign Shan ..Myanmar Vowel Sign Shan + (0x0108d, 0x0108d,), # Myanmar Sign Shan Council Emphatic Tone + (0x0109d, 0x0109d,), # Myanmar Vowel Sign Aiton Ai + (0x0135d, 0x0135f,), # Ethiopic Combining Gemin..Ethiopic Combining Gemin + (0x01712, 0x01715,), # Tagalog Vowel Sign I ..Tagalog Sign Pamudpod + (0x01732, 0x01734,), # Hanunoo Vowel Sign I ..Hanunoo Sign Pamudpod + (0x01752, 0x01753,), # Buhid Vowel Sign I ..Buhid Vowel Sign U + (0x01772, 0x01773,), # Tagbanwa Vowel Sign I ..Tagbanwa Vowel Sign U + (0x017b4, 0x017b5,), # Khmer Vowel Inherent Aq ..Khmer Vowel Inherent Aa + (0x017b7, 0x017bd,), # Khmer Vowel Sign I ..Khmer Vowel Sign Ua + (0x017c6, 0x017c6,), # Khmer Sign Nikahit + (0x017c9, 0x017d3,), # Khmer Sign Muusikatoan ..Khmer Sign Bathamasat + (0x017dd, 0x017dd,), # Khmer Sign Atthacan + (0x0180b, 0x0180d,), # Mongolian Free Variation..Mongolian Free Variation + (0x0180f, 0x0180f,), # Mongolian Free Variation Selector Four + (0x01885, 0x01886,), # Mongolian Letter Ali Gal..Mongolian Letter Ali Gal + (0x018a9, 0x018a9,), # Mongolian Letter Ali Gali Dagalga + (0x01920, 0x01922,), # Limbu Vowel Sign A ..Limbu Vowel Sign U + (0x01927, 0x01928,), # Limbu Vowel Sign E ..Limbu Vowel Sign O + (0x01932, 0x01932,), # Limbu Small Letter Anusvara + (0x01939, 0x0193b,), # Limbu Sign Mukphreng ..Limbu Sign Sa-i + (0x01a17, 0x01a18,), # Buginese Vowel Sign I ..Buginese Vowel Sign U + (0x01a1b, 0x01a1b,), # Buginese Vowel Sign Ae + (0x01a56, 0x01a56,), # Tai Tham Consonant Sign Medial La + (0x01a58, 0x01a5e,), # Tai Tham Sign Mai Kang L..Tai Tham Consonant Sign + (0x01a60, 0x01a60,), # Tai Tham Sign Sakot + (0x01a62, 0x01a62,), # Tai Tham Vowel Sign Mai Sat + (0x01a65, 0x01a6c,), # Tai Tham Vowel Sign I ..Tai Tham Vowel Sign Oa B + (0x01a73, 0x01a7c,), # Tai Tham Vowel Sign Oa A..Tai Tham Sign Khuen-lue + (0x01a7f, 0x01a7f,), # Tai Tham Combining Cryptogrammic Dot + (0x01ab0, 0x01af0,), # Combining Doubled Circum..Combining Double Comma A + (0x01b00, 0x01b03,), # Balinese Sign Ulu Ricem ..Balinese Sign Surang + (0x01b34, 0x01b3d,), # Balinese Sign Rerekan ..Balinese Vowel Sign La L + (0x01b42, 0x01b44,), # Balinese Vowel Sign Pepe..Balinese Adeg Adeg + (0x01b6b, 0x01b73,), # Balinese Musical Symbol ..Balinese Musical Symbol + (0x01b80, 0x01b81,), # Sundanese Sign Panyecek ..Sundanese Sign Panglayar + (0x01ba2, 0x01ba5,), # Sundanese Consonant Sign..Sundanese Vowel Sign Pan + (0x01ba8, 0x01bad,), # Sundanese Vowel Sign Pam..Sundanese Consonant Sign + (0x01be6, 0x01be6,), # Batak Sign Tompi + (0x01be8, 0x01be9,), # Batak Vowel Sign Pakpak ..Batak Vowel Sign Ee + (0x01bed, 0x01bed,), # Batak Vowel Sign Karo O + (0x01bef, 0x01bf3,), # Batak Vowel Sign U For S..Batak Panongonan + (0x01c2c, 0x01c33,), # Lepcha Vowel Sign E ..Lepcha Consonant Sign T + (0x01c36, 0x01c37,), # Lepcha Sign Ran ..Lepcha Sign Nukta + (0x01cd0, 0x01cd2,), # Vedic Tone Karshana ..Vedic Tone Prenkha + (0x01cd4, 0x01ce0,), # Vedic Sign Yajurvedic Mi..Vedic Tone Rigvedic Kash + (0x01ce2, 0x01ce8,), # Vedic Sign Visarga Svari..Vedic Sign Visarga Anuda + (0x01ced, 0x01ced,), # Vedic Sign Tiryak + (0x01cf4, 0x01cf4,), # Vedic Tone Candra Above + (0x01cf8, 0x01cf9,), # Vedic Tone Ring Above ..Vedic Tone Double Ring A + (0x01dc0, 0x01dff,), # Combining Dotted Grave A..Combining Right Arrowhea + (0x0200c, 0x0200c,), # Zero Width Non-joiner + (0x020d0, 0x020f0,), # Combining Left Harpoon A..Combining Asterisk Above + (0x02cef, 0x02cf1,), # Coptic Combining Ni Abov..Coptic Combining Spiritu + (0x02d7f, 0x02d7f,), # Tifinagh Consonant Joiner + (0x02de0, 0x02dff,), # Combining Cyrillic Lette..Combining Cyrillic Lette + (0x0302a, 0x0302f,), # Ideographic Level Tone M..Hangul Double Dot Tone M + (0x03099, 0x0309a,), # Combining Katakana-hirag..Combining Katakana-hirag + (0x0a66f, 0x0a672,), # Combining Cyrillic Vzmet..Combining Cyrillic Thous + (0x0a674, 0x0a67d,), # Combining Cyrillic Lette..Combining Cyrillic Payer + (0x0a69e, 0x0a69f,), # Combining Cyrillic Lette..Combining Cyrillic Lette + (0x0a6f0, 0x0a6f1,), # Bamum Combining Mark Koq..Bamum Combining Mark Tuk + (0x0a802, 0x0a802,), # Syloti Nagri Sign Dvisvara + (0x0a806, 0x0a806,), # Syloti Nagri Sign Hasanta + (0x0a80b, 0x0a80b,), # Syloti Nagri Sign Anusvara + (0x0a825, 0x0a826,), # Syloti Nagri Vowel Sign ..Syloti Nagri Vowel Sign + (0x0a82c, 0x0a82c,), # Syloti Nagri Sign Alternate Hasanta + (0x0a8c4, 0x0a8c5,), # Saurashtra Sign Virama ..Saurashtra Sign Candrabi + (0x0a8e0, 0x0a8f1,), # Combining Devanagari Dig..Combining Devanagari Sig + (0x0a8ff, 0x0a8ff,), # Devanagari Vowel Sign Ay + (0x0a926, 0x0a92d,), # Kayah Li Vowel Ue ..Kayah Li Tone Calya Plop + (0x0a947, 0x0a951,), # Rejang Vowel Sign I ..Rejang Consonant Sign R + (0x0a953, 0x0a953,), # Rejang Virama + (0x0a980, 0x0a982,), # Javanese Sign Panyangga ..Javanese Sign Layar + (0x0a9b3, 0x0a9b3,), # Javanese Sign Cecak Telu + (0x0a9b6, 0x0a9b9,), # Javanese Vowel Sign Wulu..Javanese Vowel Sign Suku + (0x0a9bc, 0x0a9bd,), # Javanese Vowel Sign Pepe..Javanese Consonant Sign + (0x0a9c0, 0x0a9c0,), # Javanese Pangkon + (0x0a9e5, 0x0a9e5,), # Myanmar Sign Shan Saw + (0x0aa29, 0x0aa2e,), # Cham Vowel Sign Aa ..Cham Vowel Sign Oe + (0x0aa31, 0x0aa32,), # Cham Vowel Sign Au ..Cham Vowel Sign Ue + (0x0aa35, 0x0aa36,), # Cham Consonant Sign La ..Cham Consonant Sign Wa + (0x0aa43, 0x0aa43,), # Cham Consonant Sign Final Ng + (0x0aa4c, 0x0aa4c,), # Cham Consonant Sign Final M + (0x0aa7c, 0x0aa7c,), # Myanmar Sign Tai Laing Tone-2 + (0x0aab0, 0x0aab0,), # Tai Viet Mai Kang + (0x0aab2, 0x0aab4,), # Tai Viet Vowel I ..Tai Viet Vowel U + (0x0aab7, 0x0aab8,), # Tai Viet Mai Khit ..Tai Viet Vowel Ia + (0x0aabe, 0x0aabf,), # Tai Viet Vowel Am ..Tai Viet Tone Mai Ek + (0x0aac1, 0x0aac1,), # Tai Viet Tone Mai Tho + (0x0aaec, 0x0aaed,), # Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + (0x0aaf6, 0x0aaf6,), # Meetei Mayek Virama + (0x0abe5, 0x0abe5,), # Meetei Mayek Vowel Sign Anap + (0x0abe8, 0x0abe8,), # Meetei Mayek Vowel Sign Unap + (0x0abed, 0x0abed,), # Meetei Mayek Apun Iyek + (0x0fb1e, 0x0fb1e,), # Hebrew Point Judeo-spanish Varika + (0x0fe00, 0x0fe0f,), # Variation Selector-1 ..Variation Selector-16 + (0x0fe20, 0x0fe2f,), # Combining Ligature Left ..Combining Cyrillic Titlo + (0x0ff9e, 0x0ff9f,), # Halfwidth Katakana Voice..Halfwidth Katakana Semi- + (0x101fd, 0x101fd,), # Phaistos Disc Sign Combining Oblique Stroke + (0x102e0, 0x102e0,), # Coptic Epact Thousands Mark + (0x10376, 0x1037a,), # Combining Old Permic Let..Combining Old Permic Let + (0x10a01, 0x10a03,), # Kharoshthi Vowel Sign I ..Kharoshthi Vowel Sign Vo + (0x10a05, 0x10a06,), # Kharoshthi Vowel Sign E ..Kharoshthi Vowel Sign O + (0x10a0c, 0x10a0f,), # Kharoshthi Vowel Length ..Kharoshthi Sign Visarga + (0x10a38, 0x10a3a,), # Kharoshthi Sign Bar Abov..Kharoshthi Sign Dot Belo + (0x10a3f, 0x10a3f,), # Kharoshthi Virama + (0x10ae5, 0x10ae6,), # Manichaean Abbreviation ..Manichaean Abbreviation + (0x10d24, 0x10d27,), # Hanifi Rohingya Sign Har..Hanifi Rohingya Sign Tas + (0x10d69, 0x10d6d,), # Garay Vowel Sign E ..Garay Consonant Nasaliza + (0x10eab, 0x10eac,), # Yezidi Combining Hamza M..Yezidi Combining Madda M + (0x10ecb, 0x10ecf,), # Arabic Northeast Pointin..Arabic Large Circle Abov + (0x10ef0, 0x10eff,), # Arabic Small Low Upright..Arabic Small Low Word Ma + (0x10f46, 0x10f50,), # Sogdian Combining Dot Be..Sogdian Combining Stroke + (0x10f82, 0x10f85,), # Old Uyghur Combining Dot..Old Uyghur Combining Two + (0x11001, 0x11001,), # Brahmi Sign Anusvara + (0x11038, 0x11046,), # Brahmi Vowel Sign Aa ..Brahmi Virama + (0x11070, 0x11070,), # Brahmi Sign Old Tamil Virama + (0x11073, 0x11074,), # Brahmi Vowel Sign Old Ta..Brahmi Vowel Sign Old Ta + (0x1107f, 0x11081,), # Brahmi Number Joiner ..Kaithi Sign Anusvara + (0x110b3, 0x110b6,), # Kaithi Vowel Sign U ..Kaithi Vowel Sign Ai + (0x110b9, 0x110ba,), # Kaithi Sign Virama ..Kaithi Sign Nukta + (0x110c2, 0x110c2,), # Kaithi Vowel Sign Vocalic R + (0x11100, 0x11102,), # Chakma Sign Candrabindu ..Chakma Sign Visarga + (0x11127, 0x1112b,), # Chakma Vowel Sign A ..Chakma Vowel Sign Uu + (0x1112d, 0x11134,), # Chakma Vowel Sign Ai ..Chakma Maayyaa + (0x11173, 0x11173,), # Mahajani Sign Nukta + (0x11180, 0x11181,), # Sharada Sign Candrabindu..Sharada Sign Anusvara + (0x111b6, 0x111be,), # Sharada Vowel Sign U ..Sharada Vowel Sign O + (0x111c0, 0x111c0,), # Sharada Sign Virama + (0x111c9, 0x111cc,), # Sharada Sandhi Mark ..Sharada Extra Short Vowe + (0x111cf, 0x111cf,), # Sharada Sign Inverted Candrabindu + (0x1122f, 0x11231,), # Khojki Vowel Sign U ..Khojki Vowel Sign Ai + (0x11234, 0x11237,), # Khojki Sign Anusvara ..Khojki Sign Shadda + (0x1123e, 0x1123e,), # Khojki Sign Sukun + (0x11241, 0x11241,), # Khojki Vowel Sign Vocalic R + (0x112df, 0x112df,), # Khudawadi Sign Anusvara + (0x112e3, 0x112ea,), # Khudawadi Vowel Sign U ..Khudawadi Sign Virama + (0x11300, 0x11301,), # Grantha Sign Combining A..Grantha Sign Candrabindu + (0x1133b, 0x1133c,), # Combining Bindu Below ..Grantha Sign Nukta + (0x1133e, 0x1133e,), # Grantha Vowel Sign Aa + (0x11340, 0x11340,), # Grantha Vowel Sign Ii + (0x1134d, 0x1134d,), # Grantha Sign Virama + (0x11357, 0x11357,), # Grantha Au Length Mark + (0x11366, 0x1136c,), # Combining Grantha Digit ..Combining Grantha Digit + (0x11370, 0x11374,), # Combining Grantha Letter..Combining Grantha Letter + (0x113b8, 0x113b8,), # Tulu-tigalari Vowel Sign Aa + (0x113bb, 0x113c0,), # Tulu-tigalari Vowel Sign..Tulu-tigalari Vowel Sign + (0x113c2, 0x113c2,), # Tulu-tigalari Vowel Sign Ee + (0x113c5, 0x113c5,), # Tulu-tigalari Vowel Sign Ai + (0x113c7, 0x113c9,), # Tulu-tigalari Vowel Sign..Tulu-tigalari Au Length + (0x113ce, 0x113d0,), # Tulu-tigalari Sign Viram..Tulu-tigalari Conjoiner + (0x113d2, 0x113d2,), # Tulu-tigalari Gemination Mark + (0x113e1, 0x113e2,), # Tulu-tigalari Vedic Tone..Tulu-tigalari Vedic Tone + (0x11438, 0x1143f,), # Newa Vowel Sign U ..Newa Vowel Sign Ai + (0x11442, 0x11444,), # Newa Sign Virama ..Newa Sign Anusvara + (0x11446, 0x11446,), # Newa Sign Nukta + (0x1145e, 0x1145e,), # Newa Sandhi Mark + (0x114b0, 0x114b0,), # Tirhuta Vowel Sign Aa + (0x114b3, 0x114b8,), # Tirhuta Vowel Sign U ..Tirhuta Vowel Sign Vocal + (0x114ba, 0x114ba,), # Tirhuta Vowel Sign Short E + (0x114bd, 0x114bd,), # Tirhuta Vowel Sign Short O + (0x114bf, 0x114c0,), # Tirhuta Sign Candrabindu..Tirhuta Sign Anusvara + (0x114c2, 0x114c3,), # Tirhuta Sign Virama ..Tirhuta Sign Nukta + (0x115af, 0x115af,), # Siddham Vowel Sign Aa + (0x115b2, 0x115b5,), # Siddham Vowel Sign U ..Siddham Vowel Sign Vocal + (0x115bc, 0x115bd,), # Siddham Sign Candrabindu..Siddham Sign Anusvara + (0x115bf, 0x115c0,), # Siddham Sign Virama ..Siddham Sign Nukta + (0x115dc, 0x115dd,), # Siddham Vowel Sign Alter..Siddham Vowel Sign Alter + (0x11633, 0x1163a,), # Modi Vowel Sign U ..Modi Vowel Sign Ai + (0x1163d, 0x1163d,), # Modi Sign Anusvara + (0x1163f, 0x11640,), # Modi Sign Virama ..Modi Sign Ardhacandra + (0x116ab, 0x116ab,), # Takri Sign Anusvara + (0x116ad, 0x116ad,), # Takri Vowel Sign Aa + (0x116b0, 0x116b7,), # Takri Vowel Sign U ..Takri Sign Nukta + (0x1171d, 0x1171d,), # Ahom Consonant Sign Medial La + (0x1171f, 0x1171f,), # Ahom Consonant Sign Medial Ligating Ra + (0x11722, 0x11725,), # Ahom Vowel Sign I ..Ahom Vowel Sign Uu + (0x11727, 0x1172b,), # Ahom Vowel Sign Aw ..Ahom Sign Killer + (0x1182f, 0x11837,), # Dogra Vowel Sign U ..Dogra Sign Anusvara + (0x11839, 0x1183a,), # Dogra Sign Virama ..Dogra Sign Nukta + (0x11930, 0x11930,), # Dives Akuru Vowel Sign Aa + (0x1193b, 0x1193e,), # Dives Akuru Sign Anusvar..Dives Akuru Virama + (0x11943, 0x11943,), # Dives Akuru Sign Nukta + (0x119d4, 0x119d7,), # Nandinagari Vowel Sign U..Nandinagari Vowel Sign V + (0x119da, 0x119db,), # Nandinagari Vowel Sign E..Nandinagari Vowel Sign A + (0x119e0, 0x119e0,), # Nandinagari Sign Virama + (0x11a01, 0x11a0a,), # Zanabazar Square Vowel S..Zanabazar Square Vowel L + (0x11a33, 0x11a38,), # Zanabazar Square Final C..Zanabazar Square Sign An + (0x11a3b, 0x11a3e,), # Zanabazar Square Cluster..Zanabazar Square Cluster + (0x11a47, 0x11a47,), # Zanabazar Square Subjoiner + (0x11a51, 0x11a56,), # Soyombo Vowel Sign I ..Soyombo Vowel Sign Oe + (0x11a59, 0x11a5b,), # Soyombo Vowel Sign Vocal..Soyombo Vowel Length Mar + (0x11a8a, 0x11a96,), # Soyombo Final Consonant ..Soyombo Sign Anusvara + (0x11a98, 0x11a99,), # Soyombo Gemination Mark ..Soyombo Subjoiner + (0x11b60, 0x11b60,), # Sharada Vowel Sign Oe + (0x11b62, 0x11b64,), # Sharada Vowel Sign Ue ..Sharada Vowel Sign Short + (0x11b66, 0x11b66,), # Sharada Vowel Sign Candra E + (0x11c30, 0x11c36,), # Bhaiksuki Vowel Sign I ..Bhaiksuki Vowel Sign Voc + (0x11c38, 0x11c3d,), # Bhaiksuki Vowel Sign E ..Bhaiksuki Sign Anusvara + (0x11c3f, 0x11c3f,), # Bhaiksuki Sign Virama + (0x11c92, 0x11ca7,), # Marchen Subjoined Letter..Marchen Subjoined Letter + (0x11caa, 0x11cb0,), # Marchen Subjoined Letter..Marchen Vowel Sign Aa + (0x11cb2, 0x11cb3,), # Marchen Vowel Sign U ..Marchen Vowel Sign E + (0x11cb5, 0x11cb6,), # Marchen Sign Anusvara ..Marchen Sign Candrabindu + (0x11d31, 0x11d36,), # Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign + (0x11d3a, 0x11d3a,), # Masaram Gondi Vowel Sign E + (0x11d3c, 0x11d3d,), # Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign + (0x11d3f, 0x11d45,), # Masaram Gondi Vowel Sign..Masaram Gondi Virama + (0x11d47, 0x11d47,), # Masaram Gondi Ra-kara + (0x11d90, 0x11d91,), # Gunjala Gondi Vowel Sign..Gunjala Gondi Vowel Sign + (0x11d95, 0x11d95,), # Gunjala Gondi Sign Anusvara + (0x11d97, 0x11d97,), # Gunjala Gondi Virama + (0x11df0, 0x11df0,), # Bengali Sign Combining Anusvara Above + (0x11ef3, 0x11ef4,), # Makasar Vowel Sign I ..Makasar Vowel Sign U + (0x11f00, 0x11f01,), # Kawi Sign Candrabindu ..Kawi Sign Anusvara + (0x11f36, 0x11f3a,), # Kawi Vowel Sign I ..Kawi Vowel Sign Vocalic + (0x11f40, 0x11f42,), # Kawi Vowel Sign Eu ..Kawi Conjoiner + (0x11f5a, 0x11f5a,), # Kawi Sign Nukta + (0x13440, 0x13440,), # Egyptian Hieroglyph Mirror Horizontally + (0x13447, 0x13455,), # Egyptian Hieroglyph Modi..Egyptian Hieroglyph Modi + (0x1611e, 0x16129,), # Gurung Khema Vowel Sign ..Gurung Khema Vowel Lengt + (0x1612d, 0x1612f,), # Gurung Khema Sign Anusva..Gurung Khema Sign Tholho + (0x16af0, 0x16af4,), # Bassa Vah Combining High..Bassa Vah Combining High + (0x16b30, 0x16b36,), # Pahawh Hmong Mark Cim Tu..Pahawh Hmong Mark Cim Ta + (0x16f4f, 0x16f4f,), # Miao Sign Consonant Modifier Bar + (0x16f8f, 0x16f92,), # Miao Tone Right ..Miao Tone Below + (0x16fe4, 0x16fe4,), # Khitan Small Script Filler + (0x16ff0, 0x16ff1,), # Vietnamese Alternate Rea..Vietnamese Alternate Rea + (0x1bc9d, 0x1bc9e,), # Duployan Thick Letter Se..Duployan Double Mark + (0x1cf00, 0x1cf2d,), # Znamenny Combining Mark ..Znamenny Combining Mark + (0x1cf30, 0x1cf46,), # Znamenny Combining Tonal..Znamenny Priznak Modifie + (0x1d127, 0x1d128,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d165, 0x1d169,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d16d, 0x1d172,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d17b, 0x1d182,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d185, 0x1d18b,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d1aa, 0x1d1ad,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d242, 0x1d244,), # Combining Greek Musical ..Combining Greek Musical + (0x1d250, 0x1d252,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d25b, 0x1d25c,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d25f, 0x1d25f,), # Musical Symbol Combining Buzz Roll Stem + (0x1d280, 0x1d281,), # Musical Symbol Combining..Musical Symbol Combining + (0x1da00, 0x1da36,), # Signwriting Head Rim ..Signwriting Air Sucking + (0x1da3b, 0x1da6c,), # Signwriting Mouth Closed..Signwriting Excitement + (0x1da75, 0x1da75,), # Signwriting Upper Body Tilting From Hip Joints + (0x1da84, 0x1da84,), # Signwriting Location Head Neck + (0x1da9b, 0x1da9f,), # Signwriting Fill Modifie..Signwriting Fill Modifie + (0x1daa1, 0x1daaf,), # Signwriting Rotation Mod..Signwriting Rotation Mod + (0x1e000, 0x1e006,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e008, 0x1e018,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e01b, 0x1e021,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e023, 0x1e024,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e026, 0x1e02a,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e08f, 0x1e08f,), # Combining Cyrillic Small Letter Byelorussian-ukr + (0x1e130, 0x1e136,), # Nyiakeng Puachue Hmong T..Nyiakeng Puachue Hmong T + (0x1e2ae, 0x1e2ae,), # Toto Sign Rising Tone + (0x1e2ec, 0x1e2ef,), # Wancho Tone Tup ..Wancho Tone Koini + (0x1e4ec, 0x1e4ef,), # Nag Mundari Sign Muhor ..Nag Mundari Sign Sutuh + (0x1e5ee, 0x1e5ef,), # Ol Onal Sign Mu ..Ol Onal Sign Ikir + (0x1e6e3, 0x1e6e3,), # Tai Yo Sign Ue + (0x1e6e6, 0x1e6e6,), # Tai Yo Sign Au + (0x1e6ee, 0x1e6ef,), # Tai Yo Sign Ay ..Tai Yo Sign Ang + (0x1e6f5, 0x1e6f5,), # Tai Yo Sign Om + (0x1e8d0, 0x1e8d6,), # Mende Kikakui Combining ..Mende Kikakui Combining + (0x1e944, 0x1e94a,), # Adlam Alif Lengthener ..Adlam Nukta + (0x1f3fb, 0x1f3ff,), # Emoji Modifier Fitzpatri..Emoji Modifier Fitzpatri + (0xe0020, 0xe007f,), # Tag Space ..Cancel Tag + (0xe0100, 0xe01ef,), # Variation Selector-17 ..Variation Selector-256 +) + +GRAPHEME_ZWJ = ( + # Source: GraphemeBreakProperty-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x0200d, 0x0200d,), # Zero Width Joiner +) + +GRAPHEME_REGIONAL_INDICATOR = ( + # Source: GraphemeBreakProperty-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x1f1e6, 0x1f1ff,), # Regional Indicator Symbo..Regional Indicator Symbo +) + +GRAPHEME_PREPEND = ( + # Source: GraphemeBreakProperty-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x00600, 0x00605,), # Arabic Number Sign ..Arabic Number Mark Above + (0x006dd, 0x006dd,), # Arabic End Of Ayah + (0x0070f, 0x0070f,), # Syriac Abbreviation Mark + (0x00890, 0x00891,), # Arabic Pound Mark Above ..Arabic Piastre Mark Abov + (0x008e2, 0x008e2,), # Arabic Disputed End Of Ayah + (0x00d4e, 0x00d4e,), # Malayalam Letter Dot Reph + (0x110bd, 0x110bd,), # Kaithi Number Sign + (0x110cd, 0x110cd,), # Kaithi Number Sign Above + (0x111c2, 0x111c3,), # Sharada Sign Jihvamuliya..Sharada Sign Upadhmaniya + (0x113d1, 0x113d1,), # Tulu-tigalari Repha + (0x1193f, 0x1193f,), # Dives Akuru Prefixed Nasal Sign + (0x11941, 0x11941,), # Dives Akuru Initial Ra + (0x11a84, 0x11a89,), # Soyombo Sign Jihvamuliya..Soyombo Cluster-initial + (0x11d46, 0x11d46,), # Masaram Gondi Repha + (0x11f02, 0x11f02,), # Kawi Sign Repha +) + +GRAPHEME_SPACINGMARK = ( + # Source: GraphemeBreakProperty-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x00903, 0x00903,), # Devanagari Sign Visarga + (0x0093b, 0x0093b,), # Devanagari Vowel Sign Ooe + (0x0093e, 0x00940,), # Devanagari Vowel Sign Aa..Devanagari Vowel Sign Ii + (0x00949, 0x0094c,), # Devanagari Vowel Sign Ca..Devanagari Vowel Sign Au + (0x0094e, 0x0094f,), # Devanagari Vowel Sign Pr..Devanagari Vowel Sign Aw + (0x00982, 0x00983,), # Bengali Sign Anusvara ..Bengali Sign Visarga + (0x009bf, 0x009c0,), # Bengali Vowel Sign I ..Bengali Vowel Sign Ii + (0x009c7, 0x009c8,), # Bengali Vowel Sign E ..Bengali Vowel Sign Ai + (0x009cb, 0x009cc,), # Bengali Vowel Sign O ..Bengali Vowel Sign Au + (0x00a03, 0x00a03,), # Gurmukhi Sign Visarga + (0x00a3e, 0x00a40,), # Gurmukhi Vowel Sign Aa ..Gurmukhi Vowel Sign Ii + (0x00a83, 0x00a83,), # Gujarati Sign Visarga + (0x00abe, 0x00ac0,), # Gujarati Vowel Sign Aa ..Gujarati Vowel Sign Ii + (0x00ac9, 0x00ac9,), # Gujarati Vowel Sign Candra O + (0x00acb, 0x00acc,), # Gujarati Vowel Sign O ..Gujarati Vowel Sign Au + (0x00b02, 0x00b03,), # Oriya Sign Anusvara ..Oriya Sign Visarga + (0x00b40, 0x00b40,), # Oriya Vowel Sign Ii + (0x00b47, 0x00b48,), # Oriya Vowel Sign E ..Oriya Vowel Sign Ai + (0x00b4b, 0x00b4c,), # Oriya Vowel Sign O ..Oriya Vowel Sign Au + (0x00bbf, 0x00bbf,), # Tamil Vowel Sign I + (0x00bc1, 0x00bc2,), # Tamil Vowel Sign U ..Tamil Vowel Sign Uu + (0x00bc6, 0x00bc8,), # Tamil Vowel Sign E ..Tamil Vowel Sign Ai + (0x00bca, 0x00bcc,), # Tamil Vowel Sign O ..Tamil Vowel Sign Au + (0x00c01, 0x00c03,), # Telugu Sign Candrabindu ..Telugu Sign Visarga + (0x00c41, 0x00c44,), # Telugu Vowel Sign U ..Telugu Vowel Sign Vocali + (0x00c82, 0x00c83,), # Kannada Sign Anusvara ..Kannada Sign Visarga + (0x00cbe, 0x00cbe,), # Kannada Vowel Sign Aa + (0x00cc1, 0x00cc1,), # Kannada Vowel Sign U + (0x00cc3, 0x00cc4,), # Kannada Vowel Sign Vocal..Kannada Vowel Sign Vocal + (0x00cf3, 0x00cf3,), # Kannada Sign Combining Anusvara Above Right + (0x00d02, 0x00d03,), # Malayalam Sign Anusvara ..Malayalam Sign Visarga + (0x00d3f, 0x00d40,), # Malayalam Vowel Sign I ..Malayalam Vowel Sign Ii + (0x00d46, 0x00d48,), # Malayalam Vowel Sign E ..Malayalam Vowel Sign Ai + (0x00d4a, 0x00d4c,), # Malayalam Vowel Sign O ..Malayalam Vowel Sign Au + (0x00d82, 0x00d83,), # Sinhala Sign Anusvaraya ..Sinhala Sign Visargaya + (0x00dd0, 0x00dd1,), # Sinhala Vowel Sign Ketti..Sinhala Vowel Sign Diga + (0x00dd8, 0x00dde,), # Sinhala Vowel Sign Gaett..Sinhala Vowel Sign Kombu + (0x00df2, 0x00df3,), # Sinhala Vowel Sign Diga ..Sinhala Vowel Sign Diga + (0x00e33, 0x00e33,), # Thai Character Sara Am + (0x00eb3, 0x00eb3,), # Lao Vowel Sign Am + (0x00f3e, 0x00f3f,), # Tibetan Sign Yar Tshes ..Tibetan Sign Mar Tshes + (0x00f7f, 0x00f7f,), # Tibetan Sign Rnam Bcad + (0x01031, 0x01031,), # Myanmar Vowel Sign E + (0x0103b, 0x0103c,), # Myanmar Consonant Sign M..Myanmar Consonant Sign M + (0x01056, 0x01057,), # Myanmar Vowel Sign Vocal..Myanmar Vowel Sign Vocal + (0x01084, 0x01084,), # Myanmar Vowel Sign Shan E + (0x017b6, 0x017b6,), # Khmer Vowel Sign Aa + (0x017be, 0x017c5,), # Khmer Vowel Sign Oe ..Khmer Vowel Sign Au + (0x017c7, 0x017c8,), # Khmer Sign Reahmuk ..Khmer Sign Yuukaleapintu + (0x01923, 0x01926,), # Limbu Vowel Sign Ee ..Limbu Vowel Sign Au + (0x01929, 0x0192b,), # Limbu Subjoined Letter Y..Limbu Subjoined Letter W + (0x01930, 0x01931,), # Limbu Small Letter Ka ..Limbu Small Letter Nga + (0x01933, 0x01938,), # Limbu Small Letter Ta ..Limbu Small Letter La + (0x01a19, 0x01a1a,), # Buginese Vowel Sign E ..Buginese Vowel Sign O + (0x01a55, 0x01a55,), # Tai Tham Consonant Sign Medial Ra + (0x01a57, 0x01a57,), # Tai Tham Consonant Sign La Tang Lai + (0x01a6d, 0x01a72,), # Tai Tham Vowel Sign Oy ..Tai Tham Vowel Sign Tham + (0x01b04, 0x01b04,), # Balinese Sign Bisah + (0x01b3e, 0x01b41,), # Balinese Vowel Sign Tali..Balinese Vowel Sign Tali + (0x01b82, 0x01b82,), # Sundanese Sign Pangwisad + (0x01ba1, 0x01ba1,), # Sundanese Consonant Sign Pamingkal + (0x01ba6, 0x01ba7,), # Sundanese Vowel Sign Pan..Sundanese Vowel Sign Pan + (0x01be7, 0x01be7,), # Batak Vowel Sign E + (0x01bea, 0x01bec,), # Batak Vowel Sign I ..Batak Vowel Sign O + (0x01bee, 0x01bee,), # Batak Vowel Sign U + (0x01c24, 0x01c2b,), # Lepcha Subjoined Letter ..Lepcha Vowel Sign Uu + (0x01c34, 0x01c35,), # Lepcha Consonant Sign Ny..Lepcha Consonant Sign Ka + (0x01ce1, 0x01ce1,), # Vedic Tone Atharvavedic Independent Svarita + (0x01cf7, 0x01cf7,), # Vedic Sign Atikrama + (0x0a823, 0x0a824,), # Syloti Nagri Vowel Sign ..Syloti Nagri Vowel Sign + (0x0a827, 0x0a827,), # Syloti Nagri Vowel Sign Oo + (0x0a880, 0x0a881,), # Saurashtra Sign Anusvara..Saurashtra Sign Visarga + (0x0a8b4, 0x0a8c3,), # Saurashtra Consonant Sig..Saurashtra Vowel Sign Au + (0x0a952, 0x0a952,), # Rejang Consonant Sign H + (0x0a983, 0x0a983,), # Javanese Sign Wignyan + (0x0a9b4, 0x0a9b5,), # Javanese Vowel Sign Taru..Javanese Vowel Sign Tolo + (0x0a9ba, 0x0a9bb,), # Javanese Vowel Sign Tali..Javanese Vowel Sign Dirg + (0x0a9be, 0x0a9bf,), # Javanese Consonant Sign ..Javanese Consonant Sign + (0x0aa2f, 0x0aa30,), # Cham Vowel Sign O ..Cham Vowel Sign Ai + (0x0aa33, 0x0aa34,), # Cham Consonant Sign Ya ..Cham Consonant Sign Ra + (0x0aa4d, 0x0aa4d,), # Cham Consonant Sign Final H + (0x0aaeb, 0x0aaeb,), # Meetei Mayek Vowel Sign Ii + (0x0aaee, 0x0aaef,), # Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + (0x0aaf5, 0x0aaf5,), # Meetei Mayek Vowel Sign Visarga + (0x0abe3, 0x0abe4,), # Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + (0x0abe6, 0x0abe7,), # Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + (0x0abe9, 0x0abea,), # Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + (0x0abec, 0x0abec,), # Meetei Mayek Lum Iyek + (0x11000, 0x11000,), # Brahmi Sign Candrabindu + (0x11002, 0x11002,), # Brahmi Sign Visarga + (0x11082, 0x11082,), # Kaithi Sign Visarga + (0x110b0, 0x110b2,), # Kaithi Vowel Sign Aa ..Kaithi Vowel Sign Ii + (0x110b7, 0x110b8,), # Kaithi Vowel Sign O ..Kaithi Vowel Sign Au + (0x1112c, 0x1112c,), # Chakma Vowel Sign E + (0x11145, 0x11146,), # Chakma Vowel Sign Aa ..Chakma Vowel Sign Ei + (0x11182, 0x11182,), # Sharada Sign Visarga + (0x111b3, 0x111b5,), # Sharada Vowel Sign Aa ..Sharada Vowel Sign Ii + (0x111bf, 0x111bf,), # Sharada Vowel Sign Au + (0x111ce, 0x111ce,), # Sharada Vowel Sign Prishthamatra E + (0x1122c, 0x1122e,), # Khojki Vowel Sign Aa ..Khojki Vowel Sign Ii + (0x11232, 0x11233,), # Khojki Vowel Sign O ..Khojki Vowel Sign Au + (0x112e0, 0x112e2,), # Khudawadi Vowel Sign Aa ..Khudawadi Vowel Sign Ii + (0x11302, 0x11303,), # Grantha Sign Anusvara ..Grantha Sign Visarga + (0x1133f, 0x1133f,), # Grantha Vowel Sign I + (0x11341, 0x11344,), # Grantha Vowel Sign U ..Grantha Vowel Sign Vocal + (0x11347, 0x11348,), # Grantha Vowel Sign Ee ..Grantha Vowel Sign Ai + (0x1134b, 0x1134c,), # Grantha Vowel Sign Oo ..Grantha Vowel Sign Au + (0x11362, 0x11363,), # Grantha Vowel Sign Vocal..Grantha Vowel Sign Vocal + (0x113b9, 0x113ba,), # Tulu-tigalari Vowel Sign..Tulu-tigalari Vowel Sign + (0x113ca, 0x113ca,), # Tulu-tigalari Sign Candra Anunasika + (0x113cc, 0x113cd,), # Tulu-tigalari Sign Anusv..Tulu-tigalari Sign Visar + (0x11435, 0x11437,), # Newa Vowel Sign Aa ..Newa Vowel Sign Ii + (0x11440, 0x11441,), # Newa Vowel Sign O ..Newa Vowel Sign Au + (0x11445, 0x11445,), # Newa Sign Visarga + (0x114b1, 0x114b2,), # Tirhuta Vowel Sign I ..Tirhuta Vowel Sign Ii + (0x114b9, 0x114b9,), # Tirhuta Vowel Sign E + (0x114bb, 0x114bc,), # Tirhuta Vowel Sign Ai ..Tirhuta Vowel Sign O + (0x114be, 0x114be,), # Tirhuta Vowel Sign Au + (0x114c1, 0x114c1,), # Tirhuta Sign Visarga + (0x115b0, 0x115b1,), # Siddham Vowel Sign I ..Siddham Vowel Sign Ii + (0x115b8, 0x115bb,), # Siddham Vowel Sign E ..Siddham Vowel Sign Au + (0x115be, 0x115be,), # Siddham Sign Visarga + (0x11630, 0x11632,), # Modi Vowel Sign Aa ..Modi Vowel Sign Ii + (0x1163b, 0x1163c,), # Modi Vowel Sign O ..Modi Vowel Sign Au + (0x1163e, 0x1163e,), # Modi Sign Visarga + (0x116ac, 0x116ac,), # Takri Sign Visarga + (0x116ae, 0x116af,), # Takri Vowel Sign I ..Takri Vowel Sign Ii + (0x1171e, 0x1171e,), # Ahom Consonant Sign Medial Ra + (0x11726, 0x11726,), # Ahom Vowel Sign E + (0x1182c, 0x1182e,), # Dogra Vowel Sign Aa ..Dogra Vowel Sign Ii + (0x11838, 0x11838,), # Dogra Sign Visarga + (0x11931, 0x11935,), # Dives Akuru Vowel Sign I..Dives Akuru Vowel Sign E + (0x11937, 0x11938,), # Dives Akuru Vowel Sign A..Dives Akuru Vowel Sign O + (0x11940, 0x11940,), # Dives Akuru Medial Ya + (0x11942, 0x11942,), # Dives Akuru Medial Ra + (0x119d1, 0x119d3,), # Nandinagari Vowel Sign A..Nandinagari Vowel Sign I + (0x119dc, 0x119df,), # Nandinagari Vowel Sign O..Nandinagari Sign Visarga + (0x119e4, 0x119e4,), # Nandinagari Vowel Sign Prishthamatra E + (0x11a39, 0x11a39,), # Zanabazar Square Sign Visarga + (0x11a57, 0x11a58,), # Soyombo Vowel Sign Ai ..Soyombo Vowel Sign Au + (0x11a97, 0x11a97,), # Soyombo Sign Visarga + (0x11b61, 0x11b61,), # Sharada Vowel Sign Ooe + (0x11b65, 0x11b65,), # Sharada Vowel Sign Short O + (0x11b67, 0x11b67,), # Sharada Vowel Sign Candra O + (0x11c2f, 0x11c2f,), # Bhaiksuki Vowel Sign Aa + (0x11c3e, 0x11c3e,), # Bhaiksuki Sign Visarga + (0x11ca9, 0x11ca9,), # Marchen Subjoined Letter Ya + (0x11cb1, 0x11cb1,), # Marchen Vowel Sign I + (0x11cb4, 0x11cb4,), # Marchen Vowel Sign O + (0x11d8a, 0x11d8e,), # Gunjala Gondi Vowel Sign..Gunjala Gondi Vowel Sign + (0x11d93, 0x11d94,), # Gunjala Gondi Vowel Sign..Gunjala Gondi Vowel Sign + (0x11d96, 0x11d96,), # Gunjala Gondi Sign Visarga + (0x11ef5, 0x11ef6,), # Makasar Vowel Sign E ..Makasar Vowel Sign O + (0x11f03, 0x11f03,), # Kawi Sign Visarga + (0x11f34, 0x11f35,), # Kawi Vowel Sign Aa ..Kawi Vowel Sign Alternat + (0x11f3e, 0x11f3f,), # Kawi Vowel Sign E ..Kawi Vowel Sign Ai + (0x1612a, 0x1612c,), # Gurung Khema Consonant S..Gurung Khema Consonant S + (0x16f51, 0x16f87,), # Miao Sign Aspiration ..Miao Vowel Sign Ui +) + +GRAPHEME_L = ( + # Source: GraphemeBreakProperty-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x01100, 0x0115f,), # Hangul Choseong Kiyeok ..Hangul Choseong Filler + (0x0a960, 0x0a97c,), # Hangul Choseong Tikeut-m..Hangul Choseong Ssangyeo +) + +GRAPHEME_V = ( + # Source: GraphemeBreakProperty-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x01160, 0x011a7,), # Hangul Jungseong Filler ..Hangul Jungseong O-yae + (0x0d7b0, 0x0d7c6,), # Hangul Jungseong O-yeo ..Hangul Jungseong Araea-e + (0x16d63, 0x16d63,), # Kirat Rai Vowel Sign Aa + (0x16d67, 0x16d6a,), # Kirat Rai Vowel Sign E ..Kirat Rai Vowel Sign Au +) + +GRAPHEME_T = ( + # Source: GraphemeBreakProperty-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x011a8, 0x011ff,), # Hangul Jongseong Kiyeok ..Hangul Jongseong Ssangni + (0x0d7cb, 0x0d7fb,), # Hangul Jongseong Nieun-r..Hangul Jongseong Phieuph +) + +GRAPHEME_LV = ( + # Source: GraphemeBreakProperty-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x0ac00, 0x0ac00,), # Hangul Syllable Ga + (0x0ac1c, 0x0ac1c,), # Hangul Syllable Gae + (0x0ac38, 0x0ac38,), # Hangul Syllable Gya + (0x0ac54, 0x0ac54,), # Hangul Syllable Gyae + (0x0ac70, 0x0ac70,), # Hangul Syllable Geo + (0x0ac8c, 0x0ac8c,), # Hangul Syllable Ge + (0x0aca8, 0x0aca8,), # Hangul Syllable Gyeo + (0x0acc4, 0x0acc4,), # Hangul Syllable Gye + (0x0ace0, 0x0ace0,), # Hangul Syllable Go + (0x0acfc, 0x0acfc,), # Hangul Syllable Gwa + (0x0ad18, 0x0ad18,), # Hangul Syllable Gwae + (0x0ad34, 0x0ad34,), # Hangul Syllable Goe + (0x0ad50, 0x0ad50,), # Hangul Syllable Gyo + (0x0ad6c, 0x0ad6c,), # Hangul Syllable Gu + (0x0ad88, 0x0ad88,), # Hangul Syllable Gweo + (0x0ada4, 0x0ada4,), # Hangul Syllable Gwe + (0x0adc0, 0x0adc0,), # Hangul Syllable Gwi + (0x0addc, 0x0addc,), # Hangul Syllable Gyu + (0x0adf8, 0x0adf8,), # Hangul Syllable Geu + (0x0ae14, 0x0ae14,), # Hangul Syllable Gyi + (0x0ae30, 0x0ae30,), # Hangul Syllable Gi + (0x0ae4c, 0x0ae4c,), # Hangul Syllable Gga + (0x0ae68, 0x0ae68,), # Hangul Syllable Ggae + (0x0ae84, 0x0ae84,), # Hangul Syllable Ggya + (0x0aea0, 0x0aea0,), # Hangul Syllable Ggyae + (0x0aebc, 0x0aebc,), # Hangul Syllable Ggeo + (0x0aed8, 0x0aed8,), # Hangul Syllable Gge + (0x0aef4, 0x0aef4,), # Hangul Syllable Ggyeo + (0x0af10, 0x0af10,), # Hangul Syllable Ggye + (0x0af2c, 0x0af2c,), # Hangul Syllable Ggo + (0x0af48, 0x0af48,), # Hangul Syllable Ggwa + (0x0af64, 0x0af64,), # Hangul Syllable Ggwae + (0x0af80, 0x0af80,), # Hangul Syllable Ggoe + (0x0af9c, 0x0af9c,), # Hangul Syllable Ggyo + (0x0afb8, 0x0afb8,), # Hangul Syllable Ggu + (0x0afd4, 0x0afd4,), # Hangul Syllable Ggweo + (0x0aff0, 0x0aff0,), # Hangul Syllable Ggwe + (0x0b00c, 0x0b00c,), # Hangul Syllable Ggwi + (0x0b028, 0x0b028,), # Hangul Syllable Ggyu + (0x0b044, 0x0b044,), # Hangul Syllable Ggeu + (0x0b060, 0x0b060,), # Hangul Syllable Ggyi + (0x0b07c, 0x0b07c,), # Hangul Syllable Ggi + (0x0b098, 0x0b098,), # Hangul Syllable Na + (0x0b0b4, 0x0b0b4,), # Hangul Syllable Nae + (0x0b0d0, 0x0b0d0,), # Hangul Syllable Nya + (0x0b0ec, 0x0b0ec,), # Hangul Syllable Nyae + (0x0b108, 0x0b108,), # Hangul Syllable Neo + (0x0b124, 0x0b124,), # Hangul Syllable Ne + (0x0b140, 0x0b140,), # Hangul Syllable Nyeo + (0x0b15c, 0x0b15c,), # Hangul Syllable Nye + (0x0b178, 0x0b178,), # Hangul Syllable No + (0x0b194, 0x0b194,), # Hangul Syllable Nwa + (0x0b1b0, 0x0b1b0,), # Hangul Syllable Nwae + (0x0b1cc, 0x0b1cc,), # Hangul Syllable Noe + (0x0b1e8, 0x0b1e8,), # Hangul Syllable Nyo + (0x0b204, 0x0b204,), # Hangul Syllable Nu + (0x0b220, 0x0b220,), # Hangul Syllable Nweo + (0x0b23c, 0x0b23c,), # Hangul Syllable Nwe + (0x0b258, 0x0b258,), # Hangul Syllable Nwi + (0x0b274, 0x0b274,), # Hangul Syllable Nyu + (0x0b290, 0x0b290,), # Hangul Syllable Neu + (0x0b2ac, 0x0b2ac,), # Hangul Syllable Nyi + (0x0b2c8, 0x0b2c8,), # Hangul Syllable Ni + (0x0b2e4, 0x0b2e4,), # Hangul Syllable Da + (0x0b300, 0x0b300,), # Hangul Syllable Dae + (0x0b31c, 0x0b31c,), # Hangul Syllable Dya + (0x0b338, 0x0b338,), # Hangul Syllable Dyae + (0x0b354, 0x0b354,), # Hangul Syllable Deo + (0x0b370, 0x0b370,), # Hangul Syllable De + (0x0b38c, 0x0b38c,), # Hangul Syllable Dyeo + (0x0b3a8, 0x0b3a8,), # Hangul Syllable Dye + (0x0b3c4, 0x0b3c4,), # Hangul Syllable Do + (0x0b3e0, 0x0b3e0,), # Hangul Syllable Dwa + (0x0b3fc, 0x0b3fc,), # Hangul Syllable Dwae + (0x0b418, 0x0b418,), # Hangul Syllable Doe + (0x0b434, 0x0b434,), # Hangul Syllable Dyo + (0x0b450, 0x0b450,), # Hangul Syllable Du + (0x0b46c, 0x0b46c,), # Hangul Syllable Dweo + (0x0b488, 0x0b488,), # Hangul Syllable Dwe + (0x0b4a4, 0x0b4a4,), # Hangul Syllable Dwi + (0x0b4c0, 0x0b4c0,), # Hangul Syllable Dyu + (0x0b4dc, 0x0b4dc,), # Hangul Syllable Deu + (0x0b4f8, 0x0b4f8,), # Hangul Syllable Dyi + (0x0b514, 0x0b514,), # Hangul Syllable Di + (0x0b530, 0x0b530,), # Hangul Syllable Dda + (0x0b54c, 0x0b54c,), # Hangul Syllable Ddae + (0x0b568, 0x0b568,), # Hangul Syllable Ddya + (0x0b584, 0x0b584,), # Hangul Syllable Ddyae + (0x0b5a0, 0x0b5a0,), # Hangul Syllable Ddeo + (0x0b5bc, 0x0b5bc,), # Hangul Syllable Dde + (0x0b5d8, 0x0b5d8,), # Hangul Syllable Ddyeo + (0x0b5f4, 0x0b5f4,), # Hangul Syllable Ddye + (0x0b610, 0x0b610,), # Hangul Syllable Ddo + (0x0b62c, 0x0b62c,), # Hangul Syllable Ddwa + (0x0b648, 0x0b648,), # Hangul Syllable Ddwae + (0x0b664, 0x0b664,), # Hangul Syllable Ddoe + (0x0b680, 0x0b680,), # Hangul Syllable Ddyo + (0x0b69c, 0x0b69c,), # Hangul Syllable Ddu + (0x0b6b8, 0x0b6b8,), # Hangul Syllable Ddweo + (0x0b6d4, 0x0b6d4,), # Hangul Syllable Ddwe + (0x0b6f0, 0x0b6f0,), # Hangul Syllable Ddwi + (0x0b70c, 0x0b70c,), # Hangul Syllable Ddyu + (0x0b728, 0x0b728,), # Hangul Syllable Ddeu + (0x0b744, 0x0b744,), # Hangul Syllable Ddyi + (0x0b760, 0x0b760,), # Hangul Syllable Ddi + (0x0b77c, 0x0b77c,), # Hangul Syllable Ra + (0x0b798, 0x0b798,), # Hangul Syllable Rae + (0x0b7b4, 0x0b7b4,), # Hangul Syllable Rya + (0x0b7d0, 0x0b7d0,), # Hangul Syllable Ryae + (0x0b7ec, 0x0b7ec,), # Hangul Syllable Reo + (0x0b808, 0x0b808,), # Hangul Syllable Re + (0x0b824, 0x0b824,), # Hangul Syllable Ryeo + (0x0b840, 0x0b840,), # Hangul Syllable Rye + (0x0b85c, 0x0b85c,), # Hangul Syllable Ro + (0x0b878, 0x0b878,), # Hangul Syllable Rwa + (0x0b894, 0x0b894,), # Hangul Syllable Rwae + (0x0b8b0, 0x0b8b0,), # Hangul Syllable Roe + (0x0b8cc, 0x0b8cc,), # Hangul Syllable Ryo + (0x0b8e8, 0x0b8e8,), # Hangul Syllable Ru + (0x0b904, 0x0b904,), # Hangul Syllable Rweo + (0x0b920, 0x0b920,), # Hangul Syllable Rwe + (0x0b93c, 0x0b93c,), # Hangul Syllable Rwi + (0x0b958, 0x0b958,), # Hangul Syllable Ryu + (0x0b974, 0x0b974,), # Hangul Syllable Reu + (0x0b990, 0x0b990,), # Hangul Syllable Ryi + (0x0b9ac, 0x0b9ac,), # Hangul Syllable Ri + (0x0b9c8, 0x0b9c8,), # Hangul Syllable Ma + (0x0b9e4, 0x0b9e4,), # Hangul Syllable Mae + (0x0ba00, 0x0ba00,), # Hangul Syllable Mya + (0x0ba1c, 0x0ba1c,), # Hangul Syllable Myae + (0x0ba38, 0x0ba38,), # Hangul Syllable Meo + (0x0ba54, 0x0ba54,), # Hangul Syllable Me + (0x0ba70, 0x0ba70,), # Hangul Syllable Myeo + (0x0ba8c, 0x0ba8c,), # Hangul Syllable Mye + (0x0baa8, 0x0baa8,), # Hangul Syllable Mo + (0x0bac4, 0x0bac4,), # Hangul Syllable Mwa + (0x0bae0, 0x0bae0,), # Hangul Syllable Mwae + (0x0bafc, 0x0bafc,), # Hangul Syllable Moe + (0x0bb18, 0x0bb18,), # Hangul Syllable Myo + (0x0bb34, 0x0bb34,), # Hangul Syllable Mu + (0x0bb50, 0x0bb50,), # Hangul Syllable Mweo + (0x0bb6c, 0x0bb6c,), # Hangul Syllable Mwe + (0x0bb88, 0x0bb88,), # Hangul Syllable Mwi + (0x0bba4, 0x0bba4,), # Hangul Syllable Myu + (0x0bbc0, 0x0bbc0,), # Hangul Syllable Meu + (0x0bbdc, 0x0bbdc,), # Hangul Syllable Myi + (0x0bbf8, 0x0bbf8,), # Hangul Syllable Mi + (0x0bc14, 0x0bc14,), # Hangul Syllable Ba + (0x0bc30, 0x0bc30,), # Hangul Syllable Bae + (0x0bc4c, 0x0bc4c,), # Hangul Syllable Bya + (0x0bc68, 0x0bc68,), # Hangul Syllable Byae + (0x0bc84, 0x0bc84,), # Hangul Syllable Beo + (0x0bca0, 0x0bca0,), # Hangul Syllable Be + (0x0bcbc, 0x0bcbc,), # Hangul Syllable Byeo + (0x0bcd8, 0x0bcd8,), # Hangul Syllable Bye + (0x0bcf4, 0x0bcf4,), # Hangul Syllable Bo + (0x0bd10, 0x0bd10,), # Hangul Syllable Bwa + (0x0bd2c, 0x0bd2c,), # Hangul Syllable Bwae + (0x0bd48, 0x0bd48,), # Hangul Syllable Boe + (0x0bd64, 0x0bd64,), # Hangul Syllable Byo + (0x0bd80, 0x0bd80,), # Hangul Syllable Bu + (0x0bd9c, 0x0bd9c,), # Hangul Syllable Bweo + (0x0bdb8, 0x0bdb8,), # Hangul Syllable Bwe + (0x0bdd4, 0x0bdd4,), # Hangul Syllable Bwi + (0x0bdf0, 0x0bdf0,), # Hangul Syllable Byu + (0x0be0c, 0x0be0c,), # Hangul Syllable Beu + (0x0be28, 0x0be28,), # Hangul Syllable Byi + (0x0be44, 0x0be44,), # Hangul Syllable Bi + (0x0be60, 0x0be60,), # Hangul Syllable Bba + (0x0be7c, 0x0be7c,), # Hangul Syllable Bbae + (0x0be98, 0x0be98,), # Hangul Syllable Bbya + (0x0beb4, 0x0beb4,), # Hangul Syllable Bbyae + (0x0bed0, 0x0bed0,), # Hangul Syllable Bbeo + (0x0beec, 0x0beec,), # Hangul Syllable Bbe + (0x0bf08, 0x0bf08,), # Hangul Syllable Bbyeo + (0x0bf24, 0x0bf24,), # Hangul Syllable Bbye + (0x0bf40, 0x0bf40,), # Hangul Syllable Bbo + (0x0bf5c, 0x0bf5c,), # Hangul Syllable Bbwa + (0x0bf78, 0x0bf78,), # Hangul Syllable Bbwae + (0x0bf94, 0x0bf94,), # Hangul Syllable Bboe + (0x0bfb0, 0x0bfb0,), # Hangul Syllable Bbyo + (0x0bfcc, 0x0bfcc,), # Hangul Syllable Bbu + (0x0bfe8, 0x0bfe8,), # Hangul Syllable Bbweo + (0x0c004, 0x0c004,), # Hangul Syllable Bbwe + (0x0c020, 0x0c020,), # Hangul Syllable Bbwi + (0x0c03c, 0x0c03c,), # Hangul Syllable Bbyu + (0x0c058, 0x0c058,), # Hangul Syllable Bbeu + (0x0c074, 0x0c074,), # Hangul Syllable Bbyi + (0x0c090, 0x0c090,), # Hangul Syllable Bbi + (0x0c0ac, 0x0c0ac,), # Hangul Syllable Sa + (0x0c0c8, 0x0c0c8,), # Hangul Syllable Sae + (0x0c0e4, 0x0c0e4,), # Hangul Syllable Sya + (0x0c100, 0x0c100,), # Hangul Syllable Syae + (0x0c11c, 0x0c11c,), # Hangul Syllable Seo + (0x0c138, 0x0c138,), # Hangul Syllable Se + (0x0c154, 0x0c154,), # Hangul Syllable Syeo + (0x0c170, 0x0c170,), # Hangul Syllable Sye + (0x0c18c, 0x0c18c,), # Hangul Syllable So + (0x0c1a8, 0x0c1a8,), # Hangul Syllable Swa + (0x0c1c4, 0x0c1c4,), # Hangul Syllable Swae + (0x0c1e0, 0x0c1e0,), # Hangul Syllable Soe + (0x0c1fc, 0x0c1fc,), # Hangul Syllable Syo + (0x0c218, 0x0c218,), # Hangul Syllable Su + (0x0c234, 0x0c234,), # Hangul Syllable Sweo + (0x0c250, 0x0c250,), # Hangul Syllable Swe + (0x0c26c, 0x0c26c,), # Hangul Syllable Swi + (0x0c288, 0x0c288,), # Hangul Syllable Syu + (0x0c2a4, 0x0c2a4,), # Hangul Syllable Seu + (0x0c2c0, 0x0c2c0,), # Hangul Syllable Syi + (0x0c2dc, 0x0c2dc,), # Hangul Syllable Si + (0x0c2f8, 0x0c2f8,), # Hangul Syllable Ssa + (0x0c314, 0x0c314,), # Hangul Syllable Ssae + (0x0c330, 0x0c330,), # Hangul Syllable Ssya + (0x0c34c, 0x0c34c,), # Hangul Syllable Ssyae + (0x0c368, 0x0c368,), # Hangul Syllable Sseo + (0x0c384, 0x0c384,), # Hangul Syllable Sse + (0x0c3a0, 0x0c3a0,), # Hangul Syllable Ssyeo + (0x0c3bc, 0x0c3bc,), # Hangul Syllable Ssye + (0x0c3d8, 0x0c3d8,), # Hangul Syllable Sso + (0x0c3f4, 0x0c3f4,), # Hangul Syllable Sswa + (0x0c410, 0x0c410,), # Hangul Syllable Sswae + (0x0c42c, 0x0c42c,), # Hangul Syllable Ssoe + (0x0c448, 0x0c448,), # Hangul Syllable Ssyo + (0x0c464, 0x0c464,), # Hangul Syllable Ssu + (0x0c480, 0x0c480,), # Hangul Syllable Ssweo + (0x0c49c, 0x0c49c,), # Hangul Syllable Sswe + (0x0c4b8, 0x0c4b8,), # Hangul Syllable Sswi + (0x0c4d4, 0x0c4d4,), # Hangul Syllable Ssyu + (0x0c4f0, 0x0c4f0,), # Hangul Syllable Sseu + (0x0c50c, 0x0c50c,), # Hangul Syllable Ssyi + (0x0c528, 0x0c528,), # Hangul Syllable Ssi + (0x0c544, 0x0c544,), # Hangul Syllable A + (0x0c560, 0x0c560,), # Hangul Syllable Ae + (0x0c57c, 0x0c57c,), # Hangul Syllable Ya + (0x0c598, 0x0c598,), # Hangul Syllable Yae + (0x0c5b4, 0x0c5b4,), # Hangul Syllable Eo + (0x0c5d0, 0x0c5d0,), # Hangul Syllable E + (0x0c5ec, 0x0c5ec,), # Hangul Syllable Yeo + (0x0c608, 0x0c608,), # Hangul Syllable Ye + (0x0c624, 0x0c624,), # Hangul Syllable O + (0x0c640, 0x0c640,), # Hangul Syllable Wa + (0x0c65c, 0x0c65c,), # Hangul Syllable Wae + (0x0c678, 0x0c678,), # Hangul Syllable Oe + (0x0c694, 0x0c694,), # Hangul Syllable Yo + (0x0c6b0, 0x0c6b0,), # Hangul Syllable U + (0x0c6cc, 0x0c6cc,), # Hangul Syllable Weo + (0x0c6e8, 0x0c6e8,), # Hangul Syllable We + (0x0c704, 0x0c704,), # Hangul Syllable Wi + (0x0c720, 0x0c720,), # Hangul Syllable Yu + (0x0c73c, 0x0c73c,), # Hangul Syllable Eu + (0x0c758, 0x0c758,), # Hangul Syllable Yi + (0x0c774, 0x0c774,), # Hangul Syllable I + (0x0c790, 0x0c790,), # Hangul Syllable Ja + (0x0c7ac, 0x0c7ac,), # Hangul Syllable Jae + (0x0c7c8, 0x0c7c8,), # Hangul Syllable Jya + (0x0c7e4, 0x0c7e4,), # Hangul Syllable Jyae + (0x0c800, 0x0c800,), # Hangul Syllable Jeo + (0x0c81c, 0x0c81c,), # Hangul Syllable Je + (0x0c838, 0x0c838,), # Hangul Syllable Jyeo + (0x0c854, 0x0c854,), # Hangul Syllable Jye + (0x0c870, 0x0c870,), # Hangul Syllable Jo + (0x0c88c, 0x0c88c,), # Hangul Syllable Jwa + (0x0c8a8, 0x0c8a8,), # Hangul Syllable Jwae + (0x0c8c4, 0x0c8c4,), # Hangul Syllable Joe + (0x0c8e0, 0x0c8e0,), # Hangul Syllable Jyo + (0x0c8fc, 0x0c8fc,), # Hangul Syllable Ju + (0x0c918, 0x0c918,), # Hangul Syllable Jweo + (0x0c934, 0x0c934,), # Hangul Syllable Jwe + (0x0c950, 0x0c950,), # Hangul Syllable Jwi + (0x0c96c, 0x0c96c,), # Hangul Syllable Jyu + (0x0c988, 0x0c988,), # Hangul Syllable Jeu + (0x0c9a4, 0x0c9a4,), # Hangul Syllable Jyi + (0x0c9c0, 0x0c9c0,), # Hangul Syllable Ji + (0x0c9dc, 0x0c9dc,), # Hangul Syllable Jja + (0x0c9f8, 0x0c9f8,), # Hangul Syllable Jjae + (0x0ca14, 0x0ca14,), # Hangul Syllable Jjya + (0x0ca30, 0x0ca30,), # Hangul Syllable Jjyae + (0x0ca4c, 0x0ca4c,), # Hangul Syllable Jjeo + (0x0ca68, 0x0ca68,), # Hangul Syllable Jje + (0x0ca84, 0x0ca84,), # Hangul Syllable Jjyeo + (0x0caa0, 0x0caa0,), # Hangul Syllable Jjye + (0x0cabc, 0x0cabc,), # Hangul Syllable Jjo + (0x0cad8, 0x0cad8,), # Hangul Syllable Jjwa + (0x0caf4, 0x0caf4,), # Hangul Syllable Jjwae + (0x0cb10, 0x0cb10,), # Hangul Syllable Jjoe + (0x0cb2c, 0x0cb2c,), # Hangul Syllable Jjyo + (0x0cb48, 0x0cb48,), # Hangul Syllable Jju + (0x0cb64, 0x0cb64,), # Hangul Syllable Jjweo + (0x0cb80, 0x0cb80,), # Hangul Syllable Jjwe + (0x0cb9c, 0x0cb9c,), # Hangul Syllable Jjwi + (0x0cbb8, 0x0cbb8,), # Hangul Syllable Jjyu + (0x0cbd4, 0x0cbd4,), # Hangul Syllable Jjeu + (0x0cbf0, 0x0cbf0,), # Hangul Syllable Jjyi + (0x0cc0c, 0x0cc0c,), # Hangul Syllable Jji + (0x0cc28, 0x0cc28,), # Hangul Syllable Ca + (0x0cc44, 0x0cc44,), # Hangul Syllable Cae + (0x0cc60, 0x0cc60,), # Hangul Syllable Cya + (0x0cc7c, 0x0cc7c,), # Hangul Syllable Cyae + (0x0cc98, 0x0cc98,), # Hangul Syllable Ceo + (0x0ccb4, 0x0ccb4,), # Hangul Syllable Ce + (0x0ccd0, 0x0ccd0,), # Hangul Syllable Cyeo + (0x0ccec, 0x0ccec,), # Hangul Syllable Cye + (0x0cd08, 0x0cd08,), # Hangul Syllable Co + (0x0cd24, 0x0cd24,), # Hangul Syllable Cwa + (0x0cd40, 0x0cd40,), # Hangul Syllable Cwae + (0x0cd5c, 0x0cd5c,), # Hangul Syllable Coe + (0x0cd78, 0x0cd78,), # Hangul Syllable Cyo + (0x0cd94, 0x0cd94,), # Hangul Syllable Cu + (0x0cdb0, 0x0cdb0,), # Hangul Syllable Cweo + (0x0cdcc, 0x0cdcc,), # Hangul Syllable Cwe + (0x0cde8, 0x0cde8,), # Hangul Syllable Cwi + (0x0ce04, 0x0ce04,), # Hangul Syllable Cyu + (0x0ce20, 0x0ce20,), # Hangul Syllable Ceu + (0x0ce3c, 0x0ce3c,), # Hangul Syllable Cyi + (0x0ce58, 0x0ce58,), # Hangul Syllable Ci + (0x0ce74, 0x0ce74,), # Hangul Syllable Ka + (0x0ce90, 0x0ce90,), # Hangul Syllable Kae + (0x0ceac, 0x0ceac,), # Hangul Syllable Kya + (0x0cec8, 0x0cec8,), # Hangul Syllable Kyae + (0x0cee4, 0x0cee4,), # Hangul Syllable Keo + (0x0cf00, 0x0cf00,), # Hangul Syllable Ke + (0x0cf1c, 0x0cf1c,), # Hangul Syllable Kyeo + (0x0cf38, 0x0cf38,), # Hangul Syllable Kye + (0x0cf54, 0x0cf54,), # Hangul Syllable Ko + (0x0cf70, 0x0cf70,), # Hangul Syllable Kwa + (0x0cf8c, 0x0cf8c,), # Hangul Syllable Kwae + (0x0cfa8, 0x0cfa8,), # Hangul Syllable Koe + (0x0cfc4, 0x0cfc4,), # Hangul Syllable Kyo + (0x0cfe0, 0x0cfe0,), # Hangul Syllable Ku + (0x0cffc, 0x0cffc,), # Hangul Syllable Kweo + (0x0d018, 0x0d018,), # Hangul Syllable Kwe + (0x0d034, 0x0d034,), # Hangul Syllable Kwi + (0x0d050, 0x0d050,), # Hangul Syllable Kyu + (0x0d06c, 0x0d06c,), # Hangul Syllable Keu + (0x0d088, 0x0d088,), # Hangul Syllable Kyi + (0x0d0a4, 0x0d0a4,), # Hangul Syllable Ki + (0x0d0c0, 0x0d0c0,), # Hangul Syllable Ta + (0x0d0dc, 0x0d0dc,), # Hangul Syllable Tae + (0x0d0f8, 0x0d0f8,), # Hangul Syllable Tya + (0x0d114, 0x0d114,), # Hangul Syllable Tyae + (0x0d130, 0x0d130,), # Hangul Syllable Teo + (0x0d14c, 0x0d14c,), # Hangul Syllable Te + (0x0d168, 0x0d168,), # Hangul Syllable Tyeo + (0x0d184, 0x0d184,), # Hangul Syllable Tye + (0x0d1a0, 0x0d1a0,), # Hangul Syllable To + (0x0d1bc, 0x0d1bc,), # Hangul Syllable Twa + (0x0d1d8, 0x0d1d8,), # Hangul Syllable Twae + (0x0d1f4, 0x0d1f4,), # Hangul Syllable Toe + (0x0d210, 0x0d210,), # Hangul Syllable Tyo + (0x0d22c, 0x0d22c,), # Hangul Syllable Tu + (0x0d248, 0x0d248,), # Hangul Syllable Tweo + (0x0d264, 0x0d264,), # Hangul Syllable Twe + (0x0d280, 0x0d280,), # Hangul Syllable Twi + (0x0d29c, 0x0d29c,), # Hangul Syllable Tyu + (0x0d2b8, 0x0d2b8,), # Hangul Syllable Teu + (0x0d2d4, 0x0d2d4,), # Hangul Syllable Tyi + (0x0d2f0, 0x0d2f0,), # Hangul Syllable Ti + (0x0d30c, 0x0d30c,), # Hangul Syllable Pa + (0x0d328, 0x0d328,), # Hangul Syllable Pae + (0x0d344, 0x0d344,), # Hangul Syllable Pya + (0x0d360, 0x0d360,), # Hangul Syllable Pyae + (0x0d37c, 0x0d37c,), # Hangul Syllable Peo + (0x0d398, 0x0d398,), # Hangul Syllable Pe + (0x0d3b4, 0x0d3b4,), # Hangul Syllable Pyeo + (0x0d3d0, 0x0d3d0,), # Hangul Syllable Pye + (0x0d3ec, 0x0d3ec,), # Hangul Syllable Po + (0x0d408, 0x0d408,), # Hangul Syllable Pwa + (0x0d424, 0x0d424,), # Hangul Syllable Pwae + (0x0d440, 0x0d440,), # Hangul Syllable Poe + (0x0d45c, 0x0d45c,), # Hangul Syllable Pyo + (0x0d478, 0x0d478,), # Hangul Syllable Pu + (0x0d494, 0x0d494,), # Hangul Syllable Pweo + (0x0d4b0, 0x0d4b0,), # Hangul Syllable Pwe + (0x0d4cc, 0x0d4cc,), # Hangul Syllable Pwi + (0x0d4e8, 0x0d4e8,), # Hangul Syllable Pyu + (0x0d504, 0x0d504,), # Hangul Syllable Peu + (0x0d520, 0x0d520,), # Hangul Syllable Pyi + (0x0d53c, 0x0d53c,), # Hangul Syllable Pi + (0x0d558, 0x0d558,), # Hangul Syllable Ha + (0x0d574, 0x0d574,), # Hangul Syllable Hae + (0x0d590, 0x0d590,), # Hangul Syllable Hya + (0x0d5ac, 0x0d5ac,), # Hangul Syllable Hyae + (0x0d5c8, 0x0d5c8,), # Hangul Syllable Heo + (0x0d5e4, 0x0d5e4,), # Hangul Syllable He + (0x0d600, 0x0d600,), # Hangul Syllable Hyeo + (0x0d61c, 0x0d61c,), # Hangul Syllable Hye + (0x0d638, 0x0d638,), # Hangul Syllable Ho + (0x0d654, 0x0d654,), # Hangul Syllable Hwa + (0x0d670, 0x0d670,), # Hangul Syllable Hwae + (0x0d68c, 0x0d68c,), # Hangul Syllable Hoe + (0x0d6a8, 0x0d6a8,), # Hangul Syllable Hyo + (0x0d6c4, 0x0d6c4,), # Hangul Syllable Hu + (0x0d6e0, 0x0d6e0,), # Hangul Syllable Hweo + (0x0d6fc, 0x0d6fc,), # Hangul Syllable Hwe + (0x0d718, 0x0d718,), # Hangul Syllable Hwi + (0x0d734, 0x0d734,), # Hangul Syllable Hyu + (0x0d750, 0x0d750,), # Hangul Syllable Heu + (0x0d76c, 0x0d76c,), # Hangul Syllable Hyi + (0x0d788, 0x0d788,), # Hangul Syllable Hi +) + +GRAPHEME_LVT = ( + # Source: GraphemeBreakProperty-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x0ac01, 0x0ac1b,), # Hangul Syllable Gag ..Hangul Syllable Gah + (0x0ac1d, 0x0ac37,), # Hangul Syllable Gaeg ..Hangul Syllable Gaeh + (0x0ac39, 0x0ac53,), # Hangul Syllable Gyag ..Hangul Syllable Gyah + (0x0ac55, 0x0ac6f,), # Hangul Syllable Gyaeg ..Hangul Syllable Gyaeh + (0x0ac71, 0x0ac8b,), # Hangul Syllable Geog ..Hangul Syllable Geoh + (0x0ac8d, 0x0aca7,), # Hangul Syllable Geg ..Hangul Syllable Geh + (0x0aca9, 0x0acc3,), # Hangul Syllable Gyeog ..Hangul Syllable Gyeoh + (0x0acc5, 0x0acdf,), # Hangul Syllable Gyeg ..Hangul Syllable Gyeh + (0x0ace1, 0x0acfb,), # Hangul Syllable Gog ..Hangul Syllable Goh + (0x0acfd, 0x0ad17,), # Hangul Syllable Gwag ..Hangul Syllable Gwah + (0x0ad19, 0x0ad33,), # Hangul Syllable Gwaeg ..Hangul Syllable Gwaeh + (0x0ad35, 0x0ad4f,), # Hangul Syllable Goeg ..Hangul Syllable Goeh + (0x0ad51, 0x0ad6b,), # Hangul Syllable Gyog ..Hangul Syllable Gyoh + (0x0ad6d, 0x0ad87,), # Hangul Syllable Gug ..Hangul Syllable Guh + (0x0ad89, 0x0ada3,), # Hangul Syllable Gweog ..Hangul Syllable Gweoh + (0x0ada5, 0x0adbf,), # Hangul Syllable Gweg ..Hangul Syllable Gweh + (0x0adc1, 0x0addb,), # Hangul Syllable Gwig ..Hangul Syllable Gwih + (0x0addd, 0x0adf7,), # Hangul Syllable Gyug ..Hangul Syllable Gyuh + (0x0adf9, 0x0ae13,), # Hangul Syllable Geug ..Hangul Syllable Geuh + (0x0ae15, 0x0ae2f,), # Hangul Syllable Gyig ..Hangul Syllable Gyih + (0x0ae31, 0x0ae4b,), # Hangul Syllable Gig ..Hangul Syllable Gih + (0x0ae4d, 0x0ae67,), # Hangul Syllable Ggag ..Hangul Syllable Ggah + (0x0ae69, 0x0ae83,), # Hangul Syllable Ggaeg ..Hangul Syllable Ggaeh + (0x0ae85, 0x0ae9f,), # Hangul Syllable Ggyag ..Hangul Syllable Ggyah + (0x0aea1, 0x0aebb,), # Hangul Syllable Ggyaeg ..Hangul Syllable Ggyaeh + (0x0aebd, 0x0aed7,), # Hangul Syllable Ggeog ..Hangul Syllable Ggeoh + (0x0aed9, 0x0aef3,), # Hangul Syllable Ggeg ..Hangul Syllable Ggeh + (0x0aef5, 0x0af0f,), # Hangul Syllable Ggyeog ..Hangul Syllable Ggyeoh + (0x0af11, 0x0af2b,), # Hangul Syllable Ggyeg ..Hangul Syllable Ggyeh + (0x0af2d, 0x0af47,), # Hangul Syllable Ggog ..Hangul Syllable Ggoh + (0x0af49, 0x0af63,), # Hangul Syllable Ggwag ..Hangul Syllable Ggwah + (0x0af65, 0x0af7f,), # Hangul Syllable Ggwaeg ..Hangul Syllable Ggwaeh + (0x0af81, 0x0af9b,), # Hangul Syllable Ggoeg ..Hangul Syllable Ggoeh + (0x0af9d, 0x0afb7,), # Hangul Syllable Ggyog ..Hangul Syllable Ggyoh + (0x0afb9, 0x0afd3,), # Hangul Syllable Ggug ..Hangul Syllable Gguh + (0x0afd5, 0x0afef,), # Hangul Syllable Ggweog ..Hangul Syllable Ggweoh + (0x0aff1, 0x0b00b,), # Hangul Syllable Ggweg ..Hangul Syllable Ggweh + (0x0b00d, 0x0b027,), # Hangul Syllable Ggwig ..Hangul Syllable Ggwih + (0x0b029, 0x0b043,), # Hangul Syllable Ggyug ..Hangul Syllable Ggyuh + (0x0b045, 0x0b05f,), # Hangul Syllable Ggeug ..Hangul Syllable Ggeuh + (0x0b061, 0x0b07b,), # Hangul Syllable Ggyig ..Hangul Syllable Ggyih + (0x0b07d, 0x0b097,), # Hangul Syllable Ggig ..Hangul Syllable Ggih + (0x0b099, 0x0b0b3,), # Hangul Syllable Nag ..Hangul Syllable Nah + (0x0b0b5, 0x0b0cf,), # Hangul Syllable Naeg ..Hangul Syllable Naeh + (0x0b0d1, 0x0b0eb,), # Hangul Syllable Nyag ..Hangul Syllable Nyah + (0x0b0ed, 0x0b107,), # Hangul Syllable Nyaeg ..Hangul Syllable Nyaeh + (0x0b109, 0x0b123,), # Hangul Syllable Neog ..Hangul Syllable Neoh + (0x0b125, 0x0b13f,), # Hangul Syllable Neg ..Hangul Syllable Neh + (0x0b141, 0x0b15b,), # Hangul Syllable Nyeog ..Hangul Syllable Nyeoh + (0x0b15d, 0x0b177,), # Hangul Syllable Nyeg ..Hangul Syllable Nyeh + (0x0b179, 0x0b193,), # Hangul Syllable Nog ..Hangul Syllable Noh + (0x0b195, 0x0b1af,), # Hangul Syllable Nwag ..Hangul Syllable Nwah + (0x0b1b1, 0x0b1cb,), # Hangul Syllable Nwaeg ..Hangul Syllable Nwaeh + (0x0b1cd, 0x0b1e7,), # Hangul Syllable Noeg ..Hangul Syllable Noeh + (0x0b1e9, 0x0b203,), # Hangul Syllable Nyog ..Hangul Syllable Nyoh + (0x0b205, 0x0b21f,), # Hangul Syllable Nug ..Hangul Syllable Nuh + (0x0b221, 0x0b23b,), # Hangul Syllable Nweog ..Hangul Syllable Nweoh + (0x0b23d, 0x0b257,), # Hangul Syllable Nweg ..Hangul Syllable Nweh + (0x0b259, 0x0b273,), # Hangul Syllable Nwig ..Hangul Syllable Nwih + (0x0b275, 0x0b28f,), # Hangul Syllable Nyug ..Hangul Syllable Nyuh + (0x0b291, 0x0b2ab,), # Hangul Syllable Neug ..Hangul Syllable Neuh + (0x0b2ad, 0x0b2c7,), # Hangul Syllable Nyig ..Hangul Syllable Nyih + (0x0b2c9, 0x0b2e3,), # Hangul Syllable Nig ..Hangul Syllable Nih + (0x0b2e5, 0x0b2ff,), # Hangul Syllable Dag ..Hangul Syllable Dah + (0x0b301, 0x0b31b,), # Hangul Syllable Daeg ..Hangul Syllable Daeh + (0x0b31d, 0x0b337,), # Hangul Syllable Dyag ..Hangul Syllable Dyah + (0x0b339, 0x0b353,), # Hangul Syllable Dyaeg ..Hangul Syllable Dyaeh + (0x0b355, 0x0b36f,), # Hangul Syllable Deog ..Hangul Syllable Deoh + (0x0b371, 0x0b38b,), # Hangul Syllable Deg ..Hangul Syllable Deh + (0x0b38d, 0x0b3a7,), # Hangul Syllable Dyeog ..Hangul Syllable Dyeoh + (0x0b3a9, 0x0b3c3,), # Hangul Syllable Dyeg ..Hangul Syllable Dyeh + (0x0b3c5, 0x0b3df,), # Hangul Syllable Dog ..Hangul Syllable Doh + (0x0b3e1, 0x0b3fb,), # Hangul Syllable Dwag ..Hangul Syllable Dwah + (0x0b3fd, 0x0b417,), # Hangul Syllable Dwaeg ..Hangul Syllable Dwaeh + (0x0b419, 0x0b433,), # Hangul Syllable Doeg ..Hangul Syllable Doeh + (0x0b435, 0x0b44f,), # Hangul Syllable Dyog ..Hangul Syllable Dyoh + (0x0b451, 0x0b46b,), # Hangul Syllable Dug ..Hangul Syllable Duh + (0x0b46d, 0x0b487,), # Hangul Syllable Dweog ..Hangul Syllable Dweoh + (0x0b489, 0x0b4a3,), # Hangul Syllable Dweg ..Hangul Syllable Dweh + (0x0b4a5, 0x0b4bf,), # Hangul Syllable Dwig ..Hangul Syllable Dwih + (0x0b4c1, 0x0b4db,), # Hangul Syllable Dyug ..Hangul Syllable Dyuh + (0x0b4dd, 0x0b4f7,), # Hangul Syllable Deug ..Hangul Syllable Deuh + (0x0b4f9, 0x0b513,), # Hangul Syllable Dyig ..Hangul Syllable Dyih + (0x0b515, 0x0b52f,), # Hangul Syllable Dig ..Hangul Syllable Dih + (0x0b531, 0x0b54b,), # Hangul Syllable Ddag ..Hangul Syllable Ddah + (0x0b54d, 0x0b567,), # Hangul Syllable Ddaeg ..Hangul Syllable Ddaeh + (0x0b569, 0x0b583,), # Hangul Syllable Ddyag ..Hangul Syllable Ddyah + (0x0b585, 0x0b59f,), # Hangul Syllable Ddyaeg ..Hangul Syllable Ddyaeh + (0x0b5a1, 0x0b5bb,), # Hangul Syllable Ddeog ..Hangul Syllable Ddeoh + (0x0b5bd, 0x0b5d7,), # Hangul Syllable Ddeg ..Hangul Syllable Ddeh + (0x0b5d9, 0x0b5f3,), # Hangul Syllable Ddyeog ..Hangul Syllable Ddyeoh + (0x0b5f5, 0x0b60f,), # Hangul Syllable Ddyeg ..Hangul Syllable Ddyeh + (0x0b611, 0x0b62b,), # Hangul Syllable Ddog ..Hangul Syllable Ddoh + (0x0b62d, 0x0b647,), # Hangul Syllable Ddwag ..Hangul Syllable Ddwah + (0x0b649, 0x0b663,), # Hangul Syllable Ddwaeg ..Hangul Syllable Ddwaeh + (0x0b665, 0x0b67f,), # Hangul Syllable Ddoeg ..Hangul Syllable Ddoeh + (0x0b681, 0x0b69b,), # Hangul Syllable Ddyog ..Hangul Syllable Ddyoh + (0x0b69d, 0x0b6b7,), # Hangul Syllable Ddug ..Hangul Syllable Dduh + (0x0b6b9, 0x0b6d3,), # Hangul Syllable Ddweog ..Hangul Syllable Ddweoh + (0x0b6d5, 0x0b6ef,), # Hangul Syllable Ddweg ..Hangul Syllable Ddweh + (0x0b6f1, 0x0b70b,), # Hangul Syllable Ddwig ..Hangul Syllable Ddwih + (0x0b70d, 0x0b727,), # Hangul Syllable Ddyug ..Hangul Syllable Ddyuh + (0x0b729, 0x0b743,), # Hangul Syllable Ddeug ..Hangul Syllable Ddeuh + (0x0b745, 0x0b75f,), # Hangul Syllable Ddyig ..Hangul Syllable Ddyih + (0x0b761, 0x0b77b,), # Hangul Syllable Ddig ..Hangul Syllable Ddih + (0x0b77d, 0x0b797,), # Hangul Syllable Rag ..Hangul Syllable Rah + (0x0b799, 0x0b7b3,), # Hangul Syllable Raeg ..Hangul Syllable Raeh + (0x0b7b5, 0x0b7cf,), # Hangul Syllable Ryag ..Hangul Syllable Ryah + (0x0b7d1, 0x0b7eb,), # Hangul Syllable Ryaeg ..Hangul Syllable Ryaeh + (0x0b7ed, 0x0b807,), # Hangul Syllable Reog ..Hangul Syllable Reoh + (0x0b809, 0x0b823,), # Hangul Syllable Reg ..Hangul Syllable Reh + (0x0b825, 0x0b83f,), # Hangul Syllable Ryeog ..Hangul Syllable Ryeoh + (0x0b841, 0x0b85b,), # Hangul Syllable Ryeg ..Hangul Syllable Ryeh + (0x0b85d, 0x0b877,), # Hangul Syllable Rog ..Hangul Syllable Roh + (0x0b879, 0x0b893,), # Hangul Syllable Rwag ..Hangul Syllable Rwah + (0x0b895, 0x0b8af,), # Hangul Syllable Rwaeg ..Hangul Syllable Rwaeh + (0x0b8b1, 0x0b8cb,), # Hangul Syllable Roeg ..Hangul Syllable Roeh + (0x0b8cd, 0x0b8e7,), # Hangul Syllable Ryog ..Hangul Syllable Ryoh + (0x0b8e9, 0x0b903,), # Hangul Syllable Rug ..Hangul Syllable Ruh + (0x0b905, 0x0b91f,), # Hangul Syllable Rweog ..Hangul Syllable Rweoh + (0x0b921, 0x0b93b,), # Hangul Syllable Rweg ..Hangul Syllable Rweh + (0x0b93d, 0x0b957,), # Hangul Syllable Rwig ..Hangul Syllable Rwih + (0x0b959, 0x0b973,), # Hangul Syllable Ryug ..Hangul Syllable Ryuh + (0x0b975, 0x0b98f,), # Hangul Syllable Reug ..Hangul Syllable Reuh + (0x0b991, 0x0b9ab,), # Hangul Syllable Ryig ..Hangul Syllable Ryih + (0x0b9ad, 0x0b9c7,), # Hangul Syllable Rig ..Hangul Syllable Rih + (0x0b9c9, 0x0b9e3,), # Hangul Syllable Mag ..Hangul Syllable Mah + (0x0b9e5, 0x0b9ff,), # Hangul Syllable Maeg ..Hangul Syllable Maeh + (0x0ba01, 0x0ba1b,), # Hangul Syllable Myag ..Hangul Syllable Myah + (0x0ba1d, 0x0ba37,), # Hangul Syllable Myaeg ..Hangul Syllable Myaeh + (0x0ba39, 0x0ba53,), # Hangul Syllable Meog ..Hangul Syllable Meoh + (0x0ba55, 0x0ba6f,), # Hangul Syllable Meg ..Hangul Syllable Meh + (0x0ba71, 0x0ba8b,), # Hangul Syllable Myeog ..Hangul Syllable Myeoh + (0x0ba8d, 0x0baa7,), # Hangul Syllable Myeg ..Hangul Syllable Myeh + (0x0baa9, 0x0bac3,), # Hangul Syllable Mog ..Hangul Syllable Moh + (0x0bac5, 0x0badf,), # Hangul Syllable Mwag ..Hangul Syllable Mwah + (0x0bae1, 0x0bafb,), # Hangul Syllable Mwaeg ..Hangul Syllable Mwaeh + (0x0bafd, 0x0bb17,), # Hangul Syllable Moeg ..Hangul Syllable Moeh + (0x0bb19, 0x0bb33,), # Hangul Syllable Myog ..Hangul Syllable Myoh + (0x0bb35, 0x0bb4f,), # Hangul Syllable Mug ..Hangul Syllable Muh + (0x0bb51, 0x0bb6b,), # Hangul Syllable Mweog ..Hangul Syllable Mweoh + (0x0bb6d, 0x0bb87,), # Hangul Syllable Mweg ..Hangul Syllable Mweh + (0x0bb89, 0x0bba3,), # Hangul Syllable Mwig ..Hangul Syllable Mwih + (0x0bba5, 0x0bbbf,), # Hangul Syllable Myug ..Hangul Syllable Myuh + (0x0bbc1, 0x0bbdb,), # Hangul Syllable Meug ..Hangul Syllable Meuh + (0x0bbdd, 0x0bbf7,), # Hangul Syllable Myig ..Hangul Syllable Myih + (0x0bbf9, 0x0bc13,), # Hangul Syllable Mig ..Hangul Syllable Mih + (0x0bc15, 0x0bc2f,), # Hangul Syllable Bag ..Hangul Syllable Bah + (0x0bc31, 0x0bc4b,), # Hangul Syllable Baeg ..Hangul Syllable Baeh + (0x0bc4d, 0x0bc67,), # Hangul Syllable Byag ..Hangul Syllable Byah + (0x0bc69, 0x0bc83,), # Hangul Syllable Byaeg ..Hangul Syllable Byaeh + (0x0bc85, 0x0bc9f,), # Hangul Syllable Beog ..Hangul Syllable Beoh + (0x0bca1, 0x0bcbb,), # Hangul Syllable Beg ..Hangul Syllable Beh + (0x0bcbd, 0x0bcd7,), # Hangul Syllable Byeog ..Hangul Syllable Byeoh + (0x0bcd9, 0x0bcf3,), # Hangul Syllable Byeg ..Hangul Syllable Byeh + (0x0bcf5, 0x0bd0f,), # Hangul Syllable Bog ..Hangul Syllable Boh + (0x0bd11, 0x0bd2b,), # Hangul Syllable Bwag ..Hangul Syllable Bwah + (0x0bd2d, 0x0bd47,), # Hangul Syllable Bwaeg ..Hangul Syllable Bwaeh + (0x0bd49, 0x0bd63,), # Hangul Syllable Boeg ..Hangul Syllable Boeh + (0x0bd65, 0x0bd7f,), # Hangul Syllable Byog ..Hangul Syllable Byoh + (0x0bd81, 0x0bd9b,), # Hangul Syllable Bug ..Hangul Syllable Buh + (0x0bd9d, 0x0bdb7,), # Hangul Syllable Bweog ..Hangul Syllable Bweoh + (0x0bdb9, 0x0bdd3,), # Hangul Syllable Bweg ..Hangul Syllable Bweh + (0x0bdd5, 0x0bdef,), # Hangul Syllable Bwig ..Hangul Syllable Bwih + (0x0bdf1, 0x0be0b,), # Hangul Syllable Byug ..Hangul Syllable Byuh + (0x0be0d, 0x0be27,), # Hangul Syllable Beug ..Hangul Syllable Beuh + (0x0be29, 0x0be43,), # Hangul Syllable Byig ..Hangul Syllable Byih + (0x0be45, 0x0be5f,), # Hangul Syllable Big ..Hangul Syllable Bih + (0x0be61, 0x0be7b,), # Hangul Syllable Bbag ..Hangul Syllable Bbah + (0x0be7d, 0x0be97,), # Hangul Syllable Bbaeg ..Hangul Syllable Bbaeh + (0x0be99, 0x0beb3,), # Hangul Syllable Bbyag ..Hangul Syllable Bbyah + (0x0beb5, 0x0becf,), # Hangul Syllable Bbyaeg ..Hangul Syllable Bbyaeh + (0x0bed1, 0x0beeb,), # Hangul Syllable Bbeog ..Hangul Syllable Bbeoh + (0x0beed, 0x0bf07,), # Hangul Syllable Bbeg ..Hangul Syllable Bbeh + (0x0bf09, 0x0bf23,), # Hangul Syllable Bbyeog ..Hangul Syllable Bbyeoh + (0x0bf25, 0x0bf3f,), # Hangul Syllable Bbyeg ..Hangul Syllable Bbyeh + (0x0bf41, 0x0bf5b,), # Hangul Syllable Bbog ..Hangul Syllable Bboh + (0x0bf5d, 0x0bf77,), # Hangul Syllable Bbwag ..Hangul Syllable Bbwah + (0x0bf79, 0x0bf93,), # Hangul Syllable Bbwaeg ..Hangul Syllable Bbwaeh + (0x0bf95, 0x0bfaf,), # Hangul Syllable Bboeg ..Hangul Syllable Bboeh + (0x0bfb1, 0x0bfcb,), # Hangul Syllable Bbyog ..Hangul Syllable Bbyoh + (0x0bfcd, 0x0bfe7,), # Hangul Syllable Bbug ..Hangul Syllable Bbuh + (0x0bfe9, 0x0c003,), # Hangul Syllable Bbweog ..Hangul Syllable Bbweoh + (0x0c005, 0x0c01f,), # Hangul Syllable Bbweg ..Hangul Syllable Bbweh + (0x0c021, 0x0c03b,), # Hangul Syllable Bbwig ..Hangul Syllable Bbwih + (0x0c03d, 0x0c057,), # Hangul Syllable Bbyug ..Hangul Syllable Bbyuh + (0x0c059, 0x0c073,), # Hangul Syllable Bbeug ..Hangul Syllable Bbeuh + (0x0c075, 0x0c08f,), # Hangul Syllable Bbyig ..Hangul Syllable Bbyih + (0x0c091, 0x0c0ab,), # Hangul Syllable Bbig ..Hangul Syllable Bbih + (0x0c0ad, 0x0c0c7,), # Hangul Syllable Sag ..Hangul Syllable Sah + (0x0c0c9, 0x0c0e3,), # Hangul Syllable Saeg ..Hangul Syllable Saeh + (0x0c0e5, 0x0c0ff,), # Hangul Syllable Syag ..Hangul Syllable Syah + (0x0c101, 0x0c11b,), # Hangul Syllable Syaeg ..Hangul Syllable Syaeh + (0x0c11d, 0x0c137,), # Hangul Syllable Seog ..Hangul Syllable Seoh + (0x0c139, 0x0c153,), # Hangul Syllable Seg ..Hangul Syllable Seh + (0x0c155, 0x0c16f,), # Hangul Syllable Syeog ..Hangul Syllable Syeoh + (0x0c171, 0x0c18b,), # Hangul Syllable Syeg ..Hangul Syllable Syeh + (0x0c18d, 0x0c1a7,), # Hangul Syllable Sog ..Hangul Syllable Soh + (0x0c1a9, 0x0c1c3,), # Hangul Syllable Swag ..Hangul Syllable Swah + (0x0c1c5, 0x0c1df,), # Hangul Syllable Swaeg ..Hangul Syllable Swaeh + (0x0c1e1, 0x0c1fb,), # Hangul Syllable Soeg ..Hangul Syllable Soeh + (0x0c1fd, 0x0c217,), # Hangul Syllable Syog ..Hangul Syllable Syoh + (0x0c219, 0x0c233,), # Hangul Syllable Sug ..Hangul Syllable Suh + (0x0c235, 0x0c24f,), # Hangul Syllable Sweog ..Hangul Syllable Sweoh + (0x0c251, 0x0c26b,), # Hangul Syllable Sweg ..Hangul Syllable Sweh + (0x0c26d, 0x0c287,), # Hangul Syllable Swig ..Hangul Syllable Swih + (0x0c289, 0x0c2a3,), # Hangul Syllable Syug ..Hangul Syllable Syuh + (0x0c2a5, 0x0c2bf,), # Hangul Syllable Seug ..Hangul Syllable Seuh + (0x0c2c1, 0x0c2db,), # Hangul Syllable Syig ..Hangul Syllable Syih + (0x0c2dd, 0x0c2f7,), # Hangul Syllable Sig ..Hangul Syllable Sih + (0x0c2f9, 0x0c313,), # Hangul Syllable Ssag ..Hangul Syllable Ssah + (0x0c315, 0x0c32f,), # Hangul Syllable Ssaeg ..Hangul Syllable Ssaeh + (0x0c331, 0x0c34b,), # Hangul Syllable Ssyag ..Hangul Syllable Ssyah + (0x0c34d, 0x0c367,), # Hangul Syllable Ssyaeg ..Hangul Syllable Ssyaeh + (0x0c369, 0x0c383,), # Hangul Syllable Sseog ..Hangul Syllable Sseoh + (0x0c385, 0x0c39f,), # Hangul Syllable Sseg ..Hangul Syllable Sseh + (0x0c3a1, 0x0c3bb,), # Hangul Syllable Ssyeog ..Hangul Syllable Ssyeoh + (0x0c3bd, 0x0c3d7,), # Hangul Syllable Ssyeg ..Hangul Syllable Ssyeh + (0x0c3d9, 0x0c3f3,), # Hangul Syllable Ssog ..Hangul Syllable Ssoh + (0x0c3f5, 0x0c40f,), # Hangul Syllable Sswag ..Hangul Syllable Sswah + (0x0c411, 0x0c42b,), # Hangul Syllable Sswaeg ..Hangul Syllable Sswaeh + (0x0c42d, 0x0c447,), # Hangul Syllable Ssoeg ..Hangul Syllable Ssoeh + (0x0c449, 0x0c463,), # Hangul Syllable Ssyog ..Hangul Syllable Ssyoh + (0x0c465, 0x0c47f,), # Hangul Syllable Ssug ..Hangul Syllable Ssuh + (0x0c481, 0x0c49b,), # Hangul Syllable Ssweog ..Hangul Syllable Ssweoh + (0x0c49d, 0x0c4b7,), # Hangul Syllable Ssweg ..Hangul Syllable Ssweh + (0x0c4b9, 0x0c4d3,), # Hangul Syllable Sswig ..Hangul Syllable Sswih + (0x0c4d5, 0x0c4ef,), # Hangul Syllable Ssyug ..Hangul Syllable Ssyuh + (0x0c4f1, 0x0c50b,), # Hangul Syllable Sseug ..Hangul Syllable Sseuh + (0x0c50d, 0x0c527,), # Hangul Syllable Ssyig ..Hangul Syllable Ssyih + (0x0c529, 0x0c543,), # Hangul Syllable Ssig ..Hangul Syllable Ssih + (0x0c545, 0x0c55f,), # Hangul Syllable Ag ..Hangul Syllable Ah + (0x0c561, 0x0c57b,), # Hangul Syllable Aeg ..Hangul Syllable Aeh + (0x0c57d, 0x0c597,), # Hangul Syllable Yag ..Hangul Syllable Yah + (0x0c599, 0x0c5b3,), # Hangul Syllable Yaeg ..Hangul Syllable Yaeh + (0x0c5b5, 0x0c5cf,), # Hangul Syllable Eog ..Hangul Syllable Eoh + (0x0c5d1, 0x0c5eb,), # Hangul Syllable Eg ..Hangul Syllable Eh + (0x0c5ed, 0x0c607,), # Hangul Syllable Yeog ..Hangul Syllable Yeoh + (0x0c609, 0x0c623,), # Hangul Syllable Yeg ..Hangul Syllable Yeh + (0x0c625, 0x0c63f,), # Hangul Syllable Og ..Hangul Syllable Oh + (0x0c641, 0x0c65b,), # Hangul Syllable Wag ..Hangul Syllable Wah + (0x0c65d, 0x0c677,), # Hangul Syllable Waeg ..Hangul Syllable Waeh + (0x0c679, 0x0c693,), # Hangul Syllable Oeg ..Hangul Syllable Oeh + (0x0c695, 0x0c6af,), # Hangul Syllable Yog ..Hangul Syllable Yoh + (0x0c6b1, 0x0c6cb,), # Hangul Syllable Ug ..Hangul Syllable Uh + (0x0c6cd, 0x0c6e7,), # Hangul Syllable Weog ..Hangul Syllable Weoh + (0x0c6e9, 0x0c703,), # Hangul Syllable Weg ..Hangul Syllable Weh + (0x0c705, 0x0c71f,), # Hangul Syllable Wig ..Hangul Syllable Wih + (0x0c721, 0x0c73b,), # Hangul Syllable Yug ..Hangul Syllable Yuh + (0x0c73d, 0x0c757,), # Hangul Syllable Eug ..Hangul Syllable Euh + (0x0c759, 0x0c773,), # Hangul Syllable Yig ..Hangul Syllable Yih + (0x0c775, 0x0c78f,), # Hangul Syllable Ig ..Hangul Syllable Ih + (0x0c791, 0x0c7ab,), # Hangul Syllable Jag ..Hangul Syllable Jah + (0x0c7ad, 0x0c7c7,), # Hangul Syllable Jaeg ..Hangul Syllable Jaeh + (0x0c7c9, 0x0c7e3,), # Hangul Syllable Jyag ..Hangul Syllable Jyah + (0x0c7e5, 0x0c7ff,), # Hangul Syllable Jyaeg ..Hangul Syllable Jyaeh + (0x0c801, 0x0c81b,), # Hangul Syllable Jeog ..Hangul Syllable Jeoh + (0x0c81d, 0x0c837,), # Hangul Syllable Jeg ..Hangul Syllable Jeh + (0x0c839, 0x0c853,), # Hangul Syllable Jyeog ..Hangul Syllable Jyeoh + (0x0c855, 0x0c86f,), # Hangul Syllable Jyeg ..Hangul Syllable Jyeh + (0x0c871, 0x0c88b,), # Hangul Syllable Jog ..Hangul Syllable Joh + (0x0c88d, 0x0c8a7,), # Hangul Syllable Jwag ..Hangul Syllable Jwah + (0x0c8a9, 0x0c8c3,), # Hangul Syllable Jwaeg ..Hangul Syllable Jwaeh + (0x0c8c5, 0x0c8df,), # Hangul Syllable Joeg ..Hangul Syllable Joeh + (0x0c8e1, 0x0c8fb,), # Hangul Syllable Jyog ..Hangul Syllable Jyoh + (0x0c8fd, 0x0c917,), # Hangul Syllable Jug ..Hangul Syllable Juh + (0x0c919, 0x0c933,), # Hangul Syllable Jweog ..Hangul Syllable Jweoh + (0x0c935, 0x0c94f,), # Hangul Syllable Jweg ..Hangul Syllable Jweh + (0x0c951, 0x0c96b,), # Hangul Syllable Jwig ..Hangul Syllable Jwih + (0x0c96d, 0x0c987,), # Hangul Syllable Jyug ..Hangul Syllable Jyuh + (0x0c989, 0x0c9a3,), # Hangul Syllable Jeug ..Hangul Syllable Jeuh + (0x0c9a5, 0x0c9bf,), # Hangul Syllable Jyig ..Hangul Syllable Jyih + (0x0c9c1, 0x0c9db,), # Hangul Syllable Jig ..Hangul Syllable Jih + (0x0c9dd, 0x0c9f7,), # Hangul Syllable Jjag ..Hangul Syllable Jjah + (0x0c9f9, 0x0ca13,), # Hangul Syllable Jjaeg ..Hangul Syllable Jjaeh + (0x0ca15, 0x0ca2f,), # Hangul Syllable Jjyag ..Hangul Syllable Jjyah + (0x0ca31, 0x0ca4b,), # Hangul Syllable Jjyaeg ..Hangul Syllable Jjyaeh + (0x0ca4d, 0x0ca67,), # Hangul Syllable Jjeog ..Hangul Syllable Jjeoh + (0x0ca69, 0x0ca83,), # Hangul Syllable Jjeg ..Hangul Syllable Jjeh + (0x0ca85, 0x0ca9f,), # Hangul Syllable Jjyeog ..Hangul Syllable Jjyeoh + (0x0caa1, 0x0cabb,), # Hangul Syllable Jjyeg ..Hangul Syllable Jjyeh + (0x0cabd, 0x0cad7,), # Hangul Syllable Jjog ..Hangul Syllable Jjoh + (0x0cad9, 0x0caf3,), # Hangul Syllable Jjwag ..Hangul Syllable Jjwah + (0x0caf5, 0x0cb0f,), # Hangul Syllable Jjwaeg ..Hangul Syllable Jjwaeh + (0x0cb11, 0x0cb2b,), # Hangul Syllable Jjoeg ..Hangul Syllable Jjoeh + (0x0cb2d, 0x0cb47,), # Hangul Syllable Jjyog ..Hangul Syllable Jjyoh + (0x0cb49, 0x0cb63,), # Hangul Syllable Jjug ..Hangul Syllable Jjuh + (0x0cb65, 0x0cb7f,), # Hangul Syllable Jjweog ..Hangul Syllable Jjweoh + (0x0cb81, 0x0cb9b,), # Hangul Syllable Jjweg ..Hangul Syllable Jjweh + (0x0cb9d, 0x0cbb7,), # Hangul Syllable Jjwig ..Hangul Syllable Jjwih + (0x0cbb9, 0x0cbd3,), # Hangul Syllable Jjyug ..Hangul Syllable Jjyuh + (0x0cbd5, 0x0cbef,), # Hangul Syllable Jjeug ..Hangul Syllable Jjeuh + (0x0cbf1, 0x0cc0b,), # Hangul Syllable Jjyig ..Hangul Syllable Jjyih + (0x0cc0d, 0x0cc27,), # Hangul Syllable Jjig ..Hangul Syllable Jjih + (0x0cc29, 0x0cc43,), # Hangul Syllable Cag ..Hangul Syllable Cah + (0x0cc45, 0x0cc5f,), # Hangul Syllable Caeg ..Hangul Syllable Caeh + (0x0cc61, 0x0cc7b,), # Hangul Syllable Cyag ..Hangul Syllable Cyah + (0x0cc7d, 0x0cc97,), # Hangul Syllable Cyaeg ..Hangul Syllable Cyaeh + (0x0cc99, 0x0ccb3,), # Hangul Syllable Ceog ..Hangul Syllable Ceoh + (0x0ccb5, 0x0cccf,), # Hangul Syllable Ceg ..Hangul Syllable Ceh + (0x0ccd1, 0x0cceb,), # Hangul Syllable Cyeog ..Hangul Syllable Cyeoh + (0x0cced, 0x0cd07,), # Hangul Syllable Cyeg ..Hangul Syllable Cyeh + (0x0cd09, 0x0cd23,), # Hangul Syllable Cog ..Hangul Syllable Coh + (0x0cd25, 0x0cd3f,), # Hangul Syllable Cwag ..Hangul Syllable Cwah + (0x0cd41, 0x0cd5b,), # Hangul Syllable Cwaeg ..Hangul Syllable Cwaeh + (0x0cd5d, 0x0cd77,), # Hangul Syllable Coeg ..Hangul Syllable Coeh + (0x0cd79, 0x0cd93,), # Hangul Syllable Cyog ..Hangul Syllable Cyoh + (0x0cd95, 0x0cdaf,), # Hangul Syllable Cug ..Hangul Syllable Cuh + (0x0cdb1, 0x0cdcb,), # Hangul Syllable Cweog ..Hangul Syllable Cweoh + (0x0cdcd, 0x0cde7,), # Hangul Syllable Cweg ..Hangul Syllable Cweh + (0x0cde9, 0x0ce03,), # Hangul Syllable Cwig ..Hangul Syllable Cwih + (0x0ce05, 0x0ce1f,), # Hangul Syllable Cyug ..Hangul Syllable Cyuh + (0x0ce21, 0x0ce3b,), # Hangul Syllable Ceug ..Hangul Syllable Ceuh + (0x0ce3d, 0x0ce57,), # Hangul Syllable Cyig ..Hangul Syllable Cyih + (0x0ce59, 0x0ce73,), # Hangul Syllable Cig ..Hangul Syllable Cih + (0x0ce75, 0x0ce8f,), # Hangul Syllable Kag ..Hangul Syllable Kah + (0x0ce91, 0x0ceab,), # Hangul Syllable Kaeg ..Hangul Syllable Kaeh + (0x0cead, 0x0cec7,), # Hangul Syllable Kyag ..Hangul Syllable Kyah + (0x0cec9, 0x0cee3,), # Hangul Syllable Kyaeg ..Hangul Syllable Kyaeh + (0x0cee5, 0x0ceff,), # Hangul Syllable Keog ..Hangul Syllable Keoh + (0x0cf01, 0x0cf1b,), # Hangul Syllable Keg ..Hangul Syllable Keh + (0x0cf1d, 0x0cf37,), # Hangul Syllable Kyeog ..Hangul Syllable Kyeoh + (0x0cf39, 0x0cf53,), # Hangul Syllable Kyeg ..Hangul Syllable Kyeh + (0x0cf55, 0x0cf6f,), # Hangul Syllable Kog ..Hangul Syllable Koh + (0x0cf71, 0x0cf8b,), # Hangul Syllable Kwag ..Hangul Syllable Kwah + (0x0cf8d, 0x0cfa7,), # Hangul Syllable Kwaeg ..Hangul Syllable Kwaeh + (0x0cfa9, 0x0cfc3,), # Hangul Syllable Koeg ..Hangul Syllable Koeh + (0x0cfc5, 0x0cfdf,), # Hangul Syllable Kyog ..Hangul Syllable Kyoh + (0x0cfe1, 0x0cffb,), # Hangul Syllable Kug ..Hangul Syllable Kuh + (0x0cffd, 0x0d017,), # Hangul Syllable Kweog ..Hangul Syllable Kweoh + (0x0d019, 0x0d033,), # Hangul Syllable Kweg ..Hangul Syllable Kweh + (0x0d035, 0x0d04f,), # Hangul Syllable Kwig ..Hangul Syllable Kwih + (0x0d051, 0x0d06b,), # Hangul Syllable Kyug ..Hangul Syllable Kyuh + (0x0d06d, 0x0d087,), # Hangul Syllable Keug ..Hangul Syllable Keuh + (0x0d089, 0x0d0a3,), # Hangul Syllable Kyig ..Hangul Syllable Kyih + (0x0d0a5, 0x0d0bf,), # Hangul Syllable Kig ..Hangul Syllable Kih + (0x0d0c1, 0x0d0db,), # Hangul Syllable Tag ..Hangul Syllable Tah + (0x0d0dd, 0x0d0f7,), # Hangul Syllable Taeg ..Hangul Syllable Taeh + (0x0d0f9, 0x0d113,), # Hangul Syllable Tyag ..Hangul Syllable Tyah + (0x0d115, 0x0d12f,), # Hangul Syllable Tyaeg ..Hangul Syllable Tyaeh + (0x0d131, 0x0d14b,), # Hangul Syllable Teog ..Hangul Syllable Teoh + (0x0d14d, 0x0d167,), # Hangul Syllable Teg ..Hangul Syllable Teh + (0x0d169, 0x0d183,), # Hangul Syllable Tyeog ..Hangul Syllable Tyeoh + (0x0d185, 0x0d19f,), # Hangul Syllable Tyeg ..Hangul Syllable Tyeh + (0x0d1a1, 0x0d1bb,), # Hangul Syllable Tog ..Hangul Syllable Toh + (0x0d1bd, 0x0d1d7,), # Hangul Syllable Twag ..Hangul Syllable Twah + (0x0d1d9, 0x0d1f3,), # Hangul Syllable Twaeg ..Hangul Syllable Twaeh + (0x0d1f5, 0x0d20f,), # Hangul Syllable Toeg ..Hangul Syllable Toeh + (0x0d211, 0x0d22b,), # Hangul Syllable Tyog ..Hangul Syllable Tyoh + (0x0d22d, 0x0d247,), # Hangul Syllable Tug ..Hangul Syllable Tuh + (0x0d249, 0x0d263,), # Hangul Syllable Tweog ..Hangul Syllable Tweoh + (0x0d265, 0x0d27f,), # Hangul Syllable Tweg ..Hangul Syllable Tweh + (0x0d281, 0x0d29b,), # Hangul Syllable Twig ..Hangul Syllable Twih + (0x0d29d, 0x0d2b7,), # Hangul Syllable Tyug ..Hangul Syllable Tyuh + (0x0d2b9, 0x0d2d3,), # Hangul Syllable Teug ..Hangul Syllable Teuh + (0x0d2d5, 0x0d2ef,), # Hangul Syllable Tyig ..Hangul Syllable Tyih + (0x0d2f1, 0x0d30b,), # Hangul Syllable Tig ..Hangul Syllable Tih + (0x0d30d, 0x0d327,), # Hangul Syllable Pag ..Hangul Syllable Pah + (0x0d329, 0x0d343,), # Hangul Syllable Paeg ..Hangul Syllable Paeh + (0x0d345, 0x0d35f,), # Hangul Syllable Pyag ..Hangul Syllable Pyah + (0x0d361, 0x0d37b,), # Hangul Syllable Pyaeg ..Hangul Syllable Pyaeh + (0x0d37d, 0x0d397,), # Hangul Syllable Peog ..Hangul Syllable Peoh + (0x0d399, 0x0d3b3,), # Hangul Syllable Peg ..Hangul Syllable Peh + (0x0d3b5, 0x0d3cf,), # Hangul Syllable Pyeog ..Hangul Syllable Pyeoh + (0x0d3d1, 0x0d3eb,), # Hangul Syllable Pyeg ..Hangul Syllable Pyeh + (0x0d3ed, 0x0d407,), # Hangul Syllable Pog ..Hangul Syllable Poh + (0x0d409, 0x0d423,), # Hangul Syllable Pwag ..Hangul Syllable Pwah + (0x0d425, 0x0d43f,), # Hangul Syllable Pwaeg ..Hangul Syllable Pwaeh + (0x0d441, 0x0d45b,), # Hangul Syllable Poeg ..Hangul Syllable Poeh + (0x0d45d, 0x0d477,), # Hangul Syllable Pyog ..Hangul Syllable Pyoh + (0x0d479, 0x0d493,), # Hangul Syllable Pug ..Hangul Syllable Puh + (0x0d495, 0x0d4af,), # Hangul Syllable Pweog ..Hangul Syllable Pweoh + (0x0d4b1, 0x0d4cb,), # Hangul Syllable Pweg ..Hangul Syllable Pweh + (0x0d4cd, 0x0d4e7,), # Hangul Syllable Pwig ..Hangul Syllable Pwih + (0x0d4e9, 0x0d503,), # Hangul Syllable Pyug ..Hangul Syllable Pyuh + (0x0d505, 0x0d51f,), # Hangul Syllable Peug ..Hangul Syllable Peuh + (0x0d521, 0x0d53b,), # Hangul Syllable Pyig ..Hangul Syllable Pyih + (0x0d53d, 0x0d557,), # Hangul Syllable Pig ..Hangul Syllable Pih + (0x0d559, 0x0d573,), # Hangul Syllable Hag ..Hangul Syllable Hah + (0x0d575, 0x0d58f,), # Hangul Syllable Haeg ..Hangul Syllable Haeh + (0x0d591, 0x0d5ab,), # Hangul Syllable Hyag ..Hangul Syllable Hyah + (0x0d5ad, 0x0d5c7,), # Hangul Syllable Hyaeg ..Hangul Syllable Hyaeh + (0x0d5c9, 0x0d5e3,), # Hangul Syllable Heog ..Hangul Syllable Heoh + (0x0d5e5, 0x0d5ff,), # Hangul Syllable Heg ..Hangul Syllable Heh + (0x0d601, 0x0d61b,), # Hangul Syllable Hyeog ..Hangul Syllable Hyeoh + (0x0d61d, 0x0d637,), # Hangul Syllable Hyeg ..Hangul Syllable Hyeh + (0x0d639, 0x0d653,), # Hangul Syllable Hog ..Hangul Syllable Hoh + (0x0d655, 0x0d66f,), # Hangul Syllable Hwag ..Hangul Syllable Hwah + (0x0d671, 0x0d68b,), # Hangul Syllable Hwaeg ..Hangul Syllable Hwaeh + (0x0d68d, 0x0d6a7,), # Hangul Syllable Hoeg ..Hangul Syllable Hoeh + (0x0d6a9, 0x0d6c3,), # Hangul Syllable Hyog ..Hangul Syllable Hyoh + (0x0d6c5, 0x0d6df,), # Hangul Syllable Hug ..Hangul Syllable Huh + (0x0d6e1, 0x0d6fb,), # Hangul Syllable Hweog ..Hangul Syllable Hweoh + (0x0d6fd, 0x0d717,), # Hangul Syllable Hweg ..Hangul Syllable Hweh + (0x0d719, 0x0d733,), # Hangul Syllable Hwig ..Hangul Syllable Hwih + (0x0d735, 0x0d74f,), # Hangul Syllable Hyug ..Hangul Syllable Hyuh + (0x0d751, 0x0d76b,), # Hangul Syllable Heug ..Hangul Syllable Heuh + (0x0d76d, 0x0d787,), # Hangul Syllable Hyig ..Hangul Syllable Hyih + (0x0d789, 0x0d7a3,), # Hangul Syllable Hig ..Hangul Syllable Hih +) + +EXTENDED_PICTOGRAPHIC = ( + # Source: emoji-data.txt + # Date: 2026-01-30, 22:30:17 GMT + # + (0x000a9, 0x000a9,), # Copyright Sign + (0x000ae, 0x000ae,), # Registered Sign + (0x0203c, 0x0203c,), # Double Exclamation Mark + (0x02049, 0x02049,), # Exclamation Question Mark + (0x02122, 0x02122,), # Trade Mark Sign + (0x02139, 0x02139,), # Information Source + (0x02194, 0x02199,), # Left Right Arrow ..South West Arrow + (0x021a9, 0x021aa,), # Leftwards Arrow With Hoo..Rightwards Arrow With Ho + (0x0231a, 0x0231b,), # Watch ..Hourglass + (0x02328, 0x02328,), # Keyboard + (0x023cf, 0x023cf,), # Eject Symbol + (0x023e9, 0x023f3,), # Black Right-pointing Dou..Hourglass With Flowing S + (0x023f8, 0x023fa,), # Double Vertical Bar ..Black Circle For Record + (0x024c2, 0x024c2,), # Circled Latin Capital Letter M + (0x025aa, 0x025ab,), # Black Small Square ..White Small Square + (0x025b6, 0x025b6,), # Black Right-pointing Triangle + (0x025c0, 0x025c0,), # Black Left-pointing Triangle + (0x025fb, 0x025fe,), # White Medium Square ..Black Medium Small Squar + (0x02600, 0x02604,), # Black Sun With Rays ..Comet + (0x0260e, 0x0260e,), # Black Telephone + (0x02611, 0x02611,), # Ballot Box With Check + (0x02614, 0x02615,), # Umbrella With Rain Drops..Hot Beverage + (0x02618, 0x02618,), # Shamrock + (0x0261d, 0x0261d,), # White Up Pointing Index + (0x02620, 0x02620,), # Skull And Crossbones + (0x02622, 0x02623,), # Radioactive Sign ..Biohazard Sign + (0x02626, 0x02626,), # Orthodox Cross + (0x0262a, 0x0262a,), # Star And Crescent + (0x0262e, 0x0262f,), # Peace Symbol ..Yin Yang + (0x02638, 0x0263a,), # Wheel Of Dharma ..White Smiling Face + (0x02640, 0x02640,), # Female Sign + (0x02642, 0x02642,), # Male Sign + (0x02648, 0x02653,), # Aries ..Pisces + (0x0265f, 0x02660,), # Black Chess Pawn ..Black Spade Suit + (0x02663, 0x02663,), # Black Club Suit + (0x02665, 0x02666,), # Black Heart Suit ..Black Diamond Suit + (0x02668, 0x02668,), # Hot Springs + (0x0267b, 0x0267b,), # Black Universal Recycling Symbol + (0x0267e, 0x0267f,), # Permanent Paper Sign ..Wheelchair Symbol + (0x02692, 0x02697,), # Hammer And Pick ..Alembic + (0x02699, 0x02699,), # Gear + (0x0269b, 0x0269c,), # Atom Symbol ..Fleur-de-lis + (0x026a0, 0x026a1,), # Warning Sign ..High Voltage Sign + (0x026a7, 0x026a7,), # Male With Stroke And Male And Female Sign + (0x026aa, 0x026ab,), # Medium White Circle ..Medium Black Circle + (0x026b0, 0x026b1,), # Coffin ..Funeral Urn + (0x026bd, 0x026be,), # Soccer Ball ..Baseball + (0x026c4, 0x026c5,), # Snowman Without Snow ..Sun Behind Cloud + (0x026c8, 0x026c8,), # Thunder Cloud And Rain + (0x026ce, 0x026cf,), # Ophiuchus ..Pick + (0x026d1, 0x026d1,), # Helmet With White Cross + (0x026d3, 0x026d4,), # Chains ..No Entry + (0x026e9, 0x026ea,), # Shinto Shrine ..Church + (0x026f0, 0x026f5,), # Mountain ..Sailboat + (0x026f7, 0x026fa,), # Skier ..Tent + (0x026fd, 0x026fd,), # Fuel Pump + (0x02702, 0x02702,), # Black Scissors + (0x02705, 0x02705,), # White Heavy Check Mark + (0x02708, 0x0270d,), # Airplane ..Writing Hand + (0x0270f, 0x0270f,), # Pencil + (0x02712, 0x02712,), # Black Nib + (0x02714, 0x02714,), # Heavy Check Mark + (0x02716, 0x02716,), # Heavy Multiplication X + (0x0271d, 0x0271d,), # Latin Cross + (0x02721, 0x02721,), # Star Of David + (0x02728, 0x02728,), # Sparkles + (0x02733, 0x02734,), # Eight Spoked Asterisk ..Eight Pointed Black Star + (0x02744, 0x02744,), # Snowflake + (0x02747, 0x02747,), # Sparkle + (0x0274c, 0x0274c,), # Cross Mark + (0x0274e, 0x0274e,), # Negative Squared Cross Mark + (0x02753, 0x02755,), # Black Question Mark Orna..White Exclamation Mark O + (0x02757, 0x02757,), # Heavy Exclamation Mark Symbol + (0x02763, 0x02764,), # Heavy Heart Exclamation ..Heavy Black Heart + (0x02795, 0x02797,), # Heavy Plus Sign ..Heavy Division Sign + (0x027a1, 0x027a1,), # Black Rightwards Arrow + (0x027b0, 0x027b0,), # Curly Loop + (0x027bf, 0x027bf,), # Double Curly Loop + (0x02934, 0x02935,), # Arrow Pointing Rightward..Arrow Pointing Rightward + (0x02b05, 0x02b07,), # Leftwards Black Arrow ..Downwards Black Arrow + (0x02b1b, 0x02b1c,), # Black Large Square ..White Large Square + (0x02b50, 0x02b50,), # White Medium Star + (0x02b55, 0x02b55,), # Heavy Large Circle + (0x03030, 0x03030,), # Wavy Dash + (0x0303d, 0x0303d,), # Part Alternation Mark + (0x03297, 0x03297,), # Circled Ideograph Congratulation + (0x03299, 0x03299,), # Circled Ideograph Secret + (0x1f004, 0x1f004,), # Mahjong Tile Red Dragon + (0x1f02c, 0x1f02f,), # (nil) + (0x1f094, 0x1f09f,), # (nil) + (0x1f0af, 0x1f0b0,), # (nil) + (0x1f0c0, 0x1f0c0,), # (nil) + (0x1f0cf, 0x1f0d0,), # Playing Card Black Joker..(nil) + (0x1f0f6, 0x1f0ff,), # (nil) + (0x1f170, 0x1f171,), # Negative Squared Latin C..Negative Squared Latin C + (0x1f17e, 0x1f17f,), # Negative Squared Latin C..Negative Squared Latin C + (0x1f18e, 0x1f18e,), # Negative Squared Ab + (0x1f191, 0x1f19a,), # Squared Cl ..Squared Vs + (0x1f1af, 0x1f1e5,), # (nil) + (0x1f201, 0x1f20f,), # Squared Katakana Koko ..(nil) + (0x1f21a, 0x1f21a,), # Squared Cjk Unified Ideograph-7121 + (0x1f22f, 0x1f22f,), # Squared Cjk Unified Ideograph-6307 + (0x1f232, 0x1f23a,), # Squared Cjk Unified Ideo..Squared Cjk Unified Ideo + (0x1f23c, 0x1f23f,), # (nil) + (0x1f249, 0x1f25f,), # (nil) + (0x1f266, 0x1f321,), # (nil) ..Thermometer + (0x1f324, 0x1f393,), # White Sun With Small Clo..Graduation Cap + (0x1f396, 0x1f397,), # Military Medal ..Reminder Ribbon + (0x1f399, 0x1f39b,), # Studio Microphone ..Control Knobs + (0x1f39e, 0x1f3f0,), # Film Frames ..European Castle + (0x1f3f3, 0x1f3f5,), # Waving White Flag ..Rosette + (0x1f3f7, 0x1f3fa,), # Label ..Amphora + (0x1f400, 0x1f4fd,), # Rat ..Film Projector + (0x1f4ff, 0x1f53d,), # Prayer Beads ..Down-pointing Small Red + (0x1f549, 0x1f54e,), # Om Symbol ..Menorah With Nine Branch + (0x1f550, 0x1f567,), # Clock Face One Oclock ..Clock Face Twelve-thirty + (0x1f56f, 0x1f570,), # Candle ..Mantelpiece Clock + (0x1f573, 0x1f57a,), # Hole ..Man Dancing + (0x1f587, 0x1f587,), # Linked Paperclips + (0x1f58a, 0x1f58d,), # Lower Left Ballpoint Pen..Lower Left Crayon + (0x1f590, 0x1f590,), # Raised Hand With Fingers Splayed + (0x1f595, 0x1f596,), # Reversed Hand With Middl..Raised Hand With Part Be + (0x1f5a4, 0x1f5a5,), # Black Heart ..Desktop Computer + (0x1f5a8, 0x1f5a8,), # Printer + (0x1f5b1, 0x1f5b2,), # Three Button Mouse ..Trackball + (0x1f5bc, 0x1f5bc,), # Frame With Picture + (0x1f5c2, 0x1f5c4,), # Card Index Dividers ..File Cabinet + (0x1f5d1, 0x1f5d3,), # Wastebasket ..Spiral Calendar Pad + (0x1f5dc, 0x1f5de,), # Compression ..Rolled-up Newspaper + (0x1f5e1, 0x1f5e1,), # Dagger Knife + (0x1f5e3, 0x1f5e3,), # Speaking Head In Silhouette + (0x1f5e8, 0x1f5e8,), # Left Speech Bubble + (0x1f5ef, 0x1f5ef,), # Right Anger Bubble + (0x1f5f3, 0x1f5f3,), # Ballot Box With Ballot + (0x1f5fa, 0x1f64f,), # World Map ..Person With Folded Hands + (0x1f680, 0x1f6c5,), # Rocket ..Left Luggage + (0x1f6cb, 0x1f6d2,), # Couch And Lamp ..Shopping Trolley + (0x1f6d5, 0x1f6e5,), # Hindu Temple ..Motor Boat + (0x1f6e9, 0x1f6e9,), # Small Airplane + (0x1f6eb, 0x1f6f0,), # Airplane Departure ..Satellite + (0x1f6f3, 0x1f6ff,), # Passenger Ship ..(nil) + (0x1f7dc, 0x1f7f0,), # (nil) ..Heavy Equals Sign + (0x1f80c, 0x1f80f,), # (nil) + (0x1f848, 0x1f84f,), # (nil) + (0x1f85a, 0x1f85f,), # (nil) + (0x1f888, 0x1f88f,), # (nil) + (0x1f8ae, 0x1f8af,), # (nil) + (0x1f8bc, 0x1f8bf,), # (nil) + (0x1f8c2, 0x1f8cf,), # (nil) + (0x1f8d9, 0x1f8ff,), # (nil) + (0x1f90c, 0x1f93a,), # Pinched Fingers ..Fencer + (0x1f93c, 0x1f945,), # Wrestlers ..Goal Net + (0x1f947, 0x1f9ff,), # First Place Medal ..Nazar Amulet + (0x1fa58, 0x1fa5f,), # (nil) + (0x1fa6e, 0x1faff,), # (nil) + (0x1fc00, 0x1fffd,), # (nil) +) + +INCB_LINKER = ( + # Source: DerivedCoreProperties + # Date: see file + # + (0x0094d, 0x0094d,), # Devanagari Sign Virama + (0x009cd, 0x009cd,), # Bengali Sign Virama + (0x00acd, 0x00acd,), # Gujarati Sign Virama + (0x00b4d, 0x00b4d,), # Oriya Sign Virama + (0x00c4d, 0x00c4d,), # Telugu Sign Virama + (0x00d4d, 0x00d4d,), # Malayalam Sign Virama + (0x01039, 0x01039,), # Myanmar Sign Virama + (0x017d2, 0x017d2,), # Khmer Sign Coeng + (0x01a60, 0x01a60,), # Tai Tham Sign Sakot + (0x01b44, 0x01b44,), # Balinese Adeg Adeg + (0x01bab, 0x01bab,), # Sundanese Sign Virama + (0x01cf5, 0x01cf6,), # Vedic Sign Jihvamuliya ..Vedic Sign Upadhmaniya + (0x0a9c0, 0x0a9c0,), # Javanese Pangkon + (0x0aaf6, 0x0aaf6,), # Meetei Mayek Virama + (0x10a3f, 0x10a3f,), # Kharoshthi Virama + (0x11133, 0x11133,), # Chakma Virama + (0x113d0, 0x113d0,), # Tulu-tigalari Conjoiner + (0x1193e, 0x1193e,), # Dives Akuru Virama + (0x11a3a, 0x11a3a,), # Zanabazar Square Cluster-initial Letter Ra + (0x11a47, 0x11a47,), # Zanabazar Square Subjoiner + (0x11a99, 0x11a99,), # Soyombo Subjoiner + (0x11f42, 0x11f42,), # Kawi Conjoiner +) + +INCB_CONSONANT = ( + # Source: DerivedCoreProperties + # Date: see file + # + (0x00915, 0x00939,), # Devanagari Letter Ka ..Devanagari Letter Ha + (0x00958, 0x0095f,), # Devanagari Letter Qa ..Devanagari Letter Yya + (0x00978, 0x0097f,), # Devanagari Letter Marwar..Devanagari Letter Bba + (0x00995, 0x009a8,), # Bengali Letter Ka ..Bengali Letter Na + (0x009aa, 0x009b0,), # Bengali Letter Pa ..Bengali Letter Ra + (0x009b2, 0x009b2,), # Bengali Letter La + (0x009b6, 0x009b9,), # Bengali Letter Sha ..Bengali Letter Ha + (0x009dc, 0x009dd,), # Bengali Letter Rra ..Bengali Letter Rha + (0x009df, 0x009df,), # Bengali Letter Yya + (0x009f0, 0x009f1,), # Bengali Letter Ra With M..Bengali Letter Ra With L + (0x00a95, 0x00aa8,), # Gujarati Letter Ka ..Gujarati Letter Na + (0x00aaa, 0x00ab0,), # Gujarati Letter Pa ..Gujarati Letter Ra + (0x00ab2, 0x00ab3,), # Gujarati Letter La ..Gujarati Letter Lla + (0x00ab5, 0x00ab9,), # Gujarati Letter Va ..Gujarati Letter Ha + (0x00af9, 0x00af9,), # Gujarati Letter Zha + (0x00b15, 0x00b28,), # Oriya Letter Ka ..Oriya Letter Na + (0x00b2a, 0x00b30,), # Oriya Letter Pa ..Oriya Letter Ra + (0x00b32, 0x00b33,), # Oriya Letter La ..Oriya Letter Lla + (0x00b35, 0x00b39,), # Oriya Letter Va ..Oriya Letter Ha + (0x00b5c, 0x00b5d,), # Oriya Letter Rra ..Oriya Letter Rha + (0x00b5f, 0x00b5f,), # Oriya Letter Yya + (0x00b71, 0x00b71,), # Oriya Letter Wa + (0x00c15, 0x00c28,), # Telugu Letter Ka ..Telugu Letter Na + (0x00c2a, 0x00c39,), # Telugu Letter Pa ..Telugu Letter Ha + (0x00c58, 0x00c5a,), # Telugu Letter Tsa ..Telugu Letter Rrra + (0x00d15, 0x00d3a,), # Malayalam Letter Ka ..Malayalam Letter Ttta + (0x01000, 0x0102a,), # Myanmar Letter Ka ..Myanmar Letter Au + (0x0103f, 0x0103f,), # Myanmar Letter Great Sa + (0x01050, 0x01055,), # Myanmar Letter Sha ..Myanmar Letter Vocalic L + (0x0105a, 0x0105d,), # Myanmar Letter Mon Nga ..Myanmar Letter Mon Bbe + (0x01061, 0x01061,), # Myanmar Letter Sgaw Karen Sha + (0x01065, 0x01066,), # Myanmar Letter Western P..Myanmar Letter Western P + (0x0106e, 0x01070,), # Myanmar Letter Eastern P..Myanmar Letter Eastern P + (0x01075, 0x01081,), # Myanmar Letter Shan Ka ..Myanmar Letter Shan Ha + (0x0108e, 0x0108e,), # Myanmar Letter Rumai Palaung Fa + (0x01780, 0x017b3,), # Khmer Letter Ka ..Khmer Independent Vowel + (0x01a20, 0x01a54,), # Tai Tham Letter High Ka ..Tai Tham Letter Great Sa + (0x01b0b, 0x01b0c,), # Balinese Letter Ra Repa ..Balinese Letter Ra Repa + (0x01b13, 0x01b33,), # Balinese Letter Ka ..Balinese Letter Ha + (0x01b45, 0x01b4c,), # Balinese Letter Kaf Sasa..Balinese Letter Archaic + (0x01b83, 0x01ba0,), # Sundanese Letter A ..Sundanese Letter Ha + (0x01bae, 0x01baf,), # Sundanese Letter Kha ..Sundanese Letter Sya + (0x01bbb, 0x01bbd,), # Sundanese Letter Reu ..Sundanese Letter Bha + (0x0a989, 0x0a98b,), # Javanese Letter Pa Cerek..Javanese Letter Nga Lele + (0x0a98f, 0x0a9b2,), # Javanese Letter Ka ..Javanese Letter Ha + (0x0a9e0, 0x0a9e4,), # Myanmar Letter Shan Gha ..Myanmar Letter Shan Bha + (0x0a9e7, 0x0a9ef,), # Myanmar Letter Tai Laing..Myanmar Letter Tai Laing + (0x0a9fa, 0x0a9fe,), # Myanmar Letter Tai Laing..Myanmar Letter Tai Laing + (0x0aa60, 0x0aa6f,), # Myanmar Letter Khamti Ga..Myanmar Letter Khamti Fa + (0x0aa71, 0x0aa73,), # Myanmar Letter Khamti Xa..Myanmar Letter Khamti Ra + (0x0aa7a, 0x0aa7a,), # Myanmar Letter Aiton Ra + (0x0aa7e, 0x0aa7f,), # Myanmar Letter Shwe Pala..Myanmar Letter Shwe Pala + (0x0aae0, 0x0aaea,), # Meetei Mayek Letter E ..Meetei Mayek Letter Ssa + (0x0abc0, 0x0abda,), # Meetei Mayek Letter Kok ..Meetei Mayek Letter Bham + (0x10a00, 0x10a00,), # Kharoshthi Letter A + (0x10a10, 0x10a13,), # Kharoshthi Letter Ka ..Kharoshthi Letter Gha + (0x10a15, 0x10a17,), # Kharoshthi Letter Ca ..Kharoshthi Letter Ja + (0x10a19, 0x10a35,), # Kharoshthi Letter Nya ..Kharoshthi Letter Vha + (0x11103, 0x11126,), # Chakma Letter Aa ..Chakma Letter Haa + (0x11144, 0x11144,), # Chakma Letter Lhaa + (0x11147, 0x11147,), # Chakma Letter Vaa + (0x11380, 0x11389,), # Tulu-tigalari Letter A ..Tulu-tigalari Letter Voc + (0x1138b, 0x1138b,), # Tulu-tigalari Letter Ee + (0x1138e, 0x1138e,), # Tulu-tigalari Letter Ai + (0x11390, 0x113b5,), # Tulu-tigalari Letter Oo ..Tulu-tigalari Letter Lll + (0x11900, 0x11906,), # Dives Akuru Letter A ..Dives Akuru Letter E + (0x11909, 0x11909,), # Dives Akuru Letter O + (0x1190c, 0x11913,), # Dives Akuru Letter Ka ..Dives Akuru Letter Ja + (0x11915, 0x11916,), # Dives Akuru Letter Nya ..Dives Akuru Letter Tta + (0x11918, 0x1192f,), # Dives Akuru Letter Dda ..Dives Akuru Letter Za + (0x11a00, 0x11a00,), # Zanabazar Square Letter A + (0x11a0b, 0x11a32,), # Zanabazar Square Letter ..Zanabazar Square Letter + (0x11a50, 0x11a50,), # Soyombo Letter A + (0x11a5c, 0x11a83,), # Soyombo Letter Ka ..Soyombo Letter Kssa + (0x11b0a, 0x11b0a,), # Devanagari Letter Alternate Ddda + (0x11df1, 0x11df1,), # Bengali Letter Alternate Bargiya Ba + (0x11f04, 0x11f10,), # Kawi Letter A ..Kawi Letter O + (0x11f12, 0x11f33,), # Kawi Letter Ka ..Kawi Letter Jnya +) + +INCB_EXTEND = ( + # Source: DerivedCoreProperties + # Date: see file + # + (0x00300, 0x0036f,), # Combining Grave Accent ..Combining Latin Small Le + (0x00483, 0x00489,), # Combining Cyrillic Titlo..Combining Cyrillic Milli + (0x00591, 0x005bd,), # Hebrew Accent Etnahta ..Hebrew Point Meteg + (0x005bf, 0x005bf,), # Hebrew Point Rafe + (0x005c1, 0x005c2,), # Hebrew Point Shin Dot ..Hebrew Point Sin Dot + (0x005c4, 0x005c5,), # Hebrew Mark Upper Dot ..Hebrew Mark Lower Dot + (0x005c7, 0x005c9,), # Hebrew Point Qamats Qata..Hebrew Point Dagesh Haza + (0x00610, 0x0061a,), # Arabic Sign Sallallahou ..Arabic Small Kasra + (0x0064b, 0x0065f,), # Arabic Fathatan ..Arabic Wavy Hamza Below + (0x00670, 0x00670,), # Arabic Letter Superscript Alef + (0x006d6, 0x006dc,), # Arabic Small High Ligatu..Arabic Small High Seen + (0x006df, 0x006e4,), # Arabic Small High Rounde..Arabic Small High Madda + (0x006e7, 0x006e8,), # Arabic Small High Yeh ..Arabic Small High Noon + (0x006ea, 0x006ed,), # Arabic Empty Centre Low ..Arabic Small Low Meem + (0x00711, 0x00711,), # Syriac Letter Superscript Alaph + (0x00730, 0x0074a,), # Syriac Pthaha Above ..Syriac Barrekh + (0x007a6, 0x007b0,), # Thaana Abafili ..Thaana Sukun + (0x007eb, 0x007f3,), # Nko Combining Short High..Nko Combining Double Dot + (0x007fd, 0x007fd,), # Nko Dantayalan + (0x00816, 0x00819,), # Samaritan Mark In ..Samaritan Mark Dagesh + (0x0081b, 0x00823,), # Samaritan Mark Epentheti..Samaritan Vowel Sign A + (0x00825, 0x00827,), # Samaritan Vowel Sign Sho..Samaritan Vowel Sign U + (0x00829, 0x0082d,), # Samaritan Vowel Sign Lon..Samaritan Mark Nequdaa + (0x00859, 0x0085b,), # Mandaic Affrication Mark..Mandaic Gemination Mark + (0x00897, 0x0089f,), # Arabic Pepet ..Arabic Half Madda Over M + (0x008ca, 0x008e1,), # Arabic Small High Farsi ..Arabic Small High Sign S + (0x008e3, 0x00902,), # Arabic Turned Damma Belo..Devanagari Sign Anusvara + (0x0093a, 0x0093a,), # Devanagari Vowel Sign Oe + (0x0093c, 0x0093c,), # Devanagari Sign Nukta + (0x00941, 0x00948,), # Devanagari Vowel Sign U ..Devanagari Vowel Sign Ai + (0x00951, 0x00957,), # Devanagari Stress Sign U..Devanagari Vowel Sign Uu + (0x00962, 0x00963,), # Devanagari Vowel Sign Vo..Devanagari Vowel Sign Vo + (0x00981, 0x00981,), # Bengali Sign Candrabindu + (0x009bc, 0x009bc,), # Bengali Sign Nukta + (0x009be, 0x009be,), # Bengali Vowel Sign Aa + (0x009c1, 0x009c4,), # Bengali Vowel Sign U ..Bengali Vowel Sign Vocal + (0x009d7, 0x009d7,), # Bengali Au Length Mark + (0x009e2, 0x009e3,), # Bengali Vowel Sign Vocal..Bengali Vowel Sign Vocal + (0x009fe, 0x009fe,), # Bengali Sandhi Mark + (0x00a01, 0x00a02,), # Gurmukhi Sign Adak Bindi..Gurmukhi Sign Bindi + (0x00a3c, 0x00a3c,), # Gurmukhi Sign Nukta + (0x00a41, 0x00a42,), # Gurmukhi Vowel Sign U ..Gurmukhi Vowel Sign Uu + (0x00a47, 0x00a48,), # Gurmukhi Vowel Sign Ee ..Gurmukhi Vowel Sign Ai + (0x00a4b, 0x00a4d,), # Gurmukhi Vowel Sign Oo ..Gurmukhi Sign Virama + (0x00a51, 0x00a51,), # Gurmukhi Sign Udaat + (0x00a70, 0x00a71,), # Gurmukhi Tippi ..Gurmukhi Addak + (0x00a75, 0x00a75,), # Gurmukhi Sign Yakash + (0x00a81, 0x00a82,), # Gujarati Sign Candrabind..Gujarati Sign Anusvara + (0x00abc, 0x00abc,), # Gujarati Sign Nukta + (0x00ac1, 0x00ac5,), # Gujarati Vowel Sign U ..Gujarati Vowel Sign Cand + (0x00ac7, 0x00ac8,), # Gujarati Vowel Sign E ..Gujarati Vowel Sign Ai + (0x00ae2, 0x00ae3,), # Gujarati Vowel Sign Voca..Gujarati Vowel Sign Voca + (0x00afa, 0x00aff,), # Gujarati Sign Sukun ..Gujarati Sign Two-circle + (0x00b01, 0x00b01,), # Oriya Sign Candrabindu + (0x00b3c, 0x00b3c,), # Oriya Sign Nukta + (0x00b3e, 0x00b3f,), # Oriya Vowel Sign Aa ..Oriya Vowel Sign I + (0x00b41, 0x00b44,), # Oriya Vowel Sign U ..Oriya Vowel Sign Vocalic + (0x00b53, 0x00b57,), # Oriya Sign Dot Above ..Oriya Au Length Mark + (0x00b62, 0x00b63,), # Oriya Vowel Sign Vocalic..Oriya Vowel Sign Vocalic + (0x00b82, 0x00b82,), # Tamil Sign Anusvara + (0x00bbe, 0x00bbe,), # Tamil Vowel Sign Aa + (0x00bc0, 0x00bc0,), # Tamil Vowel Sign Ii + (0x00bcd, 0x00bcd,), # Tamil Sign Virama + (0x00bd7, 0x00bd7,), # Tamil Au Length Mark + (0x00c00, 0x00c00,), # Telugu Sign Combining Candrabindu Above + (0x00c04, 0x00c04,), # Telugu Sign Combining Anusvara Above + (0x00c3c, 0x00c3c,), # Telugu Sign Nukta + (0x00c3e, 0x00c40,), # Telugu Vowel Sign Aa ..Telugu Vowel Sign Ii + (0x00c46, 0x00c48,), # Telugu Vowel Sign E ..Telugu Vowel Sign Ai + (0x00c4a, 0x00c4c,), # Telugu Vowel Sign O ..Telugu Vowel Sign Au + (0x00c55, 0x00c56,), # Telugu Length Mark ..Telugu Ai Length Mark + (0x00c62, 0x00c63,), # Telugu Vowel Sign Vocali..Telugu Vowel Sign Vocali + (0x00c81, 0x00c81,), # Kannada Sign Candrabindu + (0x00cbc, 0x00cbc,), # Kannada Sign Nukta + (0x00cbf, 0x00cc0,), # Kannada Vowel Sign I ..Kannada Vowel Sign Ii + (0x00cc2, 0x00cc2,), # Kannada Vowel Sign Uu + (0x00cc6, 0x00cc8,), # Kannada Vowel Sign E ..Kannada Vowel Sign Ai + (0x00cca, 0x00ccd,), # Kannada Vowel Sign O ..Kannada Sign Virama + (0x00cd5, 0x00cd6,), # Kannada Length Mark ..Kannada Ai Length Mark + (0x00ce2, 0x00ce3,), # Kannada Vowel Sign Vocal..Kannada Vowel Sign Vocal + (0x00d00, 0x00d01,), # Malayalam Sign Combining..Malayalam Sign Candrabin + (0x00d3b, 0x00d3c,), # Malayalam Sign Vertical ..Malayalam Sign Circular + (0x00d3e, 0x00d3e,), # Malayalam Vowel Sign Aa + (0x00d41, 0x00d44,), # Malayalam Vowel Sign U ..Malayalam Vowel Sign Voc + (0x00d57, 0x00d57,), # Malayalam Au Length Mark + (0x00d62, 0x00d63,), # Malayalam Vowel Sign Voc..Malayalam Vowel Sign Voc + (0x00d81, 0x00d81,), # Sinhala Sign Candrabindu + (0x00dca, 0x00dca,), # Sinhala Sign Al-lakuna + (0x00dcf, 0x00dcf,), # Sinhala Vowel Sign Aela-pilla + (0x00dd2, 0x00dd4,), # Sinhala Vowel Sign Ketti..Sinhala Vowel Sign Ketti + (0x00dd6, 0x00dd6,), # Sinhala Vowel Sign Diga Paa-pilla + (0x00ddf, 0x00ddf,), # Sinhala Vowel Sign Gayanukitta + (0x00e31, 0x00e31,), # Thai Character Mai Han-akat + (0x00e34, 0x00e3a,), # Thai Character Sara I ..Thai Character Phinthu + (0x00e47, 0x00e4e,), # Thai Character Maitaikhu..Thai Character Yamakkan + (0x00eb1, 0x00eb1,), # Lao Vowel Sign Mai Kan + (0x00eb4, 0x00ebc,), # Lao Vowel Sign I ..Lao Semivowel Sign Lo + (0x00ec8, 0x00ece,), # Lao Tone Mai Ek ..Lao Yamakkan + (0x00f18, 0x00f19,), # Tibetan Astrological Sig..Tibetan Astrological Sig + (0x00f35, 0x00f35,), # Tibetan Mark Ngas Bzung Nyi Zla + (0x00f37, 0x00f37,), # Tibetan Mark Ngas Bzung Sgor Rtags + (0x00f39, 0x00f39,), # Tibetan Mark Tsa -phru + (0x00f71, 0x00f7e,), # Tibetan Vowel Sign Aa ..Tibetan Sign Rjes Su Nga + (0x00f80, 0x00f84,), # Tibetan Vowel Sign Rever..Tibetan Mark Halanta + (0x00f86, 0x00f87,), # Tibetan Sign Lci Rtags ..Tibetan Sign Yang Rtags + (0x00f8d, 0x00f97,), # Tibetan Subjoined Sign L..Tibetan Subjoined Letter + (0x00f99, 0x00fbc,), # Tibetan Subjoined Letter..Tibetan Subjoined Letter + (0x00fc6, 0x00fc6,), # Tibetan Symbol Padma Gdan + (0x0102d, 0x01030,), # Myanmar Vowel Sign I ..Myanmar Vowel Sign Uu + (0x01032, 0x01037,), # Myanmar Vowel Sign Ai ..Myanmar Sign Dot Below + (0x0103a, 0x0103a,), # Myanmar Sign Asat + (0x0103d, 0x0103e,), # Myanmar Consonant Sign M..Myanmar Consonant Sign M + (0x01058, 0x01059,), # Myanmar Vowel Sign Vocal..Myanmar Vowel Sign Vocal + (0x0105e, 0x01060,), # Myanmar Consonant Sign M..Myanmar Consonant Sign M + (0x01071, 0x01074,), # Myanmar Vowel Sign Geba ..Myanmar Vowel Sign Kayah + (0x01082, 0x01082,), # Myanmar Consonant Sign Shan Medial Wa + (0x01085, 0x01086,), # Myanmar Vowel Sign Shan ..Myanmar Vowel Sign Shan + (0x0108d, 0x0108d,), # Myanmar Sign Shan Council Emphatic Tone + (0x0109d, 0x0109d,), # Myanmar Vowel Sign Aiton Ai + (0x0135d, 0x0135f,), # Ethiopic Combining Gemin..Ethiopic Combining Gemin + (0x01712, 0x01715,), # Tagalog Vowel Sign I ..Tagalog Sign Pamudpod + (0x01732, 0x01734,), # Hanunoo Vowel Sign I ..Hanunoo Sign Pamudpod + (0x01752, 0x01753,), # Buhid Vowel Sign I ..Buhid Vowel Sign U + (0x01772, 0x01773,), # Tagbanwa Vowel Sign I ..Tagbanwa Vowel Sign U + (0x017b4, 0x017b5,), # Khmer Vowel Inherent Aq ..Khmer Vowel Inherent Aa + (0x017b7, 0x017bd,), # Khmer Vowel Sign I ..Khmer Vowel Sign Ua + (0x017c6, 0x017c6,), # Khmer Sign Nikahit + (0x017c9, 0x017d1,), # Khmer Sign Muusikatoan ..Khmer Sign Viriam + (0x017d3, 0x017d3,), # Khmer Sign Bathamasat + (0x017dd, 0x017dd,), # Khmer Sign Atthacan + (0x0180b, 0x0180d,), # Mongolian Free Variation..Mongolian Free Variation + (0x0180f, 0x0180f,), # Mongolian Free Variation Selector Four + (0x01885, 0x01886,), # Mongolian Letter Ali Gal..Mongolian Letter Ali Gal + (0x018a9, 0x018a9,), # Mongolian Letter Ali Gali Dagalga + (0x01920, 0x01922,), # Limbu Vowel Sign A ..Limbu Vowel Sign U + (0x01927, 0x01928,), # Limbu Vowel Sign E ..Limbu Vowel Sign O + (0x01932, 0x01932,), # Limbu Small Letter Anusvara + (0x01939, 0x0193b,), # Limbu Sign Mukphreng ..Limbu Sign Sa-i + (0x01a17, 0x01a18,), # Buginese Vowel Sign I ..Buginese Vowel Sign U + (0x01a1b, 0x01a1b,), # Buginese Vowel Sign Ae + (0x01a56, 0x01a56,), # Tai Tham Consonant Sign Medial La + (0x01a58, 0x01a5e,), # Tai Tham Sign Mai Kang L..Tai Tham Consonant Sign + (0x01a62, 0x01a62,), # Tai Tham Vowel Sign Mai Sat + (0x01a65, 0x01a6c,), # Tai Tham Vowel Sign I ..Tai Tham Vowel Sign Oa B + (0x01a73, 0x01a7c,), # Tai Tham Vowel Sign Oa A..Tai Tham Sign Khuen-lue + (0x01a7f, 0x01a7f,), # Tai Tham Combining Cryptogrammic Dot + (0x01ab0, 0x01af0,), # Combining Doubled Circum..Combining Double Comma A + (0x01b00, 0x01b03,), # Balinese Sign Ulu Ricem ..Balinese Sign Surang + (0x01b34, 0x01b3d,), # Balinese Sign Rerekan ..Balinese Vowel Sign La L + (0x01b42, 0x01b43,), # Balinese Vowel Sign Pepe..Balinese Vowel Sign Pepe + (0x01b6b, 0x01b73,), # Balinese Musical Symbol ..Balinese Musical Symbol + (0x01b80, 0x01b81,), # Sundanese Sign Panyecek ..Sundanese Sign Panglayar + (0x01ba2, 0x01ba5,), # Sundanese Consonant Sign..Sundanese Vowel Sign Pan + (0x01ba8, 0x01baa,), # Sundanese Vowel Sign Pam..Sundanese Sign Pamaaeh + (0x01bac, 0x01bad,), # Sundanese Consonant Sign..Sundanese Consonant Sign + (0x01be6, 0x01be6,), # Batak Sign Tompi + (0x01be8, 0x01be9,), # Batak Vowel Sign Pakpak ..Batak Vowel Sign Ee + (0x01bed, 0x01bed,), # Batak Vowel Sign Karo O + (0x01bef, 0x01bf3,), # Batak Vowel Sign U For S..Batak Panongonan + (0x01c2c, 0x01c33,), # Lepcha Vowel Sign E ..Lepcha Consonant Sign T + (0x01c36, 0x01c37,), # Lepcha Sign Ran ..Lepcha Sign Nukta + (0x01cd0, 0x01cd2,), # Vedic Tone Karshana ..Vedic Tone Prenkha + (0x01cd4, 0x01ce0,), # Vedic Sign Yajurvedic Mi..Vedic Tone Rigvedic Kash + (0x01ce2, 0x01ce8,), # Vedic Sign Visarga Svari..Vedic Sign Visarga Anuda + (0x01ced, 0x01ced,), # Vedic Sign Tiryak + (0x01cf4, 0x01cf4,), # Vedic Tone Candra Above + (0x01cf8, 0x01cf9,), # Vedic Tone Ring Above ..Vedic Tone Double Ring A + (0x01dc0, 0x01dff,), # Combining Dotted Grave A..Combining Right Arrowhea + (0x0200d, 0x0200d,), # Zero Width Joiner + (0x020d0, 0x020f0,), # Combining Left Harpoon A..Combining Asterisk Above + (0x02cef, 0x02cf1,), # Coptic Combining Ni Abov..Coptic Combining Spiritu + (0x02d7f, 0x02d7f,), # Tifinagh Consonant Joiner + (0x02de0, 0x02dff,), # Combining Cyrillic Lette..Combining Cyrillic Lette + (0x0302a, 0x0302f,), # Ideographic Level Tone M..Hangul Double Dot Tone M + (0x03099, 0x0309a,), # Combining Katakana-hirag..Combining Katakana-hirag + (0x0a66f, 0x0a672,), # Combining Cyrillic Vzmet..Combining Cyrillic Thous + (0x0a674, 0x0a67d,), # Combining Cyrillic Lette..Combining Cyrillic Payer + (0x0a69e, 0x0a69f,), # Combining Cyrillic Lette..Combining Cyrillic Lette + (0x0a6f0, 0x0a6f1,), # Bamum Combining Mark Koq..Bamum Combining Mark Tuk + (0x0a802, 0x0a802,), # Syloti Nagri Sign Dvisvara + (0x0a806, 0x0a806,), # Syloti Nagri Sign Hasanta + (0x0a80b, 0x0a80b,), # Syloti Nagri Sign Anusvara + (0x0a825, 0x0a826,), # Syloti Nagri Vowel Sign ..Syloti Nagri Vowel Sign + (0x0a82c, 0x0a82c,), # Syloti Nagri Sign Alternate Hasanta + (0x0a8c4, 0x0a8c5,), # Saurashtra Sign Virama ..Saurashtra Sign Candrabi + (0x0a8e0, 0x0a8f1,), # Combining Devanagari Dig..Combining Devanagari Sig + (0x0a8ff, 0x0a8ff,), # Devanagari Vowel Sign Ay + (0x0a926, 0x0a92d,), # Kayah Li Vowel Ue ..Kayah Li Tone Calya Plop + (0x0a947, 0x0a951,), # Rejang Vowel Sign I ..Rejang Consonant Sign R + (0x0a953, 0x0a953,), # Rejang Virama + (0x0a980, 0x0a982,), # Javanese Sign Panyangga ..Javanese Sign Layar + (0x0a9b3, 0x0a9b3,), # Javanese Sign Cecak Telu + (0x0a9b6, 0x0a9b9,), # Javanese Vowel Sign Wulu..Javanese Vowel Sign Suku + (0x0a9bc, 0x0a9bd,), # Javanese Vowel Sign Pepe..Javanese Consonant Sign + (0x0a9e5, 0x0a9e5,), # Myanmar Sign Shan Saw + (0x0aa29, 0x0aa2e,), # Cham Vowel Sign Aa ..Cham Vowel Sign Oe + (0x0aa31, 0x0aa32,), # Cham Vowel Sign Au ..Cham Vowel Sign Ue + (0x0aa35, 0x0aa36,), # Cham Consonant Sign La ..Cham Consonant Sign Wa + (0x0aa43, 0x0aa43,), # Cham Consonant Sign Final Ng + (0x0aa4c, 0x0aa4c,), # Cham Consonant Sign Final M + (0x0aa7c, 0x0aa7c,), # Myanmar Sign Tai Laing Tone-2 + (0x0aab0, 0x0aab0,), # Tai Viet Mai Kang + (0x0aab2, 0x0aab4,), # Tai Viet Vowel I ..Tai Viet Vowel U + (0x0aab7, 0x0aab8,), # Tai Viet Mai Khit ..Tai Viet Vowel Ia + (0x0aabe, 0x0aabf,), # Tai Viet Vowel Am ..Tai Viet Tone Mai Ek + (0x0aac1, 0x0aac1,), # Tai Viet Tone Mai Tho + (0x0aaec, 0x0aaed,), # Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + (0x0abe5, 0x0abe5,), # Meetei Mayek Vowel Sign Anap + (0x0abe8, 0x0abe8,), # Meetei Mayek Vowel Sign Unap + (0x0abed, 0x0abed,), # Meetei Mayek Apun Iyek + (0x0fb1e, 0x0fb1e,), # Hebrew Point Judeo-spanish Varika + (0x0fe00, 0x0fe0f,), # Variation Selector-1 ..Variation Selector-16 + (0x0fe20, 0x0fe2f,), # Combining Ligature Left ..Combining Cyrillic Titlo + (0x0ff9e, 0x0ff9f,), # Halfwidth Katakana Voice..Halfwidth Katakana Semi- + (0x101fd, 0x101fd,), # Phaistos Disc Sign Combining Oblique Stroke + (0x102e0, 0x102e0,), # Coptic Epact Thousands Mark + (0x10376, 0x1037a,), # Combining Old Permic Let..Combining Old Permic Let + (0x10a01, 0x10a03,), # Kharoshthi Vowel Sign I ..Kharoshthi Vowel Sign Vo + (0x10a05, 0x10a06,), # Kharoshthi Vowel Sign E ..Kharoshthi Vowel Sign O + (0x10a0c, 0x10a0f,), # Kharoshthi Vowel Length ..Kharoshthi Sign Visarga + (0x10a38, 0x10a3a,), # Kharoshthi Sign Bar Abov..Kharoshthi Sign Dot Belo + (0x10ae5, 0x10ae6,), # Manichaean Abbreviation ..Manichaean Abbreviation + (0x10d24, 0x10d27,), # Hanifi Rohingya Sign Har..Hanifi Rohingya Sign Tas + (0x10d69, 0x10d6d,), # Garay Vowel Sign E ..Garay Consonant Nasaliza + (0x10eab, 0x10eac,), # Yezidi Combining Hamza M..Yezidi Combining Madda M + (0x10ecb, 0x10ecf,), # Arabic Northeast Pointin..Arabic Large Circle Abov + (0x10ef0, 0x10eff,), # Arabic Small Low Upright..Arabic Small Low Word Ma + (0x10f46, 0x10f50,), # Sogdian Combining Dot Be..Sogdian Combining Stroke + (0x10f82, 0x10f85,), # Old Uyghur Combining Dot..Old Uyghur Combining Two + (0x11001, 0x11001,), # Brahmi Sign Anusvara + (0x11038, 0x11046,), # Brahmi Vowel Sign Aa ..Brahmi Virama + (0x11070, 0x11070,), # Brahmi Sign Old Tamil Virama + (0x11073, 0x11074,), # Brahmi Vowel Sign Old Ta..Brahmi Vowel Sign Old Ta + (0x1107f, 0x11081,), # Brahmi Number Joiner ..Kaithi Sign Anusvara + (0x110b3, 0x110b6,), # Kaithi Vowel Sign U ..Kaithi Vowel Sign Ai + (0x110b9, 0x110ba,), # Kaithi Sign Virama ..Kaithi Sign Nukta + (0x110c2, 0x110c2,), # Kaithi Vowel Sign Vocalic R + (0x11100, 0x11102,), # Chakma Sign Candrabindu ..Chakma Sign Visarga + (0x11127, 0x1112b,), # Chakma Vowel Sign A ..Chakma Vowel Sign Uu + (0x1112d, 0x11132,), # Chakma Vowel Sign Ai ..Chakma Au Mark + (0x11134, 0x11134,), # Chakma Maayyaa + (0x11173, 0x11173,), # Mahajani Sign Nukta + (0x11180, 0x11181,), # Sharada Sign Candrabindu..Sharada Sign Anusvara + (0x111b6, 0x111be,), # Sharada Vowel Sign U ..Sharada Vowel Sign O + (0x111c0, 0x111c0,), # Sharada Sign Virama + (0x111c9, 0x111cc,), # Sharada Sandhi Mark ..Sharada Extra Short Vowe + (0x111cf, 0x111cf,), # Sharada Sign Inverted Candrabindu + (0x1122f, 0x11231,), # Khojki Vowel Sign U ..Khojki Vowel Sign Ai + (0x11234, 0x11237,), # Khojki Sign Anusvara ..Khojki Sign Shadda + (0x1123e, 0x1123e,), # Khojki Sign Sukun + (0x11241, 0x11241,), # Khojki Vowel Sign Vocalic R + (0x112df, 0x112df,), # Khudawadi Sign Anusvara + (0x112e3, 0x112ea,), # Khudawadi Vowel Sign U ..Khudawadi Sign Virama + (0x11300, 0x11301,), # Grantha Sign Combining A..Grantha Sign Candrabindu + (0x1133b, 0x1133c,), # Combining Bindu Below ..Grantha Sign Nukta + (0x1133e, 0x1133e,), # Grantha Vowel Sign Aa + (0x11340, 0x11340,), # Grantha Vowel Sign Ii + (0x1134d, 0x1134d,), # Grantha Sign Virama + (0x11357, 0x11357,), # Grantha Au Length Mark + (0x11366, 0x1136c,), # Combining Grantha Digit ..Combining Grantha Digit + (0x11370, 0x11374,), # Combining Grantha Letter..Combining Grantha Letter + (0x113b8, 0x113b8,), # Tulu-tigalari Vowel Sign Aa + (0x113bb, 0x113c0,), # Tulu-tigalari Vowel Sign..Tulu-tigalari Vowel Sign + (0x113c2, 0x113c2,), # Tulu-tigalari Vowel Sign Ee + (0x113c5, 0x113c5,), # Tulu-tigalari Vowel Sign Ai + (0x113c7, 0x113c9,), # Tulu-tigalari Vowel Sign..Tulu-tigalari Au Length + (0x113ce, 0x113cf,), # Tulu-tigalari Sign Viram..Tulu-tigalari Sign Loope + (0x113d2, 0x113d2,), # Tulu-tigalari Gemination Mark + (0x113e1, 0x113e2,), # Tulu-tigalari Vedic Tone..Tulu-tigalari Vedic Tone + (0x11438, 0x1143f,), # Newa Vowel Sign U ..Newa Vowel Sign Ai + (0x11442, 0x11444,), # Newa Sign Virama ..Newa Sign Anusvara + (0x11446, 0x11446,), # Newa Sign Nukta + (0x1145e, 0x1145e,), # Newa Sandhi Mark + (0x114b0, 0x114b0,), # Tirhuta Vowel Sign Aa + (0x114b3, 0x114b8,), # Tirhuta Vowel Sign U ..Tirhuta Vowel Sign Vocal + (0x114ba, 0x114ba,), # Tirhuta Vowel Sign Short E + (0x114bd, 0x114bd,), # Tirhuta Vowel Sign Short O + (0x114bf, 0x114c0,), # Tirhuta Sign Candrabindu..Tirhuta Sign Anusvara + (0x114c2, 0x114c3,), # Tirhuta Sign Virama ..Tirhuta Sign Nukta + (0x115af, 0x115af,), # Siddham Vowel Sign Aa + (0x115b2, 0x115b5,), # Siddham Vowel Sign U ..Siddham Vowel Sign Vocal + (0x115bc, 0x115bd,), # Siddham Sign Candrabindu..Siddham Sign Anusvara + (0x115bf, 0x115c0,), # Siddham Sign Virama ..Siddham Sign Nukta + (0x115dc, 0x115dd,), # Siddham Vowel Sign Alter..Siddham Vowel Sign Alter + (0x11633, 0x1163a,), # Modi Vowel Sign U ..Modi Vowel Sign Ai + (0x1163d, 0x1163d,), # Modi Sign Anusvara + (0x1163f, 0x11640,), # Modi Sign Virama ..Modi Sign Ardhacandra + (0x116ab, 0x116ab,), # Takri Sign Anusvara + (0x116ad, 0x116ad,), # Takri Vowel Sign Aa + (0x116b0, 0x116b7,), # Takri Vowel Sign U ..Takri Sign Nukta + (0x1171d, 0x1171d,), # Ahom Consonant Sign Medial La + (0x1171f, 0x1171f,), # Ahom Consonant Sign Medial Ligating Ra + (0x11722, 0x11725,), # Ahom Vowel Sign I ..Ahom Vowel Sign Uu + (0x11727, 0x1172b,), # Ahom Vowel Sign Aw ..Ahom Sign Killer + (0x1182f, 0x11837,), # Dogra Vowel Sign U ..Dogra Sign Anusvara + (0x11839, 0x1183a,), # Dogra Sign Virama ..Dogra Sign Nukta + (0x11930, 0x11930,), # Dives Akuru Vowel Sign Aa + (0x1193b, 0x1193d,), # Dives Akuru Sign Anusvar..Dives Akuru Sign Halanta + (0x11943, 0x11943,), # Dives Akuru Sign Nukta + (0x119d4, 0x119d7,), # Nandinagari Vowel Sign U..Nandinagari Vowel Sign V + (0x119da, 0x119db,), # Nandinagari Vowel Sign E..Nandinagari Vowel Sign A + (0x119e0, 0x119e0,), # Nandinagari Sign Virama + (0x11a01, 0x11a0a,), # Zanabazar Square Vowel S..Zanabazar Square Vowel L + (0x11a33, 0x11a38,), # Zanabazar Square Final C..Zanabazar Square Sign An + (0x11a3b, 0x11a3e,), # Zanabazar Square Cluster..Zanabazar Square Cluster + (0x11a51, 0x11a56,), # Soyombo Vowel Sign I ..Soyombo Vowel Sign Oe + (0x11a59, 0x11a5b,), # Soyombo Vowel Sign Vocal..Soyombo Vowel Length Mar + (0x11a8a, 0x11a96,), # Soyombo Final Consonant ..Soyombo Sign Anusvara + (0x11a98, 0x11a98,), # Soyombo Gemination Mark + (0x11b60, 0x11b60,), # Sharada Vowel Sign Oe + (0x11b62, 0x11b64,), # Sharada Vowel Sign Ue ..Sharada Vowel Sign Short + (0x11b66, 0x11b66,), # Sharada Vowel Sign Candra E + (0x11c30, 0x11c36,), # Bhaiksuki Vowel Sign I ..Bhaiksuki Vowel Sign Voc + (0x11c38, 0x11c3d,), # Bhaiksuki Vowel Sign E ..Bhaiksuki Sign Anusvara + (0x11c3f, 0x11c3f,), # Bhaiksuki Sign Virama + (0x11c92, 0x11ca7,), # Marchen Subjoined Letter..Marchen Subjoined Letter + (0x11caa, 0x11cb0,), # Marchen Subjoined Letter..Marchen Vowel Sign Aa + (0x11cb2, 0x11cb3,), # Marchen Vowel Sign U ..Marchen Vowel Sign E + (0x11cb5, 0x11cb6,), # Marchen Sign Anusvara ..Marchen Sign Candrabindu + (0x11d31, 0x11d36,), # Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign + (0x11d3a, 0x11d3a,), # Masaram Gondi Vowel Sign E + (0x11d3c, 0x11d3d,), # Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign + (0x11d3f, 0x11d45,), # Masaram Gondi Vowel Sign..Masaram Gondi Virama + (0x11d47, 0x11d47,), # Masaram Gondi Ra-kara + (0x11d90, 0x11d91,), # Gunjala Gondi Vowel Sign..Gunjala Gondi Vowel Sign + (0x11d95, 0x11d95,), # Gunjala Gondi Sign Anusvara + (0x11d97, 0x11d97,), # Gunjala Gondi Virama + (0x11df0, 0x11df0,), # Bengali Sign Combining Anusvara Above + (0x11ef3, 0x11ef4,), # Makasar Vowel Sign I ..Makasar Vowel Sign U + (0x11f00, 0x11f01,), # Kawi Sign Candrabindu ..Kawi Sign Anusvara + (0x11f36, 0x11f3a,), # Kawi Vowel Sign I ..Kawi Vowel Sign Vocalic + (0x11f40, 0x11f41,), # Kawi Vowel Sign Eu ..Kawi Sign Killer + (0x11f5a, 0x11f5a,), # Kawi Sign Nukta + (0x13440, 0x13440,), # Egyptian Hieroglyph Mirror Horizontally + (0x13447, 0x13455,), # Egyptian Hieroglyph Modi..Egyptian Hieroglyph Modi + (0x1611e, 0x16129,), # Gurung Khema Vowel Sign ..Gurung Khema Vowel Lengt + (0x1612d, 0x1612f,), # Gurung Khema Sign Anusva..Gurung Khema Sign Tholho + (0x16af0, 0x16af4,), # Bassa Vah Combining High..Bassa Vah Combining High + (0x16b30, 0x16b36,), # Pahawh Hmong Mark Cim Tu..Pahawh Hmong Mark Cim Ta + (0x16f4f, 0x16f4f,), # Miao Sign Consonant Modifier Bar + (0x16f8f, 0x16f92,), # Miao Tone Right ..Miao Tone Below + (0x16fe4, 0x16fe4,), # Khitan Small Script Filler + (0x16ff0, 0x16ff1,), # Vietnamese Alternate Rea..Vietnamese Alternate Rea + (0x1bc9d, 0x1bc9e,), # Duployan Thick Letter Se..Duployan Double Mark + (0x1cf00, 0x1cf2d,), # Znamenny Combining Mark ..Znamenny Combining Mark + (0x1cf30, 0x1cf46,), # Znamenny Combining Tonal..Znamenny Priznak Modifie + (0x1d127, 0x1d128,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d165, 0x1d169,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d16d, 0x1d172,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d17b, 0x1d182,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d185, 0x1d18b,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d1aa, 0x1d1ad,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d242, 0x1d244,), # Combining Greek Musical ..Combining Greek Musical + (0x1d250, 0x1d252,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d25b, 0x1d25c,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d25f, 0x1d25f,), # Musical Symbol Combining Buzz Roll Stem + (0x1d280, 0x1d281,), # Musical Symbol Combining..Musical Symbol Combining + (0x1da00, 0x1da36,), # Signwriting Head Rim ..Signwriting Air Sucking + (0x1da3b, 0x1da6c,), # Signwriting Mouth Closed..Signwriting Excitement + (0x1da75, 0x1da75,), # Signwriting Upper Body Tilting From Hip Joints + (0x1da84, 0x1da84,), # Signwriting Location Head Neck + (0x1da9b, 0x1da9f,), # Signwriting Fill Modifie..Signwriting Fill Modifie + (0x1daa1, 0x1daaf,), # Signwriting Rotation Mod..Signwriting Rotation Mod + (0x1e000, 0x1e006,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e008, 0x1e018,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e01b, 0x1e021,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e023, 0x1e024,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e026, 0x1e02a,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e08f, 0x1e08f,), # Combining Cyrillic Small Letter Byelorussian-ukr + (0x1e130, 0x1e136,), # Nyiakeng Puachue Hmong T..Nyiakeng Puachue Hmong T + (0x1e2ae, 0x1e2ae,), # Toto Sign Rising Tone + (0x1e2ec, 0x1e2ef,), # Wancho Tone Tup ..Wancho Tone Koini + (0x1e4ec, 0x1e4ef,), # Nag Mundari Sign Muhor ..Nag Mundari Sign Sutuh + (0x1e5ee, 0x1e5ef,), # Ol Onal Sign Mu ..Ol Onal Sign Ikir + (0x1e6e3, 0x1e6e3,), # Tai Yo Sign Ue + (0x1e6e6, 0x1e6e6,), # Tai Yo Sign Au + (0x1e6ee, 0x1e6ef,), # Tai Yo Sign Ay ..Tai Yo Sign Ang + (0x1e6f5, 0x1e6f5,), # Tai Yo Sign Om + (0x1e8d0, 0x1e8d6,), # Mende Kikakui Combining ..Mende Kikakui Combining + (0x1e944, 0x1e94a,), # Adlam Alif Lengthener ..Adlam Nukta + (0x1f3fb, 0x1f3ff,), # Emoji Modifier Fitzpatri..Emoji Modifier Fitzpatri + (0xe0020, 0xe007f,), # Tag Space ..Cancel Tag + (0xe0100, 0xe01ef,), # Variation Selector-17 ..Variation Selector-256 +) + +ISC_CONSONANT = ( + # Source: IndicSyllabicCategory + # Date: see file + # + (0x00915, 0x00939,), # Devanagari Letter Ka ..Devanagari Letter Ha + (0x00958, 0x0095f,), # Devanagari Letter Qa ..Devanagari Letter Yya + (0x00978, 0x0097f,), # Devanagari Letter Marwar..Devanagari Letter Bba + (0x00995, 0x009a8,), # Bengali Letter Ka ..Bengali Letter Na + (0x009aa, 0x009b0,), # Bengali Letter Pa ..Bengali Letter Ra + (0x009b2, 0x009b2,), # Bengali Letter La + (0x009b6, 0x009b9,), # Bengali Letter Sha ..Bengali Letter Ha + (0x009dc, 0x009dd,), # Bengali Letter Rra ..Bengali Letter Rha + (0x009df, 0x009df,), # Bengali Letter Yya + (0x009f0, 0x009f1,), # Bengali Letter Ra With M..Bengali Letter Ra With L + (0x00a15, 0x00a28,), # Gurmukhi Letter Ka ..Gurmukhi Letter Na + (0x00a2a, 0x00a30,), # Gurmukhi Letter Pa ..Gurmukhi Letter Ra + (0x00a32, 0x00a33,), # Gurmukhi Letter La ..Gurmukhi Letter Lla + (0x00a35, 0x00a36,), # Gurmukhi Letter Va ..Gurmukhi Letter Sha + (0x00a38, 0x00a39,), # Gurmukhi Letter Sa ..Gurmukhi Letter Ha + (0x00a59, 0x00a5c,), # Gurmukhi Letter Khha ..Gurmukhi Letter Rra + (0x00a5e, 0x00a5e,), # Gurmukhi Letter Fa + (0x00a95, 0x00aa8,), # Gujarati Letter Ka ..Gujarati Letter Na + (0x00aaa, 0x00ab0,), # Gujarati Letter Pa ..Gujarati Letter Ra + (0x00ab2, 0x00ab3,), # Gujarati Letter La ..Gujarati Letter Lla + (0x00ab5, 0x00ab9,), # Gujarati Letter Va ..Gujarati Letter Ha + (0x00af9, 0x00af9,), # Gujarati Letter Zha + (0x00b15, 0x00b28,), # Oriya Letter Ka ..Oriya Letter Na + (0x00b2a, 0x00b30,), # Oriya Letter Pa ..Oriya Letter Ra + (0x00b32, 0x00b33,), # Oriya Letter La ..Oriya Letter Lla + (0x00b35, 0x00b39,), # Oriya Letter Va ..Oriya Letter Ha + (0x00b5c, 0x00b5d,), # Oriya Letter Rra ..Oriya Letter Rha + (0x00b5f, 0x00b5f,), # Oriya Letter Yya + (0x00b71, 0x00b71,), # Oriya Letter Wa + (0x00b95, 0x00b95,), # Tamil Letter Ka + (0x00b99, 0x00b9a,), # Tamil Letter Nga ..Tamil Letter Ca + (0x00b9c, 0x00b9c,), # Tamil Letter Ja + (0x00b9e, 0x00b9f,), # Tamil Letter Nya ..Tamil Letter Tta + (0x00ba3, 0x00ba4,), # Tamil Letter Nna ..Tamil Letter Ta + (0x00ba8, 0x00baa,), # Tamil Letter Na ..Tamil Letter Pa + (0x00bae, 0x00bb9,), # Tamil Letter Ma ..Tamil Letter Ha + (0x00c15, 0x00c28,), # Telugu Letter Ka ..Telugu Letter Na + (0x00c2a, 0x00c39,), # Telugu Letter Pa ..Telugu Letter Ha + (0x00c58, 0x00c5a,), # Telugu Letter Tsa ..Telugu Letter Rrra + (0x00c95, 0x00ca8,), # Kannada Letter Ka ..Kannada Letter Na + (0x00caa, 0x00cb3,), # Kannada Letter Pa ..Kannada Letter Lla + (0x00cb5, 0x00cb9,), # Kannada Letter Va ..Kannada Letter Ha + (0x00cde, 0x00cde,), # Kannada Letter Fa + (0x00d15, 0x00d3a,), # Malayalam Letter Ka ..Malayalam Letter Ttta + (0x00d9a, 0x00db1,), # Sinhala Letter Alpapraan..Sinhala Letter Dantaja N + (0x00db3, 0x00dbb,), # Sinhala Letter Sanyaka D..Sinhala Letter Rayanna + (0x00dbd, 0x00dbd,), # Sinhala Letter Dantaja Layanna + (0x00dc0, 0x00dc6,), # Sinhala Letter Vayanna ..Sinhala Letter Fayanna + (0x00e01, 0x00e2e,), # Thai Character Ko Kai ..Thai Character Ho Nokhuk + (0x00e81, 0x00e82,), # Lao Letter Ko ..Lao Letter Kho Sung + (0x00e84, 0x00e84,), # Lao Letter Kho Tam + (0x00e86, 0x00e8a,), # Lao Letter Pali Gha ..Lao Letter So Tam + (0x00e8c, 0x00ea3,), # Lao Letter Pali Jha ..Lao Letter Lo Ling + (0x00ea5, 0x00ea5,), # Lao Letter Lo Loot + (0x00ea7, 0x00eae,), # Lao Letter Wo ..Lao Letter Ho Tam + (0x00edc, 0x00edf,), # Lao Ho No ..Lao Letter Khmu Nyo + (0x00f40, 0x00f47,), # Tibetan Letter Ka ..Tibetan Letter Ja + (0x00f49, 0x00f6c,), # Tibetan Letter Nya ..Tibetan Letter Rra + (0x01000, 0x01020,), # Myanmar Letter Ka ..Myanmar Letter Lla + (0x0103f, 0x0103f,), # Myanmar Letter Great Sa + (0x01050, 0x01051,), # Myanmar Letter Sha ..Myanmar Letter Ssa + (0x0105a, 0x0105d,), # Myanmar Letter Mon Nga ..Myanmar Letter Mon Bbe + (0x01061, 0x01061,), # Myanmar Letter Sgaw Karen Sha + (0x01065, 0x01066,), # Myanmar Letter Western P..Myanmar Letter Western P + (0x0106e, 0x01070,), # Myanmar Letter Eastern P..Myanmar Letter Eastern P + (0x01075, 0x01081,), # Myanmar Letter Shan Ka ..Myanmar Letter Shan Ha + (0x0108e, 0x0108e,), # Myanmar Letter Rumai Palaung Fa + (0x01703, 0x01711,), # Tagalog Letter Ka ..Tagalog Letter Ha + (0x0171f, 0x0171f,), # Tagalog Letter Archaic Ra + (0x01723, 0x01731,), # Hanunoo Letter Ka ..Hanunoo Letter Ha + (0x01743, 0x01751,), # Buhid Letter Ka ..Buhid Letter Ha + (0x01763, 0x0176c,), # Tagbanwa Letter Ka ..Tagbanwa Letter Ya + (0x0176e, 0x01770,), # Tagbanwa Letter La ..Tagbanwa Letter Sa + (0x01780, 0x017a2,), # Khmer Letter Ka ..Khmer Letter Qa + (0x01900, 0x0191e,), # Limbu Vowel-carrier Lett..Limbu Letter Tra + (0x01950, 0x01962,), # Tai Le Letter Ka ..Tai Le Letter Na + (0x01980, 0x019ab,), # New Tai Lue Letter High ..New Tai Lue Letter Low S + (0x01a00, 0x01a16,), # Buginese Letter Ka ..Buginese Letter Ha + (0x01a20, 0x01a4c,), # Tai Tham Letter High Ka ..Tai Tham Letter Low Ha + (0x01a53, 0x01a54,), # Tai Tham Letter Lae ..Tai Tham Letter Great Sa + (0x01b13, 0x01b33,), # Balinese Letter Ka ..Balinese Letter Ha + (0x01b45, 0x01b4c,), # Balinese Letter Kaf Sasa..Balinese Letter Archaic + (0x01b8a, 0x01ba0,), # Sundanese Letter Ka ..Sundanese Letter Ha + (0x01bae, 0x01baf,), # Sundanese Letter Kha ..Sundanese Letter Sya + (0x01bbb, 0x01bbd,), # Sundanese Letter Reu ..Sundanese Letter Bha + (0x01bc0, 0x01be3,), # Batak Letter A ..Batak Letter Mba + (0x01c00, 0x01c23,), # Lepcha Letter Ka ..Lepcha Letter A + (0x01c4d, 0x01c4f,), # Lepcha Letter Tta ..Lepcha Letter Dda + (0x0a807, 0x0a80a,), # Syloti Nagri Letter Ko ..Syloti Nagri Letter Gho + (0x0a80c, 0x0a822,), # Syloti Nagri Letter Co ..Syloti Nagri Letter Ho + (0x0a840, 0x0a85d,), # Phags-pa Letter Ka ..Phags-pa Letter A + (0x0a862, 0x0a865,), # Phags-pa Letter Qa ..Phags-pa Letter Gga + (0x0a869, 0x0a870,), # Phags-pa Letter Tta ..Phags-pa Letter Aspirate + (0x0a872, 0x0a872,), # Phags-pa Superfixed Letter Ra + (0x0a892, 0x0a8b3,), # Saurashtra Letter Ka ..Saurashtra Letter Lla + (0x0a90a, 0x0a921,), # Kayah Li Letter Ka ..Kayah Li Letter Ca + (0x0a930, 0x0a946,), # Rejang Letter Ka ..Rejang Letter A + (0x0a989, 0x0a98b,), # Javanese Letter Pa Cerek..Javanese Letter Nga Lele + (0x0a98f, 0x0a9b2,), # Javanese Letter Ka ..Javanese Letter Ha + (0x0a9e0, 0x0a9e4,), # Myanmar Letter Shan Gha ..Myanmar Letter Shan Bha + (0x0a9e7, 0x0a9ef,), # Myanmar Letter Tai Laing..Myanmar Letter Tai Laing + (0x0a9fa, 0x0a9fe,), # Myanmar Letter Tai Laing..Myanmar Letter Tai Laing + (0x0aa06, 0x0aa28,), # Cham Letter Ka ..Cham Letter Ha + (0x0aa60, 0x0aa6f,), # Myanmar Letter Khamti Ga..Myanmar Letter Khamti Fa + (0x0aa71, 0x0aa73,), # Myanmar Letter Khamti Xa..Myanmar Letter Khamti Ra + (0x0aa7a, 0x0aa7a,), # Myanmar Letter Aiton Ra + (0x0aa7e, 0x0aaaf,), # Myanmar Letter Shwe Pala..Tai Viet Letter High O + (0x0aae2, 0x0aaea,), # Meetei Mayek Letter Cha ..Meetei Mayek Letter Ssa + (0x0abc0, 0x0abcd,), # Meetei Mayek Letter Kok ..Meetei Mayek Letter Huk + (0x0abd0, 0x0abd0,), # Meetei Mayek Letter Pham + (0x0abd2, 0x0abda,), # Meetei Mayek Letter Gok ..Meetei Mayek Letter Bham + (0x10a00, 0x10a00,), # Kharoshthi Letter A + (0x10a10, 0x10a13,), # Kharoshthi Letter Ka ..Kharoshthi Letter Gha + (0x10a15, 0x10a17,), # Kharoshthi Letter Ca ..Kharoshthi Letter Ja + (0x10a19, 0x10a35,), # Kharoshthi Letter Nya ..Kharoshthi Letter Vha + (0x11013, 0x11037,), # Brahmi Letter Ka ..Brahmi Letter Old Tamil + (0x11075, 0x11075,), # Brahmi Letter Old Tamil Lla + (0x1108d, 0x110af,), # Kaithi Letter Ka ..Kaithi Letter Ha + (0x11107, 0x11126,), # Chakma Letter Kaa ..Chakma Letter Haa + (0x11144, 0x11144,), # Chakma Letter Lhaa + (0x11147, 0x11147,), # Chakma Letter Vaa + (0x11155, 0x11172,), # Mahajani Letter Ka ..Mahajani Letter Rra + (0x11191, 0x111b2,), # Sharada Letter Ka ..Sharada Letter Ha + (0x11208, 0x11211,), # Khojki Letter Ka ..Khojki Letter Jja + (0x11213, 0x1122b,), # Khojki Letter Nya ..Khojki Letter Lla + (0x1123f, 0x1123f,), # Khojki Letter Qa + (0x11284, 0x11286,), # Multani Letter Ka ..Multani Letter Ga + (0x11288, 0x11288,), # Multani Letter Gha + (0x1128a, 0x1128d,), # Multani Letter Ca ..Multani Letter Jja + (0x1128f, 0x1129d,), # Multani Letter Nya ..Multani Letter Ba + (0x1129f, 0x112a8,), # Multani Letter Bha ..Multani Letter Rha + (0x112ba, 0x112de,), # Khudawadi Letter Ka ..Khudawadi Letter Ha + (0x11315, 0x11328,), # Grantha Letter Ka ..Grantha Letter Na + (0x1132a, 0x11330,), # Grantha Letter Pa ..Grantha Letter Ra + (0x11332, 0x11333,), # Grantha Letter La ..Grantha Letter Lla + (0x11335, 0x11339,), # Grantha Letter Va ..Grantha Letter Ha + (0x11392, 0x113b5,), # Tulu-tigalari Letter Ka ..Tulu-tigalari Letter Lll + (0x1140e, 0x11434,), # Newa Letter Ka ..Newa Letter Ha + (0x1148f, 0x114af,), # Tirhuta Letter Ka ..Tirhuta Letter Ha + (0x1158e, 0x115ae,), # Siddham Letter Ka ..Siddham Letter Ha + (0x1160e, 0x1162f,), # Modi Letter Ka ..Modi Letter Lla + (0x1168a, 0x116aa,), # Takri Letter Ka ..Takri Letter Rra + (0x116b8, 0x116b8,), # Takri Letter Archaic Kha + (0x11700, 0x1171a,), # Ahom Letter Ka ..Ahom Letter Alternate Ba + (0x11740, 0x11746,), # Ahom Letter Ca ..Ahom Letter Lla + (0x1180a, 0x1182b,), # Dogra Letter Ka ..Dogra Letter Rra + (0x1190c, 0x11913,), # Dives Akuru Letter Ka ..Dives Akuru Letter Ja + (0x11915, 0x11916,), # Dives Akuru Letter Nya ..Dives Akuru Letter Tta + (0x11918, 0x1192f,), # Dives Akuru Letter Dda ..Dives Akuru Letter Za + (0x119ae, 0x119d0,), # Nandinagari Letter Ka ..Nandinagari Letter Rra + (0x11a00, 0x11a00,), # Zanabazar Square Letter A + (0x11a0b, 0x11a32,), # Zanabazar Square Letter ..Zanabazar Square Letter + (0x11a50, 0x11a50,), # Soyombo Letter A + (0x11a5c, 0x11a83,), # Soyombo Letter Ka ..Soyombo Letter Kssa + (0x11b0a, 0x11b0a,), # Devanagari Letter Alternate Ddda + (0x11c0e, 0x11c2e,), # Bhaiksuki Letter Ka ..Bhaiksuki Letter Ha + (0x11c72, 0x11c8f,), # Marchen Letter Ka ..Marchen Letter A + (0x11d0c, 0x11d30,), # Masaram Gondi Letter Ka ..Masaram Gondi Letter Tra + (0x11d6c, 0x11d89,), # Gunjala Gondi Letter Ya ..Gunjala Gondi Letter Sa + (0x11df1, 0x11df1,), # Bengali Letter Alternate Bargiya Ba + (0x11ee0, 0x11ef1,), # Makasar Letter Ka ..Makasar Letter A + (0x11f12, 0x11f33,), # Kawi Letter Ka ..Kawi Letter Jnya + (0x16100, 0x1611d,), # Gurung Khema Letter A ..Gurung Khema Letter Sa + (0x16d43, 0x16d62,), # Kirat Rai Letter A ..Kirat Rai Letter Ha +) + +ISC_VIRAMA = ( + # Source: IndicSyllabicCategory + # Date: see file + # + (0x0094d, 0x0094d,), # Devanagari Sign Virama + (0x009cd, 0x009cd,), # Bengali Sign Virama + (0x00a4d, 0x00a4d,), # Gurmukhi Sign Virama + (0x00acd, 0x00acd,), # Gujarati Sign Virama + (0x00b4d, 0x00b4d,), # Oriya Sign Virama + (0x00bcd, 0x00bcd,), # Tamil Sign Virama + (0x00c4d, 0x00c4d,), # Telugu Sign Virama + (0x00ccd, 0x00ccd,), # Kannada Sign Virama + (0x00d4d, 0x00d4d,), # Malayalam Sign Virama + (0x00dca, 0x00dca,), # Sinhala Sign Al-lakuna + (0x01b44, 0x01b44,), # Balinese Adeg Adeg + (0x0a806, 0x0a806,), # Syloti Nagri Sign Hasanta + (0x0a8c4, 0x0a8c4,), # Saurashtra Sign Virama + (0x0a9c0, 0x0a9c0,), # Javanese Pangkon + (0x11046, 0x11046,), # Brahmi Virama + (0x110b9, 0x110b9,), # Kaithi Sign Virama + (0x111c0, 0x111c0,), # Sharada Sign Virama + (0x11235, 0x11235,), # Khojki Sign Virama + (0x1134d, 0x1134d,), # Grantha Sign Virama + (0x11442, 0x11442,), # Newa Sign Virama + (0x114c2, 0x114c2,), # Tirhuta Sign Virama + (0x115bf, 0x115bf,), # Siddham Sign Virama + (0x1163f, 0x1163f,), # Modi Sign Virama + (0x116b6, 0x116b6,), # Takri Sign Virama + (0x11839, 0x11839,), # Dogra Sign Virama + (0x119e0, 0x119e0,), # Nandinagari Sign Virama + (0x11c3f, 0x11c3f,), # Bhaiksuki Sign Virama +) + +ISC_INVISIBLE_STACKER = ( + # Source: IndicSyllabicCategory + # Date: see file + # + (0x01039, 0x01039,), # Myanmar Sign Virama + (0x017d2, 0x017d2,), # Khmer Sign Coeng + (0x01a60, 0x01a60,), # Tai Tham Sign Sakot + (0x01bab, 0x01bab,), # Sundanese Sign Virama + (0x0aaf6, 0x0aaf6,), # Meetei Mayek Virama + (0x10a3f, 0x10a3f,), # Kharoshthi Virama + (0x11133, 0x11133,), # Chakma Virama + (0x113d0, 0x113d0,), # Tulu-tigalari Conjoiner + (0x1193e, 0x1193e,), # Dives Akuru Virama + (0x11a47, 0x11a47,), # Zanabazar Square Subjoiner + (0x11a99, 0x11a99,), # Soyombo Subjoiner + (0x11d45, 0x11d45,), # Masaram Gondi Virama + (0x11d97, 0x11d97,), # Gunjala Gondi Virama + (0x11f42, 0x11f42,), # Kawi Conjoiner +) diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__init__.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..59391478877d8405f684ff499ca2ef1d232f39ab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__init__.py @@ -0,0 +1,37 @@ +""" +Lazy-loading per-terminal grapheme override tables. + +This minimizes memory for the 99.9% of use-cases of a single 'term_program'. +""" +from __future__ import annotations + +# std imports +import importlib +from functools import lru_cache + +# local +from ._registry import _REGISTRY + + +@lru_cache(maxsize=32) +def get(term_canonical: str) -> dict[str, int]: + """ + Return grapheme override dict for a terminal, or an empty dict. + + The per-terminal module is imported on first access and cached in ``sys.modules``; subsequent + calls for the same terminal return immediately via lru_cache. + """ + hash_key = _REGISTRY.get(term_canonical) + if hash_key is None: + return {} + + try: + mod = importlib.import_module(f'._known_{hash_key}', __package__) + result: dict[str, int] = getattr(mod, 'GRAPHEMES') + return result + except ImportError: + # This can occur during a program re-install when the registry and files are out of sync + # (filesystem vs. in-memory copy differ), like "pip upgrade" during long-running process, or + # if the upgrade tool itself uses wcwidth. Terminal overrides in this situation are not + # fatal, continue without them. + return {} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b39c5d34d5435e80f3d56d945df4e53936c0f88 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_058c7585.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_058c7585.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d13c73f819790a5d7b84801795e4d47f2cbff53 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_058c7585.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7997813233cb95d065448ac69d8361b896530fbb6c19a546122ea82dc3f5ecb7 +size 117634 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_2148ff29.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_2148ff29.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13055a498c0fdac03be391e896dbcfe676e14b01 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_2148ff29.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_244dc88b.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_244dc88b.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6f2079f0c209d6b0fcf2f4c00ef2b1cb295d234 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_244dc88b.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_336a71a1.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_336a71a1.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f92736c7464cadd4ce69ebb256086d128473e4e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_336a71a1.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a7a112f8b323b6d993f82079decccff46b6f91e7917c68e6a5d10f62a0eff99 +size 137928 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_33ac73f2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_33ac73f2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e136da4c38985c0d575e712be509756f9af84624 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_33ac73f2.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_3a1895d5.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_3a1895d5.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39a6baafba6dc37d5cbe80093d357db9b4ec2904 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_3a1895d5.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_59180a0d.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_59180a0d.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72eed27becee788b3b51d4653773556cb598a283 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_59180a0d.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2c18187a1d195b8444ee5992cb23757d9ecd50875b4f19e2b7377d4cf64cecf +size 116059 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_65c6beb5.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_65c6beb5.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dba03434361112809ea719ff1bc170e15fdcd23 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_65c6beb5.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ced5ace22982c47d5434f6e6b60edbdb887db71c108bf2f15d8a67e89b3080c3 +size 122954 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_78f828e8.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_78f828e8.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b937ba4e6696e42280f541d7d64b04dd382140b2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_78f828e8.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_8c2ae14d.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_8c2ae14d.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2d7eaf47ab69c0a42f8588d8fc02f6706f76fb1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_8c2ae14d.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e550ec977fd71ca43addfebea8febba71ed9be5a13f765acdb66eaf07a57c5c9 +size 121801 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_900356bf.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_900356bf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e72e8719c2fcd83f1b22aa97cc61dacbbfd7fbf1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_900356bf.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_97904ece.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_97904ece.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa363bceffd4c0ab4ec4776c95ffd17dfa5e925d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_97904ece.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:91ec6faa42415f8ca0d476f8292efc83bf0635820353767f4677e712f7a350cd +size 114546 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_a5880eeb.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_a5880eeb.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bc1595d68663515c9c21ad0695477a6e4e0c9fb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_a5880eeb.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:facdaab88cb9d19e344b5d473e74ebdcbc37fd5a3984c9215c56a80b74d01167 +size 114536 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_b6d33cf4.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_b6d33cf4.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18b13dba03180e5510fdec2cd84b640a0589d810 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_b6d33cf4.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04f014b5b2416bcac27d1d1b5239bc2c67d6400d484acafe6c45723dec25fae1 +size 141319 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_c57c295b.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_c57c295b.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8074e4ace7c902374fd82d93a0a1947f7b661b0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_c57c295b.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc9b855ea4c79b654d28d40b0ac5a6bd4d03435b7cb67ac24a8d41ee3238d8df +size 271986 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_cf02297d.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_cf02297d.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7b437743b20f2600d88540b97be5dc8ddbefe19 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_cf02297d.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_e18ac6a7.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_e18ac6a7.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..669ccc1ebf7bf7d27875144899f4e0be3d61df3f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_e18ac6a7.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:daecbb0babd4fb3fc3dc1fe7655bdf54a3eb65a058c7d1d983b58abd09c86a27 +size 281301 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_e2b75ee3.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_e2b75ee3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d7fa1bc40811209d3dea3d7e4666b7d4b9853f7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_e2b75ee3.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_fb5fd79b.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_fb5fd79b.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b15690f85c7ed9fe725dd1cc09374071e04ba0ce --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_fb5fd79b.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e70d632402ba65482760f5a288725a52825e825b99f9060ac56f966d135a800d +size 129301 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_fdc99132.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_fdc99132.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3ba41fe3f7c6a4bdb309263f5cf9d63b7e24522 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_known_fdc99132.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b03b37180f518b4c44e6ccb30c42e211e1c848a66d9082ff431e6b3a54ba3f93 +size 117629 diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_registry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07e51ea5896536237ecefc5be96501ef562109d2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/__pycache__/_registry.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_058c7585.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_058c7585.py new file mode 100644 index 0000000000000000000000000000000000000000..44df64e7c8d253d104314984732e190d3bd35416 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_058c7585.py @@ -0,0 +1,2642 @@ +""" +Grapheme overrides for _known_058c7585. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: xterm.js +""" +# pylint: skip-file +GRAPHEMES = { + '؁۱': 1, + 'क्का': 3, + 'क्कां': 3, + 'क्को': 3, + 'क्घ्घि्': 4, + 'क्ता': 3, + 'क्ति': 3, + 'क्ती': 3, + 'क्तीं': 3, + 'क्तेः': 3, + 'क्त्योः': 5, + 'क्ना': 3, + 'क्नि': 3, + 'क्या': 3, + 'क्रा': 3, + 'क्रि': 3, + 'क्षा': 3, + 'क्षां': 3, + 'क्षाः': 4, + 'क्षि': 3, + 'क्षो': 3, + 'क्ष्ण': 3, + 'क्ष्य': 3, + 'क्ष्या': 4, + 'क्सा': 3, + 'ख्यः': 3, + 'ख्या': 3, + 'ग्या': 3, + 'ग्यैः': 3, + 'ग्र्य': 3, + 'घ्का': 3, + 'घ्र्व्य': 4, + 'घ्लि': 3, + 'घ्श्य': 3, + 'घ्स्ट': 3, + 'च्चा': 3, + 'च्चों': 3, + 'च्छा': 3, + 'च्छि': 3, + 'च्या': 3, + 'च्यां': 3, + 'च्यो': 3, + 'ज्ञा': 3, + 'ज्या': 3, + 'ज्या‌': 3, + 'ज्रा': 3, + 'ञ्चा': 3, + 'ञ्चि': 3, + 'ट्टि': 3, + 'ट्टी': 3, + 'ट्या': 3, + 'ट्रा': 3, + 'ण्डः': 3, + 'ण्डि': 3, + 'ण्या': 3, + 'ण्यां': 3, + 'ताः': 3, + 'त्का': 3, + 'त्ता': 3, + 'त्ति': 3, + 'त्त्थि': 4, + 'त्त्व': 3, + 'त्त्वा': 4, + 'त्त्वे': 3, + 'त्नी': 3, + 'त्नों': 3, + 'त्पा': 3, + 'त्पी': 3, + 'त्मा': 3, + 'त्या': 3, + 'त्यां': 3, + 'त्यि': 3, + 'त्रा': 3, + 'त्राा': 4, + 'त्राि': 4, + 'त्रि': 3, + 'त्री': 3, + 'त्र्त': 3, + 'त्र्य': 3, + 'त्र्या': 4, + 'त्र्ये': 3, + 'त्वा': 3, + 'त्वां': 3, + 'त्सा': 3, + 'त्सो': 3, + 'त्स्वा': 4, + 'द्घि': 3, + 'द्घो': 3, + 'द्दा': 3, + 'द्दि': 3, + 'द्दी': 3, + 'द्धः': 3, + 'द्धा': 3, + 'द्धां': 3, + 'द्धि': 3, + 'द्धिं': 3, + 'द्धी': 3, + 'द्धीं': 3, + 'द्धैः': 3, + 'द्भा': 3, + 'द्या': 3, + 'द्रो': 3, + 'द्वा': 3, + 'द्वि': 3, + 'धाः': 3, + 'ध्या': 3, + 'नाः': 3, + 'निः': 3, + 'न्का': 3, + 'न्चि': 3, + 'न्ञ्या': 4, + 'न्तः': 3, + 'न्ता': 3, + 'न्ति': 3, + 'न्तो': 3, + 'न्तों': 3, + 'न्त्र': 3, + 'न्त्रा': 4, + 'न्त्राः': 5, + 'न्त्रि': 4, + 'न्त्री': 4, + 'न्त्र्य': 4, + 'न्त्र्यं': 4, + 'न्त्र्या': 5, + 'न्त्र्ये': 4, + 'न्दा': 3, + 'न्दी': 3, + 'न्दो': 3, + 'न्धा': 3, + 'न्धि': 3, + 'न्धी': 3, + 'न्धों': 3, + 'न्ना': 3, + 'न्नाः': 4, + 'न्नि': 3, + 'न्मा': 3, + 'न्या': 3, + 'न्यो': 3, + 'न्हा': 3, + 'न्ह्यां': 4, + 'प्ति': 3, + 'प्तौ': 3, + 'प्या': 3, + 'प्रा': 3, + 'फ्ता': 3, + 'फ्ना': 3, + 'फ्नो': 3, + 'फ्रां': 3, + 'ब्धि': 3, + 'भिः': 3, + 'भ्यः': 3, + 'भ्या': 3, + 'भ्यां': 3, + 'भ्यो': 3, + 'म्ति': 3, + 'म्नि': 3, + 'म्पा': 3, + 'म्प्र': 3, + 'म्भि': 3, + 'म्मा': 3, + 'म्मि': 3, + 'म्या': 3, + 'म्ही': 3, + 'म्हो': 3, + 'याः': 3, + 'य्यो': 3, + 'राः': 3, + 'र्कि': 3, + 'र्गी': 3, + 'र्चि': 3, + 'र्जा': 3, + 'र्जि': 3, + 'र्जी': 3, + 'र्णां': 3, + 'र्णी': 3, + 'र्ता': 3, + 'र्ति': 3, + 'र्तिः': 4, + 'र्ती': 3, + 'र्त्त': 3, + 'र्त्ति': 4, + 'र्थि': 3, + 'र्थी': 3, + 'र्दा': 3, + 'र्दि': 3, + 'र्दो': 3, + 'र्द्ध': 3, + 'र्धा': 3, + 'र्धि': 3, + 'र्नि': 3, + 'र्बा': 3, + 'र्भा': 3, + 'र्मा': 3, + 'र्मि': 3, + 'र्या': 3, + 'र्यां': 3, + 'र्यों': 3, + 'र्रा': 3, + 'र्वा': 3, + 'र्वां': 3, + 'र्वो': 3, + 'र्सा': 3, + 'र्हाः': 4, + 'र्हि': 3, + 'र्हो': 3, + 'र्‍या': 3, + 'लाः': 3, + 'ल्का': 3, + 'ल्पि': 3, + 'ल्या': 3, + 'ल्यां': 3, + 'ल्याः': 4, + 'ल्ला': 3, + 'ल्लि': 3, + 'वाः': 3, + 'व्या': 3, + 'व्यों': 3, + 'शाः': 3, + 'श्चि': 3, + 'श्या': 3, + 'श्यि': 3, + 'श्यों': 3, + 'श्रा': 3, + 'श्रां': 3, + 'श्वा': 3, + 'श्वि': 3, + 'षाः': 3, + 'ष्का': 3, + 'ष्टः': 3, + 'ष्टा': 3, + 'ष्टां': 3, + 'ष्टाः': 4, + 'ष्टि': 3, + 'ष्टी': 3, + 'ष्टीं': 3, + 'ष्ट्र': 3, + 'ष्ट्रा': 4, + 'ष्ट्रां': 4, + 'ष्ट्रि': 4, + 'ष्ट्री': 4, + 'ष्ट्रे': 3, + 'ष्ट्रो': 4, + 'ष्ट्रों': 4, + 'ष्ठा': 3, + 'ष्ठों': 3, + 'ष्प्र': 3, + 'ष्यः': 3, + 'ष्यों': 3, + 'स्का': 3, + 'स्काः': 4, + 'स्ट्या': 4, + 'स्ता': 3, + 'स्ति': 3, + 'स्ती': 3, + 'स्तो': 3, + 'स्त्र': 3, + 'स्त्रा': 4, + 'स्त्रि': 4, + 'स्त्री': 4, + 'स्था': 3, + 'स्थां': 3, + 'स्थि': 3, + 'स्थी': 3, + 'स्थ्य': 3, + 'स्धी': 3, + 'स्मि': 3, + 'स्मिं': 3, + 'स्या': 3, + 'स्यां': 3, + 'स्याः': 4, + 'स्युः': 3, + 'स्यों': 3, + 'स्रो': 3, + 'स्वा': 3, + 'स्वी': 3, + 'स्सा': 3, + 'ह्या': 3, + 'ह्रा': 3, + 'फ़्ता': 3, + 'কিং': 3, + 'ক্তি': 3, + 'ক্রী': 3, + 'ক্ষা': 3, + 'ক্ষি': 3, + 'ক্ষে': 3, + 'ক্ষ্য': 3, + 'ক্ষ্যে': 4, + 'খ্যা': 3, + 'গ্রা': 3, + 'গ্রে': 3, + 'ঘো': 3, + 'ঙ্খা': 3, + 'ঙ্গী': 3, + 'ঙ্গে': 3, + 'চ্ছা': 3, + 'চ্ছা‌': 3, + 'চ্ছে': 3, + 'জ্ঞা': 3, + 'ঞ্চি': 3, + 'ঞ্ছি': 3, + 'ট্রে': 3, + 'ণ্ডে': 3, + 'ত্তা': 3, + 'ত্তি': 3, + 'ত্বে': 3, + 'ত্যা': 3, + 'ত্যি': 3, + 'ত্যে': 3, + 'ত্রা': 3, + 'ত্রে': 3, + 'ত্‍পী': 3, + 'ত্‍সা': 3, + 'দ্দি': 3, + 'দ্দে': 3, + 'দ্ধা': 3, + 'দ্ধি': 3, + 'দ্ধে': 3, + 'দ্বা': 3, + 'দ্রো': 3, + 'ধ্যে': 3, + 'ন্তা': 3, + 'ন্তি': 3, + 'ন্তে': 3, + 'ন্ত্রি': 4, + 'ন্ত্রে': 4, + 'ন্থী': 3, + 'ন্ধা': 3, + 'ন্মা': 3, + 'ন্যা': 3, + 'ন্যে': 3, + 'প্তা': 3, + 'প্রা': 3, + 'ব্ধি': 3, + 'ব্যা': 3, + 'ভ্রা': 3, + 'ম্পা': 3, + 'ম্মা': 3, + 'রাং': 3, + 'র্জা': 3, + 'র্থে': 3, + 'র্দো': 3, + 'র্ধা': 3, + 'র্নী': 3, + 'র্বা': 3, + 'র্বি': 3, + 'র্বো': 3, + 'র্ব্য': 3, + 'র্মে': 3, + 'র্যা': 3, + 'ল্যা': 3, + 'ল্যে': 3, + 'ল্লে': 3, + 'শ্চি': 3, + 'শ্বা': 3, + 'শ্বে': 3, + 'শ্যে': 3, + 'শ্রা': 3, + 'ষ্টা': 3, + 'ষ্টি': 3, + 'ষ্ট্র': 3, + 'ষ্ট্রী': 4, + 'ষ্ট্রে': 4, + 'ষ্ঠা': 3, + 'ষ্ঠি': 3, + 'ষ্ঠী': 3, + 'সাং': 3, + 'স্তি': 3, + 'স্তি‌': 3, + 'স্ত্র': 3, + 'স্থা': 3, + 'স্থ্য': 3, + 'স্বা': 3, + 'স্বী': 3, + 'স্যা': 3, + 'স্যে': 3, + 'ક્કા': 3, + 'ક્કો': 3, + 'ક્તિ': 3, + 'ક્ષા': 3, + 'ચ્ચા': 3, + 'ચ્છા': 3, + 'જ્ઞા': 3, + 'જ્યો': 3, + 'ત્તા': 3, + 'ત્તિ': 3, + 'ત્ત્વ': 3, + 'ત્ત્વા': 4, + 'ત્યા': 3, + 'ત્યાં': 3, + 'ત્યિ': 3, + 'ત્યો': 3, + 'ત્રી': 3, + 'ત્ર્ય': 3, + 'દ્ધા': 3, + 'દ્ધાં': 3, + 'દ્ધિ': 3, + 'દ્વા': 3, + 'ધ્યા': 3, + 'ન્તો': 3, + 'ન્મા': 3, + 'ન્યા': 3, + 'પ્રા': 3, + 'મ્યાં': 3, + 'ર્તા': 3, + 'ર્થિ': 3, + 'ર્દો': 3, + 'ર્મિ': 3, + 'ર્યા': 3, + 'ર્યો': 3, + 'વ્યા': 3, + 'વ્યો': 3, + 'ષ્ટિ': 3, + 'ષ્ટ્ર': 3, + 'ષ્ટ્રી': 4, + 'ષ્ટ્રો': 4, + 'ષ્ઠા': 3, + 'સ્તિ': 3, + 'સ્તી': 3, + 'સ્ત્રી': 4, + 'સ્થા': 3, + 'સ્થિ': 3, + 'સ્રી': 3, + 'સ્વા': 3, + 'સ્વી': 3, + 'સ્સા': 3, + 'కుం': 3, + 'క్కు': 3, + 'క్తు': 3, + 'క్రాం': 3, + 'క్రూ': 3, + 'క్షిం': 3, + 'క్స్వా': 3, + 'చ్చు': 3, + 'టుం': 3, + 'ట్లు': 3, + 'డ్రు': 3, + 'త్తు': 3, + 'త్నిం': 3, + 'త్యం': 3, + 'త్రు': 3, + 'త్ర్య': 3, + 'దుం': 3, + 'ద్దు': 3, + 'ద్ధిం': 3, + 'ద్ర్య': 3, + 'నుం': 3, + 'న్ను': 3, + 'భ్యు': 3, + 'యుం': 3, + 'ర్చు': 3, + 'ర్ణాం': 3, + 'ర్ణు': 3, + 'ర్తిం': 3, + 'ర్తృ': 3, + 'ర్థిం': 3, + 'ర్బం': 3, + 'ర్హాం': 3, + 'ర్హు': 3, + 'శ్రాం': 3, + 'ష్టు': 3, + 'ష్ట్ర': 3, + 'ష్ట్రీ': 3, + 'ష్ఠు': 3, + 'స్కృ': 3, + 'స్త్ర': 3, + 'స్త్రీ': 3, + 'స్థ్య': 3, + 'ಕಾಂ': 3, + 'ಕುಂ': 3, + 'ಕೊಂ': 3, + 'ಖಾಂ': 3, + 'ಗಾಂ': 3, + 'ಗೊಂ': 3, + 'ಟುಂ': 3, + 'ನಾಂ': 3, + 'ಯುಂ': 3, + 'ರಾಂ': 3, + 'ವುಂ': 3, + 'ಶಾಂ': 3, + 'ಸಾಂ': 3, + 'ಹೊಂ': 3, + 'ക്കാ': 3, + 'ക്കി': 3, + 'ക്കും': 3, + 'ക്കെ': 3, + 'ക്കേ': 3, + 'ക്കൊ': 3, + 'ക്കോ': 3, + 'ക്തി': 3, + 'ക്യം': 3, + 'ക്ഷാ': 3, + 'ക്ഷി': 3, + 'ക്ഷേ': 3, + 'ഖ്യാ': 3, + 'ഗ്ഗം': 3, + 'ഗ്ദാ': 3, + 'ഗ്യം': 3, + 'ങ്കി': 3, + 'ങ്കെ': 3, + 'ങ്കേ': 3, + 'ങ്ങി': 3, + 'ച്ചി': 3, + 'ച്ചും': 3, + 'ച്ചെ': 3, + 'ച്ചേ': 3, + 'ജ്യാ': 3, + 'ഞ്ഞി': 3, + 'ഞ്ഞെ': 3, + 'ട്ടാ': 3, + 'ട്ടി': 3, + 'ട്ടോ': 3, + 'ണ്ടാ': 3, + 'ണ്ടി': 3, + 'ണ്ടും': 3, + 'ണ്ടെ': 3, + 'ത്താ': 3, + 'ത്തി': 3, + 'ത്തും': 3, + 'ത്തെ': 3, + 'ത്തേ': 3, + 'ത്തോ': 3, + 'ത്നം': 3, + 'ത്നി': 3, + 'ത്യാ': 3, + 'ത്യേ': 3, + 'ത്വം': 3, + 'ദ്ധി': 3, + 'ദ്യാ': 3, + 'ന്തം': 3, + 'ന്തെ': 3, + 'ന്ത്ര': 3, + 'ന്ത്ര്യ': 4, + 'ന്ത്ര്യം': 5, + 'ന്ധി': 3, + 'ന്നാ': 3, + 'ന്നി': 3, + 'ന്നീ': 3, + 'ന്നും': 3, + 'ന്നെ': 3, + 'ന്നേ': 3, + 'ന്നോ': 3, + 'ന്മാ': 3, + 'ന്യം': 3, + 'ന്യാ': 3, + 'ന്യേ': 3, + 'ന്യോ': 3, + 'ന്റെ': 3, + 'ന്‍പി': 3, + 'പ്പി': 3, + 'പ്പെ': 3, + 'പ്പോ': 3, + 'പ്രാ': 3, + 'ബ്ലി': 3, + 'ഭ്യാ': 3, + 'ഭ്രാ': 3, + 'മ്പാ': 3, + 'മ്പ്ര': 3, + 'മ്മി': 3, + 'യ്ക്കു': 3, + 'യ്തി': 3, + 'യ്യാ': 3, + 'യ്യി': 3, + 'ര്യം': 3, + 'ര്‍ക്കു': 3, + 'ര്‍ക്കും': 4, + 'ര്‍ക്ക്‌': 3, + 'ര്‍ഗ്ഗം': 4, + 'ര്‍ച്ച': 3, + 'ര്‍ണ്ണ': 3, + 'ര്‍ത്ത': 3, + 'ര്‍ത്തി': 4, + 'ര്‍ത്തു': 3, + 'ര്‍ത്തേ': 4, + 'ര്‍ദേ': 3, + 'ര്‍ദ്ദ': 3, + 'ര്‍പ്പെ': 4, + 'ര്‍മ്മി': 4, + 'ര്‍രാ': 3, + 'ര്‍വ്വ': 3, + 'ര്‍ഹി': 3, + 'റ്റം': 3, + 'റ്റേ': 3, + 'ല്യാ': 3, + 'ല്ലാ': 3, + 'ല്ലാം': 4, + 'ല്ലെ': 3, + 'ല്‍കി': 3, + 'ല്‍കേ': 3, + 'ല്‍നി': 3, + 'ല്‍പ്പ': 3, + 'ള്ളാ': 3, + 'ള്ളി': 3, + 'ള്‍കൊ': 3, + 'ള്‍ക്ക': 3, + 'ള്‍ക്കി': 4, + 'ള്‍ക്കു': 3, + 'ള്‍ക്കും': 4, + 'ള്‍ക്കെ': 4, + 'ള്‍ക്ക്‌': 3, + 'വ്യം': 3, + 'വ്യാ': 3, + 'ശ്വാ': 3, + 'ഷ്ട്യാ': 4, + 'ഷ്ട്ര': 3, + 'ഷ്ട്രീ': 4, + 'ഷ്യാ': 3, + 'സാം': 3, + 'സ്കാ': 3, + 'സ്ത്രം': 4, + 'സ്ത്രീ': 4, + 'സ്ഥാ': 3, + 'സ്ഥി': 3, + 'സ്റ്റ്‌': 3, + 'സ്വാ': 3, + 'സ്വീ': 3, + 'സ്സാ': 3, + 'സ്സി': 3, + 'സ്സും': 3, + 'സ്സോ': 3, + 'ഹിം': 3, + 'ൻ്റെ': 3, + 'ကျေ': 3, + 'ကြေ': 3, + 'ကြွေ': 3, + 'ချေ': 3, + 'ခြေ': 3, + 'ဇြေ': 3, + 'ဒ္ဂေ': 3, + 'ပျေ': 3, + 'ပြေ': 3, + 'ဖျေံ': 3, + 'ဗ္တေ': 3, + 'ဗ္ၜေ': 3, + 'ဗြေ': 3, + 'မြေ': 3, + 'လျေ': 3, + 'လျှေ': 3, + 'သ္ဂေ': 3, + 'ក្ដៅ': 3, + 'ក្រោ': 3, + 'ក្សា': 3, + 'ខ្ជា': 3, + 'ខ្លា': 3, + 'គ្នា': 3, + 'គ្មា': 3, + 'គ្រា': 3, + 'គ្រឹះ': 3, + 'ង្កើ': 3, + 'ង្រៀ': 3, + 'ង្ហា': 3, + 'ច្ចេ': 3, + 'ច្បា': 3, + 'ឆ្នាំ': 3, + 'ឆ្នោ': 3, + 'ឆ្លើ': 3, + 'ជ្ជា': 3, + 'ជ្ញា': 3, + 'ជ្រើ': 3, + 'ជ្រៀ': 3, + 'ជ្រែ': 3, + 'ឈ្មោះ': 4, + 'ញ្ជា': 3, + 'ញ្ញា': 3, + 'ញ្ញៈ': 3, + 'ដ្ឋា': 3, + 'ណោះ': 3, + 'ណ្ដា': 3, + 'ណ្ដុះ': 3, + 'ណ្ណោះ': 4, + 'ត្រា': 3, + 'ថ្ងៃ': 3, + 'ថ្នា': 3, + 'ថ្លៃ': 3, + 'ទោះ': 3, + 'ទ្យា': 3, + 'ធ្នា': 3, + 'ធ្យា': 3, + 'ធ្យោ': 3, + 'ធ្វើ': 3, + 'នេះ': 3, + 'នោះ': 3, + 'ន្ថែ': 3, + 'ន្ថោ': 3, + 'ន្ទា': 3, + 'ន្ទៈ': 3, + 'ន្យា': 3, + 'ន្លែ': 3, + 'បោះ': 3, + 'ប្ដេ': 3, + 'ប្រា': 3, + 'ប្រើ': 3, + 'ប្រែ': 3, + 'ផ្ដា': 3, + 'ផ្ទា': 3, + 'ផ្ទេ': 3, + 'ផ្នែ': 3, + 'ផ្លា': 3, + 'ផ្សា': 3, + 'ផ្សេ': 3, + 'ផ្សៃ': 3, + 'ពោះ': 3, + 'ព្យា': 3, + 'ព្រៀ': 3, + 'ព្រៃ': 3, + 'ម្ងា': 3, + 'ម្ចា': 3, + 'ម្ដា': 3, + 'ម្ដែ': 3, + 'ម្នា': 3, + 'ម្នេ': 3, + 'ម្ភា': 3, + 'ម្រា': 3, + 'ម្រើ': 3, + 'ម្រេ': 3, + 'ម្លៀ': 3, + 'ម្លៃ': 3, + 'ល្បៈ': 3, + 'ល្មើ': 3, + 'ស្គា': 3, + 'ស្ដ្រី': 3, + 'ស្ត្រ': 3, + 'ស្ថា': 3, + 'ស្នា': 3, + 'ស្មា': 3, + 'ស្មើ': 3, + 'ស្រា': 3, + 'ស្លា': 3, + 'ស្វែ': 3, + 'ᨠᩮ᩠ᨯᩨ': 3, + 'ᨠᩯ᩠ᨯ': 3, + 'ᨠᩯ᩠ᨶ᩵': 3, + 'ᨡᩮ᩠ᨲ': 3, + 'ᨡᩯ᩠ᨠ': 3, + 'ᨡᩯ᩠ᨦ': 3, + 'ᨣᩕ᩠ᩋ': 3, + 'ᨣᩕᩮ᩠ᨦᩨ᩵': 4, + 'ᨣᩯ᩠ᨶᩢ': 3, + 'ᨣᩯ᩠ᩅ': 3, + 'ᨧᩮ᩠ᨷ': 3, + 'ᨧᩱ᩠ᨿ': 3, + 'ᨩᩮ᩠ᩋᩨ': 3, + 'ᨩᩮ᩠ᩋᩨ᩵': 3, + 'ᨩᩮ᩠ᩋᩨ᩶': 3, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 3, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 3, + 'ᨯᩯ᩠ᨦ': 3, + 'ᨯᩯ᩠ᨶ': 3, + 'ᨯᩰ᩠ᨿ': 3, + 'ᨲᩮ᩠ᨠ': 3, + 'ᨲᩮ᩠ᨦ': 3, + 'ᨲᩮ᩠ᨾ': 3, + 'ᨲᩮ᩠ᨾᩨ᩵': 3, + 'ᨲᩯ᩠ᨠ': 3, + 'ᨲᩯ᩠ᨦ᩵': 3, + 'ᨲᩯ᩠ᨾᩢ': 3, + 'ᨲᩱ᩠ᨿ': 3, + 'ᨳᩮ᩠ᨶᩨ᩵': 3, + 'ᨳᩯ᩠ᨦᩢ': 3, + 'ᨳᩯ᩠ᨾ': 3, + 'ᨴᩮ᩠ᩈ': 3, + 'ᨴᩮ᩠ᩈᩱ': 4, + 'ᨴᩯ᩠ᨶ': 3, + 'ᨴᩰ᩠ᩈ': 3, + 'ᨶᩯ᩠ᨶ': 3, + 'ᨷᩮ᩠ᨦᩨ᩶': 3, + 'ᨸᩮ᩠ᨦᩨ': 3, + 'ᨸᩮ᩠ᨶ': 3, + 'ᨹᩮᩨ᩠ᨿ': 3, + 'ᨻᩕ᩠ᩋᩢ': 3, + 'ᨻᩮ᩠ᩋᩨ᩵': 3, + 'ᨽᩱ᩠ᨿ': 3, + 'ᨾᩮ᩠ᨠᩨ': 3, + 'ᨾᩮ᩠ᨦᩨ': 3, + 'ᨾᩮ᩠ᩋᩨ᩵': 3, + 'ᨿᩮ᩠ᨶ': 3, + 'ᨿᩮ᩠ᨾᩨ': 3, + 'ᩁᩮ᩠ᨦᩨ᩵': 3, + 'ᩁᩮ᩠ᨧ': 3, + 'ᩁᩮ᩠ᨶᩨ': 3, + 'ᩁᩮᩨ᩠ᨬ': 3, + 'ᩁᩯ᩠ᨦ': 3, + 'ᩃᩮ᩠ᨠᩨ': 3, + 'ᩃᩮ᩠ᨦᩨ': 3, + 'ᩃᩰ᩠ᨠ': 3, + 'ᩅᩮ᩠ᨶ': 3, + 'ᩅᩮ᩠ᨶᩢ': 3, + 'ᩈᩮ᩠ᩈ': 3, + 'ᩈᩯ᩠ᩅ': 3, + 'ᩈᩱ᩠ᨿ': 3, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 3, + 'ᩉᩮ᩠ᨦᩢᩢ': 3, + 'ᩉᩮ᩠ᨯ': 3, + 'ᩉᩮ᩠ᨲᩩ': 3, + 'ᩉᩮ᩠ᨶᩨ': 3, + 'ᩉᩮ᩠ᨾᩨ': 3, + 'ᩉᩮ᩠ᨾᩨᩨ': 3, + 'ᩉᩯ᩠ᨦ᩵': 3, + 'ᩉᩯ᩠ᨶᩢ': 3, + 'ᩉᩯ᩠ᨾ': 3, + 'ᩉᩱ᩠ᨾ᩵': 3, + 'ᩉᩱ᩠ᨿ᩵': 3, + 'ᩣ᩠ᨲᩱ': 3, + '⛓️‍💥': 3, + '⛹🏻‍♀️': 4, + '⛹🏻‍♂️': 4, + '⛹🏼‍♀️': 4, + '⛹🏼‍♂️': 4, + '⛹🏽‍♀️': 4, + '⛹🏽‍♂️': 4, + '⛹🏾‍♀️': 4, + '⛹🏾‍♂️': 4, + '⛹🏿‍♀️': 4, + '⛹🏿‍♂️': 4, + '❤️‍🔥': 3, + '❤️‍🩹': 3, + 'ꦏꦺꦴ': 3, + 'ꦏ꧀': 2, + 'ꦏ꧀ꦏ': 3, + 'ꦏ꧀ꦏꦁ': 3, + 'ꦏ꧀ꦏꦺ': 4, + 'ꦏ꧀ꦏꦼ': 3, + 'ꦏ꧀ꦔ': 3, + 'ꦏ꧀ꦔꦸ': 3, + 'ꦏ꧀ꦔꦿ': 4, + 'ꦏ꧀ꦕ': 3, + 'ꦏ꧀ꦠ': 3, + 'ꦏ꧀ꦠꦶ': 3, + 'ꦏ꧀ꦠꦸ': 3, + 'ꦏ꧀ꦠꦺ': 4, + 'ꦏ꧀ꦢ': 3, + 'ꦏ꧀ꦢꦂ': 3, + 'ꦏ꧀ꦢꦶ': 3, + 'ꦏ꧀ꦤ': 3, + 'ꦏ꧀ꦤꦶꦁ': 3, + 'ꦏ꧀ꦥ': 3, + 'ꦏ꧀ꦥꦶ': 3, + 'ꦏ꧀ꦥꦿꦶ': 4, + 'ꦏ꧀ꦧ': 3, + 'ꦏ꧀ꦧꦶ': 3, + 'ꦏ꧀ꦧꦺ': 4, + 'ꦏ꧀ꦩ': 3, + 'ꦏ꧀ꦩꦸ': 3, + 'ꦏ꧀ꦪ': 3, + 'ꦏ꧀ꦭ': 3, + 'ꦏ꧀ꦮ': 3, + 'ꦏ꧀ꦱ': 3, + 'ꦏ꧀ꦱꦂ': 3, + 'ꦏ꧀ꦱꦶ': 3, + 'ꦏ꧀ꦱꦸ': 3, + 'ꦏ꧀ꦱꦺ': 4, + 'ꦏ꧀ꦲ': 3, + 'ꦏ꧀ꦲꦁ': 3, + 'ꦏ꧀ꦲꦶꦁ': 3, + 'ꦏ꧀ꦲꦸ': 3, + 'ꦏ꧀ꦲꦺ': 4, + 'ꦏ꧀ꦲꦺꦴ': 5, + 'ꦒꦺꦴ': 3, + 'ꦒꦿꦺ': 3, + 'ꦒ꧀ꦒ': 3, + 'ꦔꦺꦴ': 3, + 'ꦔ꧀ꦒꦼ': 3, + 'ꦔ꧀ꦒꦿꦼꦁ': 4, + 'ꦔ꧀ꦭ': 3, + 'ꦔ꧀ꦭꦁ': 3, + 'ꦔ꧀ꦭꦸ': 3, + 'ꦔ꧀ꦭꦼ': 3, + 'ꦕꦺꦴ': 3, + 'ꦗꦿꦺꦴ': 4, + 'ꦚ꧀ꦕ': 3, + 'ꦚ꧀ꦕꦶ': 3, + 'ꦚ꧀ꦗ': 3, + 'ꦚ꧀ꦗꦶ': 3, + 'ꦚ꧀ꦗꦸꦁ': 3, + 'ꦚ꧀ꦗꦸꦂ': 3, + 'ꦝꦺꦴ': 3, + 'ꦝꦺꦴꦂ': 3, + 'ꦠꦺꦃ': 3, + 'ꦠꦺꦴ': 3, + 'ꦠ꧀': 2, + 'ꦠ꧀ꦏꦁ': 3, + 'ꦠ꧀ꦏꦸ': 3, + 'ꦠ꧀ꦒ': 3, + 'ꦠ꧀ꦔꦸ': 3, + 'ꦠ꧀ꦚ': 3, + 'ꦠ꧀ꦠ': 3, + 'ꦠ꧀ꦠꦶ': 3, + 'ꦠ꧀ꦠꦶꦁ': 3, + 'ꦠ꧀ꦠꦸ': 3, + 'ꦠ꧀ꦠꦺ': 4, + 'ꦠ꧀ꦤ': 3, + 'ꦠ꧀ꦤꦶ': 3, + 'ꦠ꧀ꦩ': 3, + 'ꦠ꧀ꦩꦼ': 3, + 'ꦠ꧀ꦭ': 3, + 'ꦠ꧀ꦭꦺ': 4, + 'ꦠ꧀ꦱ': 3, + 'ꦠ꧀ꦱꦶꦁ': 3, + 'ꦠ꧀ꦱꦶꦃ': 4, + 'ꦠ꧀ꦱꦾ': 4, + 'ꦠ꧀ꦱ꧀ꦮ': 5, + 'ꦠ꧀ꦲ': 3, + 'ꦠ꧀ꦲꦶꦁ': 3, + 'ꦠ꧀ꦲꦺꦴ': 5, + 'ꦢꦺꦴ': 3, + 'ꦢ꧀': 2, + 'ꦢ꧀ꦏ': 3, + 'ꦢ꧀ꦠ': 3, + 'ꦢ꧀ꦠꦶꦁ': 3, + 'ꦢ꧀ꦢ': 3, + 'ꦢ꧀ꦥ': 3, + 'ꦢ꧀ꦩꦺꦴ': 5, + 'ꦢ꧀ꦲ': 3, + 'ꦤꦺꦃ': 3, + 'ꦤꦺꦴ': 3, + 'ꦤ꧀': 2, + 'ꦤ꧀ꦏ': 3, + 'ꦤ꧀ꦏꦁ': 3, + 'ꦤ꧀ꦏꦸ': 3, + 'ꦤ꧀ꦏꦼ': 3, + 'ꦤ꧀ꦒ': 3, + 'ꦤ꧀ꦔ': 3, + 'ꦤ꧀ꦔꦁ': 3, + 'ꦤ꧀ꦔꦶ': 3, + 'ꦤ꧀ꦔꦸ': 3, + 'ꦤ꧀ꦔꦸꦂ': 3, + 'ꦤ꧀ꦔꦺ': 4, + 'ꦤ꧀ꦔꦼ': 3, + 'ꦤ꧀ꦔꦿꦸ': 4, + 'ꦤ꧀ꦗ': 3, + 'ꦤ꧀ꦗꦸ': 3, + 'ꦤ꧀ꦗꦼ': 3, + 'ꦤ꧀ꦚꦶ': 3, + 'ꦤ꧀ꦛꦃ': 4, + 'ꦤ꧀ꦛꦶ': 3, + 'ꦤ꧀ꦝ': 3, + 'ꦤ꧀ꦝꦁ': 3, + 'ꦤ꧀ꦝꦶ': 3, + 'ꦤ꧀ꦝꦸ': 3, + 'ꦤ꧀ꦝꦸꦁ': 3, + 'ꦤ꧀ꦝꦺꦁ': 4, + 'ꦤ꧀ꦝꦺꦴꦁ': 5, + 'ꦤ꧀ꦝꦼ': 3, + 'ꦤ꧀ꦠ': 3, + 'ꦤ꧀ꦠꦂ': 3, + 'ꦤ꧀ꦠꦃ': 4, + 'ꦤ꧀ꦠꦶ': 3, + 'ꦤ꧀ꦠꦸ': 3, + 'ꦤ꧀ꦠꦸꦁ': 3, + 'ꦤ꧀ꦠꦺ': 4, + 'ꦤ꧀ꦠꦼ': 3, + 'ꦤ꧀ꦠꦼꦂ': 3, + 'ꦤ꧀ꦠꦽ': 3, + 'ꦤ꧀ꦢ': 3, + 'ꦤ꧀ꦢꦁ': 3, + 'ꦤ꧀ꦢꦂ': 3, + 'ꦤ꧀ꦢꦶ': 3, + 'ꦤ꧀ꦢꦸ': 3, + 'ꦤ꧀ꦢꦺ': 4, + 'ꦤ꧀ꦢꦼ': 3, + 'ꦤ꧀ꦤ': 3, + 'ꦤ꧀ꦤꦶ': 3, + 'ꦤ꧀ꦤꦶꦁ': 3, + 'ꦤ꧀ꦤꦺ': 4, + 'ꦤ꧀ꦤꦼ': 3, + 'ꦤ꧀ꦥ': 3, + 'ꦤ꧀ꦥꦁ': 3, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 5, + 'ꦤ꧀ꦥꦶ': 3, + 'ꦤ꧀ꦥꦸ': 3, + 'ꦤ꧀ꦥꦼ': 3, + 'ꦤ꧀ꦥꦿ': 4, + 'ꦤ꧀ꦥꦿꦶ': 4, + 'ꦤ꧀ꦧ': 3, + 'ꦤ꧀ꦧꦁ': 3, + 'ꦤ꧀ꦧꦶ': 3, + 'ꦤ꧀ꦧꦸ': 3, + 'ꦤ꧀ꦧꦺ': 4, + 'ꦤ꧀ꦧꦺꦴ': 5, + 'ꦤ꧀ꦧꦼ': 3, + 'ꦤ꧀ꦩ': 3, + 'ꦤ꧀ꦩꦂ': 3, + 'ꦤ꧀ꦩꦶ': 3, + 'ꦤ꧀ꦩꦸꦂ': 3, + 'ꦤ꧀ꦩꦼ': 3, + 'ꦤ꧀ꦭ': 3, + 'ꦤ꧀ꦭꦶ': 3, + 'ꦤ꧀ꦭꦸ': 3, + 'ꦤ꧀ꦮ': 3, + 'ꦤ꧀ꦮꦂ': 3, + 'ꦤ꧀ꦮꦶ': 3, + 'ꦤ꧀ꦮꦸ': 3, + 'ꦤ꧀ꦮꦼ': 3, + 'ꦤ꧀ꦱ': 3, + 'ꦤ꧀ꦱꦂ': 3, + 'ꦤ꧀ꦱꦃ': 4, + 'ꦤ꧀ꦱꦶ': 3, + 'ꦤ꧀ꦱꦶꦁ': 3, + 'ꦤ꧀ꦱꦸ': 3, + 'ꦤ꧀ꦱꦺꦴ': 5, + 'ꦤ꧀ꦱꦼ': 3, + 'ꦤ꧀ꦲ': 3, + 'ꦤ꧀ꦲꦁ': 3, + 'ꦤ꧀ꦲꦶ': 3, + 'ꦤ꧀ꦲꦶꦁ': 3, + 'ꦤ꧀ꦲꦸ': 3, + 'ꦤ꧀ꦲꦺꦴ': 5, + 'ꦥ꦳꧀': 2, + 'ꦥꦺꦴ': 3, + 'ꦥꦿꦃ': 3, + 'ꦥꦿꦺꦴ': 4, + 'ꦥ꧀': 2, + 'ꦥ꧀ꦏ': 3, + 'ꦥ꧀ꦏꦁ': 3, + 'ꦥ꧀ꦠ': 3, + 'ꦥ꧀ꦠꦶ': 3, + 'ꦥ꧀ꦢꦸ': 3, + 'ꦥ꧀ꦤ': 3, + 'ꦥ꧀ꦤꦶ': 3, + 'ꦥ꧀ꦥ': 3, + 'ꦥ꧀ꦥꦶ': 3, + 'ꦥ꧀ꦥꦺ': 4, + 'ꦥ꧀ꦧꦺ': 4, + 'ꦥ꧀ꦩ': 3, + 'ꦥ꧀ꦩꦂ': 3, + 'ꦥ꧀ꦫꦺ': 4, + 'ꦥ꧀ꦭ': 3, + 'ꦥ꧀ꦭꦸ': 3, + 'ꦥ꧀ꦱ': 3, + 'ꦥ꧀ꦱꦶꦂ': 3, + 'ꦥ꧀ꦱꦼ': 3, + 'ꦥ꧀ꦲ': 3, + 'ꦧꦺꦃ': 3, + 'ꦧꦺꦴ': 3, + 'ꦧ꧀': 2, + 'ꦧ꧀ꦏ': 3, + 'ꦧ꧀ꦠꦸ': 3, + 'ꦧ꧀ꦥ': 3, + 'ꦧ꧀ꦧ': 3, + 'ꦧ꧀ꦧꦺ': 4, + 'ꦧ꧀ꦲ': 3, + 'ꦧ꧀ꦲꦶ': 3, + 'ꦩꦺꦃ': 3, + 'ꦩꦺꦴ': 3, + 'ꦩꦿꦃ': 3, + 'ꦩꦿꦶꦃ': 3, + 'ꦩ꧀': 2, + 'ꦩ꧀ꦏꦁ': 3, + 'ꦩ꧀ꦔꦼ': 3, + 'ꦩ꧀ꦠꦸ': 3, + 'ꦩ꧀ꦠꦺꦴ': 5, + 'ꦩ꧀ꦤꦶꦁ': 3, + 'ꦩ꧀ꦥ': 3, + 'ꦩ꧀ꦥꦶ': 3, + 'ꦩ꧀ꦥꦸ': 3, + 'ꦩ꧀ꦥꦼ': 3, + 'ꦩ꧀ꦧ': 3, + 'ꦩ꧀ꦧꦁ': 3, + 'ꦩ꧀ꦧꦂ': 3, + 'ꦩ꧀ꦧꦃ': 4, + 'ꦩ꧀ꦧꦶ': 3, + 'ꦩ꧀ꦧꦸ': 3, + 'ꦩ꧀ꦧꦸꦁ': 3, + 'ꦩ꧀ꦧꦺ': 4, + 'ꦩ꧀ꦧꦺꦂ': 4, + 'ꦩ꧀ꦧꦼꦂ': 3, + 'ꦩ꧀ꦧꦾꦸꦂ': 4, + 'ꦩ꧀ꦩ': 3, + 'ꦩ꧀ꦩꦶ': 3, + 'ꦩ꧀ꦫ': 3, + 'ꦩ꧀ꦫꦃ': 4, + 'ꦩ꧀ꦭ': 3, + 'ꦩ꧀ꦲꦶ': 3, + 'ꦪꦺꦴ': 3, + 'ꦫꦺꦴ': 3, + 'ꦭꦺꦃ': 3, + 'ꦭꦺꦴ': 3, + 'ꦭꦺꦴꦁ': 3, + 'ꦭ꧀': 2, + 'ꦭ꧀ꦏꦁ': 3, + 'ꦭ꧀ꦚꦼꦁ': 3, + 'ꦭ꧀ꦠꦸ': 3, + 'ꦭ꧀ꦧꦸ': 3, + 'ꦭ꧀ꦩꦸ': 3, + 'ꦭ꧀ꦭ': 3, + 'ꦭ꧀ꦭꦶ': 3, + 'ꦭ꧀ꦭꦶꦁ': 3, + 'ꦭ꧀ꦭꦺ': 4, + 'ꦭ꧀ꦮ': 3, + 'ꦭ꧀ꦱ': 3, + 'ꦭ꧀ꦱꦂ': 3, + 'ꦭ꧀ꦱꦶꦁ': 3, + 'ꦭ꧀ꦱꦸ': 3, + 'ꦭ꧀ꦲ': 3, + 'ꦭ꧀ꦲꦁ': 3, + 'ꦭ꧀ꦲꦶꦁ': 3, + 'ꦭ꧀ꦲꦸ': 3, + 'ꦮꦺꦴ': 3, + 'ꦮꦺꦴꦁ': 3, + 'ꦮꦺꦴꦃ': 4, + 'ꦮꦿꦸꦃ': 3, + 'ꦱꦺꦴ': 3, + 'ꦱꦿꦃ': 3, + 'ꦱ꧀': 2, + 'ꦱ꧀ꦏ': 3, + 'ꦱ꧀ꦏꦁ': 3, + 'ꦱ꧀ꦏꦿꦶ': 4, + 'ꦱ꧀ꦒ': 3, + 'ꦱ꧀ꦔꦸ': 3, + 'ꦱ꧀ꦔꦿ': 4, + 'ꦱ꧀ꦛꦶ': 3, + 'ꦱ꧀ꦠ': 3, + 'ꦱ꧀ꦠꦿ': 4, + 'ꦱ꧀ꦢꦂ': 3, + 'ꦱ꧀ꦢꦶ': 3, + 'ꦱ꧀ꦢꦸ': 3, + 'ꦱ꧀ꦥ': 3, + 'ꦱ꧀ꦧ': 3, + 'ꦱ꧀ꦧꦁ': 3, + 'ꦱ꧀ꦩ': 3, + 'ꦱ꧀ꦩꦶ': 3, + 'ꦱ꧀ꦩꦼ': 3, + 'ꦱ꧀ꦩꦿ': 4, + 'ꦱ꧀ꦭ': 3, + 'ꦱ꧀ꦮ': 3, + 'ꦱ꧀ꦱ': 3, + 'ꦱ꧀ꦱꦂ': 3, + 'ꦱ꧀ꦱꦶ': 3, + 'ꦱ꧀ꦱꦶꦁ': 3, + 'ꦱ꧀ꦱꦸ': 3, + 'ꦱ꧀ꦱꦺ': 4, + 'ꦱ꧀ꦲ': 3, + 'ꦱ꧀ꦲꦁ': 3, + 'ꦱ꧀ꦲꦶ': 3, + 'ꦱ꧀ꦲꦶꦁ': 3, + 'ꦱ꧀ꦲꦸ': 3, + 'ꦲꦺꦴ': 3, + '𑄇𑄳𑄠𑄬': 3, + '𑄈𑄳𑄠𑄬': 3, + '𑄌𑄳𑄠𑄬': 3, + '𑄎𑄳𑄠𑄬': 3, + '𑄑𑄳𑄢𑄬': 3, + '𑄖𑄳𑄠𑄬': 3, + '𑄖𑄳𑄢𑄬': 3, + '𑄘𑄳𑄠𑄬': 3, + '𑄚𑄳𑄠𑄬': 3, + '𑄝𑄳𑄢𑄬': 3, + '𑄟𑄳𑄠𑄬': 3, + '𑄡𑄳𑄠𑄬': 3, + '𑄣𑄳𑄦𑄬': 3, + '𑌕𑌾𑌂': 3, + '𑌕𑌾𑌃': 3, + '𑌕𑍍': 2, + '𑌗𑍍': 2, + '𑌚𑍍': 2, + '𑌜𑍍': 2, + '𑌞𑍍': 2, + '𑌟𑌾𑌂': 3, + '𑌟𑌾𑌃': 3, + '𑌟𑍍': 2, + '𑌠𑍈𑌃': 3, + '𑌣𑌾𑌂': 3, + '𑌣𑍍': 2, + '𑌤𑌾𑌂': 3, + '𑌤𑌾𑌃': 3, + '𑌤𑌿𑌂': 3, + '𑌤𑌿𑌃': 3, + '𑌤𑍁𑌂': 3, + '𑌤𑍇𑌃': 3, + '𑌤𑍍': 2, + '𑌥𑌾𑌂': 3, + '𑌦𑍍': 2, + '𑌧𑌾𑌃': 3, + '𑌧𑌿𑌂': 3, + '𑌧𑍇𑌃': 3, + '𑌧𑍈𑌃': 3, + '𑌧𑍍': 2, + '𑌨𑌾𑌂': 3, + '𑌨𑌾𑌃': 3, + '𑌨𑌿𑌃': 3, + '𑌨𑍈𑌃': 3, + '𑌨𑍍': 2, + '𑌪𑍍': 2, + '𑌬𑍍': 2, + '𑌭𑌿𑌃': 3, + '𑌭𑍍': 2, + '𑌮𑌿𑌂': 3, + '𑌮𑍍': 2, + '𑌯𑌾𑌂': 3, + '𑌯𑌾𑌃': 3, + '𑌯𑍁𑌃': 3, + '𑌯𑍈𑌃': 3, + '𑌯𑍋𑌃': 3, + '𑌯𑍍': 2, + '𑌰𑌾𑌃': 3, + '𑌰𑌿𑌂': 3, + '𑌰𑍍': 2, + '𑌲𑌾𑌃': 3, + '𑌲𑌿𑌂': 3, + '𑌲𑍍': 2, + '𑌵𑌾𑌂': 3, + '𑌵𑌾𑌃': 3, + '𑌵𑍍': 2, + '𑌶𑌾𑌃': 3, + '𑌶𑍍': 2, + '𑌷𑌾𑌂': 3, + '𑌷𑌾𑌃': 3, + '𑌷𑍍': 2, + '𑌸𑌾𑌂': 3, + '𑌸𑍍': 2, + '𑌹𑌾𑌃': 3, + '🍄‍🟫': 4, + '🍋‍🟩': 4, + '🏃‍♀️': 3, + '🏃‍♀️‍➡️': 4, + '🏃‍♂️': 3, + '🏃‍♂️‍➡️': 4, + '🏃‍➡️': 3, + '🏃🏻‍♀️': 5, + '🏃🏻‍♀️‍➡️': 6, + '🏃🏻‍♂️': 5, + '🏃🏻‍♂️‍➡️': 6, + '🏃🏻‍➡️': 5, + '🏃🏼‍♀️': 5, + '🏃🏼‍♀️‍➡️': 6, + '🏃🏼‍♂️': 5, + '🏃🏼‍♂️‍➡️': 6, + '🏃🏼‍➡️': 5, + '🏃🏽‍♀️': 5, + '🏃🏽‍♀️‍➡️': 6, + '🏃🏽‍♂️': 5, + '🏃🏽‍♂️‍➡️': 6, + '🏃🏽‍➡️': 5, + '🏃🏾‍♀️': 5, + '🏃🏾‍♀️‍➡️': 6, + '🏃🏾‍♂️': 5, + '🏃🏾‍♂️‍➡️': 6, + '🏃🏾‍➡️': 5, + '🏃🏿‍♀️': 5, + '🏃🏿‍♀️‍➡️': 6, + '🏃🏿‍♂️': 5, + '🏃🏿‍♂️‍➡️': 6, + '🏃🏿‍➡️': 5, + '🏄‍♀️': 3, + '🏄‍♂️': 3, + '🏄🏻‍♀️': 5, + '🏄🏻‍♂️': 5, + '🏄🏼‍♀️': 5, + '🏄🏼‍♂️': 5, + '🏄🏽‍♀️': 5, + '🏄🏽‍♂️': 5, + '🏄🏾‍♀️': 5, + '🏄🏾‍♂️': 5, + '🏄🏿‍♀️': 5, + '🏄🏿‍♂️': 5, + '🏊‍♀️': 3, + '🏊‍♂️': 3, + '🏊🏻‍♀️': 5, + '🏊🏻‍♂️': 5, + '🏊🏼‍♀️': 5, + '🏊🏼‍♂️': 5, + '🏊🏽‍♀️': 5, + '🏊🏽‍♂️': 5, + '🏊🏾‍♀️': 5, + '🏊🏾‍♂️': 5, + '🏊🏿‍♀️': 5, + '🏊🏿‍♂️': 5, + '🏋🏻‍♀️': 4, + '🏋🏻‍♂️': 4, + '🏋🏼‍♀️': 4, + '🏋🏼‍♂️': 4, + '🏋🏽‍♀️': 4, + '🏋🏽‍♂️': 4, + '🏋🏾‍♀️': 4, + '🏋🏾‍♂️': 4, + '🏋🏿‍♀️': 4, + '🏋🏿‍♂️': 4, + '🏌🏻‍♀️': 4, + '🏌🏻‍♂️': 4, + '🏌🏼‍♀️': 4, + '🏌🏼‍♂️': 4, + '🏌🏽‍♀️': 4, + '🏌🏽‍♂️': 4, + '🏌🏾‍♀️': 4, + '🏌🏾‍♂️': 4, + '🏌🏿‍♀️': 4, + '🏌🏿‍♂️': 4, + '🏳️‍🌈': 3, + '🏴‍☠️': 3, + '🐈‍⬛': 4, + '🐕‍🦺': 4, + '🐦‍⬛': 4, + '🐦‍🔥': 4, + '🐻‍❄️': 3, + '👨‍⚕️': 3, + '👨‍⚖️': 3, + '👨‍✈️': 3, + '👨‍❤️‍👨': 5, + '👨‍❤️‍💋‍👨': 7, + '👨‍🌾': 4, + '👨‍🍳': 4, + '👨‍🍼': 4, + '👨‍🎓': 4, + '👨‍🎤': 4, + '👨‍🎨': 4, + '👨‍🏫': 4, + '👨‍🏭': 4, + '👨‍👦': 4, + '👨‍👦‍👦': 6, + '👨‍👧': 4, + '👨‍👧‍👦': 6, + '👨‍👧‍👧': 6, + '👨‍👨‍👦': 6, + '👨‍👨‍👦‍👦': 8, + '👨‍👨‍👧': 6, + '👨‍👨‍👧‍👦': 8, + '👨‍👨‍👧‍👧': 8, + '👨‍👩‍👦': 6, + '👨‍👩‍👦‍👦': 8, + '👨‍👩‍👧': 6, + '👨‍👩‍👧‍👦': 8, + '👨‍👩‍👧‍👧': 8, + '👨‍💻': 4, + '👨‍💼': 4, + '👨‍🔧': 4, + '👨‍🔬': 4, + '👨‍🚀': 4, + '👨‍🚒': 4, + '👨‍🦯': 4, + '👨‍🦯‍➡️': 5, + '👨‍🦰': 4, + '👨‍🦱': 4, + '👨‍🦲': 4, + '👨‍🦳': 4, + '👨‍🦼': 4, + '👨‍🦼‍➡️': 5, + '👨‍🦽': 4, + '👨‍🦽‍➡️': 5, + '👨🏻‍⚕️': 5, + '👨🏻‍⚖️': 5, + '👨🏻‍✈️': 5, + '👨🏻‍❤️‍👨🏻': 9, + '👨🏻‍❤️‍👨🏽': 9, + '👨🏻‍❤️‍👨🏿': 9, + '👨🏻‍❤️‍💋‍👨🏻': 11, + '👨🏻‍❤️‍💋‍👨🏽': 11, + '👨🏻‍❤️‍💋‍👨🏾': 11, + '👨🏻‍❤️‍💋‍👨🏿': 11, + '👨🏻‍🌾': 6, + '👨🏻‍🍳': 6, + '👨🏻‍🍼': 6, + '👨🏻‍🎓': 6, + '👨🏻‍🎤': 6, + '👨🏻‍🎨': 6, + '👨🏻‍🏫': 6, + '👨🏻‍🏭': 6, + '👨🏻‍🐰‍👨🏼': 10, + '👨🏻‍🐰‍👨🏽': 10, + '👨🏻‍🐰‍👨🏾': 10, + '👨🏻‍🐰‍👨🏿': 10, + '👨🏻‍💻': 6, + '👨🏻‍💼': 6, + '👨🏻‍🔧': 6, + '👨🏻‍🔬': 6, + '👨🏻‍🚀': 6, + '👨🏻‍🚒': 6, + '👨🏻‍🤝‍👨🏼': 10, + '👨🏻‍🤝‍👨🏽': 10, + '👨🏻‍🤝‍👨🏾': 10, + '👨🏻‍🤝‍👨🏿': 10, + '👨🏻‍🦯': 6, + '👨🏻‍🦯‍➡️': 7, + '👨🏻‍🦰': 6, + '👨🏻‍🦱': 6, + '👨🏻‍🦲': 6, + '👨🏻‍🦳': 6, + '👨🏻‍🦼': 6, + '👨🏻‍🦼‍➡️': 7, + '👨🏻‍🦽': 6, + '👨🏻‍🦽‍➡️': 7, + '👨🏻‍🫯‍👨🏼': 9, + '👨🏻‍🫯‍👨🏽': 9, + '👨🏻‍🫯‍👨🏾': 9, + '👨🏻‍🫯‍👨🏿': 9, + '👨🏼‍⚕️': 5, + '👨🏼‍⚖️': 5, + '👨🏼‍✈️': 5, + '👨🏼‍❤️‍👨🏼': 9, + '👨🏼‍❤️‍💋‍👨🏼': 11, + '👨🏼‍❤️‍💋‍👨🏿': 11, + '👨🏼‍🌾': 6, + '👨🏼‍🍳': 6, + '👨🏼‍🍼': 6, + '👨🏼‍🎓': 6, + '👨🏼‍🎤': 6, + '👨🏼‍🎨': 6, + '👨🏼‍🏫': 6, + '👨🏼‍🏭': 6, + '👨🏼‍🐰‍👨🏻': 10, + '👨🏼‍🐰‍👨🏽': 10, + '👨🏼‍🐰‍👨🏿': 10, + '👨🏼‍💻': 6, + '👨🏼‍💼': 6, + '👨🏼‍🔧': 6, + '👨🏼‍🔬': 6, + '👨🏼‍🚀': 6, + '👨🏼‍🚒': 6, + '👨🏼‍🤝‍👨🏻': 10, + '👨🏼‍🤝‍👨🏽': 10, + '👨🏼‍🤝‍👨🏿': 10, + '👨🏼‍🦯': 6, + '👨🏼‍🦯‍➡️': 7, + '👨🏼‍🦰': 6, + '👨🏼‍🦱': 6, + '👨🏼‍🦲': 6, + '👨🏼‍🦳': 6, + '👨🏼‍🦼': 6, + '👨🏼‍🦽': 6, + '👨🏼‍🦽‍➡️': 7, + '👨🏼‍🫯‍👨🏻': 9, + '👨🏼‍🫯‍👨🏽': 9, + '👨🏼‍🫯‍👨🏾': 9, + '👨🏼‍🫯‍👨🏿': 9, + '👨🏽‍⚕️': 5, + '👨🏽‍⚖️': 5, + '👨🏽‍✈️': 5, + '👨🏽‍❤️‍👨🏻': 9, + '👨🏽‍❤️‍👨🏽': 9, + '👨🏽‍❤️‍👨🏿': 9, + '👨🏽‍❤️‍💋‍👨🏻': 11, + '👨🏽‍❤️‍💋‍👨🏽': 11, + '👨🏽‍❤️‍💋‍👨🏿': 11, + '👨🏽‍🌾': 6, + '👨🏽‍🍳': 6, + '👨🏽‍🍼': 6, + '👨🏽‍🎓': 6, + '👨🏽‍🎤': 6, + '👨🏽‍🎨': 6, + '👨🏽‍🏫': 6, + '👨🏽‍🏭': 6, + '👨🏽‍🐰‍👨🏻': 10, + '👨🏽‍🐰‍👨🏼': 10, + '👨🏽‍🐰‍👨🏾': 10, + '👨🏽‍🐰‍👨🏿': 10, + '👨🏽‍💻': 6, + '👨🏽‍💼': 6, + '👨🏽‍🔧': 6, + '👨🏽‍🔬': 6, + '👨🏽‍🚀': 6, + '👨🏽‍🚒': 6, + '👨🏽‍🤝‍👨🏻': 10, + '👨🏽‍🤝‍👨🏼': 10, + '👨🏽‍🤝‍👨🏾': 10, + '👨🏽‍🤝‍👨🏿': 10, + '👨🏽‍🦯': 6, + '👨🏽‍🦯‍➡️': 7, + '👨🏽‍🦰': 6, + '👨🏽‍🦱': 6, + '👨🏽‍🦲': 6, + '👨🏽‍🦳': 6, + '👨🏽‍🦼': 6, + '👨🏽‍🦼‍➡️': 7, + '👨🏽‍🦽': 6, + '👨🏽‍🦽‍➡️': 7, + '👨🏽‍🫯‍👨🏻': 9, + '👨🏽‍🫯‍👨🏼': 9, + '👨🏽‍🫯‍👨🏾': 9, + '👨🏽‍🫯‍👨🏿': 9, + '👨🏾‍⚕️': 5, + '👨🏾‍⚖️': 5, + '👨🏾‍✈️': 5, + '👨🏾‍❤️‍👨🏾': 9, + '👨🏾‍❤️‍💋‍👨🏻': 11, + '👨🏾‍❤️‍💋‍👨🏾': 11, + '👨🏾‍❤️‍💋‍👨🏿': 11, + '👨🏾‍🌾': 6, + '👨🏾‍🍳': 6, + '👨🏾‍🍼': 6, + '👨🏾‍🎓': 6, + '👨🏾‍🎤': 6, + '👨🏾‍🎨': 6, + '👨🏾‍🏫': 6, + '👨🏾‍🏭': 6, + '👨🏾‍🐰‍👨🏻': 10, + '👨🏾‍🐰‍👨🏽': 10, + '👨🏾‍🐰‍👨🏿': 10, + '👨🏾‍💻': 6, + '👨🏾‍💼': 6, + '👨🏾‍🔧': 6, + '👨🏾‍🔬': 6, + '👨🏾‍🚀': 6, + '👨🏾‍🚒': 6, + '👨🏾‍🤝‍👨🏻': 10, + '👨🏾‍🤝‍👨🏽': 10, + '👨🏾‍🤝‍👨🏿': 10, + '👨🏾‍🦯': 6, + '👨🏾‍🦯‍➡️': 7, + '👨🏾‍🦰': 6, + '👨🏾‍🦱': 6, + '👨🏾‍🦲': 6, + '👨🏾‍🦳': 6, + '👨🏾‍🦼': 6, + '👨🏾‍🦽': 6, + '👨🏾‍🦽‍➡️': 7, + '👨🏾‍🫯‍👨🏻': 9, + '👨🏾‍🫯‍👨🏼': 9, + '👨🏾‍🫯‍👨🏽': 9, + '👨🏾‍🫯‍👨🏿': 9, + '👨🏿‍⚕️': 5, + '👨🏿‍⚖️': 5, + '👨🏿‍✈️': 5, + '👨🏿‍❤️‍👨🏻': 9, + '👨🏿‍❤️‍👨🏽': 9, + '👨🏿‍❤️‍👨🏿': 9, + '👨🏿‍❤️‍💋‍👨🏻': 11, + '👨🏿‍❤️‍💋‍👨🏼': 11, + '👨🏿‍❤️‍💋‍👨🏽': 11, + '👨🏿‍❤️‍💋‍👨🏾': 11, + '👨🏿‍❤️‍💋‍👨🏿': 11, + '👨🏿‍🌾': 6, + '👨🏿‍🍳': 6, + '👨🏿‍🍼': 6, + '👨🏿‍🎓': 6, + '👨🏿‍🎤': 6, + '👨🏿‍🎨': 6, + '👨🏿‍🏫': 6, + '👨🏿‍🏭': 6, + '👨🏿‍🐰‍👨🏻': 10, + '👨🏿‍🐰‍👨🏼': 10, + '👨🏿‍🐰‍👨🏽': 10, + '👨🏿‍🐰‍👨🏾': 10, + '👨🏿‍💻': 6, + '👨🏿‍💼': 6, + '👨🏿‍🔧': 6, + '👨🏿‍🔬': 6, + '👨🏿‍🚀': 6, + '👨🏿‍🚒': 6, + '👨🏿‍🤝‍👨🏻': 10, + '👨🏿‍🤝‍👨🏼': 10, + '👨🏿‍🤝‍👨🏽': 10, + '👨🏿‍🤝‍👨🏾': 10, + '👨🏿‍🦯': 6, + '👨🏿‍🦯‍➡️': 7, + '👨🏿‍🦰': 6, + '👨🏿‍🦱': 6, + '👨🏿‍🦲': 6, + '👨🏿‍🦳': 6, + '👨🏿‍🦼': 6, + '👨🏿‍🦼‍➡️': 7, + '👨🏿‍🦽': 6, + '👨🏿‍🦽‍➡️': 7, + '👨🏿‍🫯‍👨🏻': 9, + '👨🏿‍🫯‍👨🏼': 9, + '👨🏿‍🫯‍👨🏽': 9, + '👨🏿‍🫯‍👨🏾': 9, + '👩‍⚕️': 3, + '👩‍⚖️': 3, + '👩‍✈️': 3, + '👩‍❤️‍👨': 5, + '👩‍❤️‍👩': 5, + '👩‍❤️‍💋‍👨': 7, + '👩‍❤️‍💋‍👩': 7, + '👩‍🌾': 4, + '👩‍🍳': 4, + '👩‍🍼': 4, + '👩‍🎓': 4, + '👩‍🎤': 4, + '👩‍🎨': 4, + '👩‍🏫': 4, + '👩‍🏭': 4, + '👩‍👦': 4, + '👩‍👦‍👦': 6, + '👩‍👧': 4, + '👩‍👧‍👦': 6, + '👩‍👧‍👧': 6, + '👩‍👩‍👦': 6, + '👩‍👩‍👦‍👦': 8, + '👩‍👩‍👧': 6, + '👩‍👩‍👧‍👦': 8, + '👩‍👩‍👧‍👧': 8, + '👩‍💻': 4, + '👩‍💼': 4, + '👩‍🔧': 4, + '👩‍🔬': 4, + '👩‍🚀': 4, + '👩‍🚒': 4, + '👩‍🦯': 4, + '👩‍🦯‍➡️': 5, + '👩‍🦰': 4, + '👩‍🦱': 4, + '👩‍🦲': 4, + '👩‍🦳': 4, + '👩‍🦼': 4, + '👩‍🦼‍➡️': 5, + '👩‍🦽': 4, + '👩‍🦽‍➡️': 5, + '👩🏻‍⚕️': 5, + '👩🏻‍⚖️': 5, + '👩🏻‍✈️': 5, + '👩🏻‍❤️‍👨🏻': 9, + '👩🏻‍❤️‍👨🏿': 9, + '👩🏻‍❤️‍👩🏻': 9, + '👩🏻‍❤️‍💋‍👨🏻': 11, + '👩🏻‍❤️‍💋‍👨🏽': 11, + '👩🏻‍❤️‍💋‍👨🏿': 11, + '👩🏻‍❤️‍💋‍👩🏻': 11, + '👩🏻‍❤️‍💋‍👩🏽': 11, + '👩🏻‍❤️‍💋‍👩🏿': 11, + '👩🏻‍🌾': 6, + '👩🏻‍🍳': 6, + '👩🏻‍🍼': 6, + '👩🏻‍🎓': 6, + '👩🏻‍🎤': 6, + '👩🏻‍🎨': 6, + '👩🏻‍🏫': 6, + '👩🏻‍🏭': 6, + '👩🏻‍🐰‍👩🏼': 10, + '👩🏻‍🐰‍👩🏽': 10, + '👩🏻‍🐰‍👩🏾': 10, + '👩🏻‍🐰‍👩🏿': 10, + '👩🏻‍💻': 6, + '👩🏻‍💼': 6, + '👩🏻‍🔧': 6, + '👩🏻‍🔬': 6, + '👩🏻‍🚀': 6, + '👩🏻‍🚒': 6, + '👩🏻‍🤝‍👨🏽': 10, + '👩🏻‍🤝‍👨🏿': 10, + '👩🏻‍🤝‍👩🏼': 10, + '👩🏻‍🤝‍👩🏽': 10, + '👩🏻‍🤝‍👩🏾': 10, + '👩🏻‍🤝‍👩🏿': 10, + '👩🏻‍🦯': 6, + '👩🏻‍🦯‍➡️': 7, + '👩🏻‍🦰': 6, + '👩🏻‍🦱': 6, + '👩🏻‍🦲': 6, + '👩🏻‍🦳': 6, + '👩🏻‍🦼': 6, + '👩🏻‍🦼‍➡️': 7, + '👩🏻‍🦽': 6, + '👩🏻‍🦽‍➡️': 7, + '👩🏻‍🫯‍👩🏼': 9, + '👩🏻‍🫯‍👩🏽': 9, + '👩🏻‍🫯‍👩🏾': 9, + '👩🏻‍🫯‍👩🏿': 9, + '👩🏼‍⚕️': 5, + '👩🏼‍⚖️': 5, + '👩🏼‍✈️': 5, + '👩🏼‍❤️‍👨🏼': 9, + '👩🏼‍❤️‍👩🏼': 9, + '👩🏼‍❤️‍💋‍👨🏼': 11, + '👩🏼‍❤️‍💋‍👩🏼': 11, + '👩🏼‍🌾': 6, + '👩🏼‍🍳': 6, + '👩🏼‍🍼': 6, + '👩🏼‍🎓': 6, + '👩🏼‍🎤': 6, + '👩🏼‍🎨': 6, + '👩🏼‍🏫': 6, + '👩🏼‍🏭': 6, + '👩🏼‍🐰‍👩🏻': 10, + '👩🏼‍🐰‍👩🏿': 10, + '👩🏼‍💻': 6, + '👩🏼‍💼': 6, + '👩🏼‍🔧': 6, + '👩🏼‍🔬': 6, + '👩🏼‍🚀': 6, + '👩🏼‍🚒': 6, + '👩🏼‍🤝‍👩🏻': 10, + '👩🏼‍🤝‍👩🏽': 10, + '👩🏼‍🤝‍👩🏿': 10, + '👩🏼‍🦯': 6, + '👩🏼‍🦯‍➡️': 7, + '👩🏼‍🦰': 6, + '👩🏼‍🦱': 6, + '👩🏼‍🦲': 6, + '👩🏼‍🦳': 6, + '👩🏼‍🦼': 6, + '👩🏼‍🦽': 6, + '👩🏼‍🫯‍👩🏻': 9, + '👩🏼‍🫯‍👩🏽': 9, + '👩🏼‍🫯‍👩🏾': 9, + '👩🏼‍🫯‍👩🏿': 9, + '👩🏽‍⚕️': 5, + '👩🏽‍⚖️': 5, + '👩🏽‍✈️': 5, + '👩🏽‍❤️‍👨🏽': 9, + '👩🏽‍❤️‍👩🏽': 9, + '👩🏽‍❤️‍💋‍👨🏻': 11, + '👩🏽‍❤️‍💋‍👨🏽': 11, + '👩🏽‍❤️‍💋‍👨🏿': 11, + '👩🏽‍❤️‍💋‍👩🏻': 11, + '👩🏽‍❤️‍💋‍👩🏽': 11, + '👩🏽‍❤️‍💋‍👩🏿': 11, + '👩🏽‍🌾': 6, + '👩🏽‍🍳': 6, + '👩🏽‍🍼': 6, + '👩🏽‍🎓': 6, + '👩🏽‍🎤': 6, + '👩🏽‍🎨': 6, + '👩🏽‍🏫': 6, + '👩🏽‍🏭': 6, + '👩🏽‍🐰‍👩🏻': 10, + '👩🏽‍🐰‍👩🏾': 10, + '👩🏽‍🐰‍👩🏿': 10, + '👩🏽‍💻': 6, + '👩🏽‍💼': 6, + '👩🏽‍🔧': 6, + '👩🏽‍🔬': 6, + '👩🏽‍🚀': 6, + '👩🏽‍🚒': 6, + '👩🏽‍🤝‍👨🏻': 10, + '👩🏽‍🤝‍👨🏿': 10, + '👩🏽‍🤝‍👩🏻': 10, + '👩🏽‍🤝‍👩🏼': 10, + '👩🏽‍🤝‍👩🏾': 10, + '👩🏽‍🤝‍👩🏿': 10, + '👩🏽‍🦯': 6, + '👩🏽‍🦯‍➡️': 7, + '👩🏽‍🦰': 6, + '👩🏽‍🦱': 6, + '👩🏽‍🦲': 6, + '👩🏽‍🦳': 6, + '👩🏽‍🦼': 6, + '👩🏽‍🦼‍➡️': 7, + '👩🏽‍🦽': 6, + '👩🏽‍🦽‍➡️': 7, + '👩🏽‍🫯‍👩🏻': 9, + '👩🏽‍🫯‍👩🏼': 9, + '👩🏽‍🫯‍👩🏾': 9, + '👩🏽‍🫯‍👩🏿': 9, + '👩🏾‍⚕️': 5, + '👩🏾‍⚖️': 5, + '👩🏾‍✈️': 5, + '👩🏾‍❤️‍👨🏾': 9, + '👩🏾‍❤️‍👩🏾': 9, + '👩🏾‍❤️‍💋‍👨🏾': 11, + '👩🏾‍❤️‍💋‍👩🏾': 11, + '👩🏾‍🌾': 6, + '👩🏾‍🍳': 6, + '👩🏾‍🍼': 6, + '👩🏾‍🎓': 6, + '👩🏾‍🎤': 6, + '👩🏾‍🎨': 6, + '👩🏾‍🏫': 6, + '👩🏾‍🏭': 6, + '👩🏾‍🐰‍👩🏻': 10, + '👩🏾‍🐰‍👩🏽': 10, + '👩🏾‍🐰‍👩🏿': 10, + '👩🏾‍💻': 6, + '👩🏾‍💼': 6, + '👩🏾‍🔧': 6, + '👩🏾‍🔬': 6, + '👩🏾‍🚀': 6, + '👩🏾‍🚒': 6, + '👩🏾‍🤝‍👩🏻': 10, + '👩🏾‍🤝‍👩🏽': 10, + '👩🏾‍🤝‍👩🏿': 10, + '👩🏾‍🦯': 6, + '👩🏾‍🦯‍➡️': 7, + '👩🏾‍🦰': 6, + '👩🏾‍🦱': 6, + '👩🏾‍🦲': 6, + '👩🏾‍🦳': 6, + '👩🏾‍🦼': 6, + '👩🏾‍🦽': 6, + '👩🏾‍🦽‍➡️': 7, + '👩🏾‍🫯‍👩🏻': 9, + '👩🏾‍🫯‍👩🏼': 9, + '👩🏾‍🫯‍👩🏽': 9, + '👩🏾‍🫯‍👩🏿': 9, + '👩🏿‍⚕️': 5, + '👩🏿‍⚖️': 5, + '👩🏿‍✈️': 5, + '👩🏿‍❤️‍👨🏻': 9, + '👩🏿‍❤️‍👨🏿': 9, + '👩🏿‍❤️‍👩🏿': 9, + '👩🏿‍❤️‍💋‍👨🏻': 11, + '👩🏿‍❤️‍💋‍👨🏽': 11, + '👩🏿‍❤️‍💋‍👨🏿': 11, + '👩🏿‍❤️‍💋‍👩🏻': 11, + '👩🏿‍❤️‍💋‍👩🏽': 11, + '👩🏿‍❤️‍💋‍👩🏿': 11, + '👩🏿‍🌾': 6, + '👩🏿‍🍳': 6, + '👩🏿‍🍼': 6, + '👩🏿‍🎓': 6, + '👩🏿‍🎤': 6, + '👩🏿‍🎨': 6, + '👩🏿‍🏫': 6, + '👩🏿‍🏭': 6, + '👩🏿‍🐰‍👩🏻': 10, + '👩🏿‍🐰‍👩🏼': 10, + '👩🏿‍🐰‍👩🏽': 10, + '👩🏿‍🐰‍👩🏾': 10, + '👩🏿‍💻': 6, + '👩🏿‍💼': 6, + '👩🏿‍🔧': 6, + '👩🏿‍🔬': 6, + '👩🏿‍🚀': 6, + '👩🏿‍🚒': 6, + '👩🏿‍🤝‍👨🏻': 10, + '👩🏿‍🤝‍👨🏽': 10, + '👩🏿‍🤝‍👩🏻': 10, + '👩🏿‍🤝‍👩🏼': 10, + '👩🏿‍🤝‍👩🏽': 10, + '👩🏿‍🤝‍👩🏾': 10, + '👩🏿‍🦯': 6, + '👩🏿‍🦯‍➡️': 7, + '👩🏿‍🦰': 6, + '👩🏿‍🦱': 6, + '👩🏿‍🦲': 6, + '👩🏿‍🦳': 6, + '👩🏿‍🦼': 6, + '👩🏿‍🦼‍➡️': 7, + '👩🏿‍🦽': 6, + '👩🏿‍🦽‍➡️': 7, + '👩🏿‍🫯‍👩🏻': 9, + '👩🏿‍🫯‍👩🏼': 9, + '👩🏿‍🫯‍👩🏽': 9, + '👩🏿‍🫯‍👩🏾': 9, + '👮‍♀️': 3, + '👮‍♂️': 3, + '👮🏻‍♀️': 5, + '👮🏻‍♂️': 5, + '👮🏼‍♀️': 5, + '👮🏼‍♂️': 5, + '👮🏽‍♀️': 5, + '👮🏽‍♂️': 5, + '👮🏾‍♀️': 5, + '👮🏾‍♂️': 5, + '👮🏿‍♀️': 5, + '👮🏿‍♂️': 5, + '👯‍♀️': 3, + '👯‍♂️': 3, + '👯🏻‍♀️': 5, + '👯🏻‍♂️': 5, + '👯🏼‍♀️': 5, + '👯🏼‍♂️': 5, + '👯🏽‍♀️': 5, + '👯🏽‍♂️': 5, + '👯🏾‍♀️': 5, + '👯🏾‍♂️': 5, + '👯🏿‍♀️': 5, + '👯🏿‍♂️': 5, + '👰‍♀️': 3, + '👰‍♂️': 3, + '👰🏻‍♀️': 5, + '👰🏻‍♂️': 5, + '👰🏼‍♀️': 5, + '👰🏼‍♂️': 5, + '👰🏽‍♀️': 5, + '👰🏽‍♂️': 5, + '👰🏾‍♀️': 5, + '👰🏾‍♂️': 5, + '👰🏿‍♀️': 5, + '👰🏿‍♂️': 5, + '👱‍♀️': 3, + '👱‍♂️': 3, + '👱🏻‍♀️': 5, + '👱🏻‍♂️': 5, + '👱🏼‍♀️': 5, + '👱🏼‍♂️': 5, + '👱🏽‍♀️': 5, + '👱🏽‍♂️': 5, + '👱🏾‍♀️': 5, + '👱🏾‍♂️': 5, + '👱🏿‍♀️': 5, + '👱🏿‍♂️': 5, + '👳‍♀️': 3, + '👳‍♂️': 3, + '👳🏻‍♀️': 5, + '👳🏻‍♂️': 5, + '👳🏼‍♀️': 5, + '👳🏼‍♂️': 5, + '👳🏽‍♀️': 5, + '👳🏽‍♂️': 5, + '👳🏾‍♀️': 5, + '👳🏾‍♂️': 5, + '👳🏿‍♀️': 5, + '👳🏿‍♂️': 5, + '👷‍♀️': 3, + '👷‍♂️': 3, + '👷🏻‍♀️': 5, + '👷🏻‍♂️': 5, + '👷🏼‍♀️': 5, + '👷🏼‍♂️': 5, + '👷🏽‍♀️': 5, + '👷🏽‍♂️': 5, + '👷🏾‍♀️': 5, + '👷🏾‍♂️': 5, + '👷🏿‍♀️': 5, + '👷🏿‍♂️': 5, + '💁‍♀️': 3, + '💁‍♂️': 3, + '💁🏻‍♀️': 5, + '💁🏻‍♂️': 5, + '💁🏼‍♀️': 5, + '💁🏼‍♂️': 5, + '💁🏽‍♀️': 5, + '💁🏽‍♂️': 5, + '💁🏾‍♀️': 5, + '💁🏾‍♂️': 5, + '💁🏿‍♀️': 5, + '💁🏿‍♂️': 5, + '💂‍♀️': 3, + '💂‍♂️': 3, + '💂🏻‍♀️': 5, + '💂🏻‍♂️': 5, + '💂🏼‍♀️': 5, + '💂🏼‍♂️': 5, + '💂🏽‍♀️': 5, + '💂🏽‍♂️': 5, + '💂🏾‍♀️': 5, + '💂🏾‍♂️': 5, + '💂🏿‍♀️': 5, + '💂🏿‍♂️': 5, + '💆‍♀️': 3, + '💆‍♂️': 3, + '💆🏻‍♀️': 5, + '💆🏻‍♂️': 5, + '💆🏼‍♀️': 5, + '💆🏼‍♂️': 5, + '💆🏽‍♀️': 5, + '💆🏽‍♂️': 5, + '💆🏾‍♀️': 5, + '💆🏾‍♂️': 5, + '💆🏿‍♀️': 5, + '💆🏿‍♂️': 5, + '💇‍♀️': 3, + '💇‍♂️': 3, + '💇🏻‍♀️': 5, + '💇🏻‍♂️': 5, + '💇🏼‍♀️': 5, + '💇🏼‍♂️': 5, + '💇🏽‍♀️': 5, + '💇🏽‍♂️': 5, + '💇🏾‍♀️': 5, + '💇🏾‍♂️': 5, + '💇🏿‍♀️': 5, + '💇🏿‍♂️': 5, + '🕵🏻‍♀️': 4, + '🕵🏻‍♂️': 4, + '🕵🏼‍♀️': 4, + '🕵🏼‍♂️': 4, + '🕵🏽‍♀️': 4, + '🕵🏽‍♂️': 4, + '🕵🏾‍♀️': 4, + '🕵🏾‍♂️': 4, + '🕵🏿‍♀️': 4, + '🕵🏿‍♂️': 4, + '😮‍💨': 4, + '😵‍💫': 4, + '😶‍🌫️': 3, + '🙂‍↔️': 3, + '🙂‍↕️': 3, + '🙅‍♀️': 3, + '🙅‍♂️': 3, + '🙅🏻‍♀️': 5, + '🙅🏻‍♂️': 5, + '🙅🏼‍♀️': 5, + '🙅🏼‍♂️': 5, + '🙅🏽‍♀️': 5, + '🙅🏽‍♂️': 5, + '🙅🏾‍♀️': 5, + '🙅🏾‍♂️': 5, + '🙅🏿‍♀️': 5, + '🙅🏿‍♂️': 5, + '🙆‍♀️': 3, + '🙆‍♂️': 3, + '🙆🏻‍♀️': 5, + '🙆🏻‍♂️': 5, + '🙆🏼‍♀️': 5, + '🙆🏼‍♂️': 5, + '🙆🏽‍♀️': 5, + '🙆🏽‍♂️': 5, + '🙆🏾‍♀️': 5, + '🙆🏾‍♂️': 5, + '🙆🏿‍♀️': 5, + '🙆🏿‍♂️': 5, + '🙇‍♀️': 3, + '🙇‍♂️': 3, + '🙇🏻‍♀️': 5, + '🙇🏻‍♂️': 5, + '🙇🏼‍♀️': 5, + '🙇🏼‍♂️': 5, + '🙇🏽‍♀️': 5, + '🙇🏽‍♂️': 5, + '🙇🏾‍♀️': 5, + '🙇🏾‍♂️': 5, + '🙇🏿‍♀️': 5, + '🙇🏿‍♂️': 5, + '🙋‍♀️': 3, + '🙋‍♂️': 3, + '🙋🏻‍♀️': 5, + '🙋🏻‍♂️': 5, + '🙋🏼‍♀️': 5, + '🙋🏼‍♂️': 5, + '🙋🏽‍♀️': 5, + '🙋🏽‍♂️': 5, + '🙋🏾‍♀️': 5, + '🙋🏾‍♂️': 5, + '🙋🏿‍♀️': 5, + '🙋🏿‍♂️': 5, + '🙍‍♀️': 3, + '🙍‍♂️': 3, + '🙍🏻‍♀️': 5, + '🙍🏻‍♂️': 5, + '🙍🏼‍♀️': 5, + '🙍🏼‍♂️': 5, + '🙍🏽‍♀️': 5, + '🙍🏽‍♂️': 5, + '🙍🏾‍♀️': 5, + '🙍🏾‍♂️': 5, + '🙍🏿‍♀️': 5, + '🙍🏿‍♂️': 5, + '🙎‍♀️': 3, + '🙎‍♂️': 3, + '🙎🏻‍♀️': 5, + '🙎🏻‍♂️': 5, + '🙎🏼‍♀️': 5, + '🙎🏼‍♂️': 5, + '🙎🏽‍♀️': 5, + '🙎🏽‍♂️': 5, + '🙎🏾‍♀️': 5, + '🙎🏾‍♂️': 5, + '🙎🏿‍♀️': 5, + '🙎🏿‍♂️': 5, + '🚣‍♀️': 3, + '🚣‍♂️': 3, + '🚣🏻‍♀️': 5, + '🚣🏻‍♂️': 5, + '🚣🏼‍♀️': 5, + '🚣🏼‍♂️': 5, + '🚣🏽‍♀️': 5, + '🚣🏽‍♂️': 5, + '🚣🏾‍♀️': 5, + '🚣🏾‍♂️': 5, + '🚣🏿‍♀️': 5, + '🚣🏿‍♂️': 5, + '🚴‍♀️': 3, + '🚴‍♂️': 3, + '🚴🏻‍♀️': 5, + '🚴🏻‍♂️': 5, + '🚴🏼‍♀️': 5, + '🚴🏼‍♂️': 5, + '🚴🏽‍♀️': 5, + '🚴🏽‍♂️': 5, + '🚴🏾‍♀️': 5, + '🚴🏾‍♂️': 5, + '🚴🏿‍♀️': 5, + '🚴🏿‍♂️': 5, + '🚵‍♀️': 3, + '🚵‍♂️': 3, + '🚵🏻‍♀️': 5, + '🚵🏻‍♂️': 5, + '🚵🏼‍♀️': 5, + '🚵🏼‍♂️': 5, + '🚵🏽‍♀️': 5, + '🚵🏽‍♂️': 5, + '🚵🏾‍♀️': 5, + '🚵🏾‍♂️': 5, + '🚵🏿‍♀️': 5, + '🚵🏿‍♂️': 5, + '🚶‍♀️': 3, + '🚶‍♀️‍➡️': 4, + '🚶‍♂️': 3, + '🚶‍♂️‍➡️': 4, + '🚶‍➡️': 3, + '🚶🏻‍♀️': 5, + '🚶🏻‍♀️‍➡️': 6, + '🚶🏻‍♂️': 5, + '🚶🏻‍♂️‍➡️': 6, + '🚶🏻‍➡️': 5, + '🚶🏼‍♀️': 5, + '🚶🏼‍♀️‍➡️': 6, + '🚶🏼‍♂️': 5, + '🚶🏼‍♂️‍➡️': 6, + '🚶🏼‍➡️': 5, + '🚶🏽‍♀️': 5, + '🚶🏽‍♀️‍➡️': 6, + '🚶🏽‍♂️': 5, + '🚶🏽‍♂️‍➡️': 6, + '🚶🏽‍➡️': 5, + '🚶🏾‍♀️': 5, + '🚶🏾‍♀️‍➡️': 6, + '🚶🏾‍♂️': 5, + '🚶🏾‍♂️‍➡️': 6, + '🚶🏾‍➡️': 5, + '🚶🏿‍♀️': 5, + '🚶🏿‍♀️‍➡️': 6, + '🚶🏿‍♂️': 5, + '🚶🏿‍♂️‍➡️': 6, + '🚶🏿‍➡️': 5, + '🤦‍♀️': 3, + '🤦‍♂️': 3, + '🤦🏻‍♀️': 5, + '🤦🏻‍♂️': 5, + '🤦🏼‍♀️': 5, + '🤦🏼‍♂️': 5, + '🤦🏽‍♀️': 5, + '🤦🏽‍♂️': 5, + '🤦🏾‍♀️': 5, + '🤦🏾‍♂️': 5, + '🤦🏿‍♀️': 5, + '🤦🏿‍♂️': 5, + '🤵‍♀️': 3, + '🤵‍♂️': 3, + '🤵🏻‍♀️': 5, + '🤵🏻‍♂️': 5, + '🤵🏼‍♀️': 5, + '🤵🏼‍♂️': 5, + '🤵🏽‍♀️': 5, + '🤵🏽‍♂️': 5, + '🤵🏾‍♀️': 5, + '🤵🏾‍♂️': 5, + '🤵🏿‍♀️': 5, + '🤵🏿‍♂️': 5, + '🤷‍♀️': 3, + '🤷‍♂️': 3, + '🤷🏻‍♀️': 5, + '🤷🏻‍♂️': 5, + '🤷🏼‍♀️': 5, + '🤷🏼‍♂️': 5, + '🤷🏽‍♀️': 5, + '🤷🏽‍♂️': 5, + '🤷🏾‍♀️': 5, + '🤷🏾‍♂️': 5, + '🤷🏿‍♀️': 5, + '🤷🏿‍♂️': 5, + '🤸‍♀️': 3, + '🤸‍♂️': 3, + '🤸🏻‍♀️': 5, + '🤸🏻‍♂️': 5, + '🤸🏼‍♀️': 5, + '🤸🏼‍♂️': 5, + '🤸🏽‍♀️': 5, + '🤸🏽‍♂️': 5, + '🤸🏾‍♀️': 5, + '🤸🏾‍♂️': 5, + '🤸🏿‍♀️': 5, + '🤸🏿‍♂️': 5, + '🤹‍♀️': 3, + '🤹‍♂️': 3, + '🤹🏻‍♀️': 5, + '🤹🏻‍♂️': 5, + '🤹🏼‍♀️': 5, + '🤹🏼‍♂️': 5, + '🤹🏽‍♀️': 5, + '🤹🏽‍♂️': 5, + '🤹🏾‍♀️': 5, + '🤹🏾‍♂️': 5, + '🤹🏿‍♀️': 5, + '🤹🏿‍♂️': 5, + '🤼‍♀️': 3, + '🤼‍♂️': 3, + '🤼🏻‍♀️': 5, + '🤼🏻‍♂️': 5, + '🤼🏼‍♀️': 5, + '🤼🏼‍♂️': 5, + '🤼🏽‍♀️': 5, + '🤼🏽‍♂️': 5, + '🤼🏾‍♀️': 5, + '🤼🏾‍♂️': 5, + '🤼🏿‍♀️': 5, + '🤼🏿‍♂️': 5, + '🤽‍♀️': 3, + '🤽‍♂️': 3, + '🤽🏻‍♀️': 5, + '🤽🏻‍♂️': 5, + '🤽🏼‍♀️': 5, + '🤽🏼‍♂️': 5, + '🤽🏽‍♀️': 5, + '🤽🏽‍♂️': 5, + '🤽🏾‍♀️': 5, + '🤽🏾‍♂️': 5, + '🤽🏿‍♀️': 5, + '🤽🏿‍♂️': 5, + '🤾‍♀️': 3, + '🤾‍♂️': 3, + '🤾🏻‍♀️': 5, + '🤾🏻‍♂️': 5, + '🤾🏼‍♀️': 5, + '🤾🏼‍♂️': 5, + '🤾🏽‍♀️': 5, + '🤾🏽‍♂️': 5, + '🤾🏾‍♀️': 5, + '🤾🏾‍♂️': 5, + '🤾🏿‍♀️': 5, + '🤾🏿‍♂️': 5, + '🦸‍♀️': 3, + '🦸‍♂️': 3, + '🦸🏻‍♀️': 5, + '🦸🏻‍♂️': 5, + '🦸🏼‍♀️': 5, + '🦸🏼‍♂️': 5, + '🦸🏽‍♀️': 5, + '🦸🏽‍♂️': 5, + '🦸🏾‍♀️': 5, + '🦸🏾‍♂️': 5, + '🦸🏿‍♀️': 5, + '🦸🏿‍♂️': 5, + '🦹‍♀️': 3, + '🦹‍♂️': 3, + '🦹🏻‍♀️': 5, + '🦹🏻‍♂️': 5, + '🦹🏼‍♀️': 5, + '🦹🏼‍♂️': 5, + '🦹🏽‍♀️': 5, + '🦹🏽‍♂️': 5, + '🦹🏾‍♀️': 5, + '🦹🏾‍♂️': 5, + '🦹🏿‍♀️': 5, + '🦹🏿‍♂️': 5, + '🧍‍♀️': 3, + '🧍‍♂️': 3, + '🧍🏻‍♀️': 5, + '🧍🏻‍♂️': 5, + '🧍🏼‍♀️': 5, + '🧍🏼‍♂️': 5, + '🧍🏽‍♀️': 5, + '🧍🏽‍♂️': 5, + '🧍🏾‍♀️': 5, + '🧍🏾‍♂️': 5, + '🧍🏿‍♀️': 5, + '🧍🏿‍♂️': 5, + '🧎‍♀️': 3, + '🧎‍♀️‍➡️': 4, + '🧎‍♂️': 3, + '🧎‍♂️‍➡️': 4, + '🧎‍➡️': 3, + '🧎🏻‍♀️': 5, + '🧎🏻‍♀️‍➡️': 6, + '🧎🏻‍♂️': 5, + '🧎🏻‍♂️‍➡️': 6, + '🧎🏻‍➡️': 5, + '🧎🏼‍♀️': 5, + '🧎🏼‍♀️‍➡️': 6, + '🧎🏼‍♂️': 5, + '🧎🏼‍♂️‍➡️': 6, + '🧎🏼‍➡️': 5, + '🧎🏽‍♀️': 5, + '🧎🏽‍♀️‍➡️': 6, + '🧎🏽‍♂️': 5, + '🧎🏽‍♂️‍➡️': 6, + '🧎🏽‍➡️': 5, + '🧎🏾‍♀️': 5, + '🧎🏾‍♀️‍➡️': 6, + '🧎🏾‍♂️': 5, + '🧎🏾‍♂️‍➡️': 6, + '🧎🏾‍➡️': 5, + '🧎🏿‍♀️': 5, + '🧎🏿‍♀️‍➡️': 6, + '🧎🏿‍♂️': 5, + '🧎🏿‍♂️‍➡️': 6, + '🧎🏿‍➡️': 5, + '🧏‍♀️': 3, + '🧏‍♂️': 3, + '🧏🏻‍♀️': 5, + '🧏🏻‍♂️': 5, + '🧏🏼‍♀️': 5, + '🧏🏼‍♂️': 5, + '🧏🏽‍♀️': 5, + '🧏🏽‍♂️': 5, + '🧏🏾‍♀️': 5, + '🧏🏾‍♂️': 5, + '🧏🏿‍♀️': 5, + '🧏🏿‍♂️': 5, + '🧑‍⚕️': 3, + '🧑‍⚖️': 3, + '🧑‍✈️': 3, + '🧑‍🌾': 4, + '🧑‍🍳': 4, + '🧑‍🍼': 4, + '🧑‍🎄': 4, + '🧑‍🎓': 4, + '🧑‍🎤': 4, + '🧑‍🎨': 4, + '🧑‍🏫': 4, + '🧑‍🏭': 4, + '🧑‍💻': 4, + '🧑‍💼': 4, + '🧑‍🔧': 4, + '🧑‍🔬': 4, + '🧑‍🚀': 4, + '🧑‍🚒': 4, + '🧑‍🤝‍🧑': 6, + '🧑‍🦯': 4, + '🧑‍🦯‍➡️': 5, + '🧑‍🦰': 4, + '🧑‍🦱': 4, + '🧑‍🦲': 4, + '🧑‍🦳': 4, + '🧑‍🦼': 4, + '🧑‍🦼‍➡️': 5, + '🧑‍🦽': 4, + '🧑‍🦽‍➡️': 5, + '🧑‍🧑‍🧒': 6, + '🧑‍🧑‍🧒‍🧒': 8, + '🧑‍🧒': 4, + '🧑‍🧒‍🧒': 6, + '🧑‍🩰': 4, + '🧑🏻‍⚕️': 5, + '🧑🏻‍⚖️': 5, + '🧑🏻‍✈️': 5, + '🧑🏻‍❤️‍💋‍🧑🏿': 11, + '🧑🏻‍🌾': 6, + '🧑🏻‍🍳': 6, + '🧑🏻‍🍼': 6, + '🧑🏻‍🎄': 6, + '🧑🏻‍🎓': 6, + '🧑🏻‍🎤': 6, + '🧑🏻‍🎨': 6, + '🧑🏻‍🏫': 6, + '🧑🏻‍🏭': 6, + '🧑🏻‍🐰‍🧑🏽': 10, + '🧑🏻‍🐰‍🧑🏾': 10, + '🧑🏻‍🐰‍🧑🏿': 10, + '🧑🏻‍💻': 6, + '🧑🏻‍💼': 6, + '🧑🏻‍🔧': 6, + '🧑🏻‍🔬': 6, + '🧑🏻‍🚀': 6, + '🧑🏻‍🚒': 6, + '🧑🏻‍🤝‍🧑🏻': 10, + '🧑🏻‍🤝‍🧑🏼': 10, + '🧑🏻‍🤝‍🧑🏽': 10, + '🧑🏻‍🤝‍🧑🏾': 10, + '🧑🏻‍🤝‍🧑🏿': 10, + '🧑🏻‍🦯': 6, + '🧑🏻‍🦯‍➡️': 7, + '🧑🏻‍🦰': 6, + '🧑🏻‍🦱': 6, + '🧑🏻‍🦲': 6, + '🧑🏻‍🦳': 6, + '🧑🏻‍🦼': 6, + '🧑🏻‍🦼‍➡️': 7, + '🧑🏻‍🦽': 6, + '🧑🏻‍🦽‍➡️': 7, + '🧑🏻‍🩰': 6, + '🧑🏻‍🫯‍🧑🏼': 9, + '🧑🏻‍🫯‍🧑🏽': 9, + '🧑🏻‍🫯‍🧑🏾': 9, + '🧑🏻‍🫯‍🧑🏿': 9, + '🧑🏼‍⚕️': 5, + '🧑🏼‍⚖️': 5, + '🧑🏼‍✈️': 5, + '🧑🏼‍🌾': 6, + '🧑🏼‍🍳': 6, + '🧑🏼‍🍼': 6, + '🧑🏼‍🎄': 6, + '🧑🏼‍🎓': 6, + '🧑🏼‍🎤': 6, + '🧑🏼‍🎨': 6, + '🧑🏼‍🏫': 6, + '🧑🏼‍🏭': 6, + '🧑🏼‍🐰‍🧑🏿': 10, + '🧑🏼‍💻': 6, + '🧑🏼‍💼': 6, + '🧑🏼‍🔧': 6, + '🧑🏼‍🔬': 6, + '🧑🏼‍🚀': 6, + '🧑🏼‍🚒': 6, + '🧑🏼‍🤝‍🧑🏻': 10, + '🧑🏼‍🤝‍🧑🏼': 10, + '🧑🏼‍🤝‍🧑🏽': 10, + '🧑🏼‍🤝‍🧑🏿': 10, + '🧑🏼‍🦯': 6, + '🧑🏼‍🦯‍➡️': 7, + '🧑🏼‍🦰': 6, + '🧑🏼‍🦱': 6, + '🧑🏼‍🦲': 6, + '🧑🏼‍🦳': 6, + '🧑🏼‍🦼': 6, + '🧑🏼‍🦽': 6, + '🧑🏼‍🩰': 6, + '🧑🏼‍🫯‍🧑🏻': 9, + '🧑🏼‍🫯‍🧑🏽': 9, + '🧑🏼‍🫯‍🧑🏿': 9, + '🧑🏽‍⚕️': 5, + '🧑🏽‍⚖️': 5, + '🧑🏽‍✈️': 5, + '🧑🏽‍❤️‍💋‍🧑🏿': 11, + '🧑🏽‍🌾': 6, + '🧑🏽‍🍳': 6, + '🧑🏽‍🍼': 6, + '🧑🏽‍🎄': 6, + '🧑🏽‍🎓': 6, + '🧑🏽‍🎤': 6, + '🧑🏽‍🎨': 6, + '🧑🏽‍🏫': 6, + '🧑🏽‍🏭': 6, + '🧑🏽‍🐰‍🧑🏻': 10, + '🧑🏽‍🐰‍🧑🏿': 10, + '🧑🏽‍💻': 6, + '🧑🏽‍💼': 6, + '🧑🏽‍🔧': 6, + '🧑🏽‍🔬': 6, + '🧑🏽‍🚀': 6, + '🧑🏽‍🚒': 6, + '🧑🏽‍🤝‍🧑🏻': 10, + '🧑🏽‍🤝‍🧑🏼': 10, + '🧑🏽‍🤝‍🧑🏽': 10, + '🧑🏽‍🤝‍🧑🏾': 10, + '🧑🏽‍🤝‍🧑🏿': 10, + '🧑🏽‍🦯': 6, + '🧑🏽‍🦯‍➡️': 7, + '🧑🏽‍🦰': 6, + '🧑🏽‍🦱': 6, + '🧑🏽‍🦲': 6, + '🧑🏽‍🦳': 6, + '🧑🏽‍🦼': 6, + '🧑🏽‍🦼‍➡️': 7, + '🧑🏽‍🦽': 6, + '🧑🏽‍🦽‍➡️': 7, + '🧑🏽‍🩰': 6, + '🧑🏽‍🫯‍🧑🏻': 9, + '🧑🏽‍🫯‍🧑🏼': 9, + '🧑🏽‍🫯‍🧑🏾': 9, + '🧑🏽‍🫯‍🧑🏿': 9, + '🧑🏾‍⚕️': 5, + '🧑🏾‍⚖️': 5, + '🧑🏾‍✈️': 5, + '🧑🏾‍🌾': 6, + '🧑🏾‍🍳': 6, + '🧑🏾‍🍼': 6, + '🧑🏾‍🎄': 6, + '🧑🏾‍🎓': 6, + '🧑🏾‍🎤': 6, + '🧑🏾‍🎨': 6, + '🧑🏾‍🏫': 6, + '🧑🏾‍🏭': 6, + '🧑🏾‍🐰‍🧑🏻': 10, + '🧑🏾‍🐰‍🧑🏿': 10, + '🧑🏾‍💻': 6, + '🧑🏾‍💼': 6, + '🧑🏾‍🔧': 6, + '🧑🏾‍🔬': 6, + '🧑🏾‍🚀': 6, + '🧑🏾‍🚒': 6, + '🧑🏾‍🤝‍🧑🏻': 10, + '🧑🏾‍🤝‍🧑🏽': 10, + '🧑🏾‍🤝‍🧑🏾': 10, + '🧑🏾‍🤝‍🧑🏿': 10, + '🧑🏾‍🦯': 6, + '🧑🏾‍🦯‍➡️': 7, + '🧑🏾‍🦰': 6, + '🧑🏾‍🦱': 6, + '🧑🏾‍🦲': 6, + '🧑🏾‍🦳': 6, + '🧑🏾‍🦼': 6, + '🧑🏾‍🦽': 6, + '🧑🏾‍🩰': 6, + '🧑🏾‍🫯‍🧑🏻': 9, + '🧑🏾‍🫯‍🧑🏽': 9, + '🧑🏾‍🫯‍🧑🏿': 9, + '🧑🏿‍⚕️': 5, + '🧑🏿‍⚖️': 5, + '🧑🏿‍✈️': 5, + '🧑🏿‍❤️‍💋‍🧑🏻': 11, + '🧑🏿‍❤️‍💋‍🧑🏽': 11, + '🧑🏿‍🌾': 6, + '🧑🏿‍🍳': 6, + '🧑🏿‍🍼': 6, + '🧑🏿‍🎄': 6, + '🧑🏿‍🎓': 6, + '🧑🏿‍🎤': 6, + '🧑🏿‍🎨': 6, + '🧑🏿‍🏫': 6, + '🧑🏿‍🏭': 6, + '🧑🏿‍🐰‍🧑🏻': 10, + '🧑🏿‍🐰‍🧑🏼': 10, + '🧑🏿‍🐰‍🧑🏽': 10, + '🧑🏿‍🐰‍🧑🏾': 10, + '🧑🏿‍💻': 6, + '🧑🏿‍💼': 6, + '🧑🏿‍🔧': 6, + '🧑🏿‍🔬': 6, + '🧑🏿‍🚀': 6, + '🧑🏿‍🚒': 6, + '🧑🏿‍🤝‍🧑🏻': 10, + '🧑🏿‍🤝‍🧑🏼': 10, + '🧑🏿‍🤝‍🧑🏽': 10, + '🧑🏿‍🤝‍🧑🏾': 10, + '🧑🏿‍🤝‍🧑🏿': 10, + '🧑🏿‍🦯': 6, + '🧑🏿‍🦯‍➡️': 7, + '🧑🏿‍🦰': 6, + '🧑🏿‍🦱': 6, + '🧑🏿‍🦲': 6, + '🧑🏿‍🦳': 6, + '🧑🏿‍🦼': 6, + '🧑🏿‍🦼‍➡️': 7, + '🧑🏿‍🦽': 6, + '🧑🏿‍🦽‍➡️': 7, + '🧑🏿‍🩰': 6, + '🧑🏿‍🫯‍🧑🏻': 9, + '🧑🏿‍🫯‍🧑🏼': 9, + '🧑🏿‍🫯‍🧑🏽': 9, + '🧑🏿‍🫯‍🧑🏾': 9, + '🧔‍♀️': 3, + '🧔‍♂️': 3, + '🧔🏻‍♀️': 5, + '🧔🏻‍♂️': 5, + '🧔🏼‍♀️': 5, + '🧔🏼‍♂️': 5, + '🧔🏽‍♀️': 5, + '🧔🏽‍♂️': 5, + '🧔🏾‍♀️': 5, + '🧔🏾‍♂️': 5, + '🧔🏿‍♀️': 5, + '🧔🏿‍♂️': 5, + '🧖‍♀️': 3, + '🧖‍♂️': 3, + '🧖🏻‍♀️': 5, + '🧖🏻‍♂️': 5, + '🧖🏼‍♀️': 5, + '🧖🏼‍♂️': 5, + '🧖🏽‍♀️': 5, + '🧖🏽‍♂️': 5, + '🧖🏾‍♀️': 5, + '🧖🏾‍♂️': 5, + '🧖🏿‍♀️': 5, + '🧖🏿‍♂️': 5, + '🧗‍♀️': 3, + '🧗‍♂️': 3, + '🧗🏻‍♀️': 5, + '🧗🏻‍♂️': 5, + '🧗🏼‍♀️': 5, + '🧗🏼‍♂️': 5, + '🧗🏽‍♀️': 5, + '🧗🏽‍♂️': 5, + '🧗🏾‍♀️': 5, + '🧗🏾‍♂️': 5, + '🧗🏿‍♀️': 5, + '🧗🏿‍♂️': 5, + '🧘‍♀️': 3, + '🧘‍♂️': 3, + '🧘🏻‍♀️': 5, + '🧘🏻‍♂️': 5, + '🧘🏼‍♀️': 5, + '🧘🏼‍♂️': 5, + '🧘🏽‍♀️': 5, + '🧘🏽‍♂️': 5, + '🧘🏾‍♀️': 5, + '🧘🏾‍♂️': 5, + '🧘🏿‍♀️': 5, + '🧘🏿‍♂️': 5, + '🧙‍♀️': 3, + '🧙‍♂️': 3, + '🧙🏻‍♀️': 5, + '🧙🏻‍♂️': 5, + '🧙🏼‍♀️': 5, + '🧙🏼‍♂️': 5, + '🧙🏽‍♀️': 5, + '🧙🏽‍♂️': 5, + '🧙🏾‍♀️': 5, + '🧙🏾‍♂️': 5, + '🧙🏿‍♀️': 5, + '🧙🏿‍♂️': 5, + '🧚‍♀️': 3, + '🧚‍♂️': 3, + '🧚🏻‍♀️': 5, + '🧚🏻‍♂️': 5, + '🧚🏼‍♀️': 5, + '🧚🏼‍♂️': 5, + '🧚🏽‍♀️': 5, + '🧚🏽‍♂️': 5, + '🧚🏾‍♀️': 5, + '🧚🏾‍♂️': 5, + '🧚🏿‍♀️': 5, + '🧚🏿‍♂️': 5, + '🧛‍♀️': 3, + '🧛‍♂️': 3, + '🧛🏻‍♀️': 5, + '🧛🏻‍♂️': 5, + '🧛🏼‍♀️': 5, + '🧛🏼‍♂️': 5, + '🧛🏽‍♀️': 5, + '🧛🏽‍♂️': 5, + '🧛🏾‍♀️': 5, + '🧛🏾‍♂️': 5, + '🧛🏿‍♀️': 5, + '🧛🏿‍♂️': 5, + '🧜‍♀️': 3, + '🧜‍♂️': 3, + '🧜🏻‍♀️': 5, + '🧜🏻‍♂️': 5, + '🧜🏼‍♀️': 5, + '🧜🏼‍♂️': 5, + '🧜🏽‍♀️': 5, + '🧜🏽‍♂️': 5, + '🧜🏾‍♀️': 5, + '🧜🏾‍♂️': 5, + '🧜🏿‍♀️': 5, + '🧜🏿‍♂️': 5, + '🧝‍♀️': 3, + '🧝‍♂️': 3, + '🧝🏻‍♀️': 5, + '🧝🏻‍♂️': 5, + '🧝🏼‍♀️': 5, + '🧝🏼‍♂️': 5, + '🧝🏽‍♀️': 5, + '🧝🏽‍♂️': 5, + '🧝🏾‍♀️': 5, + '🧝🏾‍♂️': 5, + '🧝🏿‍♀️': 5, + '🧝🏿‍♂️': 5, + '🧞‍♀️': 3, + '🧞‍♂️': 3, + '🧟‍♀️': 3, + '🧟‍♂️': 3, + '🫱🏻‍🫲🏼': 6, + '🫱🏻‍🫲🏽': 6, + '🫱🏻‍🫲🏾': 6, + '🫱🏻‍🫲🏿': 6, + '🫱🏼‍🫲🏻': 6, + '🫱🏼‍🫲🏽': 6, + '🫱🏼‍🫲🏾': 6, + '🫱🏼‍🫲🏿': 6, + '🫱🏽‍🫲🏻': 6, + '🫱🏽‍🫲🏼': 6, + '🫱🏽‍🫲🏾': 6, + '🫱🏽‍🫲🏿': 6, + '🫱🏾‍🫲🏻': 6, + '🫱🏾‍🫲🏼': 6, + '🫱🏾‍🫲🏽': 6, + '🫱🏾‍🫲🏿': 6, + '🫱🏿‍🫲🏻': 6, + '🫱🏿‍🫲🏼': 6, + '🫱🏿‍🫲🏽': 6, + '🫱🏿‍🫲🏾': 6, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_2148ff29.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_2148ff29.py new file mode 100644 index 0000000000000000000000000000000000000000..fd2f7f3ec18bf0adb623767bf65446e06e60918f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_2148ff29.py @@ -0,0 +1,1805 @@ +""" +Grapheme overrides for _known_2148ff29. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: wezterm +""" +# pylint: skip-file +GRAPHEMES = { + '؁۱': 1, + 'का': 1, + 'कां': 1, + 'कि': 1, + 'किं': 1, + 'की': 1, + 'केा': 1, + 'को': 1, + 'कौ': 1, + 'खा': 1, + 'खि': 1, + 'खी': 1, + 'खो': 1, + 'ग़ा': 1, + 'गा': 1, + 'गाँ': 1, + 'गां': 1, + 'गि': 1, + 'गी': 1, + 'गो': 1, + 'गों': 1, + 'गौ': 1, + 'घा': 1, + 'घि': 1, + 'घी': 1, + 'घेि': 1, + 'घो': 1, + 'चा': 1, + 'चां': 1, + 'चि': 1, + 'ची': 1, + 'चो': 1, + 'चौ': 1, + 'छि': 1, + 'छुी': 1, + 'छो': 1, + 'जा': 1, + 'जि': 1, + 'जिं': 1, + 'जी': 1, + 'जो': 1, + 'झा': 1, + 'टा': 1, + 'टां': 1, + 'टि': 1, + 'टी': 1, + 'टों': 1, + 'ठा': 1, + 'ठी': 1, + 'ठैः': 1, + 'ड़ा': 1, + 'डा': 1, + 'डि': 1, + 'डी': 1, + 'डो': 1, + 'ढ़ा': 1, + 'ढ़ि': 1, + 'ढ़ी': 1, + 'ढ़ो': 1, + 'ढा': 1, + 'ढाँ': 1, + 'ढि': 1, + 'णा': 1, + 'णां': 1, + 'णि': 1, + 'णी': 1, + 'णो': 1, + 'णों': 1, + 'तः': 1, + 'ता': 1, + 'तां': 1, + 'ताः': 1, + 'ति': 1, + 'तिं': 1, + 'ती': 1, + 'तो': 1, + 'तों': 1, + 'तौ': 1, + 'था': 1, + 'थि': 1, + 'दः': 1, + 'दा': 1, + 'दां': 1, + 'दि': 1, + 'दी': 1, + 'दो': 1, + 'दौ': 1, + 'धा': 1, + 'धां': 1, + 'धाः': 1, + 'धि': 1, + 'धी': 1, + 'धेः': 1, + 'धो': 1, + 'धों': 1, + 'नः': 1, + 'ना': 1, + 'नां': 1, + 'नाः': 1, + 'ना‌': 1, + 'नि': 1, + 'निँ': 1, + 'निः': 1, + 'नी': 1, + 'नैः': 1, + 'नो': 1, + 'नों': 1, + 'नौ': 1, + 'पा': 1, + 'पाँ': 1, + 'पां': 1, + 'पि': 1, + 'पी': 1, + 'पो': 1, + 'पों': 1, + 'फा': 1, + 'फाँ': 1, + 'फौ': 1, + 'बा': 1, + 'बाँ': 1, + 'बि': 1, + 'बी': 1, + 'बो': 1, + 'भा': 1, + 'भि': 1, + 'भिः': 1, + 'भी': 1, + 'भो': 1, + 'भौ': 1, + 'मा': 1, + 'मां': 1, + 'मि': 1, + 'मी': 1, + 'मो': 1, + 'मों': 1, + 'मौ': 1, + 'यः': 1, + 'या': 1, + 'यां': 1, + 'याः': 1, + 'यि': 1, + 'यी': 1, + 'यैः': 1, + 'यो': 1, + 'यों': 1, + 'रः': 1, + 'रा': 1, + 'रां': 1, + 'राः': 1, + 'रि': 1, + 'रिं': 1, + 'री': 1, + 'रो': 1, + 'रों': 1, + 'रौ': 1, + 'ला': 1, + 'लां': 1, + 'लाः': 1, + 'लि': 1, + 'लिं': 1, + 'ली': 1, + 'लीं': 1, + 'लो': 1, + 'लों': 1, + 'लौ': 1, + 'ळा': 1, + 'ळी': 1, + 'वः': 1, + 'वा': 1, + 'वां': 1, + 'वाः': 1, + 'वि': 1, + 'वी': 1, + 'वो': 1, + 'वों': 1, + 'शः': 1, + 'शा': 1, + 'शां': 1, + 'शाः': 1, + 'शि': 1, + 'शी': 1, + 'शो': 1, + 'शों': 1, + 'षा': 1, + 'षां': 1, + 'षाः': 1, + 'षि': 1, + 'षी': 1, + 'षों': 1, + 'सः': 1, + 'सा': 1, + 'साँ': 1, + 'सां': 1, + 'सि': 1, + 'सी': 1, + 'सो': 1, + 'सौ': 1, + 'हा': 1, + 'हाँ': 1, + 'हां': 1, + 'हि': 1, + 'हिं': 1, + 'ही': 1, + 'हीं': 1, + 'हैः': 1, + 'हो': 1, + 'हों': 1, + 'हौ': 1, + 'क़ा': 1, + 'क़ि': 1, + 'ज़ा': 1, + 'ड़ा': 1, + 'ढ़ा': 1, + 'फ़ा': 1, + 'অং': 1, + 'কা': 1, + 'কা‌': 1, + 'কি': 1, + 'কিং': 1, + 'কে': 1, + 'কে‌': 1, + 'কো': 1, + 'খা': 1, + 'খি': 1, + 'খে': 1, + 'গি': 1, + 'গে': 1, + 'গো': 1, + 'ঘা': 1, + 'ঘে': 1, + 'ঘো': 1, + 'ঘো': 1, + 'চা': 1, + 'চি': 1, + 'চে': 1, + 'চো': 1, + 'চৌ': 1, + 'ছা': 1, + 'ছি': 1, + 'ছে': 1, + 'জা': 1, + 'জি': 1, + 'জী': 1, + 'জে': 1, + 'জে‌': 1, + 'ঝো': 1, + 'টা': 1, + 'টি': 1, + 'ঠি': 1, + 'ড়া': 1, + 'ণা': 1, + 'ণি': 1, + 'ণে': 1, + 'তঃ': 1, + 'তা': 1, + 'তাঁ': 1, + 'তা‌': 1, + 'তি': 1, + 'তি‌': 1, + 'তী': 1, + 'তে': 1, + 'তে‌': 1, + 'থা': 1, + 'থি': 1, + 'থে': 1, + 'দা': 1, + 'দি': 1, + 'দে': 1, + 'দে‌': 1, + 'দৈ': 1, + 'দো': 1, + 'ধা': 1, + 'ধি': 1, + 'ধী': 1, + 'ধে': 1, + 'না': 1, + 'না‌': 1, + 'নি': 1, + 'নী': 1, + 'নে': 1, + 'নৈ': 1, + 'নো': 1, + 'পা': 1, + 'পা‌': 1, + 'পি': 1, + 'পী': 1, + 'পে': 1, + 'পো': 1, + 'ফে': 1, + 'ফৌ': 1, + 'বং': 1, + 'বা': 1, + 'বা‌': 1, + 'বি': 1, + 'বী': 1, + 'বে': 1, + 'বৈ': 1, + 'বো': 1, + 'ভা': 1, + 'ভি': 1, + 'ভে': 1, + 'ভো': 1, + 'ভৌ': 1, + 'মা': 1, + 'মা‌': 1, + 'মি': 1, + 'মে': 1, + 'মৌ': 1, + 'য়া': 1, + 'য়ি': 1, + 'য়ে': 1, + 'য়ো': 1, + 'যা': 1, + 'যে': 1, + 'যো': 1, + 'রা': 1, + 'রাং': 1, + 'রি': 1, + 'রী': 1, + 'রে': 1, + 'রো': 1, + 'লা': 1, + 'লি': 1, + 'লী': 1, + 'লে': 1, + 'লে‌': 1, + 'শং': 1, + 'শা': 1, + 'শি': 1, + 'শী': 1, + 'শৃং': 1, + 'শে': 1, + 'শৈ': 1, + 'ষা': 1, + 'ষি': 1, + 'ষী': 1, + 'ষে': 1, + 'সং': 1, + 'সা': 1, + 'সাং': 1, + 'সি': 1, + 'সী': 1, + 'সে': 1, + 'সে‌': 1, + 'হা': 1, + 'হি': 1, + 'হে': 1, + 'হো': 1, + 'য়ে': 1, + 'ਕਾ': 1, + 'ਕਾਂ': 1, + 'ਕਿ': 1, + 'ਕਿ੍': 1, + 'ਕਿੱ': 1, + 'ਕੀ': 1, + 'ਖਾ': 1, + 'ਖਾਂ': 1, + 'ਖਿ': 1, + 'ਖਿ਼': 1, + 'ਖੀ': 1, + 'ਗਾ': 1, + 'ਗਿ': 1, + 'ਗਿ੍': 1, + 'ਗੀ': 1, + 'ਚਾ': 1, + 'ਚਿ': 1, + 'ਚਿੱ': 1, + 'ਚੀ': 1, + 'ਜਾ': 1, + 'ਜਾਂ': 1, + 'ਜਿ': 1, + 'ਜਿ਼': 1, + 'ਜਿ਼ੰ': 1, + 'ਜੀ': 1, + 'ਝਿ': 1, + 'ਝੀ': 1, + 'ਟਾ': 1, + 'ਟਿ': 1, + 'ਟਿ੍': 1, + 'ਟੀ': 1, + 'ਠੀ': 1, + 'ਡਾ': 1, + 'ਣਾ': 1, + 'ਣਾਂ': 1, + 'ਣੀ': 1, + 'ਤਾ': 1, + 'ਤਾਂ': 1, + 'ਤਿ': 1, + 'ਤੀ': 1, + 'ਦਾ': 1, + 'ਦਾਂ': 1, + 'ਦਿ': 1, + 'ਦਿੱ': 1, + 'ਦੀ': 1, + 'ਧਾ': 1, + 'ਧਾਂ': 1, + 'ਧਿ': 1, + 'ਧੀ': 1, + 'ਨਾ': 1, + 'ਨਾਂ': 1, + 'ਨਿ': 1, + 'ਨੀ': 1, + 'ਨੀਂ': 1, + 'ਪਾ': 1, + 'ਪਿ': 1, + 'ਪੀ': 1, + 'ਫਿ': 1, + 'ਬਾ': 1, + 'ਬਿ': 1, + 'ਬੀ': 1, + 'ਭਾ': 1, + 'ਭਿ': 1, + 'ਮਾ': 1, + 'ਮਾਂ': 1, + 'ਮਿ': 1, + 'ਮੀ': 1, + 'ਯਾ': 1, + 'ਰਾ': 1, + 'ਰਾਂ': 1, + 'ਰਿ': 1, + 'ਰੀ': 1, + 'ਲਾ': 1, + 'ਲਾਂ': 1, + 'ਲਿ': 1, + 'ਲਿੰ': 1, + 'ਲੀ': 1, + 'ਵਾ': 1, + 'ਵਾਂ': 1, + 'ਵਿ': 1, + 'ਵਿੱ': 1, + 'ਵੀ': 1, + 'ਸ਼ਾ': 1, + 'ਸ਼ਾਂ': 1, + 'ਸ਼ਿ': 1, + 'ਸ਼ੀ': 1, + 'ਸਾ': 1, + 'ਸਾਂ': 1, + 'ਸਿ': 1, + 'ਸਿੱ': 1, + 'ਸੀ': 1, + 'ਹਾ': 1, + 'ਹਾਂ': 1, + 'ਹਿ': 1, + 'ਹਿੰ': 1, + 'ਹਿੱ': 1, + 'ਹੀ': 1, + 'ਹੀਂ': 1, + 'ਜ਼ਾ': 1, + 'ਜ਼ੀ': 1, + 'ੜਾ': 1, + 'ੜੀਂ': 1, + 'ਫ਼ਾ': 1, + 'કઃ': 1, + 'કા': 1, + 'કાં': 1, + 'કિ': 1, + 'કી': 1, + 'કો': 1, + 'ખા': 1, + 'ખી': 1, + 'ખો': 1, + 'ગા': 1, + 'ગિ': 1, + 'ગી': 1, + 'ગો': 1, + 'ઘા': 1, + 'ઘો': 1, + 'ચા': 1, + 'ચિ': 1, + 'ચી': 1, + 'છા': 1, + 'છો': 1, + 'જા': 1, + 'જાં': 1, + 'જિ': 1, + 'જી': 1, + 'જો': 1, + 'ટઃ': 1, + 'ડા': 1, + 'ડાં': 1, + 'ડી': 1, + 'ઢા': 1, + 'ઢિ': 1, + 'ણા': 1, + 'ણી': 1, + 'તઃ': 1, + 'તા': 1, + 'તાં': 1, + 'તિ': 1, + 'તી': 1, + 'તો': 1, + 'થા': 1, + 'થી': 1, + 'દા': 1, + 'દી': 1, + 'દો': 1, + 'ધા': 1, + 'ધાં': 1, + 'ધિ': 1, + 'ધી': 1, + 'ધો': 1, + 'નઃ': 1, + 'ના': 1, + 'નાં': 1, + 'નિ': 1, + 'ની': 1, + 'નો': 1, + 'પા': 1, + 'પિ': 1, + 'પી': 1, + 'પો': 1, + 'ફા': 1, + 'ફો': 1, + 'બા': 1, + 'બાં': 1, + 'બી': 1, + 'ભા': 1, + 'ભાં': 1, + 'ભિ': 1, + 'ભો': 1, + 'ભૌ': 1, + 'મઃ': 1, + 'મા': 1, + 'માં': 1, + 'મિ': 1, + 'મી': 1, + 'મો': 1, + 'યા': 1, + 'યિ': 1, + 'યી': 1, + 'યો': 1, + 'રા': 1, + 'રિ': 1, + 'રી': 1, + 'રો': 1, + 'લા': 1, + 'લાં': 1, + 'લિ': 1, + 'લિં': 1, + 'લી': 1, + 'લો': 1, + 'ળા': 1, + 'ળી': 1, + 'વા': 1, + 'વાં': 1, + 'વિ': 1, + 'વી': 1, + 'વો': 1, + 'શા': 1, + 'શાં': 1, + 'શિ': 1, + 'શી': 1, + 'શો': 1, + 'ષા': 1, + 'ષી': 1, + 'ષો': 1, + 'સા': 1, + 'સાં': 1, + 'સિ': 1, + 'સી': 1, + 'સો': 1, + 'હા': 1, + 'હિ': 1, + 'હી': 1, + 'હો': 1, + 'கா': 1, + 'கி': 1, + 'கு': 1, + 'கூ': 1, + 'கெ': 1, + 'கே': 1, + 'கை': 1, + 'கொ': 1, + 'கோ': 1, + 'சா': 1, + 'சி': 1, + 'சு': 1, + 'சூ': 1, + 'செ': 1, + 'சே': 1, + 'சை': 1, + 'சொ': 1, + 'டா': 1, + 'டி': 1, + 'டு': 1, + 'டெ': 1, + 'டை': 1, + 'ணா': 1, + 'ணி': 1, + 'ணு': 1, + 'ணை': 1, + 'தா': 1, + 'தி': 1, + 'து': 1, + 'தூ': 1, + 'தெ': 1, + 'தே': 1, + 'தை': 1, + 'தொ': 1, + 'தோ': 1, + 'நா': 1, + 'நி': 1, + 'நு': 1, + 'நெ': 1, + 'நே': 1, + 'நோ': 1, + 'னா': 1, + 'னி': 1, + 'னு': 1, + 'னே': 1, + 'னை': 1, + 'னொ': 1, + 'பா': 1, + 'பி': 1, + 'பு': 1, + 'பெ': 1, + 'பே': 1, + 'பை': 1, + 'பொ': 1, + 'போ': 1, + 'மா': 1, + 'மி': 1, + 'மு': 1, + 'மூ': 1, + 'மெ': 1, + 'மே': 1, + 'மை': 1, + 'மொ': 1, + 'மோ': 1, + 'யா': 1, + 'யி': 1, + 'யு': 1, + 'யே': 1, + 'யை': 1, + 'யோ': 1, + 'ரா': 1, + 'ரி': 1, + 'ரு': 1, + 'ரெ': 1, + 'ரை': 1, + 'றா': 1, + 'றி': 1, + 'று': 1, + 'றே': 1, + 'றை': 1, + 'றொ': 1, + 'றோ': 1, + 'லா': 1, + 'லி': 1, + 'லு': 1, + 'லெ': 1, + 'லே': 1, + 'லை': 1, + 'லோ': 1, + 'ளா': 1, + 'ளி': 1, + 'ளு': 1, + 'ளெ': 1, + 'ளை': 1, + 'ழி': 1, + 'ழு': 1, + 'ழை': 1, + 'வா': 1, + 'வி': 1, + 'வு': 1, + 'வூ': 1, + 'வெ': 1, + 'வே': 1, + 'வை': 1, + 'வொ': 1, + 'வோ': 1, + 'అం': 1, + 'ఆం': 1, + 'ఒం': 1, + 'కం': 1, + 'కాం': 1, + 'కు': 1, + 'కుం': 1, + 'కూ': 1, + 'కృ': 1, + 'కెం': 1, + 'గిం': 1, + 'గు': 1, + 'గూ': 1, + 'గృ': 1, + 'చు': 1, + 'చెం': 1, + 'టం': 1, + 'టిం': 1, + 'టు': 1, + 'టుం': 1, + 'డు': 1, + 'ణిం': 1, + 'తం': 1, + 'తః': 1, + 'తు': 1, + 'తృ': 1, + 'దం': 1, + 'దిం': 1, + 'దు': 1, + 'దుం': 1, + 'దృ': 1, + 'ధిం': 1, + 'ధు': 1, + 'నం': 1, + 'నః': 1, + 'నాం': 1, + 'నిం': 1, + 'ను': 1, + 'నుం': 1, + 'నొం': 1, + 'పం': 1, + 'పిం': 1, + 'పు': 1, + 'పూ': 1, + 'పెం': 1, + 'పొం': 1, + 'బం': 1, + 'భం': 1, + 'భు': 1, + 'మిం': 1, + 'ము': 1, + 'మూ': 1, + 'యం': 1, + 'యః': 1, + 'యిం': 1, + 'యు': 1, + 'యుం': 1, + 'రం': 1, + 'రిం': 1, + 'రు': 1, + 'రూ': 1, + 'ఱు': 1, + 'లం': 1, + 'లిం': 1, + 'లు': 1, + 'విం': 1, + 'వు': 1, + 'వృ': 1, + 'శాం': 1, + 'శిం': 1, + 'శు': 1, + 'షిం': 1, + 'షు': 1, + 'సం': 1, + 'సాం': 1, + 'సు': 1, + 'సూ': 1, + 'హిం': 1, + 'ಅಂ': 1, + 'ಇಂ': 1, + 'ಉಂ': 1, + 'ಎಂ': 1, + 'ಒಂ': 1, + 'ಕಾ': 1, + 'ಕಾಂ': 1, + 'ಕಿಂ': 1, + 'ಕೀ': 1, + 'ಕು': 1, + 'ಕುಂ': 1, + 'ಕೂ': 1, + 'ಕೃ': 1, + 'ಕೆಂ': 1, + 'ಕೇ': 1, + 'ಕೈ': 1, + 'ಕೊ': 1, + 'ಕೊಂ': 1, + 'ಖಾಂ': 1, + 'ಗಾ': 1, + 'ಗಾಂ': 1, + 'ಗೀ': 1, + 'ಗು': 1, + 'ಗೂ': 1, + 'ಗೈ': 1, + 'ಗೊ': 1, + 'ಗೊಂ': 1, + 'ಗೋ': 1, + 'ಚಾ': 1, + 'ಚೀ': 1, + 'ಚು': 1, + 'ಛಾ': 1, + 'ಜಾ': 1, + 'ಜೀ': 1, + 'ಟು': 1, + 'ಟುಂ': 1, + 'ಟೇ': 1, + 'ಠಾ': 1, + 'ಡಾ': 1, + 'ಡು': 1, + 'ಡೂ': 1, + 'ಢೀ': 1, + 'ಣಂ': 1, + 'ಣಾ': 1, + 'ಣು': 1, + 'ಣೈ': 1, + 'ತಂ': 1, + 'ತಃ': 1, + 'ತಾ': 1, + 'ತೀ': 1, + 'ತು': 1, + 'ತೃ': 1, + 'ತೊ': 1, + 'ತೋ': 1, + 'ಥಾ': 1, + 'ದಂ': 1, + 'ದಾ': 1, + 'ದಿಂ': 1, + 'ದು': 1, + 'ದೂ': 1, + 'ದೃ': 1, + 'ದೇ': 1, + 'ದೊ': 1, + 'ದೋ': 1, + 'ಧಾ': 1, + 'ಧೀ': 1, + 'ಧೂ': 1, + 'ನಃ': 1, + 'ನಾ': 1, + 'ನಾಂ': 1, + 'ನಿಂ': 1, + 'ನು': 1, + 'ನೂ': 1, + 'ನೇ': 1, + 'ನೈ': 1, + 'ನೊ': 1, + 'ಪಂ': 1, + 'ಪಾ': 1, + 'ಪು': 1, + 'ಪೂ': 1, + 'ಪೇ': 1, + 'ಬಂ': 1, + 'ಬಾ': 1, + 'ಬು': 1, + 'ಬೇ': 1, + 'ಬೋ': 1, + 'ಭಾ': 1, + 'ಭೀ': 1, + 'ಭು': 1, + 'ಭೇ': 1, + 'ಭೋ': 1, + 'ಮಾ': 1, + 'ಮೀ': 1, + 'ಮು': 1, + 'ಮೂ': 1, + 'ಮೇ': 1, + 'ಮೈ': 1, + 'ಯಂ': 1, + 'ಯಾ': 1, + 'ಯಿಂ': 1, + 'ಯು': 1, + 'ಯುಂ': 1, + 'ಯೂ': 1, + 'ಯೆಂ': 1, + 'ಯೇ': 1, + 'ಯೊ': 1, + 'ಯೋ': 1, + 'ರಂ': 1, + 'ರಾ': 1, + 'ರಾಂ': 1, + 'ರಿಂ': 1, + 'ರೀ': 1, + 'ರು': 1, + 'ರೂ': 1, + 'ರೆಂ': 1, + 'ರೊ': 1, + 'ರೋ': 1, + 'ಲಂ': 1, + 'ಲಾ': 1, + 'ಲೀ': 1, + 'ಲು': 1, + 'ಲೂ': 1, + 'ಲೆಂ': 1, + 'ಲೇ': 1, + 'ಲೋ': 1, + 'ಳಾ': 1, + 'ಳಿಂ': 1, + 'ಳು': 1, + 'ಳೂ': 1, + 'ವಾ': 1, + 'ವೀ': 1, + 'ವು': 1, + 'ವುಂ': 1, + 'ವೂ': 1, + 'ವೃ': 1, + 'ವೆಂ': 1, + 'ವೇ': 1, + 'ವೈ': 1, + 'ವೋ': 1, + 'ಶಾ': 1, + 'ಶಾಂ': 1, + 'ಶೀ': 1, + 'ಶೇ': 1, + 'ಷಾ': 1, + 'ಷೇ': 1, + 'ಸಂ': 1, + 'ಸಾ': 1, + 'ಸಾಂ': 1, + 'ಸು': 1, + 'ಸೂ': 1, + 'ಸೇ': 1, + 'ಹಾ': 1, + 'ಹು': 1, + 'ಹೇ': 1, + 'ಹೊ': 1, + 'ಹೊಂ': 1, + 'ಹೋ': 1, + 'അം': 1, + 'കാ': 1, + 'കി': 1, + 'കെ': 1, + 'കേ': 1, + 'കൈ': 1, + 'കൊ': 1, + 'കോ': 1, + 'ഗം': 1, + 'ഗി': 1, + 'ഗീ': 1, + 'ഘി': 1, + 'ചാ': 1, + 'ചി': 1, + 'ചെ': 1, + 'ചേ': 1, + 'ചോ': 1, + 'ജാ': 1, + 'ജി': 1, + 'ജീ': 1, + 'ടാ': 1, + 'ടി': 1, + 'ടും': 1, + 'ടെ': 1, + 'ടേ': 1, + 'ഠി': 1, + 'ണം': 1, + 'ണാ': 1, + 'ണി': 1, + 'ണെ': 1, + 'തം': 1, + 'താ': 1, + 'തി': 1, + 'തീ': 1, + 'തും': 1, + 'തെ': 1, + 'തേ': 1, + 'തൊ': 1, + 'തോ': 1, + 'ദം': 1, + 'ദാ': 1, + 'ദി': 1, + 'ദേ': 1, + 'ധാ': 1, + 'ധി': 1, + 'നം': 1, + 'നാ': 1, + 'നി': 1, + 'നീ': 1, + 'നും': 1, + 'നെ': 1, + 'നേ': 1, + 'പാ': 1, + 'പി': 1, + 'പീ': 1, + 'പെ': 1, + 'പൈ': 1, + 'പൊ': 1, + 'പോ': 1, + 'പൌ': 1, + 'ബം': 1, + 'ബാ': 1, + 'ബോ': 1, + 'ഭാ': 1, + 'ഭി': 1, + 'ഭേ': 1, + 'ഭൌ': 1, + 'മം': 1, + 'മാ': 1, + 'മി': 1, + 'മെ': 1, + 'മേ': 1, + 'മൊ': 1, + 'മോ': 1, + 'മൌ': 1, + 'യം': 1, + 'യാ': 1, + 'യി': 1, + 'യും': 1, + 'യെ': 1, + 'യേ': 1, + 'യോ': 1, + 'രം': 1, + 'രാ': 1, + 'രി': 1, + 'രീ': 1, + 'രും': 1, + 'രെ': 1, + 'രേ': 1, + 'രോ': 1, + 'റം': 1, + 'റി': 1, + 'റെ': 1, + 'ലം': 1, + 'ലാ': 1, + 'ലി': 1, + 'ലും': 1, + 'ലെ': 1, + 'ലേ': 1, + 'ലോ': 1, + 'ളം': 1, + 'ളാ': 1, + 'ളി': 1, + 'ളും': 1, + 'ളെ': 1, + 'ളേ': 1, + 'ളോ': 1, + 'ഴി': 1, + 'വാ': 1, + 'വി': 1, + 'വും': 1, + 'വെ': 1, + 'വേ': 1, + 'വൈ': 1, + 'വോ': 1, + 'ശാ': 1, + 'ശി': 1, + 'ശീ': 1, + 'ശേ': 1, + 'ഷം': 1, + 'ഷി': 1, + 'സം': 1, + 'സാ': 1, + 'സാം': 1, + 'സി': 1, + 'സൌ': 1, + 'ഹം': 1, + 'ഹാ': 1, + 'ഹി': 1, + 'ഹിം': 1, + 'කා': 1, + 'කැ': 1, + 'කෘ': 1, + 'කෙ': 1, + 'කො': 1, + 'කෝ': 1, + 'කෲ': 1, + 'ගා': 1, + 'ගැ': 1, + 'ගෙ': 1, + 'ගේ': 1, + 'චා': 1, + 'චැ': 1, + 'චෝ': 1, + 'ජා': 1, + 'ඥා': 1, + 'ටා': 1, + 'ටේ': 1, + 'ඨා': 1, + 'ඩං': 1, + 'ඩා': 1, + 'තා': 1, + 'තැ': 1, + 'තෘ': 1, + 'තෙ': 1, + 'තේ': 1, + 'තො': 1, + 'තෝ': 1, + 'ථා': 1, + 'දා': 1, + 'දැ': 1, + 'දිං': 1, + 'දෙ': 1, + 'දේ': 1, + 'දෝ': 1, + 'ධා': 1, + 'නා': 1, + 'නැ': 1, + 'නෑ': 1, + 'නෙ': 1, + 'නේ': 1, + 'නො': 1, + 'ඳා': 1, + 'පා': 1, + 'පැ': 1, + 'පෑ': 1, + 'පෙ': 1, + 'පේ': 1, + 'පො': 1, + 'පෞ': 1, + 'බා': 1, + 'බැ': 1, + 'බෙ': 1, + 'බේ': 1, + 'බෝ': 1, + 'භා': 1, + 'භෞ': 1, + 'මා': 1, + 'මැ': 1, + 'මෙ': 1, + 'මේ': 1, + 'යා': 1, + 'යෙ': 1, + 'යේ': 1, + 'යො': 1, + 'යෝ': 1, + 'රා': 1, + 'රැ': 1, + 'රෙ': 1, + 'රේ': 1, + 'රෝ': 1, + 'ලං': 1, + 'ලා': 1, + 'ලැ': 1, + 'ලෙ': 1, + 'ලේ': 1, + 'ලෝ': 1, + 'වං': 1, + 'වා': 1, + 'වැ': 1, + 'වෘ': 1, + 'වෙ': 1, + 'වේ': 1, + 'වෝ': 1, + 'ශේ': 1, + 'ෂා': 1, + 'සං': 1, + 'සා': 1, + 'සැ': 1, + 'සෑ': 1, + 'සෙ': 1, + 'සේ': 1, + 'සෞ': 1, + 'හා': 1, + 'හැ': 1, + 'හිං': 1, + 'හෘ': 1, + 'හෙ': 1, + 'හො': 1, + 'හෝ': 1, + 'ළැ': 1, + 'ကေ': 1, + 'ကေု': 1, + 'က်ျ': 1, + 'ကျ': 1, + 'ကျို': 1, + 'ကျူ': 1, + 'ကျေ': 1, + 'ကျွ': 1, + 'ကြ': 1, + 'ကြို': 1, + 'ကြီ': 1, + 'ကြု': 1, + 'ကြေ': 1, + 'ကြံ': 1, + 'ကြွေ': 1, + 'ကၠေ': 1, + 'ကၠေံ': 1, + 'ခေ': 1, + 'ချ': 1, + 'ချိ': 1, + 'ချို': 1, + 'ချို့': 1, + 'ချီ': 1, + 'ချု': 1, + 'ချေ': 1, + 'ချဳ': 1, + 'ခြ': 1, + 'ခြုံ': 1, + 'ခြေ': 1, + 'ဂျို': 1, + 'ဂၠေ': 1, + 'ငြ': 1, + 'ငြိ': 1, + 'ငွေ': 1, + 'ငႄ': 1, + 'စေ': 1, + 'စှ်ေ': 1, + 'စၞေ': 1, + 'စၠေ': 1, + 'ဆေ': 1, + 'ဇြ': 1, + 'ဇြေ': 1, + 'ဇြဳ': 1, + 'ဇၞေ': 1, + 'ညေ': 1, + 'တေ': 1, + 'တေံ': 1, + 'တြ': 1, + 'တြုံ': 1, + 'တွေ': 1, + 'တှ်ေ': 1, + 'တၟေ': 1, + 'ထေ': 1, + 'ထွေ': 1, + 'ဒေ': 1, + 'ဒေံ': 1, + 'ဒြ': 1, + 'နေ': 1, + 'နေ့': 1, + 'နှေ': 1, + 'ပေ': 1, + 'ပေဲ': 1, + 'ပျ': 1, + 'ပျေ': 1, + 'ပျဲ': 1, + 'ပြ': 1, + 'ပြီ': 1, + 'ပြု': 1, + 'ပြေ': 1, + 'ပြဳ': 1, + 'ပြံ': 1, + 'ဖေ': 1, + 'ဖျ': 1, + 'ဖျု': 1, + 'ဖျေံ': 1, + 'ဖြ': 1, + 'ဖြို': 1, + 'ဗျဵု': 1, + 'ဗြေ': 1, + 'ဗြဴ': 1, + 'ဗၠေ': 1, + 'ဘေ': 1, + 'မေ': 1, + 'မျ': 1, + 'မျို': 1, + 'မျီု': 1, + 'မျှ': 1, + 'မြ': 1, + 'မြေ': 1, + 'မြှ': 1, + 'မွေ': 1, + 'မွေ့': 1, + 'မှေ': 1, + 'မၠေ': 1, + 'မႄ': 1, + 'ယေ': 1, + 'ယျ': 1, + 'ယျဵု': 1, + 'ယြဴ': 1, + 'ရေ': 1, + 'ရေံ': 1, + 'ရွေ': 1, + 'ရွှေ့': 1, + 'ရှေ': 1, + 'ရှေ့': 1, + 'ရှ်ေ': 1, + 'လေ': 1, + 'လျ': 1, + 'လျို': 1, + 'လျေ': 1, + 'လျှ': 1, + 'လျှို့': 1, + 'လျှေ': 1, + 'လၟေ': 1, + 'လႄ': 1, + 'ဝေ': 1, + 'သေ': 1, + 'သြ': 1, + 'သြို': 1, + 'သှ်ေ': 1, + 'သၞေ': 1, + 'ဟေ': 1, + 'အေ': 1, + 'ၜေ': 1, + 'ၵေ': 1, + 'ၵႄ': 1, + 'ၶေ': 1, + 'ၼေ': 1, + 'ၼႄ': 1, + 'ၽႄ': 1, + 'ႁေ': 1, + 'ႁႄ': 1, + 'កា': 1, + 'កើ': 1, + 'កេ': 1, + 'កោ': 1, + 'ខា': 1, + 'ខែ': 1, + 'គា': 1, + 'គាំ': 1, + 'គេ': 1, + 'គោ': 1, + 'ឃា': 1, + 'ឃើ': 1, + 'ឃោ': 1, + 'ឃៅ': 1, + 'ងា': 1, + 'ចា': 1, + 'ចាំ': 1, + 'ចេ': 1, + 'ចែ': 1, + 'ចោ': 1, + 'ឆាំ': 1, + 'ជា': 1, + 'ជៀ': 1, + 'ឈា': 1, + 'ញុះ': 1, + 'ដា': 1, + 'ដើ': 1, + 'ដែ': 1, + 'ដៃ': 1, + 'ដោ': 1, + 'ដៅ': 1, + 'ឋា': 1, + 'ណា': 1, + 'ណើ': 1, + 'ណែ': 1, + 'ណោ': 1, + 'ណោះ': 1, + 'ណៈ': 1, + 'តា': 1, + 'តេ': 1, + 'តែ': 1, + 'ថា': 1, + 'ថែ': 1, + 'ទា': 1, + 'ទាំ': 1, + 'ទៀ': 1, + 'ទេ': 1, + 'ទៃ': 1, + 'ទោ': 1, + 'ទោះ': 1, + 'ទៅ': 1, + 'ធា': 1, + 'នា': 1, + 'នាំ': 1, + 'នឿ': 1, + 'នេះ': 1, + 'នៃ': 1, + 'នោះ': 1, + 'នៅ': 1, + 'នៈ': 1, + 'បា': 1, + 'បើ': 1, + 'បៀ': 1, + 'បែ': 1, + 'បោ': 1, + 'បោះ': 1, + 'បះ': 1, + 'ប៉ះ': 1, + 'ពា': 1, + 'ពើ': 1, + 'ពេ': 1, + 'ពោះ': 1, + 'ភា': 1, + 'ភេ': 1, + 'មា': 1, + 'មើ': 1, + 'មេ': 1, + 'មែ': 1, + 'ម៉ា': 1, + 'ម៉ោ': 1, + 'យា': 1, + 'យោ': 1, + 'យៈ': 1, + 'យ៉ា': 1, + 'រា': 1, + 'រាំ': 1, + 'រើ': 1, + 'រឿ': 1, + 'រៀ': 1, + 'រះ': 1, + 'រៈ': 1, + 'លា': 1, + 'លុះ': 1, + 'លើ': 1, + 'លេ': 1, + 'លោ': 1, + 'លៈ': 1, + 'វា': 1, + 'វេ': 1, + 'វៈ': 1, + 'សា': 1, + 'សើ': 1, + 'សេ': 1, + 'សៈ': 1, + 'ស្ដ្រី': 3, + 'ស្ត្រ': 3, + 'ហា': 1, + 'ហើ': 1, + 'ហេ': 1, + 'ហែ': 1, + 'ហោ': 1, + 'ឡា': 1, + 'ឡើ': 1, + 'អា': 1, + 'អើ': 1, + 'អៀ': 1, + 'ᨠᩮ᩠': 1, + 'ᨠᩮᩢ᩵': 1, + 'ᨠᩮ᩵': 1, + 'ᨠᩯ᩠': 1, + 'ᨠᩯ᩵': 1, + 'ᨡᩮ᩠': 1, + 'ᨡᩮᩢ': 1, + 'ᨡᩮᩢᩢ': 1, + 'ᨡᩯ᩠': 1, + 'ᨡᩱᩢ': 1, + 'ᨣᩕ': 1, + 'ᨣᩕ᩠': 1, + 'ᨣᩕᩮ᩠': 1, + 'ᨣᩭ': 1, + 'ᨣᩮᩢᩢ': 1, + 'ᨣᩯ᩠': 1, + 'ᨤᩮᩢ': 1, + 'ᨤᩱ᩵': 1, + 'ᨧᩮ': 1, + 'ᨧᩮ᩠': 1, + 'ᨧᩮᩢᩢ': 1, + 'ᨧᩱ': 1, + 'ᨧᩱ᩠': 1, + 'ᨩᩭ᩵': 1, + 'ᨩᩮ᩠': 1, + 'ᨩᩱᩢ': 1, + 'ᨩ᩵ᩭ': 1, + 'ᨪᩮᩢ': 1, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 3, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 3, + 'ᨯᩪᩯ': 1, + 'ᨯᩯ᩠': 1, + 'ᨯᩰ᩠': 1, + 'ᨯᩱ': 1, + 'ᨯᩱᩢ': 1, + 'ᨲᩕ': 1, + 'ᨲᩕᩦ': 1, + 'ᨲᩕ᩼': 1, + 'ᨲᩮ᩠': 1, + 'ᨲᩯ᩠': 1, + 'ᨲᩯ᩵': 1, + 'ᨲᩱ': 1, + 'ᨲᩱ᩠': 1, + 'ᨲᩱᩢ': 1, + 'ᨳᩮ᩠': 1, + 'ᨳᩮᩢᩢ': 1, + 'ᨳᩯ᩠': 1, + 'ᨴᩮ᩠': 1, + 'ᨴᩮᩢᩢ': 1, + 'ᨴᩮᩢ᩵': 1, + 'ᨴᩯ᩠': 1, + 'ᨴᩯᩢ': 1, + 'ᨴᩰ᩠': 1, + 'ᨶᩮ': 1, + 'ᨶᩯ᩠': 1, + 'ᨶᩱ': 1, + 'ᨷᩕ': 1, + 'ᨷᩮ᩠': 1, + 'ᨸᩮ᩠': 1, + 'ᨸᩮᩢ᩵': 1, + 'ᨹᩪᩢᩱ': 1, + 'ᨹᩮᩨ᩠': 1, + 'ᨻᩕ᩠': 1, + 'ᨻᩮ᩠': 1, + 'ᨻᩱ': 1, + 'ᨽᩱ᩠': 1, + 'ᨾᩮ᩠': 1, + 'ᨾᩯ᩵': 1, + 'ᨾᩱ': 1, + 'ᨿᩮ᩠': 1, + 'ᨿᩰ': 1, + 'ᩁᩢᩭ': 1, + 'ᩁᩮ᩠': 1, + 'ᩁᩮᩨ᩠': 1, + 'ᩁᩯ᩠': 1, + 'ᩃᩮ᩠': 1, + 'ᩃᩯ': 1, + 'ᩃᩰ᩠': 1, + 'ᩅᩮ': 1, + 'ᩅᩮ᩠': 1, + 'ᩅᩱᩢ': 1, + 'ᩈᩮ': 1, + 'ᩈᩮ᩠': 1, + 'ᩈᩯ᩠': 1, + 'ᩈᩱ': 1, + 'ᩈᩱ᩠': 1, + 'ᩉᩕᩨ': 1, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 3, + 'ᩉᩮᩖᩨ': 1, + 'ᩉᩮ᩠': 1, + 'ᩉᩯ᩠': 1, + 'ᩉᩯ᩵': 1, + 'ᩉᩱ᩠': 1, + 'ꦏꦃ': 1, + 'ꦏꦺ': 1, + 'ꦏꦺꦴ': 1, + 'ꦏꦿ': 1, + 'ꦏꦿꦁ': 1, + 'ꦏꦿꦂ': 1, + 'ꦒꦸꦃ': 1, + 'ꦒꦺꦴ': 1, + 'ꦒꦿ': 1, + 'ꦒꦿꦺ': 1, + 'ꦔꦃ': 1, + 'ꦔꦺ': 1, + 'ꦔꦺꦴ': 1, + 'ꦔꦿ': 1, + 'ꦕꦃ': 1, + 'ꦕꦺꦴ': 1, + 'ꦗꦃ': 1, + 'ꦗꦺ': 1, + 'ꦗꦿꦺꦴ': 1, + 'ꦝꦃ': 1, + 'ꦝꦺ': 1, + 'ꦝꦺꦴ': 1, + 'ꦝꦺꦴꦂ': 1, + 'ꦠꦸꦃ': 1, + 'ꦠꦺ': 1, + 'ꦠꦺꦃ': 1, + 'ꦠꦺꦴ': 1, + 'ꦠꦾ': 1, + 'ꦠꦿ': 1, + 'ꦠꦿꦶ': 1, + 'ꦠ꧀ꦱ꧀ꦮ': 3, + 'ꦢꦃ': 1, + 'ꦢꦺ': 1, + 'ꦢꦺꦴ': 1, + 'ꦢꦾ': 1, + 'ꦢꦿ': 1, + 'ꦤꦺ': 1, + 'ꦤꦺꦃ': 1, + 'ꦤꦺꦴ': 1, + 'ꦥꦃ': 1, + 'ꦥꦺ': 1, + 'ꦥꦺꦴ': 1, + 'ꦥꦿ': 1, + 'ꦥꦿꦃ': 1, + 'ꦥꦿꦶ': 1, + 'ꦥꦿꦺꦴ': 1, + 'ꦧꦺ': 1, + 'ꦧꦺꦃ': 1, + 'ꦧꦺꦴ': 1, + 'ꦧꦿ': 1, + 'ꦩꦃ': 1, + 'ꦩꦺ': 1, + 'ꦩꦺꦃ': 1, + 'ꦩꦺꦴ': 1, + 'ꦩꦿ': 1, + 'ꦩꦿꦃ': 1, + 'ꦩꦿꦶꦃ': 1, + 'ꦪꦃ': 1, + 'ꦪꦸꦃ': 1, + 'ꦪꦺꦴ': 1, + 'ꦫꦶꦃ': 1, + 'ꦫꦺ': 1, + 'ꦫꦺꦴ': 1, + 'ꦫꦾ': 1, + 'ꦭꦃ': 1, + 'ꦭꦶꦃ': 1, + 'ꦭꦺ': 1, + 'ꦭꦺꦃ': 1, + 'ꦭꦺꦴ': 1, + 'ꦭꦺꦴꦁ': 1, + 'ꦮꦃ': 1, + 'ꦮꦶꦃ': 1, + 'ꦮꦸꦃ': 1, + 'ꦮꦺ': 1, + 'ꦮꦺꦴ': 1, + 'ꦮꦺꦴꦁ': 1, + 'ꦮꦺꦴꦃ': 1, + 'ꦮꦿꦸꦃ': 1, + 'ꦱꦶꦃ': 1, + 'ꦱꦺ': 1, + 'ꦱꦺꦴ': 1, + 'ꦱꦾ': 1, + 'ꦱꦿ': 1, + 'ꦱꦿꦃ': 1, + 'ꦲꦺ': 1, + 'ꦲꦺꦴ': 1, + '𑄃𑄬': 1, + '𑄃𑄬𑄭': 1, + '𑄇𑄬': 1, + '𑄈𑄬': 1, + '𑄉𑄬': 1, + '𑄉𑄬𑄭': 1, + '𑄊𑄬': 1, + '𑄌𑄬': 1, + '𑄎𑄬': 1, + '𑄎𑄬𑄭': 1, + '𑄏𑄬': 1, + '𑄑𑄬': 1, + '𑄖𑄬': 1, + '𑄗𑄬': 1, + '𑄘𑄬': 1, + '𑄙𑄬': 1, + '𑄚𑄬': 1, + '𑄚𑄬𑄭': 1, + '𑄛𑄬': 1, + '𑄜𑄬': 1, + '𑄝𑄬': 1, + '𑄞𑄬': 1, + '𑄞𑄬𑄭': 1, + '𑄟𑄬': 1, + '𑄠𑄬': 1, + '𑄠𑄬𑄭': 1, + '𑄡𑄬': 1, + '𑄡𑄬𑄭': 1, + '𑄢𑄬': 1, + '𑄢𑄬𑄭': 1, + '𑄣𑄬': 1, + '𑄣𑄬𑄭': 1, + '𑄥𑄬': 1, + '𑄦𑄬': 1, + '𑌅𑌂': 1, + '𑌕𑌂': 1, + '𑌕𑌾': 1, + '𑌕𑌾𑌂': 1, + '𑌕𑌾𑌃': 1, + '𑌕𑌿': 1, + '𑌕𑍂': 1, + '𑌕𑍃': 1, + '𑌕𑍇': 1, + '𑌕𑍋': 1, + '𑌗𑌾': 1, + '𑌗𑌿': 1, + '𑌗𑍁': 1, + '𑌗𑍃': 1, + '𑌗𑍇': 1, + '𑌗𑍌': 1, + '𑌘𑌾': 1, + '𑌘𑍇': 1, + '𑌘𑍋': 1, + '𑌚𑌾': 1, + '𑌚𑌿': 1, + '𑌚𑍇': 1, + '𑌚𑍈': 1, + '𑌛𑌾': 1, + '𑌛𑍁': 1, + '𑌛𑍇': 1, + '𑌜𑌾': 1, + '𑌜𑌿': 1, + '𑌜𑍇': 1, + '𑌞𑌾': 1, + '𑌟𑌃': 1, + '𑌟𑌾': 1, + '𑌟𑌾𑌂': 1, + '𑌟𑌾𑌃': 1, + '𑌠𑌾': 1, + '𑌠𑍇': 1, + '𑌠𑍈𑌃': 1, + '𑌡𑌂': 1, + '𑌡𑌃': 1, + '𑌡𑌿': 1, + '𑌣𑌂': 1, + '𑌣𑌾': 1, + '𑌣𑌾𑌂': 1, + '𑌣𑌿': 1, + '𑌣𑍁': 1, + '𑌣𑍇': 1, + '𑌤𑌂': 1, + '𑌤𑌃': 1, + '𑌤𑌾': 1, + '𑌤𑌾𑌂': 1, + '𑌤𑌾𑌃': 1, + '𑌤𑌿': 1, + '𑌤𑌿𑌂': 1, + '𑌤𑌿𑌃': 1, + '𑌤𑍁': 1, + '𑌤𑍁𑌂': 1, + '𑌤𑍃': 1, + '𑌤𑍇': 1, + '𑌤𑍇𑌃': 1, + '𑌤𑍈': 1, + '𑌤𑍋': 1, + '𑌤𑍌': 1, + '𑌥𑌂': 1, + '𑌥𑌾': 1, + '𑌥𑌾𑌂': 1, + '𑌥𑌿': 1, + '𑌦𑌂': 1, + '𑌦𑌃': 1, + '𑌦𑌾': 1, + '𑌦𑌿': 1, + '𑌦𑍁': 1, + '𑌦𑍃': 1, + '𑌦𑍇': 1, + '𑌦𑍋': 1, + '𑌧𑌃': 1, + '𑌧𑌾': 1, + '𑌧𑌾𑌃': 1, + '𑌧𑌿': 1, + '𑌧𑌿𑌂': 1, + '𑌧𑍁': 1, + '𑌧𑍃': 1, + '𑌧𑍇': 1, + '𑌧𑍇𑌃': 1, + '𑌧𑍈𑌃': 1, + '𑌨𑌂': 1, + '𑌨𑌃': 1, + '𑌨𑌾': 1, + '𑌨𑌾𑌂': 1, + '𑌨𑌾𑌃': 1, + '𑌨𑌿': 1, + '𑌨𑌿𑌃': 1, + '𑌨𑍁': 1, + '𑌨𑍂': 1, + '𑌨𑍇': 1, + '𑌨𑍈': 1, + '𑌨𑍈𑌃': 1, + '𑌨𑍋': 1, + '𑌪𑌂': 1, + '𑌪𑌾': 1, + '𑌪𑌿': 1, + '𑌪𑍁': 1, + '𑌪𑍂': 1, + '𑌪𑍇': 1, + '𑌪𑍋': 1, + '𑌬𑌾': 1, + '𑌬𑍃': 1, + '𑌭𑌾': 1, + '𑌭𑌿': 1, + '𑌭𑌿𑌃': 1, + '𑌭𑍁': 1, + '𑌭𑍂': 1, + '𑌭𑍇': 1, + '𑌮𑌂': 1, + '𑌮𑌾': 1, + '𑌮𑌿': 1, + '𑌮𑌿𑌂': 1, + '𑌮𑍁': 1, + '𑌮𑍂': 1, + '𑌮𑍇': 1, + '𑌮𑍈': 1, + '𑌮𑍋': 1, + '𑌮𑍌': 1, + '𑌯𑌂': 1, + '𑌯𑌃': 1, + '𑌯𑌾': 1, + '𑌯𑌾𑌂': 1, + '𑌯𑌾𑌃': 1, + '𑌯𑌿': 1, + '𑌯𑍁': 1, + '𑌯𑍁𑌃': 1, + '𑌯𑍇': 1, + '𑌯𑍈': 1, + '𑌯𑍈𑌃': 1, + '𑌯𑍋': 1, + '𑌯𑍋𑌃': 1, + '𑌰𑌂': 1, + '𑌰𑌃': 1, + '𑌰𑌾': 1, + '𑌰𑌾𑌃': 1, + '𑌰𑌿': 1, + '𑌰𑌿𑌂': 1, + '𑌰𑍁': 1, + '𑌰𑍂': 1, + '𑌰𑍇': 1, + '𑌰𑍋': 1, + '𑌰𑍌': 1, + '𑌲𑌂': 1, + '𑌲𑌾': 1, + '𑌲𑌾𑌃': 1, + '𑌲𑌿': 1, + '𑌲𑌿𑌂': 1, + '𑌲𑍇': 1, + '𑌲𑍈': 1, + '𑌲𑍋': 1, + '𑌵𑌂': 1, + '𑌵𑌃': 1, + '𑌵𑌾': 1, + '𑌵𑌾𑌂': 1, + '𑌵𑌾𑌃': 1, + '𑌵𑌿': 1, + '𑌵𑍃': 1, + '𑌵𑍇': 1, + '𑌵𑍈': 1, + '𑌵𑍋': 1, + '𑌶𑌂': 1, + '𑌶𑌃': 1, + '𑌶𑌾': 1, + '𑌶𑌾𑌃': 1, + '𑌶𑌿': 1, + '𑌶𑍁': 1, + '𑌶𑍂': 1, + '𑌶𑍇': 1, + '𑌶𑍋': 1, + '𑌷𑌂': 1, + '𑌷𑌾': 1, + '𑌷𑌾𑌂': 1, + '𑌷𑌾𑌃': 1, + '𑌷𑌿': 1, + '𑌷𑍁': 1, + '𑌷𑍇': 1, + '𑌷𑍈': 1, + '𑌷𑍋': 1, + '𑌸𑌂': 1, + '𑌸𑌃': 1, + '𑌸𑌾': 1, + '𑌸𑌾𑌂': 1, + '𑌸𑌿': 1, + '𑌸𑍁': 1, + '𑌸𑍂': 1, + '𑌸𑍇': 1, + '𑌸𑍋': 1, + '𑌸𑍌': 1, + '𑌹𑌾': 1, + '𑌹𑌾𑌃': 1, + '𑌹𑌿': 1, + '𑌹𑍇': 1, + '𑌹𑍋': 1, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_244dc88b.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_244dc88b.py new file mode 100644 index 0000000000000000000000000000000000000000..1a454f686d36faa5dc68b13b48b97f952753421c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_244dc88b.py @@ -0,0 +1,82 @@ +""" +Grapheme overrides for _known_244dc88b. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: contour +""" +# pylint: skip-file +GRAPHEMES = { + 'ൻ്റെ': 3, + 'ᨠᩮ᩠ᨯᩨ': 3, + 'ᨠᩯ᩠ᨯ': 3, + 'ᨠᩯ᩠ᨶ᩵': 3, + 'ᨡᩮ᩠ᨲ': 3, + 'ᨡᩯ᩠ᨠ': 3, + 'ᨡᩯ᩠ᨦ': 3, + 'ᨣᩕ᩠ᩋ': 3, + 'ᨣᩕᩮ᩠ᨦᩨ᩵': 3, + 'ᨣᩯ᩠ᨶᩢ': 3, + 'ᨣᩯ᩠ᩅ': 3, + 'ᨧᩮ᩠ᨷ': 3, + 'ᨧᩱ᩠ᨿ': 3, + 'ᨩᩮ᩠ᩋᩨ': 3, + 'ᨩᩮ᩠ᩋᩨ᩵': 3, + 'ᨩᩮ᩠ᩋᩨ᩶': 3, + 'ᨯᩯ᩠ᨦ': 3, + 'ᨯᩯ᩠ᨶ': 3, + 'ᨯᩰ᩠ᨿ': 3, + 'ᨲᩮ᩠ᨠ': 3, + 'ᨲᩮ᩠ᨦ': 3, + 'ᨲᩮ᩠ᨾ': 3, + 'ᨲᩮ᩠ᨾᩨ᩵': 3, + 'ᨲᩯ᩠ᨠ': 3, + 'ᨲᩯ᩠ᨦ᩵': 3, + 'ᨲᩯ᩠ᨾᩢ': 3, + 'ᨲᩱ᩠ᨿ': 3, + 'ᨳᩮ᩠ᨶᩨ᩵': 3, + 'ᨳᩯ᩠ᨦᩢ': 3, + 'ᨳᩯ᩠ᨾ': 3, + 'ᨴᩮ᩠ᩈ': 3, + 'ᨴᩮ᩠ᩈᩱ': 4, + 'ᨴᩯ᩠ᨶ': 3, + 'ᨴᩰ᩠ᩈ': 3, + 'ᨶᩯ᩠ᨶ': 3, + 'ᨷᩮ᩠ᨦᩨ᩶': 3, + 'ᨸᩮ᩠ᨦᩨ': 3, + 'ᨸᩮ᩠ᨶ': 3, + 'ᨹᩮᩨ᩠ᨿ': 3, + 'ᨻᩕ᩠ᩋᩢ': 3, + 'ᨻᩮ᩠ᩋᩨ᩵': 3, + 'ᨽᩱ᩠ᨿ': 3, + 'ᨾᩮ᩠ᨠᩨ': 3, + 'ᨾᩮ᩠ᨦᩨ': 3, + 'ᨾᩮ᩠ᩋᩨ᩵': 3, + 'ᨿᩮ᩠ᨶ': 3, + 'ᨿᩮ᩠ᨾᩨ': 3, + 'ᩁᩮ᩠ᨦᩨ᩵': 3, + 'ᩁᩮ᩠ᨧ': 3, + 'ᩁᩮ᩠ᨶᩨ': 3, + 'ᩁᩮᩨ᩠ᨬ': 3, + 'ᩁᩯ᩠ᨦ': 3, + 'ᩃᩮ᩠ᨠᩨ': 3, + 'ᩃᩮ᩠ᨦᩨ': 3, + 'ᩃᩰ᩠ᨠ': 3, + 'ᩅᩮ᩠ᨶ': 3, + 'ᩅᩮ᩠ᨶᩢ': 3, + 'ᩈᩮ᩠ᩈ': 3, + 'ᩈᩯ᩠ᩅ': 3, + 'ᩈᩱ᩠ᨿ': 3, + 'ᩉᩮ᩠ᨦᩢᩢ': 3, + 'ᩉᩮ᩠ᨯ': 3, + 'ᩉᩮ᩠ᨲᩩ': 3, + 'ᩉᩮ᩠ᨶᩨ': 3, + 'ᩉᩮ᩠ᨾᩨ': 3, + 'ᩉᩮ᩠ᨾᩨᩨ': 3, + 'ᩉᩯ᩠ᨦ᩵': 3, + 'ᩉᩯ᩠ᨶᩢ': 3, + 'ᩉᩯ᩠ᨾ': 3, + 'ᩉᩱ᩠ᨾ᩵': 3, + 'ᩉᩱ᩠ᨿ᩵': 3, + 'ᩣ᩠ᨲᩱ': 3, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_336a71a1.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_336a71a1.py new file mode 100644 index 0000000000000000000000000000000000000000..947b0c4b52dbd4d93f87815a443a2ddbefd7d9a6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_336a71a1.py @@ -0,0 +1,3590 @@ +""" +Grapheme overrides for _known_336a71a1. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: kitty +""" +# pylint: skip-file +GRAPHEMES = { + '؁۱': 0, + 'का': 1, + 'कां': 1, + 'कि': 1, + 'किं': 1, + 'की': 1, + 'केा': 1, + 'को': 1, + 'कौ': 1, + 'क्क': 1, + 'क्का': 1, + 'क्कां': 1, + 'क्को': 1, + 'क्घ्घि्': 1, + 'क्छ': 1, + 'क्त': 1, + 'क्ता': 1, + 'क्ति': 1, + 'क्ती': 1, + 'क्तीं': 1, + 'क्तुं': 1, + 'क्तेः': 1, + 'क्त्योः': 1, + 'क्ना': 1, + 'क्नि': 1, + 'क्य': 1, + 'क्या': 1, + 'क्र': 1, + 'क्रा': 1, + 'क्रि': 1, + 'क्रू': 1, + 'क्ष': 1, + 'क्षं': 1, + 'क्षा': 1, + 'क्षां': 1, + 'क्षाः': 1, + 'क्षि': 1, + 'क्षे': 1, + 'क्षै': 1, + 'क्षो': 1, + 'क्ष्ण': 1, + 'क्ष्य': 1, + 'क्ष्या': 1, + 'क्सा': 1, + 'खा': 1, + 'खि': 1, + 'खी': 1, + 'खो': 1, + 'ख्त': 1, + 'ख्ने': 1, + 'ख्य': 1, + 'ख्यः': 1, + 'ख्या': 1, + 'ख्‍ने': 1, + 'ग़ा': 1, + 'गा': 1, + 'गाँ': 1, + 'गां': 1, + 'गि': 1, + 'गी': 1, + 'गो': 1, + 'गों': 1, + 'गौ': 1, + 'ग्ण': 1, + 'ग्न': 1, + 'ग्ने': 1, + 'ग्भे': 1, + 'ग्य': 1, + 'ग्या': 1, + 'ग्ये': 1, + 'ग्यैः': 1, + 'ग्र': 1, + 'ग्रे': 1, + 'ग्र्य': 1, + 'घा': 1, + 'घि': 1, + 'घी': 1, + 'घेि': 1, + 'घो': 1, + 'घ्ंत': 1, + 'घ्का': 1, + 'घ्त': 1, + 'घ्र': 1, + 'घ्र्व्य': 1, + 'घ्लि': 1, + 'घ्व': 1, + 'घ्श्य': 1, + 'घ्स्ट': 1, + 'ङ्ग': 1, + 'ङ्घ': 1, + 'चा': 1, + 'चां': 1, + 'चि': 1, + 'ची': 1, + 'चो': 1, + 'चौ': 1, + 'च्च': 1, + 'च्चा': 1, + 'च्चे': 1, + 'च्चों': 1, + 'च्छ': 1, + 'च्छं': 1, + 'च्छा': 1, + 'च्छि': 1, + 'च्छु': 1, + 'च्छे': 1, + 'च्या': 1, + 'च्यां': 1, + 'च्यो': 1, + 'छि': 1, + 'छुी': 1, + 'छो': 1, + 'जा': 1, + 'जि': 1, + 'जिं': 1, + 'जी': 1, + 'जो': 1, + 'ज्ज': 1, + 'ज्ञा': 1, + 'ज्ञे': 1, + 'ज्ने': 1, + 'ज्य': 1, + 'ज्या': 1, + 'ज्या‌': 1, + 'ज्रा': 1, + 'झा': 1, + 'ञ्च': 1, + 'ञ्चा': 1, + 'ञ्चि': 1, + 'टा': 1, + 'टां': 1, + 'टि': 1, + 'टी': 1, + 'टों': 1, + 'ट्ज़': 1, + 'ट्टि': 1, + 'ट्टी': 1, + 'ट्या': 1, + 'ट्र': 1, + 'ट्रा': 1, + 'ट्रे': 1, + 'ठा': 1, + 'ठी': 1, + 'ठैः': 1, + 'ड़ा': 1, + 'डा': 1, + 'डि': 1, + 'डी': 1, + 'डो': 1, + 'ढ़ा': 1, + 'ढ़ि': 1, + 'ढ़ी': 1, + 'ढ़ो': 1, + 'ढा': 1, + 'ढाँ': 1, + 'ढि': 1, + 'णा': 1, + 'णां': 1, + 'णि': 1, + 'णी': 1, + 'णो': 1, + 'णों': 1, + 'ण्ड': 1, + 'ण्डं': 1, + 'ण्डः': 1, + 'ण्डि': 1, + 'ण्य': 1, + 'ण्या': 1, + 'ण्यां': 1, + 'तः': 1, + 'ता': 1, + 'तां': 1, + 'ताः': 1, + 'ति': 1, + 'तिं': 1, + 'ती': 1, + 'तो': 1, + 'तों': 1, + 'तौ': 1, + 'त्का': 1, + 'त्त': 1, + 'त्ता': 1, + 'त्ति': 1, + 'त्ते': 1, + 'त्त्थि': 1, + 'त्त्व': 1, + 'त्त्वा': 1, + 'त्त्वे': 1, + 'त्न': 1, + 'त्नी': 1, + 'त्नों': 1, + 'त्प': 1, + 'त्पा': 1, + 'त्पी': 1, + 'त्पू': 1, + 'त्म': 1, + 'त्मा': 1, + 'त्य': 1, + 'त्यं': 1, + 'त्या': 1, + 'त्यां': 1, + 'त्यि': 1, + 'त्ये': 1, + 'त्यै': 1, + 'त्र': 1, + 'त्रा': 1, + 'त्राा': 1, + 'त्राि': 1, + 'त्रि': 1, + 'त्री': 1, + 'त्रे': 1, + 'त्र्त': 1, + 'त्र्य': 1, + 'त्र्या': 1, + 'त्र्ये': 1, + 'त्व': 1, + 'त्वं': 1, + 'त्वा': 1, + 'त्वां': 1, + 'त्वे': 1, + 'त्सं': 1, + 'त्सा': 1, + 'त्सो': 1, + 'त्स्वा': 1, + 'था': 1, + 'थि': 1, + 'थ्य': 1, + 'दः': 1, + 'दा': 1, + 'दां': 1, + 'दि': 1, + 'दी': 1, + 'दो': 1, + 'दौ': 1, + 'द्घ': 1, + 'द्घि': 1, + 'द्घो': 1, + 'द्द': 1, + 'द्दा': 1, + 'द्दि': 1, + 'द्दी': 1, + 'द्दे': 1, + 'द्ध': 1, + 'द्धः': 1, + 'द्धा': 1, + 'द्धां': 1, + 'द्धि': 1, + 'द्धिं': 1, + 'द्धी': 1, + 'द्धीं': 1, + 'द्धैः': 1, + 'द्भ': 1, + 'द्भा': 1, + 'द्य': 1, + 'द्या': 1, + 'द्र': 1, + 'द्रो': 1, + 'द्व': 1, + 'द्वा': 1, + 'द्वि': 1, + 'द्वे': 1, + 'द्स': 1, + 'धा': 1, + 'धां': 1, + 'धाः': 1, + 'धि': 1, + 'धी': 1, + 'धेः': 1, + 'धो': 1, + 'धों': 1, + 'ध्य': 1, + 'ध्या': 1, + 'ध्ये': 1, + 'ध्व': 1, + 'नः': 1, + 'ना': 1, + 'नां': 1, + 'नाः': 1, + 'ना‌': 1, + 'नि': 1, + 'निँ': 1, + 'निः': 1, + 'नी': 1, + 'नैः': 1, + 'नो': 1, + 'नों': 1, + 'नौ': 1, + 'न्का': 1, + 'न्चि': 1, + 'न्छे': 1, + 'न्जे': 1, + 'न्ञ्या': 1, + 'न्त': 1, + 'न्तं': 1, + 'न्तः': 1, + 'न्ता': 1, + 'न्ति': 1, + 'न्तु': 1, + 'न्तुं': 1, + 'न्ते': 1, + 'न्तो': 1, + 'न्तों': 1, + 'न्त्र': 1, + 'न्त्रा': 1, + 'न्त्राः': 1, + 'न्त्रि': 1, + 'न्त्री': 1, + 'न्त्र्य': 1, + 'न्त्र्यं': 1, + 'न्त्र्या': 1, + 'न्त्र्ये': 1, + 'न्द': 1, + 'न्दा': 1, + 'न्दी': 1, + 'न्दो': 1, + 'न्ध': 1, + 'न्धा': 1, + 'न्धि': 1, + 'न्धी': 1, + 'न्धु': 1, + 'न्धों': 1, + 'न्न': 1, + 'न्ना': 1, + 'न्नाः': 1, + 'न्नि': 1, + 'न्ने': 1, + 'न्म': 1, + 'न्मा': 1, + 'न्मु': 1, + 'न्मे': 1, + 'न्य': 1, + 'न्या': 1, + 'न्ये': 1, + 'न्यै': 1, + 'न्यो': 1, + 'न्व': 1, + 'न्वे': 1, + 'न्स': 1, + 'न्हा': 1, + 'न्हें': 1, + 'न्ह्यां': 1, + 'पा': 1, + 'पाँ': 1, + 'पां': 1, + 'पि': 1, + 'पी': 1, + 'पो': 1, + 'पों': 1, + 'प्त': 1, + 'प्तं': 1, + 'प्ति': 1, + 'प्तुं': 1, + 'प्तौ': 1, + 'प्य': 1, + 'प्यं': 1, + 'प्या': 1, + 'प्र': 1, + 'प्रा': 1, + 'फा': 1, + 'फाँ': 1, + 'फौ': 1, + 'फ्त': 1, + 'फ्ता': 1, + 'फ्ना': 1, + 'फ्नो': 1, + 'फ्रां': 1, + 'बा': 1, + 'बाँ': 1, + 'बि': 1, + 'बी': 1, + 'बो': 1, + 'ब्द': 1, + 'ब्ध': 1, + 'ब्धि': 1, + 'ब्यू': 1, + 'भा': 1, + 'भि': 1, + 'भिः': 1, + 'भी': 1, + 'भो': 1, + 'भौ': 1, + 'भ्य': 1, + 'भ्यः': 1, + 'भ्या': 1, + 'भ्यां': 1, + 'भ्यु': 1, + 'भ्यो': 1, + 'भ्र': 1, + 'मा': 1, + 'मां': 1, + 'मि': 1, + 'मी': 1, + 'मो': 1, + 'मों': 1, + 'मौ': 1, + 'म्ति': 1, + 'म्न': 1, + 'म्नि': 1, + 'म्प': 1, + 'म्पा': 1, + 'म्प्र': 1, + 'म्ब': 1, + 'म्बु': 1, + 'म्भि': 1, + 'म्म': 1, + 'म्मा': 1, + 'म्मि': 1, + 'म्मे': 1, + 'म्या': 1, + 'म्से': 1, + 'म्ह': 1, + 'म्ही': 1, + 'म्हो': 1, + 'यः': 1, + 'या': 1, + 'यां': 1, + 'याः': 1, + 'यि': 1, + 'यी': 1, + 'यैः': 1, + 'यो': 1, + 'यों': 1, + 'य्य': 1, + 'य्यो': 1, + 'रः': 1, + 'रा': 1, + 'रां': 1, + 'राः': 1, + 'रि': 1, + 'रिं': 1, + 'री': 1, + 'रो': 1, + 'रों': 1, + 'रौ': 1, + 'र्क': 1, + 'र्कि': 1, + 'र्ग': 1, + 'र्गी': 1, + 'र्गे': 1, + 'र्चि': 1, + 'र्छ': 1, + 'र्ज': 1, + 'र्जा': 1, + 'र्जि': 1, + 'र्जी': 1, + 'र्ट': 1, + 'र्ढ': 1, + 'र्ण': 1, + 'र्णं': 1, + 'र्णां': 1, + 'र्णी': 1, + 'र्त': 1, + 'र्ता': 1, + 'र्ति': 1, + 'र्तिः': 1, + 'र्ती': 1, + 'र्तुं': 1, + 'र्त्त': 1, + 'र्त्ति': 1, + 'र्थ': 1, + 'र्थं': 1, + 'र्थि': 1, + 'र्थी': 1, + 'र्द': 1, + 'र्दा': 1, + 'र्दि': 1, + 'र्दु': 1, + 'र्दे': 1, + 'र्दै': 1, + 'र्दो': 1, + 'र्द्ध': 1, + 'र्ध': 1, + 'र्धा': 1, + 'र्धि': 1, + 'र्न': 1, + 'र्नि': 1, + 'र्नु': 1, + 'र्नू': 1, + 'र्ने': 1, + 'र्फ': 1, + 'र्ब': 1, + 'र्बं': 1, + 'र्बा': 1, + 'र्भ': 1, + 'र्भा': 1, + 'र्म': 1, + 'र्मं': 1, + 'र्मा': 1, + 'र्मि': 1, + 'र्य': 1, + 'र्यं': 1, + 'र्या': 1, + 'र्यां': 1, + 'र्ये': 1, + 'र्यों': 1, + 'र्रा': 1, + 'र्व': 1, + 'र्वा': 1, + 'र्वां': 1, + 'र्वृ': 1, + 'र्वे': 1, + 'र्वो': 1, + 'र्श': 1, + 'र्ष': 1, + 'र्षे': 1, + 'र्स': 1, + 'र्सा': 1, + 'र्ह': 1, + 'र्हाः': 1, + 'र्हि': 1, + 'र्हो': 1, + 'र्‍या': 1, + 'ला': 1, + 'लां': 1, + 'लाः': 1, + 'लि': 1, + 'लिं': 1, + 'ली': 1, + 'लीं': 1, + 'लो': 1, + 'लों': 1, + 'लौ': 1, + 'ल्क': 1, + 'ल्का': 1, + 'ल्ने': 1, + 'ल्प': 1, + 'ल्पि': 1, + 'ल्म': 1, + 'ल्य': 1, + 'ल्यं': 1, + 'ल्या': 1, + 'ल्यां': 1, + 'ल्याः': 1, + 'ल्ये': 1, + 'ल्ल': 1, + 'ल्लं': 1, + 'ल्ला': 1, + 'ल्लि': 1, + 'ल्ले': 1, + 'ल्ह': 1, + 'ळा': 1, + 'ळी': 1, + 'वः': 1, + 'वा': 1, + 'वां': 1, + 'वाः': 1, + 'वि': 1, + 'वी': 1, + 'वो': 1, + 'वों': 1, + 'व्य': 1, + 'व्या': 1, + 'व्ये': 1, + 'व्यों': 1, + 'शः': 1, + 'शा': 1, + 'शां': 1, + 'शाः': 1, + 'शि': 1, + 'शी': 1, + 'शो': 1, + 'शों': 1, + 'श्च': 1, + 'श्चि': 1, + 'श्य': 1, + 'श्या': 1, + 'श्यि': 1, + 'श्यों': 1, + 'श्र': 1, + 'श्रा': 1, + 'श्रां': 1, + 'श्रु': 1, + 'श्व': 1, + 'श्वा': 1, + 'श्वि': 1, + 'षा': 1, + 'षां': 1, + 'षाः': 1, + 'षि': 1, + 'षी': 1, + 'षों': 1, + 'ष्का': 1, + 'ष्ट': 1, + 'ष्टः': 1, + 'ष्टा': 1, + 'ष्टां': 1, + 'ष्टाः': 1, + 'ष्टि': 1, + 'ष्टी': 1, + 'ष्टीं': 1, + 'ष्ट्र': 1, + 'ष्ट्रा': 1, + 'ष्ट्रां': 1, + 'ष्ट्रि': 1, + 'ष्ट्री': 1, + 'ष्ट्रे': 1, + 'ष्ट्रो': 1, + 'ष्ट्रों': 1, + 'ष्ठा': 1, + 'ष्ठे': 1, + 'ष्ठों': 1, + 'ष्णु': 1, + 'ष्प': 1, + 'ष्प्र': 1, + 'ष्य': 1, + 'ष्यः': 1, + 'ष्यों': 1, + 'सः': 1, + 'सा': 1, + 'साँ': 1, + 'सां': 1, + 'सि': 1, + 'सी': 1, + 'सो': 1, + 'सौ': 1, + 'स्क': 1, + 'स्का': 1, + 'स्काः': 1, + 'स्कु': 1, + 'स्कू': 1, + 'स्कृ': 1, + 'स्ट': 1, + 'स्ट्या': 1, + 'स्त': 1, + 'स्ता': 1, + 'स्ति': 1, + 'स्ती': 1, + 'स्तु': 1, + 'स्तुं': 1, + 'स्तै': 1, + 'स्तो': 1, + 'स्त्र': 1, + 'स्त्रा': 1, + 'स्त्रि': 1, + 'स्त्री': 1, + 'स्थ': 1, + 'स्था': 1, + 'स्थां': 1, + 'स्थि': 1, + 'स्थी': 1, + 'स्थे': 1, + 'स्थ्य': 1, + 'स्धी': 1, + 'स्प': 1, + 'स्पे': 1, + 'स्म': 1, + 'स्मि': 1, + 'स्मिं': 1, + 'स्मै': 1, + 'स्य': 1, + 'स्या': 1, + 'स्यां': 1, + 'स्याः': 1, + 'स्युः': 1, + 'स्यों': 1, + 'स्रो': 1, + 'स्ल': 1, + 'स्व': 1, + 'स्वं': 1, + 'स्वा': 1, + 'स्वी': 1, + 'स्वे': 1, + 'स्स': 1, + 'स्सा': 1, + 'हा': 1, + 'हाँ': 1, + 'हां': 1, + 'हि': 1, + 'हिं': 1, + 'ही': 1, + 'हीं': 1, + 'हैः': 1, + 'हो': 1, + 'हों': 1, + 'हौ': 1, + 'ह्या': 1, + 'ह्रा': 1, + 'क़ा': 1, + 'क़ि': 1, + 'ज़ा': 1, + 'ड़ा': 1, + 'ढ़ा': 1, + 'फ़ा': 1, + 'फ़्ता': 1, + 'অং': 1, + 'কা': 1, + 'কা‌': 1, + 'কি': 1, + 'কিং': 1, + 'কে': 1, + 'কে‌': 1, + 'কো': 1, + 'ক্ত': 1, + 'ক্তি': 1, + 'ক্য': 1, + 'ক্র': 1, + 'ক্রী': 1, + 'ক্ষ': 1, + 'ক্ষা': 1, + 'ক্ষি': 1, + 'ক্ষে': 1, + 'ক্ষ্য': 1, + 'ক্ষ্যে': 1, + 'খা': 1, + 'খি': 1, + 'খে': 1, + 'খ্যা': 1, + 'গি': 1, + 'গে': 1, + 'গো': 1, + 'গ্য': 1, + 'গ্র': 1, + 'গ্রা': 1, + 'গ্রে': 1, + 'ঘা': 1, + 'ঘে': 1, + 'ঘো': 1, + 'ঘো': 1, + 'ঙ্খা': 1, + 'ঙ্গ': 1, + 'ঙ্গী': 1, + 'ঙ্গে': 1, + 'ঙ্ঘ': 1, + 'চা': 1, + 'চি': 1, + 'চে': 1, + 'চো': 1, + 'চৌ': 1, + 'চ্চ': 1, + 'চ্ছ': 1, + 'চ্ছা': 1, + 'চ্ছা‌': 1, + 'চ্ছু': 1, + 'চ্ছে': 1, + 'ছা': 1, + 'ছি': 1, + 'ছে': 1, + 'জা': 1, + 'জি': 1, + 'জী': 1, + 'জে': 1, + 'জে‌': 1, + 'জ্ঞ': 1, + 'জ্ঞা': 1, + 'জ্য': 1, + 'ঝো': 1, + 'ঞ্চি': 1, + 'ঞ্ছি': 1, + 'টা': 1, + 'টি': 1, + 'ট্রে': 1, + 'ঠি': 1, + 'ড়া': 1, + 'ণা': 1, + 'ণি': 1, + 'ণে': 1, + 'ণ্ড': 1, + 'ণ্ডে': 1, + 'ণ্য': 1, + 'তঃ': 1, + 'তা': 1, + 'তাঁ': 1, + 'তা‌': 1, + 'তি': 1, + 'তি‌': 1, + 'তী': 1, + 'তে': 1, + 'তে‌': 1, + 'ত্ত': 1, + 'ত্তা': 1, + 'ত্তি': 1, + 'ত্ন': 1, + 'ত্ব': 1, + 'ত্বে': 1, + 'ত্ম': 1, + 'ত্য': 1, + 'ত্যা': 1, + 'ত্যি': 1, + 'ত্যে': 1, + 'ত্র': 1, + 'ত্রা': 1, + 'ত্রে': 1, + 'ত্‍প': 1, + 'ত্‍পী': 1, + 'ত্‍সা': 1, + 'থা': 1, + 'থি': 1, + 'থে': 1, + 'থ্য': 1, + 'দা': 1, + 'দি': 1, + 'দে': 1, + 'দে‌': 1, + 'দৈ': 1, + 'দো': 1, + 'দ্দি': 1, + 'দ্দে': 1, + 'দ্ধ': 1, + 'দ্ধা': 1, + 'দ্ধি': 1, + 'দ্ধে': 1, + 'দ্বা': 1, + 'দ্ভ': 1, + 'দ্ভূ': 1, + 'দ্য': 1, + 'দ্রো': 1, + 'ধা': 1, + 'ধি': 1, + 'ধী': 1, + 'ধে': 1, + 'ধ্য': 1, + 'ধ্যে': 1, + 'না': 1, + 'না‌': 1, + 'নি': 1, + 'নী': 1, + 'নে': 1, + 'নৈ': 1, + 'নো': 1, + 'ন্ড': 1, + 'ন্ত': 1, + 'ন্তা': 1, + 'ন্তি': 1, + 'ন্তে': 1, + 'ন্ত্রি': 1, + 'ন্ত্রে': 1, + 'ন্থী': 1, + 'ন্ধ': 1, + 'ন্ধা': 1, + 'ন্ধু': 1, + 'ন্ন': 1, + 'ন্ম': 1, + 'ন্মা': 1, + 'ন্মু': 1, + 'ন্য': 1, + 'ন্যা': 1, + 'ন্যে': 1, + 'পা': 1, + 'পা‌': 1, + 'পি': 1, + 'পী': 1, + 'পে': 1, + 'পো': 1, + 'প্ত': 1, + 'প্তা': 1, + 'প্র': 1, + 'প্রা': 1, + 'ফে': 1, + 'ফৌ': 1, + 'বং': 1, + 'বা': 1, + 'বা‌': 1, + 'বি': 1, + 'বী': 1, + 'বে': 1, + 'বৈ': 1, + 'বো': 1, + 'ব্ধি': 1, + 'ব্য': 1, + 'ব্যা': 1, + 'ব্র': 1, + 'ভা': 1, + 'ভি': 1, + 'ভে': 1, + 'ভো': 1, + 'ভৌ': 1, + 'ভ্য': 1, + 'ভ্রা': 1, + 'মা': 1, + 'মা‌': 1, + 'মি': 1, + 'মে': 1, + 'মৌ': 1, + 'ম্প': 1, + 'ম্পা': 1, + 'ম্ব': 1, + 'ম্ভ': 1, + 'ম্ম': 1, + 'ম্মা': 1, + 'ম্য': 1, + 'য়া': 1, + 'য়ি': 1, + 'য়ে': 1, + 'য়ো': 1, + 'যা': 1, + 'যে': 1, + 'যো': 1, + 'য্য': 1, + 'রা': 1, + 'রাং': 1, + 'রি': 1, + 'রী': 1, + 'রে': 1, + 'রো': 1, + 'র্ক': 1, + 'র্জ': 1, + 'র্জা': 1, + 'র্ণ': 1, + 'র্ত': 1, + 'র্থ': 1, + 'র্থে': 1, + 'র্দো': 1, + 'র্ধ': 1, + 'র্ধা': 1, + 'র্নী': 1, + 'র্ব': 1, + 'র্বা': 1, + 'র্বি': 1, + 'র্বো': 1, + 'র্ব্য': 1, + 'র্ভূ': 1, + 'র্ম': 1, + 'র্মে': 1, + 'র্য': 1, + 'র্যা': 1, + 'লা': 1, + 'লি': 1, + 'লী': 1, + 'লে': 1, + 'লে‌': 1, + 'ল্প': 1, + 'ল্য': 1, + 'ল্যা': 1, + 'ল্যে': 1, + 'ল্লে': 1, + 'শং': 1, + 'শা': 1, + 'শি': 1, + 'শী': 1, + 'শৃং': 1, + 'শে': 1, + 'শৈ': 1, + 'শ্চ': 1, + 'শ্চি': 1, + 'শ্বা': 1, + 'শ্বে': 1, + 'শ্য': 1, + 'শ্যে': 1, + 'শ্র': 1, + 'শ্রা': 1, + 'ষা': 1, + 'ষি': 1, + 'ষী': 1, + 'ষে': 1, + 'ষ্ট': 1, + 'ষ্টা': 1, + 'ষ্টি': 1, + 'ষ্ট্র': 1, + 'ষ্ট্রী': 1, + 'ষ্ট্রে': 1, + 'ষ্ঠা': 1, + 'ষ্ঠি': 1, + 'ষ্ঠী': 1, + 'ষ্ঠু': 1, + 'ষ্ণু': 1, + 'সং': 1, + 'সা': 1, + 'সাং': 1, + 'সি': 1, + 'সী': 1, + 'সে': 1, + 'সে‌': 1, + 'স্ক': 1, + 'স্কৃ': 1, + 'স্ত': 1, + 'স্তি': 1, + 'স্তি‌': 1, + 'স্ত্র': 1, + 'স্থ': 1, + 'স্থা': 1, + 'স্থ্য': 1, + 'স্ব': 1, + 'স্বা': 1, + 'স্বী': 1, + 'স্য': 1, + 'স্যা': 1, + 'স্যে': 1, + 'হা': 1, + 'হি': 1, + 'হে': 1, + 'হো': 1, + 'হ্য': 1, + 'য়ে': 1, + 'ਕਾ': 1, + 'ਕਾਂ': 1, + 'ਕਿ': 1, + 'ਕਿ੍': 1, + 'ਕਿੱ': 1, + 'ਕੀ': 1, + 'ਖਾ': 1, + 'ਖਾਂ': 1, + 'ਖਿ': 1, + 'ਖਿ਼': 1, + 'ਖੀ': 1, + 'ਗਾ': 1, + 'ਗਿ': 1, + 'ਗਿ੍': 1, + 'ਗੀ': 1, + 'ਚਾ': 1, + 'ਚਿ': 1, + 'ਚਿੱ': 1, + 'ਚੀ': 1, + 'ਜਾ': 1, + 'ਜਾਂ': 1, + 'ਜਿ': 1, + 'ਜਿ਼': 1, + 'ਜਿ਼ੰ': 1, + 'ਜੀ': 1, + 'ਝਿ': 1, + 'ਝੀ': 1, + 'ਟਾ': 1, + 'ਟਿ': 1, + 'ਟਿ੍': 1, + 'ਟੀ': 1, + 'ਠੀ': 1, + 'ਡਾ': 1, + 'ਣਾ': 1, + 'ਣਾਂ': 1, + 'ਣੀ': 1, + 'ਤਾ': 1, + 'ਤਾਂ': 1, + 'ਤਿ': 1, + 'ਤੀ': 1, + 'ਦਾ': 1, + 'ਦਾਂ': 1, + 'ਦਿ': 1, + 'ਦਿੱ': 1, + 'ਦੀ': 1, + 'ਧਾ': 1, + 'ਧਾਂ': 1, + 'ਧਿ': 1, + 'ਧੀ': 1, + 'ਨਾ': 1, + 'ਨਾਂ': 1, + 'ਨਿ': 1, + 'ਨੀ': 1, + 'ਨੀਂ': 1, + 'ਪਾ': 1, + 'ਪਿ': 1, + 'ਪੀ': 1, + 'ਫਿ': 1, + 'ਬਾ': 1, + 'ਬਿ': 1, + 'ਬੀ': 1, + 'ਭਾ': 1, + 'ਭਿ': 1, + 'ਮਾ': 1, + 'ਮਾਂ': 1, + 'ਮਿ': 1, + 'ਮੀ': 1, + 'ਯਾ': 1, + 'ਰਾ': 1, + 'ਰਾਂ': 1, + 'ਰਿ': 1, + 'ਰੀ': 1, + 'ਲਾ': 1, + 'ਲਾਂ': 1, + 'ਲਿ': 1, + 'ਲਿੰ': 1, + 'ਲੀ': 1, + 'ਵਾ': 1, + 'ਵਾਂ': 1, + 'ਵਿ': 1, + 'ਵਿੱ': 1, + 'ਵੀ': 1, + 'ਸ਼ਾ': 1, + 'ਸ਼ਾਂ': 1, + 'ਸ਼ਿ': 1, + 'ਸ਼ੀ': 1, + 'ਸਾ': 1, + 'ਸਾਂ': 1, + 'ਸਿ': 1, + 'ਸਿੱ': 1, + 'ਸੀ': 1, + 'ਹਾ': 1, + 'ਹਾਂ': 1, + 'ਹਿ': 1, + 'ਹਿੰ': 1, + 'ਹਿੱ': 1, + 'ਹੀ': 1, + 'ਹੀਂ': 1, + 'ਜ਼ਾ': 1, + 'ਜ਼ੀ': 1, + 'ੜਾ': 1, + 'ੜੀਂ': 1, + 'ਫ਼ਾ': 1, + 'કઃ': 1, + 'કા': 1, + 'કાં': 1, + 'કિ': 1, + 'કી': 1, + 'કો': 1, + 'ક્ક': 1, + 'ક્કા': 1, + 'ક્કો': 1, + 'ક્તિ': 1, + 'ક્ર': 1, + 'ક્ષ': 1, + 'ક્ષા': 1, + 'ખા': 1, + 'ખી': 1, + 'ખો': 1, + 'ખ્ત': 1, + 'ગા': 1, + 'ગિ': 1, + 'ગી': 1, + 'ગો': 1, + 'ગ્ન': 1, + 'ગ્ય': 1, + 'ઘા': 1, + 'ઘો': 1, + 'ચા': 1, + 'ચિ': 1, + 'ચી': 1, + 'ચ્ચ': 1, + 'ચ્ચા': 1, + 'ચ્ચે': 1, + 'ચ્છા': 1, + 'ચ્છે': 1, + 'છા': 1, + 'છો': 1, + 'જા': 1, + 'જાં': 1, + 'જિ': 1, + 'જી': 1, + 'જો': 1, + 'જ્ઞા': 1, + 'જ્ય': 1, + 'જ્યો': 1, + 'ટઃ': 1, + 'ટ્ર': 1, + 'ટ્રે': 1, + 'ડા': 1, + 'ડાં': 1, + 'ડી': 1, + 'ઢા': 1, + 'ઢિ': 1, + 'ણા': 1, + 'ણી': 1, + 'તઃ': 1, + 'તા': 1, + 'તાં': 1, + 'તિ': 1, + 'તી': 1, + 'તો': 1, + 'ત્તા': 1, + 'ત્તિ': 1, + 'ત્ત્વ': 1, + 'ત્ત્વા': 1, + 'ત્ન': 1, + 'ત્મ': 1, + 'ત્ય': 1, + 'ત્યા': 1, + 'ત્યાં': 1, + 'ત્યિ': 1, + 'ત્યે': 1, + 'ત્યો': 1, + 'ત્ર': 1, + 'ત્રી': 1, + 'ત્ર્ય': 1, + 'ત્વ': 1, + 'થા': 1, + 'થી': 1, + 'દા': 1, + 'દી': 1, + 'દો': 1, + 'દ્ધ': 1, + 'દ્ધા': 1, + 'દ્ધાં': 1, + 'દ્ધિ': 1, + 'દ્ભ': 1, + 'દ્વા': 1, + 'ધા': 1, + 'ધાં': 1, + 'ધિ': 1, + 'ધી': 1, + 'ધો': 1, + 'ધ્ય': 1, + 'ધ્યા': 1, + 'નઃ': 1, + 'ના': 1, + 'નાં': 1, + 'નિ': 1, + 'ની': 1, + 'નો': 1, + 'ન્ત': 1, + 'ન્તો': 1, + 'ન્મ': 1, + 'ન્મા': 1, + 'ન્મે': 1, + 'ન્ય': 1, + 'ન્યા': 1, + 'ન્યૂં': 1, + 'પા': 1, + 'પિ': 1, + 'પી': 1, + 'પો': 1, + 'પ્ત': 1, + 'પ્ર': 1, + 'પ્રા': 1, + 'ફા': 1, + 'ફો': 1, + 'બા': 1, + 'બાં': 1, + 'બી': 1, + 'બ્ધ': 1, + 'ભા': 1, + 'ભાં': 1, + 'ભિ': 1, + 'ભો': 1, + 'ભૌ': 1, + 'ભ્ય': 1, + 'મઃ': 1, + 'મા': 1, + 'માં': 1, + 'મિ': 1, + 'મી': 1, + 'મો': 1, + 'મ્ય': 1, + 'મ્યાં': 1, + 'યા': 1, + 'યિ': 1, + 'યી': 1, + 'યો': 1, + 'રા': 1, + 'રિ': 1, + 'રી': 1, + 'રો': 1, + 'ર્જ': 1, + 'ર્ણ': 1, + 'ર્ત': 1, + 'ર્તા': 1, + 'ર્થ': 1, + 'ર્થિ': 1, + 'ર્દો': 1, + 'ર્મ': 1, + 'ર્મિ': 1, + 'ર્મે': 1, + 'ર્ય': 1, + 'ર્યા': 1, + 'ર્યો': 1, + 'ર્વ': 1, + 'લા': 1, + 'લાં': 1, + 'લિ': 1, + 'લિં': 1, + 'લી': 1, + 'લો': 1, + 'લ્મ': 1, + 'લ્ય': 1, + 'ળા': 1, + 'ળી': 1, + 'વા': 1, + 'વાં': 1, + 'વિ': 1, + 'વી': 1, + 'વો': 1, + 'વ્ય': 1, + 'વ્યા': 1, + 'વ્યો': 1, + 'શા': 1, + 'શાં': 1, + 'શિ': 1, + 'શી': 1, + 'શો': 1, + 'શ્કે': 1, + 'શ્ચ': 1, + 'શ્ય': 1, + 'શ્ર': 1, + 'શ્વ': 1, + 'ષા': 1, + 'ષી': 1, + 'ષો': 1, + 'ષ્ટિ': 1, + 'ષ્ટ્ર': 1, + 'ષ્ટ્રી': 1, + 'ષ્ટ્રો': 1, + 'ષ્ઠા': 1, + 'ષ્ણુ': 1, + 'ષ્પ': 1, + 'સા': 1, + 'સાં': 1, + 'સિ': 1, + 'સી': 1, + 'સો': 1, + 'સ્કૃ': 1, + 'સ્ટ': 1, + 'સ્તિ': 1, + 'સ્તી': 1, + 'સ્ત્રી': 1, + 'સ્થા': 1, + 'સ્થિ': 1, + 'સ્પ': 1, + 'સ્રી': 1, + 'સ્વ': 1, + 'સ્વા': 1, + 'સ્વી': 1, + 'સ્સા': 1, + 'હા': 1, + 'હિ': 1, + 'હી': 1, + 'હો': 1, + 'கா': 1, + 'கி': 1, + 'கு': 1, + 'கூ': 1, + 'கெ': 1, + 'கே': 1, + 'கை': 1, + 'கொ': 1, + 'கோ': 1, + 'சா': 1, + 'சி': 1, + 'சு': 1, + 'சூ': 1, + 'செ': 1, + 'சே': 1, + 'சை': 1, + 'சொ': 1, + 'டா': 1, + 'டி': 1, + 'டு': 1, + 'டெ': 1, + 'டை': 1, + 'ணா': 1, + 'ணி': 1, + 'ணு': 1, + 'ணை': 1, + 'தா': 1, + 'தி': 1, + 'து': 1, + 'தூ': 1, + 'தெ': 1, + 'தே': 1, + 'தை': 1, + 'தொ': 1, + 'தோ': 1, + 'நா': 1, + 'நி': 1, + 'நு': 1, + 'நெ': 1, + 'நே': 1, + 'நோ': 1, + 'னா': 1, + 'னி': 1, + 'னு': 1, + 'னே': 1, + 'னை': 1, + 'னொ': 1, + 'பா': 1, + 'பி': 1, + 'பு': 1, + 'பெ': 1, + 'பே': 1, + 'பை': 1, + 'பொ': 1, + 'போ': 1, + 'மா': 1, + 'மி': 1, + 'மு': 1, + 'மூ': 1, + 'மெ': 1, + 'மே': 1, + 'மை': 1, + 'மொ': 1, + 'மோ': 1, + 'யா': 1, + 'யி': 1, + 'யு': 1, + 'யே': 1, + 'யை': 1, + 'யோ': 1, + 'ரா': 1, + 'ரி': 1, + 'ரு': 1, + 'ரெ': 1, + 'ரை': 1, + 'றா': 1, + 'றி': 1, + 'று': 1, + 'றே': 1, + 'றை': 1, + 'றொ': 1, + 'றோ': 1, + 'லா': 1, + 'லி': 1, + 'லு': 1, + 'லெ': 1, + 'லே': 1, + 'லை': 1, + 'லோ': 1, + 'ளா': 1, + 'ளி': 1, + 'ளு': 1, + 'ளெ': 1, + 'ளை': 1, + 'ழி': 1, + 'ழு': 1, + 'ழை': 1, + 'வா': 1, + 'வி': 1, + 'வு': 1, + 'வூ': 1, + 'வெ': 1, + 'வே': 1, + 'வை': 1, + 'வொ': 1, + 'வோ': 1, + 'అం': 1, + 'ఆం': 1, + 'ఒం': 1, + 'కం': 1, + 'కాం': 1, + 'కు': 1, + 'కుం': 1, + 'కూ': 1, + 'కృ': 1, + 'కెం': 1, + 'క్క': 1, + 'క్కు': 1, + 'క్త': 1, + 'క్తి': 1, + 'క్తీ': 1, + 'క్తు': 1, + 'క్య': 1, + 'క్ర': 1, + 'క్రాం': 1, + 'క్రి': 1, + 'క్రూ': 1, + 'క్ష': 1, + 'క్షా': 1, + 'క్షి': 1, + 'క్షిం': 1, + 'క్షే': 1, + 'క్షో': 1, + 'క్స్వా': 1, + 'ఖ్య': 1, + 'ఖ్యా': 1, + 'గిం': 1, + 'గు': 1, + 'గూ': 1, + 'గృ': 1, + 'గ్భా': 1, + 'గ్మ': 1, + 'గ్య': 1, + 'గ్ర': 1, + 'గ్రి': 1, + 'చు': 1, + 'చెం': 1, + 'చ్చు': 1, + 'చ్ఛ': 1, + 'చ్ఛా': 1, + 'చ్ఛే': 1, + 'ఛ్ఛా': 1, + 'జ్ఞ': 1, + 'జ్ఞా': 1, + 'జ్య': 1, + 'టం': 1, + 'టిం': 1, + 'టు': 1, + 'టుం': 1, + 'ట్టి': 1, + 'ట్లు': 1, + 'డు': 1, + 'డ్డ': 1, + 'డ్రు': 1, + 'ణిం': 1, + 'తం': 1, + 'తః': 1, + 'తు': 1, + 'తృ': 1, + 'త్కా': 1, + 'త్త': 1, + 'త్తి': 1, + 'త్తు': 1, + 'త్న': 1, + 'త్నిం': 1, + 'త్ప': 1, + 'త్ఫ': 1, + 'త్య': 1, + 'త్యం': 1, + 'త్యా': 1, + 'త్ర': 1, + 'త్రు': 1, + 'త్ర్య': 1, + 'త్వ': 1, + 'త్వా': 1, + 'త్స': 1, + 'దం': 1, + 'దిం': 1, + 'దు': 1, + 'దుం': 1, + 'దృ': 1, + 'ద్ఘో': 1, + 'ద్ది': 1, + 'ద్దు': 1, + 'ద్దే': 1, + 'ద్ధ': 1, + 'ద్ధి': 1, + 'ద్ధిం': 1, + 'ద్య': 1, + 'ద్యా': 1, + 'ద్యో': 1, + 'ద్ర్య': 1, + 'ద్వా': 1, + 'ధిం': 1, + 'ధు': 1, + 'ధ్య': 1, + 'నం': 1, + 'నః': 1, + 'నాం': 1, + 'నిం': 1, + 'ను': 1, + 'నుం': 1, + 'నొం': 1, + 'న్ధ': 1, + 'న్న': 1, + 'న్నా': 1, + 'న్ని': 1, + 'న్ను': 1, + 'న్మ': 1, + 'న్య': 1, + 'న్యా': 1, + 'న్వే': 1, + 'పం': 1, + 'పిం': 1, + 'పు': 1, + 'పూ': 1, + 'పెం': 1, + 'పొం': 1, + 'ప్త': 1, + 'ప్ర': 1, + 'ప్రా': 1, + 'ప్రే': 1, + 'బం': 1, + 'బ్ర': 1, + 'భం': 1, + 'భు': 1, + 'భ్య': 1, + 'భ్యు': 1, + 'భ్ర': 1, + 'భ్రా': 1, + 'మిం': 1, + 'ము': 1, + 'మూ': 1, + 'మ్య': 1, + 'యం': 1, + 'యః': 1, + 'యిం': 1, + 'యు': 1, + 'యుం': 1, + 'రం': 1, + 'రిం': 1, + 'రు': 1, + 'రూ': 1, + 'ర్గ': 1, + 'ర్చి': 1, + 'ర్చు': 1, + 'ర్ణ': 1, + 'ర్ణాం': 1, + 'ర్ణు': 1, + 'ర్త': 1, + 'ర్తి': 1, + 'ర్తిం': 1, + 'ర్తృ': 1, + 'ర్థ': 1, + 'ర్థి': 1, + 'ర్థిం': 1, + 'ర్ద': 1, + 'ర్దో': 1, + 'ర్ధ': 1, + 'ర్ప': 1, + 'ర్బం': 1, + 'ర్భ': 1, + 'ర్భా': 1, + 'ర్య': 1, + 'ర్యా': 1, + 'ర్రా': 1, + 'ర్వ': 1, + 'ర్వా': 1, + 'ర్హ': 1, + 'ర్హాం': 1, + 'ర్హు': 1, + 'ఱు': 1, + 'లం': 1, + 'లిం': 1, + 'లు': 1, + 'ల్క': 1, + 'ల్గొ': 1, + 'ల్ప': 1, + 'ల్ల': 1, + 'ల్లి': 1, + 'విం': 1, + 'వు': 1, + 'వృ': 1, + 'వ్య': 1, + 'వ్యా': 1, + 'వ్వ': 1, + 'శాం': 1, + 'శిం': 1, + 'శు': 1, + 'శ్చ': 1, + 'శ్చి': 1, + 'శ్య': 1, + 'శ్ర': 1, + 'శ్రాం': 1, + 'శ్లే': 1, + 'శ్వా': 1, + 'షిం': 1, + 'షు': 1, + 'ష్ట': 1, + 'ష్టు': 1, + 'ష్ట్ర': 1, + 'ష్ట్రీ': 1, + 'ష్ఠ': 1, + 'ష్ఠా': 1, + 'ష్ఠు': 1, + 'ష్థ': 1, + 'ష్ప': 1, + 'సం': 1, + 'సాం': 1, + 'సు': 1, + 'సూ': 1, + 'స్కృ': 1, + 'స్తా': 1, + 'స్తి': 1, + 'స్త్ర': 1, + 'స్త్రీ': 1, + 'స్థ': 1, + 'స్థా': 1, + 'స్థి': 1, + 'స్థ్య': 1, + 'స్ప': 1, + 'స్య': 1, + 'స్వ': 1, + 'స్వా': 1, + 'స్వీ': 1, + 'స్వే': 1, + 'హిం': 1, + 'ಅಂ': 1, + 'ಇಂ': 1, + 'ಉಂ': 1, + 'ಎಂ': 1, + 'ಒಂ': 1, + 'ಕಾ': 1, + 'ಕಾಂ': 1, + 'ಕಿಂ': 1, + 'ಕೀ': 1, + 'ಕು': 1, + 'ಕುಂ': 1, + 'ಕೂ': 1, + 'ಕೃ': 1, + 'ಕೆಂ': 1, + 'ಕೇ': 1, + 'ಕೈ': 1, + 'ಕೊ': 1, + 'ಕೊಂ': 1, + 'ಖಾಂ': 1, + 'ಗಾ': 1, + 'ಗಾಂ': 1, + 'ಗೀ': 1, + 'ಗು': 1, + 'ಗೂ': 1, + 'ಗೈ': 1, + 'ಗೊ': 1, + 'ಗೊಂ': 1, + 'ಗೋ': 1, + 'ಚಾ': 1, + 'ಚೀ': 1, + 'ಚು': 1, + 'ಛಾ': 1, + 'ಜಾ': 1, + 'ಜೀ': 1, + 'ಟು': 1, + 'ಟುಂ': 1, + 'ಟೇ': 1, + 'ಠಾ': 1, + 'ಡಾ': 1, + 'ಡು': 1, + 'ಡೂ': 1, + 'ಢೀ': 1, + 'ಣಂ': 1, + 'ಣಾ': 1, + 'ಣು': 1, + 'ಣೈ': 1, + 'ತಂ': 1, + 'ತಃ': 1, + 'ತಾ': 1, + 'ತೀ': 1, + 'ತು': 1, + 'ತೃ': 1, + 'ತೊ': 1, + 'ತೋ': 1, + 'ಥಾ': 1, + 'ದಂ': 1, + 'ದಾ': 1, + 'ದಿಂ': 1, + 'ದು': 1, + 'ದೂ': 1, + 'ದೃ': 1, + 'ದೇ': 1, + 'ದೊ': 1, + 'ದೋ': 1, + 'ಧಾ': 1, + 'ಧೀ': 1, + 'ಧೂ': 1, + 'ನಃ': 1, + 'ನಾ': 1, + 'ನಾಂ': 1, + 'ನಿಂ': 1, + 'ನು': 1, + 'ನೂ': 1, + 'ನೇ': 1, + 'ನೈ': 1, + 'ನೊ': 1, + 'ಪಂ': 1, + 'ಪಾ': 1, + 'ಪು': 1, + 'ಪೂ': 1, + 'ಪೇ': 1, + 'ಬಂ': 1, + 'ಬಾ': 1, + 'ಬು': 1, + 'ಬೇ': 1, + 'ಬೋ': 1, + 'ಭಾ': 1, + 'ಭೀ': 1, + 'ಭು': 1, + 'ಭೇ': 1, + 'ಭೋ': 1, + 'ಮಾ': 1, + 'ಮೀ': 1, + 'ಮು': 1, + 'ಮೂ': 1, + 'ಮೇ': 1, + 'ಮೈ': 1, + 'ಯಂ': 1, + 'ಯಾ': 1, + 'ಯಿಂ': 1, + 'ಯು': 1, + 'ಯುಂ': 1, + 'ಯೂ': 1, + 'ಯೆಂ': 1, + 'ಯೇ': 1, + 'ಯೊ': 1, + 'ಯೋ': 1, + 'ರಂ': 1, + 'ರಾ': 1, + 'ರಾಂ': 1, + 'ರಿಂ': 1, + 'ರೀ': 1, + 'ರು': 1, + 'ರೂ': 1, + 'ರೆಂ': 1, + 'ರೊ': 1, + 'ರೋ': 1, + 'ಲಂ': 1, + 'ಲಾ': 1, + 'ಲೀ': 1, + 'ಲು': 1, + 'ಲೂ': 1, + 'ಲೆಂ': 1, + 'ಲೇ': 1, + 'ಲೋ': 1, + 'ಳಾ': 1, + 'ಳಿಂ': 1, + 'ಳು': 1, + 'ಳೂ': 1, + 'ವಾ': 1, + 'ವೀ': 1, + 'ವು': 1, + 'ವುಂ': 1, + 'ವೂ': 1, + 'ವೃ': 1, + 'ವೆಂ': 1, + 'ವೇ': 1, + 'ವೈ': 1, + 'ವೋ': 1, + 'ಶಾ': 1, + 'ಶಾಂ': 1, + 'ಶೀ': 1, + 'ಶೇ': 1, + 'ಷಾ': 1, + 'ಷೇ': 1, + 'ಸಂ': 1, + 'ಸಾ': 1, + 'ಸಾಂ': 1, + 'ಸು': 1, + 'ಸೂ': 1, + 'ಸೇ': 1, + 'ಹಾ': 1, + 'ಹು': 1, + 'ಹೇ': 1, + 'ಹೊ': 1, + 'ಹೊಂ': 1, + 'ಹೋ': 1, + 'അം': 1, + 'കാ': 1, + 'കി': 1, + 'കെ': 1, + 'കേ': 1, + 'കൈ': 1, + 'കൊ': 1, + 'കോ': 1, + 'ക്ക': 1, + 'ക്കാ': 1, + 'ക്കി': 1, + 'ക്കു': 1, + 'ക്കും': 1, + 'ക്കെ': 1, + 'ക്കേ': 1, + 'ക്കൊ': 1, + 'ക്കോ': 1, + 'ക്ക്‌': 1, + 'ക്തി': 1, + 'ക്യ': 1, + 'ക്യം': 1, + 'ക്ര': 1, + 'ക്രൂ': 1, + 'ക്ഷ': 1, + 'ക്ഷാ': 1, + 'ക്ഷി': 1, + 'ക്ഷേ': 1, + 'ഖ്യാ': 1, + 'ഗം': 1, + 'ഗി': 1, + 'ഗീ': 1, + 'ഗ്ഗം': 1, + 'ഗ്ദാ': 1, + 'ഗ്യ': 1, + 'ഗ്യം': 1, + 'ഗ്ര': 1, + 'ഘി': 1, + 'ങ്കി': 1, + 'ങ്കെ': 1, + 'ങ്കേ': 1, + 'ങ്ങ': 1, + 'ങ്ങി': 1, + 'ചാ': 1, + 'ചി': 1, + 'ചെ': 1, + 'ചേ': 1, + 'ചോ': 1, + 'ച്ച': 1, + 'ച്ചി': 1, + 'ച്ചു': 1, + 'ച്ചും': 1, + 'ച്ചെ': 1, + 'ച്ചേ': 1, + 'ജാ': 1, + 'ജി': 1, + 'ജീ': 1, + 'ജ്യ': 1, + 'ജ്യാ': 1, + 'ഞ്ച': 1, + 'ഞ്ഞ': 1, + 'ഞ്ഞി': 1, + 'ഞ്ഞെ': 1, + 'ടാ': 1, + 'ടി': 1, + 'ടും': 1, + 'ടെ': 1, + 'ടേ': 1, + 'ട്ട': 1, + 'ട്ടാ': 1, + 'ട്ടി': 1, + 'ട്ടു': 1, + 'ട്ടോ': 1, + 'ഠി': 1, + 'ണം': 1, + 'ണാ': 1, + 'ണി': 1, + 'ണെ': 1, + 'ണ്ട': 1, + 'ണ്ടാ': 1, + 'ണ്ടി': 1, + 'ണ്ടു': 1, + 'ണ്ടും': 1, + 'ണ്ടെ': 1, + 'ണ്ട്‌': 1, + 'ണ്ഡ': 1, + 'ണ്ണ': 1, + 'തം': 1, + 'താ': 1, + 'തി': 1, + 'തീ': 1, + 'തും': 1, + 'തെ': 1, + 'തേ': 1, + 'തൊ': 1, + 'തോ': 1, + 'ത്ത': 1, + 'ത്താ': 1, + 'ത്തി': 1, + 'ത്തു': 1, + 'ത്തും': 1, + 'ത്തെ': 1, + 'ത്തേ': 1, + 'ത്തോ': 1, + 'ത്ത്‌': 1, + 'ത്ന': 1, + 'ത്നം': 1, + 'ത്നി': 1, + 'ത്യ': 1, + 'ത്യാ': 1, + 'ത്യേ': 1, + 'ത്ര': 1, + 'ത്വ': 1, + 'ത്വം': 1, + 'ദം': 1, + 'ദാ': 1, + 'ദി': 1, + 'ദേ': 1, + 'ദ്ദ': 1, + 'ദ്ധ': 1, + 'ദ്ധി': 1, + 'ദ്യ': 1, + 'ദ്യാ': 1, + 'ദ്ര': 1, + 'ധാ': 1, + 'ധി': 1, + 'ധ്യ': 1, + 'നം': 1, + 'നാ': 1, + 'നി': 1, + 'നീ': 1, + 'നും': 1, + 'നെ': 1, + 'നേ': 1, + 'ന്ത': 1, + 'ന്തം': 1, + 'ന്തെ': 1, + 'ന്ത്ര': 1, + 'ന്ത്ര്യ': 1, + 'ന്ത്ര്യം': 1, + 'ന്ഥ': 1, + 'ന്ദ': 1, + 'ന്ധ': 1, + 'ന്ധി': 1, + 'ന്ന': 1, + 'ന്നാ': 1, + 'ന്നി': 1, + 'ന്നീ': 1, + 'ന്നു': 1, + 'ന്നും': 1, + 'ന്നെ': 1, + 'ന്നേ': 1, + 'ന്നോ': 1, + 'ന്ന്': 1, + 'ന്മ': 1, + 'ന്മാ': 1, + 'ന്മു': 1, + 'ന്മൂ': 1, + 'ന്യ': 1, + 'ന്യം': 1, + 'ന്യാ': 1, + 'ന്യേ': 1, + 'ന്യോ': 1, + 'ന്റെ': 1, + 'ന്‍കൂ': 1, + 'ന്‍പി': 1, + 'പാ': 1, + 'പി': 1, + 'പീ': 1, + 'പെ': 1, + 'പൈ': 1, + 'പൊ': 1, + 'പോ': 1, + 'പൌ': 1, + 'പ്പ': 1, + 'പ്പി': 1, + 'പ്പു': 1, + 'പ്പെ': 1, + 'പ്പോ': 1, + 'പ്പ്‌': 1, + 'പ്ര': 1, + 'പ്രാ': 1, + 'ബം': 1, + 'ബാ': 1, + 'ബോ': 1, + 'ബ്ലി': 1, + 'ഭാ': 1, + 'ഭി': 1, + 'ഭേ': 1, + 'ഭൌ': 1, + 'ഭ്യാ': 1, + 'ഭ്രാ': 1, + 'മം': 1, + 'മാ': 1, + 'മി': 1, + 'മെ': 1, + 'മേ': 1, + 'മൊ': 1, + 'മോ': 1, + 'മൌ': 1, + 'മ്പ': 1, + 'മ്പാ': 1, + 'മ്പ്ര': 1, + 'മ്മ': 1, + 'മ്മി': 1, + 'യം': 1, + 'യാ': 1, + 'യി': 1, + 'യും': 1, + 'യെ': 1, + 'യേ': 1, + 'യോ': 1, + 'യ്ക്കു': 1, + 'യ്തി': 1, + 'യ്തു': 1, + 'യ്മ': 1, + 'യ്യാ': 1, + 'യ്യി': 1, + 'രം': 1, + 'രാ': 1, + 'രി': 1, + 'രീ': 1, + 'രും': 1, + 'രെ': 1, + 'രേ': 1, + 'രോ': 1, + 'ര്യ': 1, + 'ര്യം': 1, + 'ര്‍ക്കു': 1, + 'ര്‍ക്കും': 1, + 'ര്‍ക്ക്‌': 1, + 'ര്‍ഗ്ഗം': 1, + 'ര്‍ച്ച': 1, + 'ര്‍ണ്ണ': 1, + 'ര്‍ത്ത': 1, + 'ര്‍ത്തി': 1, + 'ര്‍ത്തു': 1, + 'ര്‍ത്തേ': 1, + 'ര്‍ദേ': 1, + 'ര്‍ദ്ദ': 1, + 'ര്‍പ്പെ': 1, + 'ര്‍ബ': 1, + 'ര്‍ഭ': 1, + 'ര്‍മ്മി': 1, + 'ര്‍രാ': 1, + 'ര്‍വ്വ': 1, + 'ര്‍ഹ': 1, + 'ര്‍ഹി': 1, + 'റം': 1, + 'റി': 1, + 'റ്റ': 1, + 'റ്റം': 1, + 'റ്റു': 1, + 'റ്റേ': 1, + 'ലം': 1, + 'ലാ': 1, + 'ലി': 1, + 'ലും': 1, + 'ലെ': 1, + 'ലേ': 1, + 'ലോ': 1, + 'ല്യ': 1, + 'ല്യാ': 1, + 'ല്ല': 1, + 'ല്ലാ': 1, + 'ല്ലാം': 1, + 'ല്ലെ': 1, + 'ല്‍കി': 1, + 'ല്‍കു': 1, + 'ല്‍കേ': 1, + 'ല്‍ത': 1, + 'ല്‍നി': 1, + 'ല്‍പ്പ': 1, + 'ളം': 1, + 'ളാ': 1, + 'ളി': 1, + 'ളും': 1, + 'ളെ': 1, + 'ളേ': 1, + 'ളോ': 1, + 'ള്ള': 1, + 'ള്ളാ': 1, + 'ള്ളി': 1, + 'ള്ളൂ': 1, + 'ള്‍കൊ': 1, + 'ള്‍ക്ക': 1, + 'ള്‍ക്കി': 1, + 'ള്‍ക്കു': 1, + 'ള്‍ക്കും': 1, + 'ള്‍ക്കെ': 1, + 'ള്‍ക്ക്‌': 1, + 'ഴി': 1, + 'വാ': 1, + 'വി': 1, + 'വും': 1, + 'വെ': 1, + 'വേ': 1, + 'വൈ': 1, + 'വോ': 1, + 'വ്യ': 1, + 'വ്യം': 1, + 'വ്യാ': 1, + 'വ്വ': 1, + 'ശാ': 1, + 'ശി': 1, + 'ശീ': 1, + 'ശേ': 1, + 'ശ്യ': 1, + 'ശ്ര': 1, + 'ശ്വാ': 1, + 'ഷം': 1, + 'ഷി': 1, + 'ഷ്ട': 1, + 'ഷ്ട്യാ': 1, + 'ഷ്ട്ര': 1, + 'ഷ്ട്രീ': 1, + 'ഷ്ണു': 1, + 'ഷ്യ': 1, + 'ഷ്യാ': 1, + 'സം': 1, + 'സാ': 1, + 'സാം': 1, + 'സി': 1, + 'സൌ': 1, + 'സ്കാ': 1, + 'സ്തു': 1, + 'സ്ത്രം': 1, + 'സ്ത്രീ': 1, + 'സ്ഥ': 1, + 'സ്ഥാ': 1, + 'സ്ഥി': 1, + 'സ്യ': 1, + 'സ്റ്റ്‌': 1, + 'സ്വ': 1, + 'സ്വാ': 1, + 'സ്വീ': 1, + 'സ്സ': 1, + 'സ്സാ': 1, + 'സ്സി': 1, + 'സ്സും': 1, + 'സ്സോ': 1, + 'ഹം': 1, + 'ഹാ': 1, + 'ഹി': 1, + 'ഹിം': 1, + 'කා': 1, + 'කැ': 1, + 'කෘ': 1, + 'කෙ': 1, + 'කො': 1, + 'කෝ': 1, + 'කෲ': 1, + 'ගා': 1, + 'ගැ': 1, + 'ගෙ': 1, + 'ගේ': 1, + 'චා': 1, + 'චැ': 1, + 'චෝ': 1, + 'ජා': 1, + 'ඥා': 1, + 'ටා': 1, + 'ටේ': 1, + 'ඨා': 1, + 'ඩං': 1, + 'ඩා': 1, + 'තා': 1, + 'තැ': 1, + 'තෘ': 1, + 'තෙ': 1, + 'තේ': 1, + 'තො': 1, + 'තෝ': 1, + 'ථා': 1, + 'දා': 1, + 'දැ': 1, + 'දිං': 1, + 'දෙ': 1, + 'දේ': 1, + 'දෝ': 1, + 'ධා': 1, + 'නා': 1, + 'නැ': 1, + 'නෑ': 1, + 'නෙ': 1, + 'නේ': 1, + 'නො': 1, + 'ඳා': 1, + 'පා': 1, + 'පැ': 1, + 'පෑ': 1, + 'පෙ': 1, + 'පේ': 1, + 'පො': 1, + 'පෞ': 1, + 'බා': 1, + 'බැ': 1, + 'බෙ': 1, + 'බේ': 1, + 'බෝ': 1, + 'භා': 1, + 'භෞ': 1, + 'මා': 1, + 'මැ': 1, + 'මෙ': 1, + 'මේ': 1, + 'යා': 1, + 'යෙ': 1, + 'යේ': 1, + 'යො': 1, + 'යෝ': 1, + 'රා': 1, + 'රැ': 1, + 'රෙ': 1, + 'රේ': 1, + 'රෝ': 1, + 'ලං': 1, + 'ලා': 1, + 'ලැ': 1, + 'ලෙ': 1, + 'ලේ': 1, + 'ලෝ': 1, + 'වං': 1, + 'වා': 1, + 'වැ': 1, + 'වෘ': 1, + 'වෙ': 1, + 'වේ': 1, + 'වෝ': 1, + 'ශේ': 1, + 'ෂා': 1, + 'සං': 1, + 'සා': 1, + 'සැ': 1, + 'සෑ': 1, + 'සෙ': 1, + 'සේ': 1, + 'සෞ': 1, + 'හා': 1, + 'හැ': 1, + 'හිං': 1, + 'හෘ': 1, + 'හෙ': 1, + 'හො': 1, + 'හෝ': 1, + 'ළැ': 1, + 'กำ': 1, + 'คำ': 1, + 'จำ': 1, + 'ดำ': 1, + 'ต่ำ': 1, + 'ทำ': 1, + 'ธำ': 1, + 'นำ': 1, + 'บำ': 1, + 'พำ': 1, + 'ย่ำ': 1, + 'รำ': 1, + 'ลำ': 1, + 'สำ': 1, + 'อำ': 1, + 'ກຳ': 1, + 'ຄຳ': 1, + 'ຈຳ': 1, + 'ດຳ': 1, + 'ຕຳ': 1, + 'ທຳ': 1, + 'ນຳ': 1, + 'ລຳ': 1, + 'ສຳ': 1, + 'ອຳ': 1, + 'ကေ': 1, + 'ကေု': 1, + 'က္က': 1, + 'က္ခ': 1, + 'က္ဍ': 1, + 'က္ဍို': 1, + 'က်ျ': 1, + 'ကျ': 1, + 'ကျို': 1, + 'ကျူ': 1, + 'ကျေ': 1, + 'ကျွ': 1, + 'ကြ': 1, + 'ကြို': 1, + 'ကြီ': 1, + 'ကြု': 1, + 'ကြေ': 1, + 'ကြံ': 1, + 'ကြွေ': 1, + 'ကၠေ': 1, + 'ကၠေံ': 1, + 'ခေ': 1, + 'ချ': 1, + 'ချိ': 1, + 'ချို': 1, + 'ချို့': 1, + 'ချီ': 1, + 'ချု': 1, + 'ချေ': 1, + 'ချဳ': 1, + 'ခြ': 1, + 'ခြုံ': 1, + 'ခြေ': 1, + 'ဂ္ဂ': 1, + 'ဂ္ဂို': 1, + 'ဂျို': 1, + 'ဂၠေ': 1, + 'င်္ဂ': 1, + 'ငြ': 1, + 'ငြိ': 1, + 'ငွေ': 1, + 'ငႄ': 1, + 'စေ': 1, + 'စ္စ': 1, + 'စှ်ေ': 1, + 'စၞေ': 1, + 'စၠေ': 1, + 'ဆေ': 1, + 'ဇြ': 1, + 'ဇြေ': 1, + 'ဇြဳ': 1, + 'ဇၞေ': 1, + 'ညေ': 1, + 'ဋ္ဌ': 1, + 'တေ': 1, + 'တေံ': 1, + 'တ္တ': 1, + 'တ္ၚဲ': 1, + 'တြ': 1, + 'တြုံ': 1, + 'တွေ': 1, + 'တှ်ေ': 1, + 'တၟေ': 1, + 'ထေ': 1, + 'ထ္ၜ': 1, + 'ထွေ': 1, + 'ဒေ': 1, + 'ဒေံ': 1, + 'ဒ္ဂေ': 1, + 'ဒြ': 1, + 'နေ': 1, + 'နေ့': 1, + 'န္ဒ': 1, + 'န္နိ': 1, + 'နှေ': 1, + 'ပေ': 1, + 'ပေဲ': 1, + 'ပ္ဍဲ': 1, + 'ပ္တံ': 1, + 'ပ္ပ': 1, + 'ပ္ပံ': 1, + 'ပျ': 1, + 'ပျေ': 1, + 'ပျဲ': 1, + 'ပြ': 1, + 'ပြီ': 1, + 'ပြု': 1, + 'ပြေ': 1, + 'ပြဳ': 1, + 'ပြံ': 1, + 'ဖေ': 1, + 'ဖျ': 1, + 'ဖျု': 1, + 'ဖျေံ': 1, + 'ဖြ': 1, + 'ဖြို': 1, + 'ဗ္တေ': 1, + 'ဗ္ၜေ': 1, + 'ဗျဵု': 1, + 'ဗြေ': 1, + 'ဗြဴ': 1, + 'ဗၠေ': 1, + 'ဘေ': 1, + 'မေ': 1, + 'မ္ဂ': 1, + 'မ္တီ': 1, + 'မ္ဘ': 1, + 'မ္မ': 1, + 'မ္ၚဵု': 1, + 'မျ': 1, + 'မျို': 1, + 'မျီု': 1, + 'မျှ': 1, + 'မြ': 1, + 'မြေ': 1, + 'မြှ': 1, + 'မွေ': 1, + 'မွေ့': 1, + 'မှေ': 1, + 'မၠေ': 1, + 'မႄ': 1, + 'ယေ': 1, + 'ယျ': 1, + 'ယျဵု': 1, + 'ယြဴ': 1, + 'ရေ': 1, + 'ရေံ': 1, + 'ရွေ': 1, + 'ရွှေ့': 1, + 'ရှေ': 1, + 'ရှေ့': 1, + 'ရှ်ေ': 1, + 'လေ': 1, + 'လ္ပ': 1, + 'လ္ၚ': 1, + 'လျ': 1, + 'လျို': 1, + 'လျေ': 1, + 'လျှ': 1, + 'လျှို့': 1, + 'လျှေ': 1, + 'လၟေ': 1, + 'လႄ': 1, + 'ဝေ': 1, + 'သေ': 1, + 'သ္က': 1, + 'သ္ကံ': 1, + 'သ္ဂု': 1, + 'သ္ဂေ': 1, + 'သ္ဇို': 1, + 'သ္ဒ': 1, + 'သ္ပ': 1, + 'သ္ၚိ': 1, + 'သြ': 1, + 'သြို': 1, + 'သှ်ေ': 1, + 'သၞေ': 1, + 'ဟေ': 1, + 'အေ': 1, + 'ၜေ': 1, + 'ၵေ': 1, + 'ၵႄ': 1, + 'ၶေ': 1, + 'ၼေ': 1, + 'ၼႄ': 1, + 'ၽႄ': 1, + 'ႁေ': 1, + 'ႁႄ': 1, + 'កា': 1, + 'កើ': 1, + 'កេ': 1, + 'កោ': 1, + 'ក្ខ': 1, + 'ក្ដិ': 1, + 'ក្ដី': 1, + 'ក្ដៅ': 1, + 'ក្នុ': 1, + 'ក្រ': 1, + 'ក្រុ': 1, + 'ក្រោ': 1, + 'ក្ស': 1, + 'ក្សា': 1, + 'ខា': 1, + 'ខែ': 1, + 'ខ្ជា': 1, + 'ខ្ព': 1, + 'ខ្លា': 1, + 'ខ្លួ': 1, + 'គា': 1, + 'គាំ': 1, + 'គេ': 1, + 'គោ': 1, + 'គ្គ': 1, + 'គ្នា': 1, + 'គ្មា': 1, + 'គ្រ': 1, + 'គ្រា': 1, + 'គ្រឹះ': 1, + 'គ្រួ': 1, + 'ឃា': 1, + 'ឃើ': 1, + 'ឃោ': 1, + 'ឃៅ': 1, + 'ឃ្ន': 1, + 'ងា': 1, + 'ង្ក': 1, + 'ង្កើ': 1, + 'ង្ខិ': 1, + 'ង្ខំ': 1, + 'ង្គ': 1, + 'ង្រី': 1, + 'ង្រឹ': 1, + 'ង្រៀ': 1, + 'ង្ហា': 1, + 'ង្អ': 1, + 'ចា': 1, + 'ចាំ': 1, + 'ចេ': 1, + 'ចែ': 1, + 'ចោ': 1, + 'ច្ច': 1, + 'ច្ចេ': 1, + 'ច្បា': 1, + 'ឆាំ': 1, + 'ឆ្នាំ': 1, + 'ឆ្នោ': 1, + 'ឆ្ល': 1, + 'ឆ្លើ': 1, + 'ជា': 1, + 'ជៀ': 1, + 'ជ្ជ': 1, + 'ជ្ជា': 1, + 'ជ្ញា': 1, + 'ជ្យ': 1, + 'ជ្រ': 1, + 'ជ្រើ': 1, + 'ជ្រៀ': 1, + 'ជ្រែ': 1, + 'ឈា': 1, + 'ឈ្មោះ': 1, + 'ញុះ': 1, + 'ញ្ចូ': 1, + 'ញ្ជា': 1, + 'ញ្ញ': 1, + 'ញ្ញា': 1, + 'ញ្ញៈ': 1, + 'ដា': 1, + 'ដើ': 1, + 'ដែ': 1, + 'ដៃ': 1, + 'ដោ': 1, + 'ដៅ': 1, + 'ដ្ឋ': 1, + 'ដ្ឋា': 1, + 'ឋា': 1, + 'ឌ្ឍ': 1, + 'ណា': 1, + 'ណើ': 1, + 'ណែ': 1, + 'ណោ': 1, + 'ណោះ': 1, + 'ណៈ': 1, + 'ណ្ដា': 1, + 'ណ្ដុះ': 1, + 'ណ្ឌ': 1, + 'ណ្ណោះ': 1, + 'តា': 1, + 'តេ': 1, + 'តែ': 1, + 'ត្ដ': 1, + 'ត្ដិ': 1, + 'ត្ថ': 1, + 'ត្ថិ': 1, + 'ត្យ': 1, + 'ត្រ': 1, + 'ត្រា': 1, + 'ត្រឹ': 1, + 'ត្រូ': 1, + 'ត្ស': 1, + 'ថា': 1, + 'ថែ': 1, + 'ថ្ងៃ': 1, + 'ថ្នា': 1, + 'ថ្នូ': 1, + 'ថ្មី': 1, + 'ថ្លៃ': 1, + 'ទា': 1, + 'ទាំ': 1, + 'ទៀ': 1, + 'ទេ': 1, + 'ទៃ': 1, + 'ទោ': 1, + 'ទោះ': 1, + 'ទៅ': 1, + 'ទ្ធ': 1, + 'ទ្ធិ': 1, + 'ទ្យា': 1, + 'ទ្រ': 1, + 'ធា': 1, + 'ធ្ង': 1, + 'ធ្នា': 1, + 'ធ្នូ': 1, + 'ធ្យា': 1, + 'ធ្យោ': 1, + 'ធ្វើ': 1, + 'នា': 1, + 'នាំ': 1, + 'នឿ': 1, + 'នេះ': 1, + 'នៃ': 1, + 'នោះ': 1, + 'នៅ': 1, + 'នៈ': 1, + 'ន្ដ': 1, + 'ន្ដិ': 1, + 'ន្ថែ': 1, + 'ន្ថោ': 1, + 'ន្ទា': 1, + 'ន្ទៈ': 1, + 'ន្ធ': 1, + 'ន្និ': 1, + 'ន្ម': 1, + 'ន្យា': 1, + 'ន្លែ': 1, + 'បា': 1, + 'បើ': 1, + 'បៀ': 1, + 'បែ': 1, + 'បោ': 1, + 'បោះ': 1, + 'បះ': 1, + 'ប៉ះ': 1, + 'ប្ដី': 1, + 'ប្ដូ': 1, + 'ប្ដេ': 1, + 'ប្ប': 1, + 'ប្បី': 1, + 'ប្រ': 1, + 'ប្រា': 1, + 'ប្រឹ': 1, + 'ប្រុ': 1, + 'ប្រើ': 1, + 'ប្រែ': 1, + 'ប្អូ': 1, + 'ផ្ដ': 1, + 'ផ្ដា': 1, + 'ផ្ទា': 1, + 'ផ្ទុ': 1, + 'ផ្ទេ': 1, + 'ផ្នែ': 1, + 'ផ្លា': 1, + 'ផ្លិ': 1, + 'ផ្ស': 1, + 'ផ្សា': 1, + 'ផ្សេ': 1, + 'ផ្សៃ': 1, + 'ពា': 1, + 'ពើ': 1, + 'ពេ': 1, + 'ពោះ': 1, + 'ព្យ': 1, + 'ព្យា': 1, + 'ព្រ': 1, + 'ព្រឹ': 1, + 'ព្រៀ': 1, + 'ព្រៃ': 1, + 'ព្រំ': 1, + 'ព្វ': 1, + 'ភា': 1, + 'ភេ': 1, + 'មា': 1, + 'មើ': 1, + 'មេ': 1, + 'មែ': 1, + 'ម៉ា': 1, + 'ម៉ោ': 1, + 'ម្ងា': 1, + 'ម្ចា': 1, + 'ម្ដា': 1, + 'ម្ដែ': 1, + 'ម្នា': 1, + 'ម្នេ': 1, + 'ម្ប': 1, + 'ម្បី': 1, + 'ម្បុ': 1, + 'ម្ភា': 1, + 'ម្ម': 1, + 'ម្រ': 1, + 'ម្រា': 1, + 'ម្រិ': 1, + 'ម្រូ': 1, + 'ម្រើ': 1, + 'ម្រេ': 1, + 'ម្លៀ': 1, + 'ម្លៃ': 1, + 'យា': 1, + 'យោ': 1, + 'យៈ': 1, + 'យ៉ា': 1, + 'យ្យ': 1, + 'រា': 1, + 'រាំ': 1, + 'រើ': 1, + 'រឿ': 1, + 'រៀ': 1, + 'រះ': 1, + 'រៈ': 1, + 'រ្ដិ៍': 1, + 'លា': 1, + 'លុះ': 1, + 'លើ': 1, + 'លេ': 1, + 'លោ': 1, + 'លៈ': 1, + 'ល្បៈ': 1, + 'ល្មើ': 1, + 'វា': 1, + 'វេ': 1, + 'វៈ': 1, + 'សា': 1, + 'សើ': 1, + 'សេ': 1, + 'សៈ': 1, + 'ស្គា': 1, + 'ស្ដី': 1, + 'ស្ដ្រី': 1, + 'ស្ត្រ': 1, + 'ស្ថា': 1, + 'ស្ថិ': 1, + 'ស្ទួ': 1, + 'ស្នា': 1, + 'ស្មា': 1, + 'ស្មើ': 1, + 'ស្រ': 1, + 'ស្រា': 1, + 'ស្រី': 1, + 'ស្រ័': 1, + 'ស្លា': 1, + 'ស្វែ': 1, + 'ស្វ័': 1, + 'ស្ស': 1, + 'ហា': 1, + 'ហើ': 1, + 'ហេ': 1, + 'ហែ': 1, + 'ហោ': 1, + 'ហ្ម': 1, + 'ឡា': 1, + 'ឡើ': 1, + 'អា': 1, + 'អើ': 1, + 'អៀ': 1, + 'អ្ន': 1, + 'អ្វី': 1, + 'ឱ្យ': 1, + 'ᨠ᩠ᨠ': 1, + 'ᨠ᩠ᨦᩢᩢ': 1, + 'ᨠ᩠ᨦᩨ᩵': 1, + 'ᨠ᩠ᨭᩫ': 1, + 'ᨠ᩠ᨯᩢ': 1, + 'ᨠ᩠ᨶᩢ': 1, + 'ᨠ᩠ᨶᩥ': 1, + 'ᨠ᩠ᩅ': 1, + 'ᨠ᩠ᩅᩢ': 1, + 'ᨠ᩠ᩅᩫ': 1, + 'ᨠ᩠ᩋ᩵': 1, + 'ᨠᩢ᩠ᨷ': 1, + 'ᨠᩮᩢ᩵': 1, + 'ᨠᩮ᩵': 1, + 'ᨠᩯ᩵': 1, + 'ᨡ᩠ᨦᩢ': 1, + 'ᨡ᩠ᨯᩢ': 1, + 'ᨡ᩠ᨶ': 1, + 'ᨡ᩠ᨶᩢ': 1, + 'ᨡ᩠ᨶᩨ᩶': 1, + 'ᨡ᩠ᩅ': 1, + 'ᨡ᩠ᩋ': 1, + 'ᨡᩮᩢ': 1, + 'ᨡᩮᩢᩢ': 1, + 'ᨡᩱᩢ': 1, + 'ᨣᩕ': 1, + 'ᨣ᩠ᨣ': 1, + 'ᨣ᩠ᨯᩧ': 1, + 'ᨣ᩠ᨶᩢ': 1, + 'ᨣ᩠ᨾᩫ': 1, + 'ᨣ᩠ᩅ': 1, + 'ᨣ᩠ᩋᩢ': 1, + 'ᨣᩢ᩠ᨷ': 1, + 'ᨣᩭ': 1, + 'ᨣᩮᩢᩢ': 1, + 'ᨤ᩠ᨯᩥ': 1, + 'ᨤ᩠ᨶᩨ': 1, + 'ᨤ᩠ᨶᩫ': 1, + 'ᨤ᩠ᩅᩫ': 1, + 'ᨤ᩠ᩋ': 1, + 'ᨤᩢ᩠ᨬ': 1, + 'ᨤᩮᩢ': 1, + 'ᨤᩱ᩵': 1, + 'ᨧ᩠ᨦᩥ᩵': 1, + 'ᨧ᩠ᨯᩢ': 1, + 'ᨧᩮ': 1, + 'ᨧᩮᩢᩢ': 1, + 'ᨧᩱ': 1, + 'ᨨ᩠ᨶᩢ': 1, + 'ᨩ᩠ᨶᩢᩢ': 1, + 'ᨩ᩠ᨶ᩼': 1, + 'ᨩᩭ᩵': 1, + 'ᨩᩱᩢ': 1, + 'ᨩ᩵ᩭ': 1, + 'ᨪ᩠ᨦᩨ᩵': 1, + 'ᨪᩮᩢ': 1, + 'ᨬ᩠ᨬ': 1, + 'ᨯ᩠ᨦᩢ᩵': 1, + 'ᨯ᩠ᨰ': 1, + 'ᨯ᩠ᨶᩥ': 1, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 1, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 1, + 'ᨯᩪᩯ': 1, + 'ᨯᩱ': 1, + 'ᨯᩱᩢ': 1, + 'ᨯᩴ᩠ᨿ': 1, + 'ᨱ᩠ᨱ': 1, + 'ᨲᩕ': 1, + 'ᨲᩕᩦ': 1, + 'ᨲᩕ᩼': 1, + 'ᨲ᩠ᨠᩫ': 1, + 'ᨲ᩠ᨦᩢᩢ': 1, + 'ᨲ᩠ᨯᩢ': 1, + 'ᨲ᩠ᨲᩥ': 1, + 'ᨲ᩠ᨳᩩ': 1, + 'ᨲ᩠ᨶᩫ': 1, + 'ᨲ᩠ᨶᩫᩢ': 1, + 'ᨲ᩠ᩅᩫ': 1, + 'ᨲ᩠ᩋᩢ': 1, + 'ᨲᩯ᩵': 1, + 'ᨲᩱᩢ': 1, + 'ᨳ᩠ᨦᩨ': 1, + 'ᨳ᩠ᩅᩢ': 1, + 'ᨳᩫ᩠ᨷ': 1, + 'ᨳᩮᩢᩢ': 1, + 'ᨴ᩠ᨦᩢ': 1, + 'ᨴ᩠ᨦᩨ': 1, + 'ᨴ᩠ᨵᩥ': 1, + 'ᨴ᩠ᨿ': 1, + 'ᨴ᩠ᨿ᩵': 1, + 'ᨴ᩠ᩅᩢ': 1, + 'ᨴ᩠ᩅᩫ᩵': 1, + 'ᨴᩮᩢᩢ': 1, + 'ᨴᩮᩢ᩵': 1, + 'ᨴᩯᩢ': 1, + 'ᨶ᩠ᨲᩥ': 1, + 'ᨶ᩠ᨶᩢᩢ': 1, + 'ᨶ᩠ᨶᩥ': 1, + 'ᨶ᩠ᩋ': 1, + 'ᨶ᩠ᩋᩢ': 1, + 'ᨶᩢ᩠ᨷ': 1, + 'ᨶᩮ': 1, + 'ᨶᩱ': 1, + 'ᨷᩕ': 1, + 'ᨷ᩠ᨦᩢ': 1, + 'ᨷ᩠ᨯᩢ': 1, + 'ᨷ᩠ᨲᩢ': 1, + 'ᨷ᩠ᨲᩥ': 1, + 'ᨷ᩠ᨴᩫ': 1, + 'ᨷ᩠ᨿ': 1, + 'ᨷ᩠ᩅᩫ': 1, + 'ᨷ᩠ᩋ': 1, + 'ᨸ᩠ᨠᩫ': 1, + 'ᨸ᩠ᨯᩨ': 1, + 'ᨸ᩠ᨶᩢ': 1, + 'ᨸ᩠ᩋ': 1, + 'ᨸᩮᩢ᩵': 1, + 'ᨸ᩠᩵ᨿ': 1, + 'ᨹ᩠ᨯᩥ': 1, + 'ᨹ᩠ᨿ᩵': 1, + 'ᨹ᩠ᩅᩥ': 1, + 'ᨹᩪᩢᩱ': 1, + 'ᨹᩫ᩠ᩃ': 1, + 'ᨻ᩠ᨦ': 1, + 'ᨻ᩠ᨶᩨ᩶': 1, + 'ᨻ᩠ᨶᩫ᩶': 1, + 'ᨻ᩠ᨿ': 1, + 'ᨻ᩠ᩋ': 1, + 'ᨻᩱ': 1, + 'ᨾ᩠ᨲᩥ': 1, + 'ᨾ᩠ᨾ': 1, + 'ᨾ᩠ᨾ᩼': 1, + 'ᨾ᩠ᩅ': 1, + 'ᨾ᩠ᩅ᩵': 1, + 'ᨾᩯ᩵': 1, + 'ᨾᩱ': 1, + 'ᨿ᩠ᨦᩢ': 1, + 'ᨿ᩠ᨦᩢᩢ': 1, + 'ᨿ᩠ᨦᩥ': 1, + 'ᨿ᩠ᨦᩥ᩵': 1, + 'ᨿ᩠ᩋ': 1, + 'ᨿᩢ᩠ᨷ': 1, + 'ᨿᩫ᩠ᩈ': 1, + 'ᨿᩰ': 1, + 'ᩁ᩠ᨠᩢ': 1, + 'ᩁ᩠ᨮᩢ': 1, + 'ᩁ᩠ᨾᩫ': 1, + 'ᩁ᩠ᨿ': 1, + 'ᩁ᩠ᩅ': 1, + 'ᩁ᩠ᩅ᩵': 1, + 'ᩁ᩠ᩋ': 1, + 'ᩁᩢ᩠ᨷ': 1, + 'ᩁᩢᩭ': 1, + 'ᩁᩫ᩠ᨷ': 1, + 'ᩃ᩠ᨦᩫ': 1, + 'ᩃ᩠ᩅ᩵': 1, + 'ᩃᩢ᩠ᨿ': 1, + 'ᩃᩨ᩠ᨷ': 1, + 'ᩃᩯ': 1, + 'ᩅ᩠ᨲᩥ': 1, + 'ᩅ᩠ᨶᩢ': 1, + 'ᩅ᩠ᨿ': 1, + 'ᩅ᩠ᩅ᩵': 1, + 'ᩅᩮ': 1, + 'ᩅᩱᩢ': 1, + 'ᩈ᩠ᨠᩢ': 1, + 'ᩈ᩠ᨠᩧ': 1, + 'ᩈ᩠ᨦᩢ': 1, + 'ᩈ᩠ᨦᩥ᩵': 1, + 'ᩈ᩠ᨦᩫ': 1, + 'ᩈ᩠ᨶᩫ': 1, + 'ᩈ᩠ᨾᩫ': 1, + 'ᩈ᩠ᨿ': 1, + 'ᩈ᩠ᩅ᩵': 1, + 'ᩈ᩠ᩋ': 1, + 'ᩈᩢ᩠ᨿ': 1, + 'ᩈᩫ᩠ᨾ': 1, + 'ᩈᩮ': 1, + 'ᩉᩕᩨ': 1, + 'ᩉ᩠ᨶᩢ': 1, + 'ᩉ᩠ᨶᩦ': 1, + 'ᩉ᩠ᨶᩧ': 1, + 'ᩉ᩠ᨶᩧ᩵': 1, + 'ᩉ᩠ᨶᩫ': 1, + 'ᩉ᩠ᨾ': 1, + 'ᩉ᩠ᨾᩢ': 1, + 'ᩉ᩠ᨾᩢᩢ': 1, + 'ᩉ᩠ᨾᩪ᩵': 1, + 'ᩉ᩠ᨾᩳ': 1, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 1, + 'ᩉ᩠ᨿᩩ': 1, + 'ᩉ᩠ᩅᩫ': 1, + 'ᩉ᩠ᩅ᩵': 1, + 'ᩉᩮᩖᩨ': 1, + 'ᩉᩯ᩵': 1, + 'ᩋ᩠ᨶᩢ': 1, + 'ᩋ᩠ᨶᩨ᩵': 1, + 'ᩋ᩠ᩋ': 1, + 'ᩓ᩠ᩅᩢ': 1, + 'ᩣ᩠ᨠ': 1, + 'ᩣ᩠ᨦ': 1, + 'ᩣ᩠ᨧ': 1, + 'ᩣ᩠ᨩ': 1, + 'ᩣ᩠ᨯ': 1, + 'ᩣ᩠ᨲ': 1, + 'ᩣ᩠ᨲᩱ': 1, + 'ᩣ᩠ᨶ': 1, + 'ᩣ᩠ᨷ': 1, + 'ᩣ᩠ᨾ': 1, + 'ᩣ᩠ᨿ': 1, + 'ᩣ᩠ᩁ': 1, + 'ᩣ᩠ᩃ': 1, + 'ᩣ᩠ᩅ': 1, + 'ᩣ᩠ᩈ': 1, + 'ᩤ᩠ᨦ': 1, + 'ᩤ᩠ᨶᩢ': 1, + 'ꦏꦃ': 1, + 'ꦏꦺ': 1, + 'ꦏꦺꦴ': 1, + 'ꦏꦿ': 1, + 'ꦏꦿꦁ': 1, + 'ꦏꦿꦂ': 1, + 'ꦏ꧀ꦏ': 1, + 'ꦏ꧀ꦏꦁ': 1, + 'ꦏ꧀ꦏꦺ': 1, + 'ꦏ꧀ꦏꦼ': 1, + 'ꦏ꧀ꦔ': 1, + 'ꦏ꧀ꦔꦸ': 1, + 'ꦏ꧀ꦔꦿ': 1, + 'ꦏ꧀ꦕ': 1, + 'ꦏ꧀ꦠ': 1, + 'ꦏ꧀ꦠꦶ': 1, + 'ꦏ꧀ꦠꦸ': 1, + 'ꦏ꧀ꦠꦺ': 1, + 'ꦏ꧀ꦢ': 1, + 'ꦏ꧀ꦢꦂ': 1, + 'ꦏ꧀ꦢꦶ': 1, + 'ꦏ꧀ꦤ': 1, + 'ꦏ꧀ꦤꦶꦁ': 1, + 'ꦏ꧀ꦥ': 1, + 'ꦏ꧀ꦥꦶ': 1, + 'ꦏ꧀ꦥꦿꦶ': 1, + 'ꦏ꧀ꦧ': 1, + 'ꦏ꧀ꦧꦶ': 1, + 'ꦏ꧀ꦧꦺ': 1, + 'ꦏ꧀ꦩ': 1, + 'ꦏ꧀ꦩꦸ': 1, + 'ꦏ꧀ꦪ': 1, + 'ꦏ꧀ꦭ': 1, + 'ꦏ꧀ꦮ': 1, + 'ꦏ꧀ꦱ': 1, + 'ꦏ꧀ꦱꦂ': 1, + 'ꦏ꧀ꦱꦶ': 1, + 'ꦏ꧀ꦱꦸ': 1, + 'ꦏ꧀ꦱꦺ': 1, + 'ꦏ꧀ꦲ': 1, + 'ꦏ꧀ꦲꦁ': 1, + 'ꦏ꧀ꦲꦶꦁ': 1, + 'ꦏ꧀ꦲꦸ': 1, + 'ꦏ꧀ꦲꦺ': 1, + 'ꦏ꧀ꦲꦺꦴ': 1, + 'ꦒꦸꦃ': 1, + 'ꦒꦺꦴ': 1, + 'ꦒꦿ': 1, + 'ꦒꦿꦺ': 1, + 'ꦒ꧀ꦒ': 1, + 'ꦔꦃ': 1, + 'ꦔꦺ': 1, + 'ꦔꦺꦴ': 1, + 'ꦔꦿ': 1, + 'ꦔ꧀ꦒꦼ': 1, + 'ꦔ꧀ꦒꦿꦼꦁ': 1, + 'ꦔ꧀ꦭ': 1, + 'ꦔ꧀ꦭꦁ': 1, + 'ꦔ꧀ꦭꦸ': 1, + 'ꦔ꧀ꦭꦼ': 1, + 'ꦕꦃ': 1, + 'ꦕꦺꦴ': 1, + 'ꦗꦃ': 1, + 'ꦗꦺ': 1, + 'ꦗꦿꦺꦴ': 1, + 'ꦚ꧀ꦕ': 1, + 'ꦚ꧀ꦕꦶ': 1, + 'ꦚ꧀ꦗ': 1, + 'ꦚ꧀ꦗꦶ': 1, + 'ꦚ꧀ꦗꦸꦁ': 1, + 'ꦚ꧀ꦗꦸꦂ': 1, + 'ꦝꦃ': 1, + 'ꦝꦺ': 1, + 'ꦝꦺꦴ': 1, + 'ꦝꦺꦴꦂ': 1, + 'ꦠꦸꦃ': 1, + 'ꦠꦺ': 1, + 'ꦠꦺꦃ': 1, + 'ꦠꦺꦴ': 1, + 'ꦠꦾ': 1, + 'ꦠꦿ': 1, + 'ꦠꦿꦶ': 1, + 'ꦠ꧀ꦏꦁ': 1, + 'ꦠ꧀ꦏꦸ': 1, + 'ꦠ꧀ꦒ': 1, + 'ꦠ꧀ꦔꦸ': 1, + 'ꦠ꧀ꦚ': 1, + 'ꦠ꧀ꦠ': 1, + 'ꦠ꧀ꦠꦶ': 1, + 'ꦠ꧀ꦠꦶꦁ': 1, + 'ꦠ꧀ꦠꦸ': 1, + 'ꦠ꧀ꦠꦺ': 1, + 'ꦠ꧀ꦤ': 1, + 'ꦠ꧀ꦤꦶ': 1, + 'ꦠ꧀ꦩ': 1, + 'ꦠ꧀ꦩꦼ': 1, + 'ꦠ꧀ꦭ': 1, + 'ꦠ꧀ꦭꦺ': 1, + 'ꦠ꧀ꦱ': 1, + 'ꦠ꧀ꦱꦶꦁ': 1, + 'ꦠ꧀ꦱꦶꦃ': 1, + 'ꦠ꧀ꦱꦾ': 1, + 'ꦠ꧀ꦱ꧀ꦮ': 1, + 'ꦠ꧀ꦲ': 1, + 'ꦠ꧀ꦲꦶꦁ': 1, + 'ꦠ꧀ꦲꦺꦴ': 1, + 'ꦢꦃ': 1, + 'ꦢꦺ': 1, + 'ꦢꦺꦴ': 1, + 'ꦢꦾ': 1, + 'ꦢꦿ': 1, + 'ꦢ꧀ꦏ': 1, + 'ꦢ꧀ꦠ': 1, + 'ꦢ꧀ꦠꦶꦁ': 1, + 'ꦢ꧀ꦢ': 1, + 'ꦢ꧀ꦥ': 1, + 'ꦢ꧀ꦩꦺꦴ': 1, + 'ꦢ꧀ꦲ': 1, + 'ꦤꦺ': 1, + 'ꦤꦺꦃ': 1, + 'ꦤꦺꦴ': 1, + 'ꦤ꧀ꦏ': 1, + 'ꦤ꧀ꦏꦁ': 1, + 'ꦤ꧀ꦏꦸ': 1, + 'ꦤ꧀ꦏꦼ': 1, + 'ꦤ꧀ꦒ': 1, + 'ꦤ꧀ꦔ': 1, + 'ꦤ꧀ꦔꦁ': 1, + 'ꦤ꧀ꦔꦶ': 1, + 'ꦤ꧀ꦔꦸ': 1, + 'ꦤ꧀ꦔꦸꦂ': 1, + 'ꦤ꧀ꦔꦺ': 1, + 'ꦤ꧀ꦔꦼ': 1, + 'ꦤ꧀ꦔꦿꦸ': 1, + 'ꦤ꧀ꦗ': 1, + 'ꦤ꧀ꦗꦸ': 1, + 'ꦤ꧀ꦗꦼ': 1, + 'ꦤ꧀ꦚꦶ': 1, + 'ꦤ꧀ꦛꦃ': 1, + 'ꦤ꧀ꦛꦶ': 1, + 'ꦤ꧀ꦝ': 1, + 'ꦤ꧀ꦝꦁ': 1, + 'ꦤ꧀ꦝꦶ': 1, + 'ꦤ꧀ꦝꦸ': 1, + 'ꦤ꧀ꦝꦸꦁ': 1, + 'ꦤ꧀ꦝꦺꦁ': 1, + 'ꦤ꧀ꦝꦺꦴꦁ': 1, + 'ꦤ꧀ꦝꦼ': 1, + 'ꦤ꧀ꦠ': 1, + 'ꦤ꧀ꦠꦂ': 1, + 'ꦤ꧀ꦠꦃ': 1, + 'ꦤ꧀ꦠꦶ': 1, + 'ꦤ꧀ꦠꦸ': 1, + 'ꦤ꧀ꦠꦸꦁ': 1, + 'ꦤ꧀ꦠꦺ': 1, + 'ꦤ꧀ꦠꦼ': 1, + 'ꦤ꧀ꦠꦼꦂ': 1, + 'ꦤ꧀ꦠꦽ': 1, + 'ꦤ꧀ꦢ': 1, + 'ꦤ꧀ꦢꦁ': 1, + 'ꦤ꧀ꦢꦂ': 1, + 'ꦤ꧀ꦢꦶ': 1, + 'ꦤ꧀ꦢꦸ': 1, + 'ꦤ꧀ꦢꦺ': 1, + 'ꦤ꧀ꦢꦼ': 1, + 'ꦤ꧀ꦤ': 1, + 'ꦤ꧀ꦤꦶ': 1, + 'ꦤ꧀ꦤꦶꦁ': 1, + 'ꦤ꧀ꦤꦺ': 1, + 'ꦤ꧀ꦤꦼ': 1, + 'ꦤ꧀ꦥ': 1, + 'ꦤ꧀ꦥꦁ': 1, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 1, + 'ꦤ꧀ꦥꦶ': 1, + 'ꦤ꧀ꦥꦸ': 1, + 'ꦤ꧀ꦥꦼ': 1, + 'ꦤ꧀ꦥꦿ': 1, + 'ꦤ꧀ꦥꦿꦶ': 1, + 'ꦤ꧀ꦧ': 1, + 'ꦤ꧀ꦧꦁ': 1, + 'ꦤ꧀ꦧꦶ': 1, + 'ꦤ꧀ꦧꦸ': 1, + 'ꦤ꧀ꦧꦺ': 1, + 'ꦤ꧀ꦧꦺꦴ': 1, + 'ꦤ꧀ꦧꦼ': 1, + 'ꦤ꧀ꦩ': 1, + 'ꦤ꧀ꦩꦂ': 1, + 'ꦤ꧀ꦩꦶ': 1, + 'ꦤ꧀ꦩꦸꦂ': 1, + 'ꦤ꧀ꦩꦼ': 1, + 'ꦤ꧀ꦭ': 1, + 'ꦤ꧀ꦭꦶ': 1, + 'ꦤ꧀ꦭꦸ': 1, + 'ꦤ꧀ꦮ': 1, + 'ꦤ꧀ꦮꦂ': 1, + 'ꦤ꧀ꦮꦶ': 1, + 'ꦤ꧀ꦮꦸ': 1, + 'ꦤ꧀ꦮꦼ': 1, + 'ꦤ꧀ꦱ': 1, + 'ꦤ꧀ꦱꦂ': 1, + 'ꦤ꧀ꦱꦃ': 1, + 'ꦤ꧀ꦱꦶ': 1, + 'ꦤ꧀ꦱꦶꦁ': 1, + 'ꦤ꧀ꦱꦸ': 1, + 'ꦤ꧀ꦱꦺꦴ': 1, + 'ꦤ꧀ꦱꦼ': 1, + 'ꦤ꧀ꦲ': 1, + 'ꦤ꧀ꦲꦁ': 1, + 'ꦤ꧀ꦲꦶ': 1, + 'ꦤ꧀ꦲꦶꦁ': 1, + 'ꦤ꧀ꦲꦸ': 1, + 'ꦤ꧀ꦲꦺꦴ': 1, + 'ꦥꦃ': 1, + 'ꦥꦺ': 1, + 'ꦥꦺꦴ': 1, + 'ꦥꦿ': 1, + 'ꦥꦿꦃ': 1, + 'ꦥꦿꦶ': 1, + 'ꦥꦿꦺꦴ': 1, + 'ꦥ꧀ꦏ': 1, + 'ꦥ꧀ꦏꦁ': 1, + 'ꦥ꧀ꦠ': 1, + 'ꦥ꧀ꦠꦶ': 1, + 'ꦥ꧀ꦢꦸ': 1, + 'ꦥ꧀ꦤ': 1, + 'ꦥ꧀ꦤꦶ': 1, + 'ꦥ꧀ꦥ': 1, + 'ꦥ꧀ꦥꦶ': 1, + 'ꦥ꧀ꦥꦺ': 1, + 'ꦥ꧀ꦧꦺ': 1, + 'ꦥ꧀ꦩ': 1, + 'ꦥ꧀ꦩꦂ': 1, + 'ꦥ꧀ꦫꦺ': 1, + 'ꦥ꧀ꦭ': 1, + 'ꦥ꧀ꦭꦸ': 1, + 'ꦥ꧀ꦱ': 1, + 'ꦥ꧀ꦱꦶꦂ': 1, + 'ꦥ꧀ꦱꦼ': 1, + 'ꦥ꧀ꦲ': 1, + 'ꦧꦺ': 1, + 'ꦧꦺꦃ': 1, + 'ꦧꦺꦴ': 1, + 'ꦧꦿ': 1, + 'ꦧ꧀ꦏ': 1, + 'ꦧ꧀ꦠꦸ': 1, + 'ꦧ꧀ꦥ': 1, + 'ꦧ꧀ꦧ': 1, + 'ꦧ꧀ꦧꦺ': 1, + 'ꦧ꧀ꦲ': 1, + 'ꦧ꧀ꦲꦶ': 1, + 'ꦩꦃ': 1, + 'ꦩꦺ': 1, + 'ꦩꦺꦃ': 1, + 'ꦩꦺꦴ': 1, + 'ꦩꦿ': 1, + 'ꦩꦿꦃ': 1, + 'ꦩꦿꦶꦃ': 1, + 'ꦩ꧀ꦏꦁ': 1, + 'ꦩ꧀ꦔꦼ': 1, + 'ꦩ꧀ꦠꦸ': 1, + 'ꦩ꧀ꦠꦺꦴ': 1, + 'ꦩ꧀ꦤꦶꦁ': 1, + 'ꦩ꧀ꦥ': 1, + 'ꦩ꧀ꦥꦶ': 1, + 'ꦩ꧀ꦥꦸ': 1, + 'ꦩ꧀ꦥꦼ': 1, + 'ꦩ꧀ꦧ': 1, + 'ꦩ꧀ꦧꦁ': 1, + 'ꦩ꧀ꦧꦂ': 1, + 'ꦩ꧀ꦧꦃ': 1, + 'ꦩ꧀ꦧꦶ': 1, + 'ꦩ꧀ꦧꦸ': 1, + 'ꦩ꧀ꦧꦸꦁ': 1, + 'ꦩ꧀ꦧꦺ': 1, + 'ꦩ꧀ꦧꦺꦂ': 1, + 'ꦩ꧀ꦧꦼꦂ': 1, + 'ꦩ꧀ꦧꦾꦸꦂ': 1, + 'ꦩ꧀ꦩ': 1, + 'ꦩ꧀ꦩꦶ': 1, + 'ꦩ꧀ꦫ': 1, + 'ꦩ꧀ꦫꦃ': 1, + 'ꦩ꧀ꦭ': 1, + 'ꦩ꧀ꦲꦶ': 1, + 'ꦪꦃ': 1, + 'ꦪꦸꦃ': 1, + 'ꦪꦺꦴ': 1, + 'ꦫꦶꦃ': 1, + 'ꦫꦺ': 1, + 'ꦫꦺꦴ': 1, + 'ꦫꦾ': 1, + 'ꦭꦃ': 1, + 'ꦭꦶꦃ': 1, + 'ꦭꦺ': 1, + 'ꦭꦺꦃ': 1, + 'ꦭꦺꦴ': 1, + 'ꦭꦺꦴꦁ': 1, + 'ꦭ꧀ꦏꦁ': 1, + 'ꦭ꧀ꦚꦼꦁ': 1, + 'ꦭ꧀ꦠꦸ': 1, + 'ꦭ꧀ꦧꦸ': 1, + 'ꦭ꧀ꦩꦸ': 1, + 'ꦭ꧀ꦭ': 1, + 'ꦭ꧀ꦭꦶ': 1, + 'ꦭ꧀ꦭꦶꦁ': 1, + 'ꦭ꧀ꦭꦺ': 1, + 'ꦭ꧀ꦮ': 1, + 'ꦭ꧀ꦱ': 1, + 'ꦭ꧀ꦱꦂ': 1, + 'ꦭ꧀ꦱꦶꦁ': 1, + 'ꦭ꧀ꦱꦸ': 1, + 'ꦭ꧀ꦲ': 1, + 'ꦭ꧀ꦲꦁ': 1, + 'ꦭ꧀ꦲꦶꦁ': 1, + 'ꦭ꧀ꦲꦸ': 1, + 'ꦮꦃ': 1, + 'ꦮꦶꦃ': 1, + 'ꦮꦸꦃ': 1, + 'ꦮꦺ': 1, + 'ꦮꦺꦴ': 1, + 'ꦮꦺꦴꦁ': 1, + 'ꦮꦺꦴꦃ': 1, + 'ꦮꦿꦸꦃ': 1, + 'ꦱꦶꦃ': 1, + 'ꦱꦺ': 1, + 'ꦱꦺꦴ': 1, + 'ꦱꦾ': 1, + 'ꦱꦿ': 1, + 'ꦱꦿꦃ': 1, + 'ꦱ꧀ꦏ': 1, + 'ꦱ꧀ꦏꦁ': 1, + 'ꦱ꧀ꦏꦿꦶ': 1, + 'ꦱ꧀ꦒ': 1, + 'ꦱ꧀ꦔꦸ': 1, + 'ꦱ꧀ꦔꦿ': 1, + 'ꦱ꧀ꦛꦶ': 1, + 'ꦱ꧀ꦠ': 1, + 'ꦱ꧀ꦠꦿ': 1, + 'ꦱ꧀ꦢꦂ': 1, + 'ꦱ꧀ꦢꦶ': 1, + 'ꦱ꧀ꦢꦸ': 1, + 'ꦱ꧀ꦥ': 1, + 'ꦱ꧀ꦧ': 1, + 'ꦱ꧀ꦧꦁ': 1, + 'ꦱ꧀ꦩ': 1, + 'ꦱ꧀ꦩꦶ': 1, + 'ꦱ꧀ꦩꦼ': 1, + 'ꦱ꧀ꦩꦿ': 1, + 'ꦱ꧀ꦭ': 1, + 'ꦱ꧀ꦮ': 1, + 'ꦱ꧀ꦱ': 1, + 'ꦱ꧀ꦱꦂ': 1, + 'ꦱ꧀ꦱꦶ': 1, + 'ꦱ꧀ꦱꦶꦁ': 1, + 'ꦱ꧀ꦱꦸ': 1, + 'ꦱ꧀ꦱꦺ': 1, + 'ꦱ꧀ꦲ': 1, + 'ꦱ꧀ꦲꦁ': 1, + 'ꦱ꧀ꦲꦶ': 1, + 'ꦱ꧀ꦲꦶꦁ': 1, + 'ꦱ꧀ꦲꦸ': 1, + 'ꦲꦺ': 1, + 'ꦲꦺꦴ': 1, + '𑄃𑄬': 1, + '𑄃𑄬𑄭': 1, + '𑄃𑄳𑄃': 1, + '𑄃𑄳𑄦𑄧': 1, + '𑄃𑄳𑄦𑄨': 1, + '𑄇𑄬': 1, + '𑄇𑄳𑄠': 1, + '𑄇𑄳𑄠𑄬': 1, + '𑄇𑄳𑄠𑄴': 1, + '𑄇𑄳𑄢𑄨': 1, + '𑄇𑄳𑄦𑄧': 1, + '𑄇𑄳𑄦𑄴': 1, + '𑄈𑄬': 1, + '𑄈𑄳𑄠': 1, + '𑄈𑄳𑄠𑄬': 1, + '𑄉𑄬': 1, + '𑄉𑄬𑄭': 1, + '𑄉𑄳𑄠': 1, + '𑄉𑄳𑄢𑄧': 1, + '𑄊𑄬': 1, + '𑄌𑄬': 1, + '𑄌𑄳𑄠𑄬': 1, + '𑄌𑄳𑄠𑄴': 1, + '𑄎𑄬': 1, + '𑄎𑄬𑄭': 1, + '𑄎𑄳𑄠𑄧': 1, + '𑄎𑄳𑄠𑄬': 1, + '𑄏𑄬': 1, + '𑄑𑄬': 1, + '𑄑𑄳𑄢𑄬': 1, + '𑄖𑄬': 1, + '𑄖𑄳𑄠𑄧': 1, + '𑄖𑄳𑄠𑄬': 1, + '𑄖𑄳𑄠𑄴': 1, + '𑄖𑄳𑄢𑄨': 1, + '𑄖𑄳𑄢𑄬': 1, + '𑄖𑄳𑄦𑄴': 1, + '𑄗𑄬': 1, + '𑄘𑄬': 1, + '𑄘𑄳𑄠𑄧': 1, + '𑄘𑄳𑄠𑄬': 1, + '𑄙𑄬': 1, + '𑄙𑄳𑄠': 1, + '𑄙𑄳𑄠𑄧': 1, + '𑄚𑄬': 1, + '𑄚𑄬𑄭': 1, + '𑄚𑄳𑄠𑄧': 1, + '𑄚𑄳𑄠𑄬': 1, + '𑄚𑄳𑄠𑄴': 1, + '𑄚𑄳𑄢𑄧𑄧': 1, + '𑄚𑄳𑄦𑄧': 1, + '𑄚𑄳𑄦𑄨': 1, + '𑄚𑄳𑄦𑄴': 1, + '𑄛𑄬': 1, + '𑄛𑄳𑄢': 1, + '𑄛𑄳𑄢𑄧': 1, + '𑄛𑄳𑄦': 1, + '𑄜𑄬': 1, + '𑄝𑄬': 1, + '𑄝𑄳𑄠': 1, + '𑄝𑄳𑄢𑄨': 1, + '𑄝𑄳𑄢𑄬': 1, + '𑄞𑄬': 1, + '𑄞𑄬𑄭': 1, + '𑄟𑄬': 1, + '𑄟𑄳𑄠𑄬': 1, + '𑄠𑄬': 1, + '𑄠𑄬𑄭': 1, + '𑄡𑄬': 1, + '𑄡𑄬𑄭': 1, + '𑄡𑄳𑄠𑄬': 1, + '𑄢𑄬': 1, + '𑄢𑄬𑄭': 1, + '𑄢𑄳𑄦𑄧𑄱𑄱': 1, + '𑄣𑄬': 1, + '𑄣𑄬𑄭': 1, + '𑄣𑄳𑄦𑄬': 1, + '𑄣𑄳𑄦𑄴': 1, + '𑄥𑄬': 1, + '𑄥𑄳𑄠': 1, + '𑄥𑄳𑄠𑄧': 1, + '𑄥𑄳𑄢𑄧': 1, + '𑄥𑄳𑄢𑄨𑄁': 1, + '𑄦𑄬': 1, + '𑌅𑌂': 1, + '𑌕𑌂': 1, + '𑌕𑌾': 1, + '𑌕𑌾𑌂': 1, + '𑌕𑌾𑌃': 1, + '𑌕𑌿': 1, + '𑌕𑍂': 1, + '𑌕𑍃': 1, + '𑌕𑍇': 1, + '𑌕𑍋': 1, + '𑌗𑌾': 1, + '𑌗𑌿': 1, + '𑌗𑍁': 1, + '𑌗𑍃': 1, + '𑌗𑍇': 1, + '𑌗𑍌': 1, + '𑌘𑌾': 1, + '𑌘𑍇': 1, + '𑌘𑍋': 1, + '𑌚𑌾': 1, + '𑌚𑌿': 1, + '𑌚𑍇': 1, + '𑌚𑍈': 1, + '𑌛𑌾': 1, + '𑌛𑍁': 1, + '𑌛𑍇': 1, + '𑌜𑌾': 1, + '𑌜𑌿': 1, + '𑌜𑍇': 1, + '𑌞𑌾': 1, + '𑌟𑌃': 1, + '𑌟𑌾': 1, + '𑌟𑌾𑌂': 1, + '𑌟𑌾𑌃': 1, + '𑌠𑌾': 1, + '𑌠𑍇': 1, + '𑌠𑍈𑌃': 1, + '𑌡𑌂': 1, + '𑌡𑌃': 1, + '𑌡𑌿': 1, + '𑌣𑌂': 1, + '𑌣𑌾': 1, + '𑌣𑌾𑌂': 1, + '𑌣𑌿': 1, + '𑌣𑍁': 1, + '𑌣𑍇': 1, + '𑌤𑌂': 1, + '𑌤𑌃': 1, + '𑌤𑌾': 1, + '𑌤𑌾𑌂': 1, + '𑌤𑌾𑌃': 1, + '𑌤𑌿': 1, + '𑌤𑌿𑌂': 1, + '𑌤𑌿𑌃': 1, + '𑌤𑍁': 1, + '𑌤𑍁𑌂': 1, + '𑌤𑍃': 1, + '𑌤𑍇': 1, + '𑌤𑍇𑌃': 1, + '𑌤𑍈': 1, + '𑌤𑍋': 1, + '𑌤𑍌': 1, + '𑌥𑌂': 1, + '𑌥𑌾': 1, + '𑌥𑌾𑌂': 1, + '𑌥𑌿': 1, + '𑌦𑌂': 1, + '𑌦𑌃': 1, + '𑌦𑌾': 1, + '𑌦𑌿': 1, + '𑌦𑍁': 1, + '𑌦𑍃': 1, + '𑌦𑍇': 1, + '𑌦𑍋': 1, + '𑌧𑌃': 1, + '𑌧𑌾': 1, + '𑌧𑌾𑌃': 1, + '𑌧𑌿': 1, + '𑌧𑌿𑌂': 1, + '𑌧𑍁': 1, + '𑌧𑍃': 1, + '𑌧𑍇': 1, + '𑌧𑍇𑌃': 1, + '𑌧𑍈𑌃': 1, + '𑌨𑌂': 1, + '𑌨𑌃': 1, + '𑌨𑌾': 1, + '𑌨𑌾𑌂': 1, + '𑌨𑌾𑌃': 1, + '𑌨𑌿': 1, + '𑌨𑌿𑌃': 1, + '𑌨𑍁': 1, + '𑌨𑍂': 1, + '𑌨𑍇': 1, + '𑌨𑍈': 1, + '𑌨𑍈𑌃': 1, + '𑌨𑍋': 1, + '𑌪𑌂': 1, + '𑌪𑌾': 1, + '𑌪𑌿': 1, + '𑌪𑍁': 1, + '𑌪𑍂': 1, + '𑌪𑍇': 1, + '𑌪𑍋': 1, + '𑌬𑌾': 1, + '𑌬𑍃': 1, + '𑌭𑌾': 1, + '𑌭𑌿': 1, + '𑌭𑌿𑌃': 1, + '𑌭𑍁': 1, + '𑌭𑍂': 1, + '𑌭𑍇': 1, + '𑌮𑌂': 1, + '𑌮𑌾': 1, + '𑌮𑌿': 1, + '𑌮𑌿𑌂': 1, + '𑌮𑍁': 1, + '𑌮𑍂': 1, + '𑌮𑍇': 1, + '𑌮𑍈': 1, + '𑌮𑍋': 1, + '𑌮𑍌': 1, + '𑌯𑌂': 1, + '𑌯𑌃': 1, + '𑌯𑌾': 1, + '𑌯𑌾𑌂': 1, + '𑌯𑌾𑌃': 1, + '𑌯𑌿': 1, + '𑌯𑍁': 1, + '𑌯𑍁𑌃': 1, + '𑌯𑍇': 1, + '𑌯𑍈': 1, + '𑌯𑍈𑌃': 1, + '𑌯𑍋': 1, + '𑌯𑍋𑌃': 1, + '𑌰𑌂': 1, + '𑌰𑌃': 1, + '𑌰𑌾': 1, + '𑌰𑌾𑌃': 1, + '𑌰𑌿': 1, + '𑌰𑌿𑌂': 1, + '𑌰𑍁': 1, + '𑌰𑍂': 1, + '𑌰𑍇': 1, + '𑌰𑍋': 1, + '𑌰𑍌': 1, + '𑌲𑌂': 1, + '𑌲𑌾': 1, + '𑌲𑌾𑌃': 1, + '𑌲𑌿': 1, + '𑌲𑌿𑌂': 1, + '𑌲𑍇': 1, + '𑌲𑍈': 1, + '𑌲𑍋': 1, + '𑌵𑌂': 1, + '𑌵𑌃': 1, + '𑌵𑌾': 1, + '𑌵𑌾𑌂': 1, + '𑌵𑌾𑌃': 1, + '𑌵𑌿': 1, + '𑌵𑍃': 1, + '𑌵𑍇': 1, + '𑌵𑍈': 1, + '𑌵𑍋': 1, + '𑌶𑌂': 1, + '𑌶𑌃': 1, + '𑌶𑌾': 1, + '𑌶𑌾𑌃': 1, + '𑌶𑌿': 1, + '𑌶𑍁': 1, + '𑌶𑍂': 1, + '𑌶𑍇': 1, + '𑌶𑍋': 1, + '𑌷𑌂': 1, + '𑌷𑌾': 1, + '𑌷𑌾𑌂': 1, + '𑌷𑌾𑌃': 1, + '𑌷𑌿': 1, + '𑌷𑍁': 1, + '𑌷𑍇': 1, + '𑌷𑍈': 1, + '𑌷𑍋': 1, + '𑌸𑌂': 1, + '𑌸𑌃': 1, + '𑌸𑌾': 1, + '𑌸𑌾𑌂': 1, + '𑌸𑌿': 1, + '𑌸𑍁': 1, + '𑌸𑍂': 1, + '𑌸𑍇': 1, + '𑌸𑍋': 1, + '𑌸𑍌': 1, + '𑌹𑌾': 1, + '𑌹𑌾𑌃': 1, + '𑌹𑌿': 1, + '𑌹𑍇': 1, + '𑌹𑍋': 1, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_33ac73f2.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_33ac73f2.py new file mode 100644 index 0000000000000000000000000000000000000000..10f2eb2792c92ddb436290a2a4a00aa9811dfa75 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_33ac73f2.py @@ -0,0 +1,1969 @@ +""" +Grapheme overrides for _known_33ac73f2. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: alacritty +""" +# pylint: skip-file +GRAPHEMES = { + 'क्का': 3, + 'क्कां': 3, + 'क्को': 3, + 'क्घ्घि्': 4, + 'क्ता': 3, + 'क्ति': 3, + 'क्ती': 3, + 'क्तीं': 3, + 'क्तेः': 3, + 'क्त्योः': 5, + 'क्ना': 3, + 'क्नि': 3, + 'क्या': 3, + 'क्रा': 3, + 'क्रि': 3, + 'क्षा': 3, + 'क्षां': 3, + 'क्षाः': 4, + 'क्षि': 3, + 'क्षो': 3, + 'क्ष्ण': 3, + 'क्ष्य': 3, + 'क्ष्या': 4, + 'क्सा': 3, + 'ख्यः': 3, + 'ख्या': 3, + 'ग्या': 3, + 'ग्यैः': 3, + 'ग्र्य': 3, + 'घ्का': 3, + 'घ्र्व्य': 4, + 'घ्लि': 3, + 'घ्श्य': 3, + 'घ्स्ट': 3, + 'च्चा': 3, + 'च्चों': 3, + 'च्छा': 3, + 'च्छि': 3, + 'च्या': 3, + 'च्यां': 3, + 'च्यो': 3, + 'ज्ञा': 3, + 'ज्या': 3, + 'ज्या‌': 3, + 'ज्रा': 3, + 'ञ्चा': 3, + 'ञ्चि': 3, + 'ट्टि': 3, + 'ट्टी': 3, + 'ट्या': 3, + 'ट्रा': 3, + 'ण्डः': 3, + 'ण्डि': 3, + 'ण्या': 3, + 'ण्यां': 3, + 'ताः': 3, + 'त्का': 3, + 'त्ता': 3, + 'त्ति': 3, + 'त्त्थि': 4, + 'त्त्व': 3, + 'त्त्वा': 4, + 'त्त्वे': 3, + 'त्नी': 3, + 'त्नों': 3, + 'त्पा': 3, + 'त्पी': 3, + 'त्मा': 3, + 'त्या': 3, + 'त्यां': 3, + 'त्यि': 3, + 'त्रा': 3, + 'त्राा': 4, + 'त्राि': 4, + 'त्रि': 3, + 'त्री': 3, + 'त्र्त': 3, + 'त्र्य': 3, + 'त्र्या': 4, + 'त्र्ये': 3, + 'त्वा': 3, + 'त्वां': 3, + 'त्सा': 3, + 'त्सो': 3, + 'त्स्वा': 4, + 'द्घि': 3, + 'द्घो': 3, + 'द्दा': 3, + 'द्दि': 3, + 'द्दी': 3, + 'द्धः': 3, + 'द्धा': 3, + 'द्धां': 3, + 'द्धि': 3, + 'द्धिं': 3, + 'द्धी': 3, + 'द्धीं': 3, + 'द्धैः': 3, + 'द्भा': 3, + 'द्या': 3, + 'द्रो': 3, + 'द्वा': 3, + 'द्वि': 3, + 'धाः': 3, + 'ध्या': 3, + 'नाः': 3, + 'निः': 3, + 'न्का': 3, + 'न्चि': 3, + 'न्ञ्या': 4, + 'न्तः': 3, + 'न्ता': 3, + 'न्ति': 3, + 'न्तो': 3, + 'न्तों': 3, + 'न्त्र': 3, + 'न्त्रा': 4, + 'न्त्राः': 5, + 'न्त्रि': 4, + 'न्त्री': 4, + 'न्त्र्य': 4, + 'न्त्र्यं': 4, + 'न्त्र्या': 5, + 'न्त्र्ये': 4, + 'न्दा': 3, + 'न्दी': 3, + 'न्दो': 3, + 'न्धा': 3, + 'न्धि': 3, + 'न्धी': 3, + 'न्धों': 3, + 'न्ना': 3, + 'न्नाः': 4, + 'न्नि': 3, + 'न्मा': 3, + 'न्या': 3, + 'न्यो': 3, + 'न्हा': 3, + 'न्ह्यां': 4, + 'प्ति': 3, + 'प्तौ': 3, + 'प्या': 3, + 'प्रा': 3, + 'फ्ता': 3, + 'फ्ना': 3, + 'फ्नो': 3, + 'फ्रां': 3, + 'ब्धि': 3, + 'भिः': 3, + 'भ्यः': 3, + 'भ्या': 3, + 'भ्यां': 3, + 'भ्यो': 3, + 'म्ति': 3, + 'म्नि': 3, + 'म्पा': 3, + 'म्प्र': 3, + 'म्भि': 3, + 'म्मा': 3, + 'म्मि': 3, + 'म्या': 3, + 'म्ही': 3, + 'म्हो': 3, + 'याः': 3, + 'य्यो': 3, + 'राः': 3, + 'र्कि': 3, + 'र्गी': 3, + 'र्चि': 3, + 'र्जा': 3, + 'र्जि': 3, + 'र्जी': 3, + 'र्णां': 3, + 'र्णी': 3, + 'र्ता': 3, + 'र्ति': 3, + 'र्तिः': 4, + 'र्ती': 3, + 'र्त्त': 3, + 'र्त्ति': 4, + 'र्थि': 3, + 'र्थी': 3, + 'र्दा': 3, + 'र्दि': 3, + 'र्दो': 3, + 'र्द्ध': 3, + 'र्धा': 3, + 'र्धि': 3, + 'र्नि': 3, + 'र्बा': 3, + 'र्भा': 3, + 'र्मा': 3, + 'र्मि': 3, + 'र्या': 3, + 'र्यां': 3, + 'र्यों': 3, + 'र्रा': 3, + 'र्वा': 3, + 'र्वां': 3, + 'र्वो': 3, + 'र्सा': 3, + 'र्हाः': 4, + 'र्हि': 3, + 'र्हो': 3, + 'र्‍या': 3, + 'लाः': 3, + 'ल्का': 3, + 'ल्पि': 3, + 'ल्या': 3, + 'ल्यां': 3, + 'ल्याः': 4, + 'ल्ला': 3, + 'ल्लि': 3, + 'वाः': 3, + 'व्या': 3, + 'व्यों': 3, + 'शाः': 3, + 'श्चि': 3, + 'श्या': 3, + 'श्यि': 3, + 'श्यों': 3, + 'श्रा': 3, + 'श्रां': 3, + 'श्वा': 3, + 'श्वि': 3, + 'षाः': 3, + 'ष्का': 3, + 'ष्टः': 3, + 'ष्टा': 3, + 'ष्टां': 3, + 'ष्टाः': 4, + 'ष्टि': 3, + 'ष्टी': 3, + 'ष्टीं': 3, + 'ष्ट्र': 3, + 'ष्ट्रा': 4, + 'ष्ट्रां': 4, + 'ष्ट्रि': 4, + 'ष्ट्री': 4, + 'ष्ट्रे': 3, + 'ष्ट्रो': 4, + 'ष्ट्रों': 4, + 'ष्ठा': 3, + 'ष्ठों': 3, + 'ष्प्र': 3, + 'ष्यः': 3, + 'ष्यों': 3, + 'स्का': 3, + 'स्काः': 4, + 'स्ट्या': 4, + 'स्ता': 3, + 'स्ति': 3, + 'स्ती': 3, + 'स्तो': 3, + 'स्त्र': 3, + 'स्त्रा': 4, + 'स्त्रि': 4, + 'स्त्री': 4, + 'स्था': 3, + 'स्थां': 3, + 'स्थि': 3, + 'स्थी': 3, + 'स्थ्य': 3, + 'स्धी': 3, + 'स्मि': 3, + 'स्मिं': 3, + 'स्या': 3, + 'स्यां': 3, + 'स्याः': 4, + 'स्युः': 3, + 'स्यों': 3, + 'स्रो': 3, + 'स्वा': 3, + 'स्वी': 3, + 'स्सा': 3, + 'ह्या': 3, + 'ह्रा': 3, + 'फ़्ता': 3, + 'কা': 1, + 'কা‌': 1, + 'কিং': 3, + 'ক্তি': 3, + 'ক্রী': 3, + 'ক্ষি': 3, + 'ক্ষে': 3, + 'ক্ষ্য': 3, + 'ক্ষ্যে': 4, + 'খা': 1, + 'গ্রে': 3, + 'ঘা': 1, + 'ঙ্গী': 3, + 'ঙ্গে': 3, + 'চা': 1, + 'চ্ছে': 3, + 'ছা': 1, + 'জা': 1, + 'ঞ্চি': 3, + 'ঞ্ছি': 3, + 'টা': 1, + 'ট্রে': 3, + 'ড়া': 1, + 'ণা': 1, + 'ণ্ডে': 3, + 'তা': 1, + 'তাঁ': 1, + 'তা‌': 1, + 'ত্তি': 3, + 'ত্বে': 3, + 'ত্যি': 3, + 'ত্যে': 3, + 'ত্রে': 3, + 'ত্‍পী': 3, + 'থা': 1, + 'দা': 1, + 'দ্দি': 3, + 'দ্দে': 3, + 'দ্ধি': 3, + 'দ্ধে': 3, + 'দ্রো': 3, + 'ধা': 1, + 'ধ্যে': 3, + 'না': 1, + 'না‌': 1, + 'ন্তি': 3, + 'ন্তে': 3, + 'ন্ত্রি': 4, + 'ন্ত্রে': 4, + 'ন্থী': 3, + 'ন্যে': 3, + 'পা': 1, + 'পা‌': 1, + 'বা': 1, + 'বা‌': 1, + 'ব্ধি': 3, + 'ভা': 1, + 'মা': 1, + 'মা‌': 1, + 'য়া': 1, + 'যা': 1, + 'রা': 1, + 'র্থে': 3, + 'র্দো': 3, + 'র্নী': 3, + 'র্বি': 3, + 'র্বো': 3, + 'র্ব্য': 3, + 'র্মে': 3, + 'লা': 1, + 'ল্যে': 3, + 'ল্লে': 3, + 'শা': 1, + 'শ্চি': 3, + 'শ্বে': 3, + 'শ্যে': 3, + 'ষা': 1, + 'ষ্টি': 3, + 'ষ্ট্র': 3, + 'ষ্ট্রী': 4, + 'ষ্ট্রে': 4, + 'ষ্ঠি': 3, + 'ষ্ঠী': 3, + 'সা': 1, + 'স্তি': 3, + 'স্তি‌': 3, + 'স্ত্র': 3, + 'স্থ্য': 3, + 'স্বী': 3, + 'স্যে': 3, + 'হা': 1, + 'ક્કા': 3, + 'ક્કો': 3, + 'ક્તિ': 3, + 'ક્ષા': 3, + 'ચ્ચા': 3, + 'ચ્છા': 3, + 'જ્ઞા': 3, + 'જ્યો': 3, + 'ત્તા': 3, + 'ત્તિ': 3, + 'ત્ત્વ': 3, + 'ત્ત્વા': 4, + 'ત્યા': 3, + 'ત્યાં': 3, + 'ત્યિ': 3, + 'ત્યો': 3, + 'ત્રી': 3, + 'ત્ર્ય': 3, + 'દ્ધા': 3, + 'દ્ધાં': 3, + 'દ્ધિ': 3, + 'દ્વા': 3, + 'ધ્યા': 3, + 'ન્તો': 3, + 'ન્મા': 3, + 'ન્યા': 3, + 'પ્રા': 3, + 'મ્યાં': 3, + 'ર્તા': 3, + 'ર્થિ': 3, + 'ર્દો': 3, + 'ર્મિ': 3, + 'ર્યા': 3, + 'ર્યો': 3, + 'વ્યા': 3, + 'વ્યો': 3, + 'ષ્ટિ': 3, + 'ષ્ટ્ર': 3, + 'ષ્ટ્રી': 4, + 'ષ્ટ્રો': 4, + 'ષ્ઠા': 3, + 'સ્તિ': 3, + 'સ્તી': 3, + 'સ્ત્રી': 4, + 'સ્થા': 3, + 'સ્થિ': 3, + 'સ્રી': 3, + 'સ્વા': 3, + 'સ્વી': 3, + 'સ્સા': 3, + 'கா': 1, + 'சா': 1, + 'டா': 1, + 'ணா': 1, + 'தா': 1, + 'நா': 1, + 'னா': 1, + 'பா': 1, + 'மா': 1, + 'யா': 1, + 'ரா': 1, + 'றா': 1, + 'லா': 1, + 'ளா': 1, + 'வா': 1, + 'కుం': 3, + 'క్కు': 3, + 'క్తు': 3, + 'క్రాం': 3, + 'క్రూ': 3, + 'క్షిం': 3, + 'క్స్వా': 3, + 'చ్చు': 3, + 'టుం': 3, + 'ట్లు': 3, + 'డ్రు': 3, + 'త్తు': 3, + 'త్నిం': 3, + 'త్యం': 3, + 'త్రు': 3, + 'త్ర్య': 3, + 'దుం': 3, + 'ద్దు': 3, + 'ద్ధిం': 3, + 'ద్ర్య': 3, + 'నుం': 3, + 'న్ను': 3, + 'భ్యు': 3, + 'యుం': 3, + 'ర్చు': 3, + 'ర్ణాం': 3, + 'ర్ణు': 3, + 'ర్తిం': 3, + 'ర్తృ': 3, + 'ర్థిం': 3, + 'ర్బం': 3, + 'ర్హాం': 3, + 'ర్హు': 3, + 'శ్రాం': 3, + 'ష్టు': 3, + 'ష్ట్ర': 3, + 'ష్ట్రీ': 3, + 'ష్ఠు': 3, + 'స్కృ': 3, + 'స్త్ర': 3, + 'స్త్రీ': 3, + 'స్థ్య': 3, + 'ಕಾಂ': 3, + 'ಕೀ': 1, + 'ಕುಂ': 3, + 'ಕೂ': 1, + 'ಕೇ': 1, + 'ಕೈ': 1, + 'ಕೊ': 1, + 'ಖಾಂ': 3, + 'ಗಾಂ': 3, + 'ಗೀ': 1, + 'ಗೂ': 1, + 'ಗೈ': 1, + 'ಗೊ': 1, + 'ಗೋ': 1, + 'ಚೀ': 1, + 'ಜೀ': 1, + 'ಟುಂ': 3, + 'ಟೇ': 1, + 'ಡೂ': 1, + 'ಢೀ': 1, + 'ಣೈ': 1, + 'ತೀ': 1, + 'ತೊ': 1, + 'ತೋ': 1, + 'ದೂ': 1, + 'ದೇ': 1, + 'ದೊ': 1, + 'ದೋ': 1, + 'ಧೀ': 1, + 'ಧೂ': 1, + 'ನಾಂ': 3, + 'ನೂ': 1, + 'ನೇ': 1, + 'ನೈ': 1, + 'ನೊ': 1, + 'ಪೂ': 1, + 'ಪೇ': 1, + 'ಬೇ': 1, + 'ಬೋ': 1, + 'ಭೀ': 1, + 'ಭೇ': 1, + 'ಭೋ': 1, + 'ಮೀ': 1, + 'ಮೂ': 1, + 'ಮೇ': 1, + 'ಮೈ': 1, + 'ಯುಂ': 3, + 'ಯೂ': 1, + 'ಯೇ': 1, + 'ಯೊ': 1, + 'ಯೋ': 1, + 'ರಾಂ': 3, + 'ರೀ': 1, + 'ರೂ': 1, + 'ರೊ': 1, + 'ರೋ': 1, + 'ಲೀ': 1, + 'ಲೂ': 1, + 'ಲೇ': 1, + 'ಲೋ': 1, + 'ಳೂ': 1, + 'ವೀ': 1, + 'ವುಂ': 3, + 'ವೂ': 1, + 'ವೇ': 1, + 'ವೈ': 1, + 'ವೋ': 1, + 'ಶಾಂ': 3, + 'ಶೀ': 1, + 'ಶೇ': 1, + 'ಷೇ': 1, + 'ಸಾಂ': 3, + 'ಸೂ': 1, + 'ಸೇ': 1, + 'ಹೇ': 1, + 'ಹೊ': 1, + 'ಹೋ': 1, + 'കാ': 1, + 'ക്കി': 3, + 'ക്കും': 3, + 'ക്കെ': 3, + 'ക്കേ': 3, + 'ക്കൊ': 3, + 'ക്കോ': 3, + 'ക്തി': 3, + 'ക്യം': 3, + 'ക്ഷി': 3, + 'ക്ഷേ': 3, + 'ഗ്ഗം': 3, + 'ഗ്യം': 3, + 'ങ്കി': 3, + 'ങ്കെ': 3, + 'ങ്കേ': 3, + 'ങ്ങി': 3, + 'ചാ': 1, + 'ച്ചി': 3, + 'ച്ചും': 3, + 'ച്ചെ': 3, + 'ച്ചേ': 3, + 'ജാ': 1, + 'ഞ്ഞി': 3, + 'ഞ്ഞെ': 3, + 'ടാ': 1, + 'ട്ടി': 3, + 'ട്ടോ': 3, + 'ണാ': 1, + 'ണ്ടി': 3, + 'ണ്ടും': 3, + 'ണ്ടെ': 3, + 'താ': 1, + 'ത്തി': 3, + 'ത്തും': 3, + 'ത്തെ': 3, + 'ത്തേ': 3, + 'ത്തോ': 3, + 'ത്നം': 3, + 'ത്നി': 3, + 'ത്യേ': 3, + 'ത്വം': 3, + 'ദാ': 1, + 'ദ്ധി': 3, + 'ധാ': 1, + 'നാ': 1, + 'ന്തം': 3, + 'ന്തെ': 3, + 'ന്ത്ര': 3, + 'ന്ത്ര്യ': 4, + 'ന്ത്ര്യം': 5, + 'ന്ധി': 3, + 'ന്നി': 3, + 'ന്നീ': 3, + 'ന്നും': 3, + 'ന്നെ': 3, + 'ന്നേ': 3, + 'ന്നോ': 3, + 'ന്യം': 3, + 'ന്യേ': 3, + 'ന്യോ': 3, + 'ന്റെ': 3, + 'ന്‍പി': 3, + 'പാ': 1, + 'പ്പി': 3, + 'പ്പെ': 3, + 'പ്പോ': 3, + 'ബാ': 1, + 'ബ്ലി': 3, + 'ഭാ': 1, + 'മാ': 1, + 'മ്പ്ര': 3, + 'മ്മി': 3, + 'യാ': 1, + 'യ്ക്കു': 3, + 'യ്തി': 3, + 'യ്യി': 3, + 'രാ': 1, + 'ര്യം': 3, + 'ര്‍ക്കു': 3, + 'ര്‍ക്കും': 4, + 'ര്‍ക്ക്‌': 3, + 'ര്‍ഗ്ഗം': 4, + 'ര്‍ച്ച': 3, + 'ര്‍ണ്ണ': 3, + 'ര്‍ത്ത': 3, + 'ര്‍ത്തി': 4, + 'ര്‍ത്തു': 3, + 'ര്‍ത്തേ': 4, + 'ര്‍ദേ': 3, + 'ര്‍ദ്ദ': 3, + 'ര്‍പ്പെ': 4, + 'ര്‍മ്മി': 4, + 'ര്‍വ്വ': 3, + 'ര്‍ഹി': 3, + 'റ്റം': 3, + 'റ്റേ': 3, + 'ലാ': 1, + 'ല്ലാം': 3, + 'ല്ലെ': 3, + 'ല്‍കി': 3, + 'ല്‍കേ': 3, + 'ല്‍നി': 3, + 'ല്‍പ്പ': 3, + 'ളാ': 1, + 'ള്ളി': 3, + 'ള്‍കൊ': 3, + 'ള്‍ക്ക': 3, + 'ള്‍ക്കി': 4, + 'ള്‍ക്കു': 3, + 'ള്‍ക്കും': 4, + 'ള്‍ക്കെ': 4, + 'ള്‍ക്ക്‌': 3, + 'വാ': 1, + 'വ്യം': 3, + 'ശാ': 1, + 'ഷ്ട്യാ': 3, + 'ഷ്ട്ര': 3, + 'ഷ്ട്രീ': 4, + 'സാ': 1, + 'സ്ത്രം': 4, + 'സ്ത്രീ': 4, + 'സ്ഥി': 3, + 'സ്റ്റ്‌': 3, + 'സ്വീ': 3, + 'സ്സി': 3, + 'സ്സും': 3, + 'സ്സോ': 3, + 'ഹാ': 1, + 'ഹിം': 3, + 'කා': 1, + 'ගා': 1, + 'චා': 1, + 'ජා': 1, + 'ඥා': 1, + 'ටා': 1, + 'ඨා': 1, + 'ඩා': 1, + 'තා': 1, + 'ථා': 1, + 'දා': 1, + 'ධා': 1, + 'නා': 1, + 'ඳා': 1, + 'පා': 1, + 'බා': 1, + 'භා': 1, + 'මා': 1, + 'යා': 1, + 'රා': 1, + 'ලා': 1, + 'වා': 1, + 'ෂා': 1, + 'සා': 1, + 'හා': 1, + 'ကျေ': 3, + 'ကြေ': 3, + 'ကြွေ': 3, + 'ချေ': 3, + 'ခြေ': 3, + 'ဇြေ': 3, + 'ဒ္ဂေ': 3, + 'ပျေ': 3, + 'ပြေ': 3, + 'ဖျေံ': 3, + 'ဗ္တေ': 3, + 'ဗ္ၜေ': 3, + 'ဗြေ': 3, + 'မြေ': 3, + 'လျေ': 3, + 'လျှေ': 3, + 'သ္ဂေ': 3, + 'ក្ដៅ': 3, + 'ក្រោ': 3, + 'ក្សា': 3, + 'ខ្ជា': 3, + 'ខ្លា': 3, + 'គ្នា': 3, + 'គ្មា': 3, + 'គ្រា': 3, + 'គ្រឹះ': 3, + 'ង្កើ': 3, + 'ង្រៀ': 3, + 'ង្ហា': 3, + 'ច្ចេ': 3, + 'ច្បា': 3, + 'ឆ្នាំ': 3, + 'ឆ្នោ': 3, + 'ឆ្លើ': 3, + 'ជ្ជា': 3, + 'ជ្ញា': 3, + 'ជ្រើ': 3, + 'ជ្រៀ': 3, + 'ជ្រែ': 3, + 'ឈ្មោះ': 4, + 'ញ្ជា': 3, + 'ញ្ញា': 3, + 'ញ្ញៈ': 3, + 'ដ្ឋា': 3, + 'ណោះ': 3, + 'ណ្ដា': 3, + 'ណ្ដុះ': 3, + 'ណ្ណោះ': 4, + 'ត្រា': 3, + 'ថ្ងៃ': 3, + 'ថ្នា': 3, + 'ថ្លៃ': 3, + 'ទោះ': 3, + 'ទ្យា': 3, + 'ធ្នា': 3, + 'ធ្យា': 3, + 'ធ្យោ': 3, + 'ធ្វើ': 3, + 'នេះ': 3, + 'នោះ': 3, + 'ន្ថែ': 3, + 'ន្ថោ': 3, + 'ន្ទា': 3, + 'ន្ទៈ': 3, + 'ន្យា': 3, + 'ន្លែ': 3, + 'បោះ': 3, + 'ប្ដេ': 3, + 'ប្រា': 3, + 'ប្រើ': 3, + 'ប្រែ': 3, + 'ផ្ដា': 3, + 'ផ្ទា': 3, + 'ផ្ទេ': 3, + 'ផ្នែ': 3, + 'ផ្លា': 3, + 'ផ្សា': 3, + 'ផ្សេ': 3, + 'ផ្សៃ': 3, + 'ពោះ': 3, + 'ព្យា': 3, + 'ព្រៀ': 3, + 'ព្រៃ': 3, + 'ម្ងា': 3, + 'ម្ចា': 3, + 'ម្ដា': 3, + 'ម្ដែ': 3, + 'ម្នា': 3, + 'ម្នេ': 3, + 'ម្ភា': 3, + 'ម្រា': 3, + 'ម្រើ': 3, + 'ម្រេ': 3, + 'ម្លៀ': 3, + 'ម្លៃ': 3, + 'ល្បៈ': 3, + 'ល្មើ': 3, + 'ស្គា': 3, + 'ស្ដ្រី': 3, + 'ស្ត្រ': 3, + 'ស្ថា': 3, + 'ស្នា': 3, + 'ស្មា': 3, + 'ស្មើ': 3, + 'ស្រា': 3, + 'ស្លា': 3, + 'ស្វែ': 3, + 'ᨣᩕᩮ᩠': 3, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 3, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 3, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 3, + '⛓️‍💥': 3, + '⛹🏻‍♀️': 4, + '⛹🏻‍♂️': 4, + '⛹🏼‍♀️': 4, + '⛹🏼‍♂️': 4, + '⛹🏽‍♀️': 4, + '⛹🏽‍♂️': 4, + '⛹🏾‍♀️': 4, + '⛹🏾‍♂️': 4, + '⛹🏿‍♀️': 4, + '⛹🏿‍♂️': 4, + '❤️‍🔥': 3, + '❤️‍🩹': 3, + 'ꦏꦺꦴ': 3, + 'ꦏ꧀ꦏꦺ': 3, + 'ꦏ꧀ꦔꦿ': 3, + 'ꦏ꧀ꦠꦺ': 3, + 'ꦏ꧀ꦥꦿꦶ': 3, + 'ꦏ꧀ꦧꦺ': 3, + 'ꦏ꧀ꦱꦺ': 3, + 'ꦏ꧀ꦲꦺ': 3, + 'ꦏ꧀ꦲꦺꦴ': 4, + 'ꦒꦺꦴ': 3, + 'ꦒꦿꦺ': 3, + 'ꦔꦺꦴ': 3, + 'ꦔ꧀ꦒꦿꦼꦁ': 3, + 'ꦕꦺꦴ': 3, + 'ꦗꦿꦺꦴ': 4, + 'ꦝꦺꦴ': 3, + 'ꦝꦺꦴꦂ': 3, + 'ꦠꦺꦃ': 3, + 'ꦠꦺꦴ': 3, + 'ꦠ꧀ꦠꦺ': 3, + 'ꦠ꧀ꦭꦺ': 3, + 'ꦠ꧀ꦱꦶꦃ': 3, + 'ꦠ꧀ꦱꦾ': 3, + 'ꦠ꧀ꦱ꧀ꦮ': 3, + 'ꦠ꧀ꦲꦺꦴ': 4, + 'ꦢꦺꦴ': 3, + 'ꦢ꧀ꦩꦺꦴ': 4, + 'ꦤꦺꦃ': 3, + 'ꦤꦺꦴ': 3, + 'ꦤ꧀ꦔꦺ': 3, + 'ꦤ꧀ꦔꦿꦸ': 3, + 'ꦤ꧀ꦛꦃ': 3, + 'ꦤ꧀ꦝꦺꦁ': 3, + 'ꦤ꧀ꦝꦺꦴꦁ': 4, + 'ꦤ꧀ꦠꦃ': 3, + 'ꦤ꧀ꦠꦺ': 3, + 'ꦤ꧀ꦢꦺ': 3, + 'ꦤ꧀ꦤꦺ': 3, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 4, + 'ꦤ꧀ꦥꦿ': 3, + 'ꦤ꧀ꦥꦿꦶ': 3, + 'ꦤ꧀ꦧꦺ': 3, + 'ꦤ꧀ꦧꦺꦴ': 4, + 'ꦤ꧀ꦱꦃ': 3, + 'ꦤ꧀ꦱꦺꦴ': 4, + 'ꦤ꧀ꦲꦺꦴ': 4, + 'ꦥꦺꦴ': 3, + 'ꦥꦿꦃ': 3, + 'ꦥꦿꦺꦴ': 4, + 'ꦥ꧀ꦥꦺ': 3, + 'ꦥ꧀ꦧꦺ': 3, + 'ꦥ꧀ꦫꦺ': 3, + 'ꦧꦺꦃ': 3, + 'ꦧꦺꦴ': 3, + 'ꦧ꧀ꦧꦺ': 3, + 'ꦩꦺꦃ': 3, + 'ꦩꦺꦴ': 3, + 'ꦩꦿꦃ': 3, + 'ꦩꦿꦶꦃ': 3, + 'ꦩ꧀ꦠꦺꦴ': 4, + 'ꦩ꧀ꦧꦃ': 3, + 'ꦩ꧀ꦧꦺ': 3, + 'ꦩ꧀ꦧꦺꦂ': 3, + 'ꦩ꧀ꦧꦾꦸꦂ': 3, + 'ꦩ꧀ꦫꦃ': 3, + 'ꦪꦺꦴ': 3, + 'ꦫꦺꦴ': 3, + 'ꦭꦺꦃ': 3, + 'ꦭꦺꦴ': 3, + 'ꦭꦺꦴꦁ': 3, + 'ꦭ꧀ꦭꦺ': 3, + 'ꦮꦺꦴ': 3, + 'ꦮꦺꦴꦁ': 3, + 'ꦮꦺꦴꦃ': 4, + 'ꦮꦿꦸꦃ': 3, + 'ꦱꦺꦴ': 3, + 'ꦱꦿꦃ': 3, + 'ꦱ꧀ꦏꦿꦶ': 3, + 'ꦱ꧀ꦔꦿ': 3, + 'ꦱ꧀ꦠꦿ': 3, + 'ꦱ꧀ꦩꦿ': 3, + 'ꦱ꧀ꦱꦺ': 3, + 'ꦲꦺꦴ': 3, + '𑄇𑄳𑄠𑄬': 3, + '𑄈𑄳𑄠𑄬': 3, + '𑄌𑄳𑄠𑄬': 3, + '𑄎𑄳𑄠𑄬': 3, + '𑄑𑄳𑄢𑄬': 3, + '𑄖𑄳𑄠𑄬': 3, + '𑄖𑄳𑄢𑄬': 3, + '𑄘𑄳𑄠𑄬': 3, + '𑄚𑄳𑄠𑄬': 3, + '𑄝𑄳𑄢𑄬': 3, + '𑄟𑄳𑄠𑄬': 3, + '𑄡𑄳𑄠𑄬': 3, + '𑄣𑄳𑄦𑄬': 3, + '𑌕𑌾': 1, + '𑌗𑌾': 1, + '𑌘𑌾': 1, + '𑌚𑌾': 1, + '𑌛𑌾': 1, + '𑌜𑌾': 1, + '𑌞𑌾': 1, + '𑌟𑌾': 1, + '𑌠𑌾': 1, + '𑌠𑍈𑌃': 3, + '𑌣𑌾': 1, + '𑌤𑌾': 1, + '𑌤𑌿𑌂': 3, + '𑌤𑌿𑌃': 3, + '𑌤𑍁𑌂': 3, + '𑌤𑍇𑌃': 3, + '𑌥𑌾': 1, + '𑌦𑌾': 1, + '𑌧𑌾': 1, + '𑌧𑌿𑌂': 3, + '𑌧𑍇𑌃': 3, + '𑌧𑍈𑌃': 3, + '𑌨𑌾': 1, + '𑌨𑌿𑌃': 3, + '𑌨𑍈𑌃': 3, + '𑌪𑌾': 1, + '𑌬𑌾': 1, + '𑌭𑌾': 1, + '𑌭𑌿𑌃': 3, + '𑌮𑌾': 1, + '𑌮𑌿𑌂': 3, + '𑌯𑌾': 1, + '𑌯𑍁𑌃': 3, + '𑌯𑍈𑌃': 3, + '𑌯𑍋𑌃': 3, + '𑌰𑌾': 1, + '𑌰𑌿𑌂': 3, + '𑌲𑌾': 1, + '𑌲𑌿𑌂': 3, + '𑌵𑌾': 1, + '𑌶𑌾': 1, + '𑌷𑌾': 1, + '𑌸𑌾': 1, + '𑌹𑌾': 1, + '🍄‍🟫': 4, + '🍋‍🟩': 4, + '🏃‍♀️': 3, + '🏃‍♀️‍➡️': 4, + '🏃‍♂️': 3, + '🏃‍♂️‍➡️': 4, + '🏃‍➡️': 3, + '🏃🏻‍♀️': 5, + '🏃🏻‍♀️‍➡️': 6, + '🏃🏻‍♂️': 5, + '🏃🏻‍♂️‍➡️': 6, + '🏃🏻‍➡️': 5, + '🏃🏼‍♀️': 5, + '🏃🏼‍♀️‍➡️': 6, + '🏃🏼‍♂️': 5, + '🏃🏼‍♂️‍➡️': 6, + '🏃🏼‍➡️': 5, + '🏃🏽‍♀️': 5, + '🏃🏽‍♀️‍➡️': 6, + '🏃🏽‍♂️': 5, + '🏃🏽‍♂️‍➡️': 6, + '🏃🏽‍➡️': 5, + '🏃🏾‍♀️': 5, + '🏃🏾‍♀️‍➡️': 6, + '🏃🏾‍♂️': 5, + '🏃🏾‍♂️‍➡️': 6, + '🏃🏾‍➡️': 5, + '🏃🏿‍♀️': 5, + '🏃🏿‍♀️‍➡️': 6, + '🏃🏿‍♂️': 5, + '🏃🏿‍♂️‍➡️': 6, + '🏃🏿‍➡️': 5, + '🏄‍♀️': 3, + '🏄‍♂️': 3, + '🏄🏻‍♀️': 5, + '🏄🏻‍♂️': 5, + '🏄🏼‍♀️': 5, + '🏄🏼‍♂️': 5, + '🏄🏽‍♀️': 5, + '🏄🏽‍♂️': 5, + '🏄🏾‍♀️': 5, + '🏄🏾‍♂️': 5, + '🏄🏿‍♀️': 5, + '🏄🏿‍♂️': 5, + '🏊‍♀️': 3, + '🏊‍♂️': 3, + '🏊🏻‍♀️': 5, + '🏊🏻‍♂️': 5, + '🏊🏼‍♀️': 5, + '🏊🏼‍♂️': 5, + '🏊🏽‍♀️': 5, + '🏊🏽‍♂️': 5, + '🏊🏾‍♀️': 5, + '🏊🏾‍♂️': 5, + '🏊🏿‍♀️': 5, + '🏊🏿‍♂️': 5, + '🏋🏻‍♀️': 4, + '🏋🏻‍♂️': 4, + '🏋🏼‍♀️': 4, + '🏋🏼‍♂️': 4, + '🏋🏽‍♀️': 4, + '🏋🏽‍♂️': 4, + '🏋🏾‍♀️': 4, + '🏋🏾‍♂️': 4, + '🏋🏿‍♀️': 4, + '🏋🏿‍♂️': 4, + '🏌🏻‍♀️': 4, + '🏌🏻‍♂️': 4, + '🏌🏼‍♀️': 4, + '🏌🏼‍♂️': 4, + '🏌🏽‍♀️': 4, + '🏌🏽‍♂️': 4, + '🏌🏾‍♀️': 4, + '🏌🏾‍♂️': 4, + '🏌🏿‍♀️': 4, + '🏌🏿‍♂️': 4, + '🏳️‍🌈': 3, + '🏴‍☠️': 3, + '🐈‍⬛': 4, + '🐕‍🦺': 4, + '🐦‍⬛': 4, + '🐦‍🔥': 4, + '🐻‍❄️': 3, + '👨‍⚕️': 3, + '👨‍⚖️': 3, + '👨‍✈️': 3, + '👨‍❤️‍👨': 5, + '👨‍❤️‍💋‍👨': 7, + '👨‍🌾': 4, + '👨‍🍳': 4, + '👨‍🍼': 4, + '👨‍🎓': 4, + '👨‍🎤': 4, + '👨‍🎨': 4, + '👨‍🏫': 4, + '👨‍🏭': 4, + '👨‍👦': 4, + '👨‍👦‍👦': 6, + '👨‍👧': 4, + '👨‍👧‍👦': 6, + '👨‍👧‍👧': 6, + '👨‍👨‍👦': 6, + '👨‍👨‍👦‍👦': 8, + '👨‍👨‍👧': 6, + '👨‍👨‍👧‍👦': 8, + '👨‍👨‍👧‍👧': 8, + '👨‍👩‍👦': 6, + '👨‍👩‍👦‍👦': 8, + '👨‍👩‍👧': 6, + '👨‍👩‍👧‍👦': 8, + '👨‍👩‍👧‍👧': 8, + '👨‍💻': 4, + '👨‍💼': 4, + '👨‍🔧': 4, + '👨‍🔬': 4, + '👨‍🚀': 4, + '👨‍🚒': 4, + '👨‍🦯': 4, + '👨‍🦯‍➡️': 5, + '👨‍🦰': 4, + '👨‍🦱': 4, + '👨‍🦲': 4, + '👨‍🦳': 4, + '👨‍🦼': 4, + '👨‍🦼‍➡️': 5, + '👨‍🦽': 4, + '👨‍🦽‍➡️': 5, + '👨🏻‍⚕️': 5, + '👨🏻‍⚖️': 5, + '👨🏻‍✈️': 5, + '👨🏻‍❤️‍👨🏻': 9, + '👨🏻‍❤️‍👨🏽': 9, + '👨🏻‍❤️‍👨🏿': 9, + '👨🏻‍❤️‍💋‍👨🏻': 11, + '👨🏻‍❤️‍💋‍👨🏽': 11, + '👨🏻‍❤️‍💋‍👨🏾': 11, + '👨🏻‍❤️‍💋‍👨🏿': 11, + '👨🏻‍🌾': 6, + '👨🏻‍🍳': 6, + '👨🏻‍🍼': 6, + '👨🏻‍🎓': 6, + '👨🏻‍🎤': 6, + '👨🏻‍🎨': 6, + '👨🏻‍🏫': 6, + '👨🏻‍🏭': 6, + '👨🏻‍🐰‍👨🏼': 10, + '👨🏻‍🐰‍👨🏽': 10, + '👨🏻‍🐰‍👨🏾': 10, + '👨🏻‍🐰‍👨🏿': 10, + '👨🏻‍💻': 6, + '👨🏻‍💼': 6, + '👨🏻‍🔧': 6, + '👨🏻‍🔬': 6, + '👨🏻‍🚀': 6, + '👨🏻‍🚒': 6, + '👨🏻‍🤝‍👨🏼': 10, + '👨🏻‍🤝‍👨🏽': 10, + '👨🏻‍🤝‍👨🏾': 10, + '👨🏻‍🤝‍👨🏿': 10, + '👨🏻‍🦯': 6, + '👨🏻‍🦯‍➡️': 7, + '👨🏻‍🦰': 6, + '👨🏻‍🦱': 6, + '👨🏻‍🦲': 6, + '👨🏻‍🦳': 6, + '👨🏻‍🦼': 6, + '👨🏻‍🦼‍➡️': 7, + '👨🏻‍🦽': 6, + '👨🏻‍🦽‍➡️': 7, + '👨🏻‍🫯‍👨🏼': 10, + '👨🏻‍🫯‍👨🏽': 10, + '👨🏻‍🫯‍👨🏾': 10, + '👨🏻‍🫯‍👨🏿': 10, + '👨🏼‍⚕️': 5, + '👨🏼‍⚖️': 5, + '👨🏼‍✈️': 5, + '👨🏼‍❤️‍👨🏼': 9, + '👨🏼‍❤️‍💋‍👨🏼': 11, + '👨🏼‍❤️‍💋‍👨🏿': 11, + '👨🏼‍🌾': 6, + '👨🏼‍🍳': 6, + '👨🏼‍🍼': 6, + '👨🏼‍🎓': 6, + '👨🏼‍🎤': 6, + '👨🏼‍🎨': 6, + '👨🏼‍🏫': 6, + '👨🏼‍🏭': 6, + '👨🏼‍🐰‍👨🏻': 10, + '👨🏼‍🐰‍👨🏽': 10, + '👨🏼‍🐰‍👨🏿': 10, + '👨🏼‍💻': 6, + '👨🏼‍💼': 6, + '👨🏼‍🔧': 6, + '👨🏼‍🔬': 6, + '👨🏼‍🚀': 6, + '👨🏼‍🚒': 6, + '👨🏼‍🤝‍👨🏻': 10, + '👨🏼‍🤝‍👨🏽': 10, + '👨🏼‍🤝‍👨🏿': 10, + '👨🏼‍🦯': 6, + '👨🏼‍🦯‍➡️': 7, + '👨🏼‍🦰': 6, + '👨🏼‍🦱': 6, + '👨🏼‍🦲': 6, + '👨🏼‍🦳': 6, + '👨🏼‍🦼': 6, + '👨🏼‍🦽': 6, + '👨🏼‍🦽‍➡️': 7, + '👨🏼‍🫯‍👨🏻': 10, + '👨🏼‍🫯‍👨🏽': 10, + '👨🏼‍🫯‍👨🏾': 10, + '👨🏼‍🫯‍👨🏿': 10, + '👨🏽‍⚕️': 5, + '👨🏽‍⚖️': 5, + '👨🏽‍✈️': 5, + '👨🏽‍❤️‍👨🏻': 9, + '👨🏽‍❤️‍👨🏽': 9, + '👨🏽‍❤️‍👨🏿': 9, + '👨🏽‍❤️‍💋‍👨🏻': 11, + '👨🏽‍❤️‍💋‍👨🏽': 11, + '👨🏽‍❤️‍💋‍👨🏿': 11, + '👨🏽‍🌾': 6, + '👨🏽‍🍳': 6, + '👨🏽‍🍼': 6, + '👨🏽‍🎓': 6, + '👨🏽‍🎤': 6, + '👨🏽‍🎨': 6, + '👨🏽‍🏫': 6, + '👨🏽‍🏭': 6, + '👨🏽‍🐰‍👨🏻': 10, + '👨🏽‍🐰‍👨🏼': 10, + '👨🏽‍🐰‍👨🏾': 10, + '👨🏽‍🐰‍👨🏿': 10, + '👨🏽‍💻': 6, + '👨🏽‍💼': 6, + '👨🏽‍🔧': 6, + '👨🏽‍🔬': 6, + '👨🏽‍🚀': 6, + '👨🏽‍🚒': 6, + '👨🏽‍🤝‍👨🏻': 10, + '👨🏽‍🤝‍👨🏼': 10, + '👨🏽‍🤝‍👨🏾': 10, + '👨🏽‍🤝‍👨🏿': 10, + '👨🏽‍🦯': 6, + '👨🏽‍🦯‍➡️': 7, + '👨🏽‍🦰': 6, + '👨🏽‍🦱': 6, + '👨🏽‍🦲': 6, + '👨🏽‍🦳': 6, + '👨🏽‍🦼': 6, + '👨🏽‍🦼‍➡️': 7, + '👨🏽‍🦽': 6, + '👨🏽‍🦽‍➡️': 7, + '👨🏽‍🫯‍👨🏻': 10, + '👨🏽‍🫯‍👨🏼': 10, + '👨🏽‍🫯‍👨🏾': 10, + '👨🏽‍🫯‍👨🏿': 10, + '👨🏾‍⚕️': 5, + '👨🏾‍⚖️': 5, + '👨🏾‍✈️': 5, + '👨🏾‍❤️‍👨🏾': 9, + '👨🏾‍❤️‍💋‍👨🏻': 11, + '👨🏾‍❤️‍💋‍👨🏾': 11, + '👨🏾‍❤️‍💋‍👨🏿': 11, + '👨🏾‍🌾': 6, + '👨🏾‍🍳': 6, + '👨🏾‍🍼': 6, + '👨🏾‍🎓': 6, + '👨🏾‍🎤': 6, + '👨🏾‍🎨': 6, + '👨🏾‍🏫': 6, + '👨🏾‍🏭': 6, + '👨🏾‍🐰‍👨🏻': 10, + '👨🏾‍🐰‍👨🏽': 10, + '👨🏾‍🐰‍👨🏿': 10, + '👨🏾‍💻': 6, + '👨🏾‍💼': 6, + '👨🏾‍🔧': 6, + '👨🏾‍🔬': 6, + '👨🏾‍🚀': 6, + '👨🏾‍🚒': 6, + '👨🏾‍🤝‍👨🏻': 10, + '👨🏾‍🤝‍👨🏽': 10, + '👨🏾‍🤝‍👨🏿': 10, + '👨🏾‍🦯': 6, + '👨🏾‍🦯‍➡️': 7, + '👨🏾‍🦰': 6, + '👨🏾‍🦱': 6, + '👨🏾‍🦲': 6, + '👨🏾‍🦳': 6, + '👨🏾‍🦼': 6, + '👨🏾‍🦽': 6, + '👨🏾‍🦽‍➡️': 7, + '👨🏾‍🫯‍👨🏻': 10, + '👨🏾‍🫯‍👨🏼': 10, + '👨🏾‍🫯‍👨🏽': 10, + '👨🏾‍🫯‍👨🏿': 10, + '👨🏿‍⚕️': 5, + '👨🏿‍⚖️': 5, + '👨🏿‍✈️': 5, + '👨🏿‍❤️‍👨🏻': 9, + '👨🏿‍❤️‍👨🏽': 9, + '👨🏿‍❤️‍👨🏿': 9, + '👨🏿‍❤️‍💋‍👨🏻': 11, + '👨🏿‍❤️‍💋‍👨🏼': 11, + '👨🏿‍❤️‍💋‍👨🏽': 11, + '👨🏿‍❤️‍💋‍👨🏾': 11, + '👨🏿‍❤️‍💋‍👨🏿': 11, + '👨🏿‍🌾': 6, + '👨🏿‍🍳': 6, + '👨🏿‍🍼': 6, + '👨🏿‍🎓': 6, + '👨🏿‍🎤': 6, + '👨🏿‍🎨': 6, + '👨🏿‍🏫': 6, + '👨🏿‍🏭': 6, + '👨🏿‍🐰‍👨🏻': 10, + '👨🏿‍🐰‍👨🏼': 10, + '👨🏿‍🐰‍👨🏽': 10, + '👨🏿‍🐰‍👨🏾': 10, + '👨🏿‍💻': 6, + '👨🏿‍💼': 6, + '👨🏿‍🔧': 6, + '👨🏿‍🔬': 6, + '👨🏿‍🚀': 6, + '👨🏿‍🚒': 6, + '👨🏿‍🤝‍👨🏻': 10, + '👨🏿‍🤝‍👨🏼': 10, + '👨🏿‍🤝‍👨🏽': 10, + '👨🏿‍🤝‍👨🏾': 10, + '👨🏿‍🦯': 6, + '👨🏿‍🦯‍➡️': 7, + '👨🏿‍🦰': 6, + '👨🏿‍🦱': 6, + '👨🏿‍🦲': 6, + '👨🏿‍🦳': 6, + '👨🏿‍🦼': 6, + '👨🏿‍🦼‍➡️': 7, + '👨🏿‍🦽': 6, + '👨🏿‍🦽‍➡️': 7, + '👨🏿‍🫯‍👨🏻': 10, + '👨🏿‍🫯‍👨🏼': 10, + '👨🏿‍🫯‍👨🏽': 10, + '👨🏿‍🫯‍👨🏾': 10, + '👩‍⚕️': 3, + '👩‍⚖️': 3, + '👩‍✈️': 3, + '👩‍❤️‍👨': 5, + '👩‍❤️‍👩': 5, + '👩‍❤️‍💋‍👨': 7, + '👩‍❤️‍💋‍👩': 7, + '👩‍🌾': 4, + '👩‍🍳': 4, + '👩‍🍼': 4, + '👩‍🎓': 4, + '👩‍🎤': 4, + '👩‍🎨': 4, + '👩‍🏫': 4, + '👩‍🏭': 4, + '👩‍👦': 4, + '👩‍👦‍👦': 6, + '👩‍👧': 4, + '👩‍👧‍👦': 6, + '👩‍👧‍👧': 6, + '👩‍👩‍👦': 6, + '👩‍👩‍👦‍👦': 8, + '👩‍👩‍👧': 6, + '👩‍👩‍👧‍👦': 8, + '👩‍👩‍👧‍👧': 8, + '👩‍💻': 4, + '👩‍💼': 4, + '👩‍🔧': 4, + '👩‍🔬': 4, + '👩‍🚀': 4, + '👩‍🚒': 4, + '👩‍🦯': 4, + '👩‍🦯‍➡️': 5, + '👩‍🦰': 4, + '👩‍🦱': 4, + '👩‍🦲': 4, + '👩‍🦳': 4, + '👩‍🦼': 4, + '👩‍🦼‍➡️': 5, + '👩‍🦽': 4, + '👩‍🦽‍➡️': 5, + '👩🏻‍⚕️': 5, + '👩🏻‍⚖️': 5, + '👩🏻‍✈️': 5, + '👩🏻‍❤️‍👨🏻': 9, + '👩🏻‍❤️‍👨🏿': 9, + '👩🏻‍❤️‍👩🏻': 9, + '👩🏻‍❤️‍💋‍👨🏻': 11, + '👩🏻‍❤️‍💋‍👨🏽': 11, + '👩🏻‍❤️‍💋‍👨🏿': 11, + '👩🏻‍❤️‍💋‍👩🏻': 11, + '👩🏻‍❤️‍💋‍👩🏽': 11, + '👩🏻‍❤️‍💋‍👩🏿': 11, + '👩🏻‍🌾': 6, + '👩🏻‍🍳': 6, + '👩🏻‍🍼': 6, + '👩🏻‍🎓': 6, + '👩🏻‍🎤': 6, + '👩🏻‍🎨': 6, + '👩🏻‍🏫': 6, + '👩🏻‍🏭': 6, + '👩🏻‍🐰‍👩🏼': 10, + '👩🏻‍🐰‍👩🏽': 10, + '👩🏻‍🐰‍👩🏾': 10, + '👩🏻‍🐰‍👩🏿': 10, + '👩🏻‍💻': 6, + '👩🏻‍💼': 6, + '👩🏻‍🔧': 6, + '👩🏻‍🔬': 6, + '👩🏻‍🚀': 6, + '👩🏻‍🚒': 6, + '👩🏻‍🤝‍👨🏽': 10, + '👩🏻‍🤝‍👨🏿': 10, + '👩🏻‍🤝‍👩🏼': 10, + '👩🏻‍🤝‍👩🏽': 10, + '👩🏻‍🤝‍👩🏾': 10, + '👩🏻‍🤝‍👩🏿': 10, + '👩🏻‍🦯': 6, + '👩🏻‍🦯‍➡️': 7, + '👩🏻‍🦰': 6, + '👩🏻‍🦱': 6, + '👩🏻‍🦲': 6, + '👩🏻‍🦳': 6, + '👩🏻‍🦼': 6, + '👩🏻‍🦼‍➡️': 7, + '👩🏻‍🦽': 6, + '👩🏻‍🦽‍➡️': 7, + '👩🏻‍🫯‍👩🏼': 10, + '👩🏻‍🫯‍👩🏽': 10, + '👩🏻‍🫯‍👩🏾': 10, + '👩🏻‍🫯‍👩🏿': 10, + '👩🏼‍⚕️': 5, + '👩🏼‍⚖️': 5, + '👩🏼‍✈️': 5, + '👩🏼‍❤️‍👨🏼': 9, + '👩🏼‍❤️‍👩🏼': 9, + '👩🏼‍❤️‍💋‍👨🏼': 11, + '👩🏼‍❤️‍💋‍👩🏼': 11, + '👩🏼‍🌾': 6, + '👩🏼‍🍳': 6, + '👩🏼‍🍼': 6, + '👩🏼‍🎓': 6, + '👩🏼‍🎤': 6, + '👩🏼‍🎨': 6, + '👩🏼‍🏫': 6, + '👩🏼‍🏭': 6, + '👩🏼‍🐰‍👩🏻': 10, + '👩🏼‍🐰‍👩🏿': 10, + '👩🏼‍💻': 6, + '👩🏼‍💼': 6, + '👩🏼‍🔧': 6, + '👩🏼‍🔬': 6, + '👩🏼‍🚀': 6, + '👩🏼‍🚒': 6, + '👩🏼‍🤝‍👩🏻': 10, + '👩🏼‍🤝‍👩🏽': 10, + '👩🏼‍🤝‍👩🏿': 10, + '👩🏼‍🦯': 6, + '👩🏼‍🦯‍➡️': 7, + '👩🏼‍🦰': 6, + '👩🏼‍🦱': 6, + '👩🏼‍🦲': 6, + '👩🏼‍🦳': 6, + '👩🏼‍🦼': 6, + '👩🏼‍🦽': 6, + '👩🏼‍🫯‍👩🏻': 10, + '👩🏼‍🫯‍👩🏽': 10, + '👩🏼‍🫯‍👩🏾': 10, + '👩🏼‍🫯‍👩🏿': 10, + '👩🏽‍⚕️': 5, + '👩🏽‍⚖️': 5, + '👩🏽‍✈️': 5, + '👩🏽‍❤️‍👨🏽': 9, + '👩🏽‍❤️‍👩🏽': 9, + '👩🏽‍❤️‍💋‍👨🏻': 11, + '👩🏽‍❤️‍💋‍👨🏽': 11, + '👩🏽‍❤️‍💋‍👨🏿': 11, + '👩🏽‍❤️‍💋‍👩🏻': 11, + '👩🏽‍❤️‍💋‍👩🏽': 11, + '👩🏽‍❤️‍💋‍👩🏿': 11, + '👩🏽‍🌾': 6, + '👩🏽‍🍳': 6, + '👩🏽‍🍼': 6, + '👩🏽‍🎓': 6, + '👩🏽‍🎤': 6, + '👩🏽‍🎨': 6, + '👩🏽‍🏫': 6, + '👩🏽‍🏭': 6, + '👩🏽‍🐰‍👩🏻': 10, + '👩🏽‍🐰‍👩🏾': 10, + '👩🏽‍🐰‍👩🏿': 10, + '👩🏽‍💻': 6, + '👩🏽‍💼': 6, + '👩🏽‍🔧': 6, + '👩🏽‍🔬': 6, + '👩🏽‍🚀': 6, + '👩🏽‍🚒': 6, + '👩🏽‍🤝‍👨🏻': 10, + '👩🏽‍🤝‍👨🏿': 10, + '👩🏽‍🤝‍👩🏻': 10, + '👩🏽‍🤝‍👩🏼': 10, + '👩🏽‍🤝‍👩🏾': 10, + '👩🏽‍🤝‍👩🏿': 10, + '👩🏽‍🦯': 6, + '👩🏽‍🦯‍➡️': 7, + '👩🏽‍🦰': 6, + '👩🏽‍🦱': 6, + '👩🏽‍🦲': 6, + '👩🏽‍🦳': 6, + '👩🏽‍🦼': 6, + '👩🏽‍🦼‍➡️': 7, + '👩🏽‍🦽': 6, + '👩🏽‍🦽‍➡️': 7, + '👩🏽‍🫯‍👩🏻': 10, + '👩🏽‍🫯‍👩🏼': 10, + '👩🏽‍🫯‍👩🏾': 10, + '👩🏽‍🫯‍👩🏿': 10, + '👩🏾‍⚕️': 5, + '👩🏾‍⚖️': 5, + '👩🏾‍✈️': 5, + '👩🏾‍❤️‍👨🏾': 9, + '👩🏾‍❤️‍👩🏾': 9, + '👩🏾‍❤️‍💋‍👨🏾': 11, + '👩🏾‍❤️‍💋‍👩🏾': 11, + '👩🏾‍🌾': 6, + '👩🏾‍🍳': 6, + '👩🏾‍🍼': 6, + '👩🏾‍🎓': 6, + '👩🏾‍🎤': 6, + '👩🏾‍🎨': 6, + '👩🏾‍🏫': 6, + '👩🏾‍🏭': 6, + '👩🏾‍🐰‍👩🏻': 10, + '👩🏾‍🐰‍👩🏽': 10, + '👩🏾‍🐰‍👩🏿': 10, + '👩🏾‍💻': 6, + '👩🏾‍💼': 6, + '👩🏾‍🔧': 6, + '👩🏾‍🔬': 6, + '👩🏾‍🚀': 6, + '👩🏾‍🚒': 6, + '👩🏾‍🤝‍👩🏻': 10, + '👩🏾‍🤝‍👩🏽': 10, + '👩🏾‍🤝‍👩🏿': 10, + '👩🏾‍🦯': 6, + '👩🏾‍🦯‍➡️': 7, + '👩🏾‍🦰': 6, + '👩🏾‍🦱': 6, + '👩🏾‍🦲': 6, + '👩🏾‍🦳': 6, + '👩🏾‍🦼': 6, + '👩🏾‍🦽': 6, + '👩🏾‍🦽‍➡️': 7, + '👩🏾‍🫯‍👩🏻': 10, + '👩🏾‍🫯‍👩🏼': 10, + '👩🏾‍🫯‍👩🏽': 10, + '👩🏾‍🫯‍👩🏿': 10, + '👩🏿‍⚕️': 5, + '👩🏿‍⚖️': 5, + '👩🏿‍✈️': 5, + '👩🏿‍❤️‍👨🏻': 9, + '👩🏿‍❤️‍👨🏿': 9, + '👩🏿‍❤️‍👩🏿': 9, + '👩🏿‍❤️‍💋‍👨🏻': 11, + '👩🏿‍❤️‍💋‍👨🏽': 11, + '👩🏿‍❤️‍💋‍👨🏿': 11, + '👩🏿‍❤️‍💋‍👩🏻': 11, + '👩🏿‍❤️‍💋‍👩🏽': 11, + '👩🏿‍❤️‍💋‍👩🏿': 11, + '👩🏿‍🌾': 6, + '👩🏿‍🍳': 6, + '👩🏿‍🍼': 6, + '👩🏿‍🎓': 6, + '👩🏿‍🎤': 6, + '👩🏿‍🎨': 6, + '👩🏿‍🏫': 6, + '👩🏿‍🏭': 6, + '👩🏿‍🐰‍👩🏻': 10, + '👩🏿‍🐰‍👩🏼': 10, + '👩🏿‍🐰‍👩🏽': 10, + '👩🏿‍🐰‍👩🏾': 10, + '👩🏿‍💻': 6, + '👩🏿‍💼': 6, + '👩🏿‍🔧': 6, + '👩🏿‍🔬': 6, + '👩🏿‍🚀': 6, + '👩🏿‍🚒': 6, + '👩🏿‍🤝‍👨🏻': 10, + '👩🏿‍🤝‍👨🏽': 10, + '👩🏿‍🤝‍👩🏻': 10, + '👩🏿‍🤝‍👩🏼': 10, + '👩🏿‍🤝‍👩🏽': 10, + '👩🏿‍🤝‍👩🏾': 10, + '👩🏿‍🦯': 6, + '👩🏿‍🦯‍➡️': 7, + '👩🏿‍🦰': 6, + '👩🏿‍🦱': 6, + '👩🏿‍🦲': 6, + '👩🏿‍🦳': 6, + '👩🏿‍🦼': 6, + '👩🏿‍🦼‍➡️': 7, + '👩🏿‍🦽': 6, + '👩🏿‍🦽‍➡️': 7, + '👩🏿‍🫯‍👩🏻': 10, + '👩🏿‍🫯‍👩🏼': 10, + '👩🏿‍🫯‍👩🏽': 10, + '👩🏿‍🫯‍👩🏾': 10, + '👮‍♀️': 3, + '👮‍♂️': 3, + '👮🏻‍♀️': 5, + '👮🏻‍♂️': 5, + '👮🏼‍♀️': 5, + '👮🏼‍♂️': 5, + '👮🏽‍♀️': 5, + '👮🏽‍♂️': 5, + '👮🏾‍♀️': 5, + '👮🏾‍♂️': 5, + '👮🏿‍♀️': 5, + '👮🏿‍♂️': 5, + '👯‍♀️': 3, + '👯‍♂️': 3, + '👯🏻‍♀️': 5, + '👯🏻‍♂️': 5, + '👯🏼‍♀️': 5, + '👯🏼‍♂️': 5, + '👯🏽‍♀️': 5, + '👯🏽‍♂️': 5, + '👯🏾‍♀️': 5, + '👯🏾‍♂️': 5, + '👯🏿‍♀️': 5, + '👯🏿‍♂️': 5, + '👰‍♀️': 3, + '👰‍♂️': 3, + '👰🏻‍♀️': 5, + '👰🏻‍♂️': 5, + '👰🏼‍♀️': 5, + '👰🏼‍♂️': 5, + '👰🏽‍♀️': 5, + '👰🏽‍♂️': 5, + '👰🏾‍♀️': 5, + '👰🏾‍♂️': 5, + '👰🏿‍♀️': 5, + '👰🏿‍♂️': 5, + '👱‍♀️': 3, + '👱‍♂️': 3, + '👱🏻‍♀️': 5, + '👱🏻‍♂️': 5, + '👱🏼‍♀️': 5, + '👱🏼‍♂️': 5, + '👱🏽‍♀️': 5, + '👱🏽‍♂️': 5, + '👱🏾‍♀️': 5, + '👱🏾‍♂️': 5, + '👱🏿‍♀️': 5, + '👱🏿‍♂️': 5, + '👳‍♀️': 3, + '👳‍♂️': 3, + '👳🏻‍♀️': 5, + '👳🏻‍♂️': 5, + '👳🏼‍♀️': 5, + '👳🏼‍♂️': 5, + '👳🏽‍♀️': 5, + '👳🏽‍♂️': 5, + '👳🏾‍♀️': 5, + '👳🏾‍♂️': 5, + '👳🏿‍♀️': 5, + '👳🏿‍♂️': 5, + '👷‍♀️': 3, + '👷‍♂️': 3, + '👷🏻‍♀️': 5, + '👷🏻‍♂️': 5, + '👷🏼‍♀️': 5, + '👷🏼‍♂️': 5, + '👷🏽‍♀️': 5, + '👷🏽‍♂️': 5, + '👷🏾‍♀️': 5, + '👷🏾‍♂️': 5, + '👷🏿‍♀️': 5, + '👷🏿‍♂️': 5, + '💁‍♀️': 3, + '💁‍♂️': 3, + '💁🏻‍♀️': 5, + '💁🏻‍♂️': 5, + '💁🏼‍♀️': 5, + '💁🏼‍♂️': 5, + '💁🏽‍♀️': 5, + '💁🏽‍♂️': 5, + '💁🏾‍♀️': 5, + '💁🏾‍♂️': 5, + '💁🏿‍♀️': 5, + '💁🏿‍♂️': 5, + '💂‍♀️': 3, + '💂‍♂️': 3, + '💂🏻‍♀️': 5, + '💂🏻‍♂️': 5, + '💂🏼‍♀️': 5, + '💂🏼‍♂️': 5, + '💂🏽‍♀️': 5, + '💂🏽‍♂️': 5, + '💂🏾‍♀️': 5, + '💂🏾‍♂️': 5, + '💂🏿‍♀️': 5, + '💂🏿‍♂️': 5, + '💆‍♀️': 3, + '💆‍♂️': 3, + '💆🏻‍♀️': 5, + '💆🏻‍♂️': 5, + '💆🏼‍♀️': 5, + '💆🏼‍♂️': 5, + '💆🏽‍♀️': 5, + '💆🏽‍♂️': 5, + '💆🏾‍♀️': 5, + '💆🏾‍♂️': 5, + '💆🏿‍♀️': 5, + '💆🏿‍♂️': 5, + '💇‍♀️': 3, + '💇‍♂️': 3, + '💇🏻‍♀️': 5, + '💇🏻‍♂️': 5, + '💇🏼‍♀️': 5, + '💇🏼‍♂️': 5, + '💇🏽‍♀️': 5, + '💇🏽‍♂️': 5, + '💇🏾‍♀️': 5, + '💇🏾‍♂️': 5, + '💇🏿‍♀️': 5, + '💇🏿‍♂️': 5, + '🕵🏻‍♀️': 4, + '🕵🏻‍♂️': 4, + '🕵🏼‍♀️': 4, + '🕵🏼‍♂️': 4, + '🕵🏽‍♀️': 4, + '🕵🏽‍♂️': 4, + '🕵🏾‍♀️': 4, + '🕵🏾‍♂️': 4, + '🕵🏿‍♀️': 4, + '🕵🏿‍♂️': 4, + '😮‍💨': 4, + '😵‍💫': 4, + '😶‍🌫️': 3, + '🙂‍↔️': 3, + '🙂‍↕️': 3, + '🙅‍♀️': 3, + '🙅‍♂️': 3, + '🙅🏻‍♀️': 5, + '🙅🏻‍♂️': 5, + '🙅🏼‍♀️': 5, + '🙅🏼‍♂️': 5, + '🙅🏽‍♀️': 5, + '🙅🏽‍♂️': 5, + '🙅🏾‍♀️': 5, + '🙅🏾‍♂️': 5, + '🙅🏿‍♀️': 5, + '🙅🏿‍♂️': 5, + '🙆‍♀️': 3, + '🙆‍♂️': 3, + '🙆🏻‍♀️': 5, + '🙆🏻‍♂️': 5, + '🙆🏼‍♀️': 5, + '🙆🏼‍♂️': 5, + '🙆🏽‍♀️': 5, + '🙆🏽‍♂️': 5, + '🙆🏾‍♀️': 5, + '🙆🏾‍♂️': 5, + '🙆🏿‍♀️': 5, + '🙆🏿‍♂️': 5, + '🙇‍♀️': 3, + '🙇‍♂️': 3, + '🙇🏻‍♀️': 5, + '🙇🏻‍♂️': 5, + '🙇🏼‍♀️': 5, + '🙇🏼‍♂️': 5, + '🙇🏽‍♀️': 5, + '🙇🏽‍♂️': 5, + '🙇🏾‍♀️': 5, + '🙇🏾‍♂️': 5, + '🙇🏿‍♀️': 5, + '🙇🏿‍♂️': 5, + '🙋‍♀️': 3, + '🙋‍♂️': 3, + '🙋🏻‍♀️': 5, + '🙋🏻‍♂️': 5, + '🙋🏼‍♀️': 5, + '🙋🏼‍♂️': 5, + '🙋🏽‍♀️': 5, + '🙋🏽‍♂️': 5, + '🙋🏾‍♀️': 5, + '🙋🏾‍♂️': 5, + '🙋🏿‍♀️': 5, + '🙋🏿‍♂️': 5, + '🙍‍♀️': 3, + '🙍‍♂️': 3, + '🙍🏻‍♀️': 5, + '🙍🏻‍♂️': 5, + '🙍🏼‍♀️': 5, + '🙍🏼‍♂️': 5, + '🙍🏽‍♀️': 5, + '🙍🏽‍♂️': 5, + '🙍🏾‍♀️': 5, + '🙍🏾‍♂️': 5, + '🙍🏿‍♀️': 5, + '🙍🏿‍♂️': 5, + '🙎‍♀️': 3, + '🙎‍♂️': 3, + '🙎🏻‍♀️': 5, + '🙎🏻‍♂️': 5, + '🙎🏼‍♀️': 5, + '🙎🏼‍♂️': 5, + '🙎🏽‍♀️': 5, + '🙎🏽‍♂️': 5, + '🙎🏾‍♀️': 5, + '🙎🏾‍♂️': 5, + '🙎🏿‍♀️': 5, + '🙎🏿‍♂️': 5, + '🚣‍♀️': 3, + '🚣‍♂️': 3, + '🚣🏻‍♀️': 5, + '🚣🏻‍♂️': 5, + '🚣🏼‍♀️': 5, + '🚣🏼‍♂️': 5, + '🚣🏽‍♀️': 5, + '🚣🏽‍♂️': 5, + '🚣🏾‍♀️': 5, + '🚣🏾‍♂️': 5, + '🚣🏿‍♀️': 5, + '🚣🏿‍♂️': 5, + '🚴‍♀️': 3, + '🚴‍♂️': 3, + '🚴🏻‍♀️': 5, + '🚴🏻‍♂️': 5, + '🚴🏼‍♀️': 5, + '🚴🏼‍♂️': 5, + '🚴🏽‍♀️': 5, + '🚴🏽‍♂️': 5, + '🚴🏾‍♀️': 5, + '🚴🏾‍♂️': 5, + '🚴🏿‍♀️': 5, + '🚴🏿‍♂️': 5, + '🚵‍♀️': 3, + '🚵‍♂️': 3, + '🚵🏻‍♀️': 5, + '🚵🏻‍♂️': 5, + '🚵🏼‍♀️': 5, + '🚵🏼‍♂️': 5, + '🚵🏽‍♀️': 5, + '🚵🏽‍♂️': 5, + '🚵🏾‍♀️': 5, + '🚵🏾‍♂️': 5, + '🚵🏿‍♀️': 5, + '🚵🏿‍♂️': 5, + '🚶‍♀️': 3, + '🚶‍♀️‍➡️': 4, + '🚶‍♂️': 3, + '🚶‍♂️‍➡️': 4, + '🚶‍➡️': 3, + '🚶🏻‍♀️': 5, + '🚶🏻‍♀️‍➡️': 6, + '🚶🏻‍♂️': 5, + '🚶🏻‍♂️‍➡️': 6, + '🚶🏻‍➡️': 5, + '🚶🏼‍♀️': 5, + '🚶🏼‍♀️‍➡️': 6, + '🚶🏼‍♂️': 5, + '🚶🏼‍♂️‍➡️': 6, + '🚶🏼‍➡️': 5, + '🚶🏽‍♀️': 5, + '🚶🏽‍♀️‍➡️': 6, + '🚶🏽‍♂️': 5, + '🚶🏽‍♂️‍➡️': 6, + '🚶🏽‍➡️': 5, + '🚶🏾‍♀️': 5, + '🚶🏾‍♀️‍➡️': 6, + '🚶🏾‍♂️': 5, + '🚶🏾‍♂️‍➡️': 6, + '🚶🏾‍➡️': 5, + '🚶🏿‍♀️': 5, + '🚶🏿‍♀️‍➡️': 6, + '🚶🏿‍♂️': 5, + '🚶🏿‍♂️‍➡️': 6, + '🚶🏿‍➡️': 5, + '🤦‍♀️': 3, + '🤦‍♂️': 3, + '🤦🏻‍♀️': 5, + '🤦🏻‍♂️': 5, + '🤦🏼‍♀️': 5, + '🤦🏼‍♂️': 5, + '🤦🏽‍♀️': 5, + '🤦🏽‍♂️': 5, + '🤦🏾‍♀️': 5, + '🤦🏾‍♂️': 5, + '🤦🏿‍♀️': 5, + '🤦🏿‍♂️': 5, + '🤵‍♀️': 3, + '🤵‍♂️': 3, + '🤵🏻‍♀️': 5, + '🤵🏻‍♂️': 5, + '🤵🏼‍♀️': 5, + '🤵🏼‍♂️': 5, + '🤵🏽‍♀️': 5, + '🤵🏽‍♂️': 5, + '🤵🏾‍♀️': 5, + '🤵🏾‍♂️': 5, + '🤵🏿‍♀️': 5, + '🤵🏿‍♂️': 5, + '🤷‍♀️': 3, + '🤷‍♂️': 3, + '🤷🏻‍♀️': 5, + '🤷🏻‍♂️': 5, + '🤷🏼‍♀️': 5, + '🤷🏼‍♂️': 5, + '🤷🏽‍♀️': 5, + '🤷🏽‍♂️': 5, + '🤷🏾‍♀️': 5, + '🤷🏾‍♂️': 5, + '🤷🏿‍♀️': 5, + '🤷🏿‍♂️': 5, + '🤸‍♀️': 3, + '🤸‍♂️': 3, + '🤸🏻‍♀️': 5, + '🤸🏻‍♂️': 5, + '🤸🏼‍♀️': 5, + '🤸🏼‍♂️': 5, + '🤸🏽‍♀️': 5, + '🤸🏽‍♂️': 5, + '🤸🏾‍♀️': 5, + '🤸🏾‍♂️': 5, + '🤸🏿‍♀️': 5, + '🤸🏿‍♂️': 5, + '🤹‍♀️': 3, + '🤹‍♂️': 3, + '🤹🏻‍♀️': 5, + '🤹🏻‍♂️': 5, + '🤹🏼‍♀️': 5, + '🤹🏼‍♂️': 5, + '🤹🏽‍♀️': 5, + '🤹🏽‍♂️': 5, + '🤹🏾‍♀️': 5, + '🤹🏾‍♂️': 5, + '🤹🏿‍♀️': 5, + '🤹🏿‍♂️': 5, + '🤼‍♀️': 3, + '🤼‍♂️': 3, + '🤼🏻‍♀️': 5, + '🤼🏻‍♂️': 5, + '🤼🏼‍♀️': 5, + '🤼🏼‍♂️': 5, + '🤼🏽‍♀️': 5, + '🤼🏽‍♂️': 5, + '🤼🏾‍♀️': 5, + '🤼🏾‍♂️': 5, + '🤼🏿‍♀️': 5, + '🤼🏿‍♂️': 5, + '🤽‍♀️': 3, + '🤽‍♂️': 3, + '🤽🏻‍♀️': 5, + '🤽🏻‍♂️': 5, + '🤽🏼‍♀️': 5, + '🤽🏼‍♂️': 5, + '🤽🏽‍♀️': 5, + '🤽🏽‍♂️': 5, + '🤽🏾‍♀️': 5, + '🤽🏾‍♂️': 5, + '🤽🏿‍♀️': 5, + '🤽🏿‍♂️': 5, + '🤾‍♀️': 3, + '🤾‍♂️': 3, + '🤾🏻‍♀️': 5, + '🤾🏻‍♂️': 5, + '🤾🏼‍♀️': 5, + '🤾🏼‍♂️': 5, + '🤾🏽‍♀️': 5, + '🤾🏽‍♂️': 5, + '🤾🏾‍♀️': 5, + '🤾🏾‍♂️': 5, + '🤾🏿‍♀️': 5, + '🤾🏿‍♂️': 5, + '🦸‍♀️': 3, + '🦸‍♂️': 3, + '🦸🏻‍♀️': 5, + '🦸🏻‍♂️': 5, + '🦸🏼‍♀️': 5, + '🦸🏼‍♂️': 5, + '🦸🏽‍♀️': 5, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_3a1895d5.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_3a1895d5.py new file mode 100644 index 0000000000000000000000000000000000000000..7a987be4b9cede40f9a0c211e5adcb2851340114 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_3a1895d5.py @@ -0,0 +1,1207 @@ +""" +Grapheme overrides for _known_3a1895d5. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: mintty +""" +# pylint: skip-file +GRAPHEMES = { + '؁۱': 1, + 'क्का': 3, + 'क्कां': 3, + 'क्को': 3, + 'क्घ्घि्': 4, + 'क्ता': 3, + 'क्ति': 3, + 'क्ती': 3, + 'क्तीं': 3, + 'क्तेः': 3, + 'क्त्योः': 5, + 'क्ना': 3, + 'क्नि': 3, + 'क्या': 3, + 'क्रा': 3, + 'क्रि': 3, + 'क्षा': 3, + 'क्षां': 3, + 'क्षाः': 4, + 'क्षि': 3, + 'क्षो': 3, + 'क्ष्ण': 3, + 'क्ष्य': 3, + 'क्ष्या': 4, + 'क्सा': 3, + 'ख्यः': 3, + 'ख्या': 3, + 'ग्या': 3, + 'ग्यैः': 3, + 'ग्र्य': 3, + 'घ्का': 3, + 'घ्र्व्य': 4, + 'घ्लि': 3, + 'घ्श्य': 3, + 'घ्स्ट': 3, + 'च्चा': 3, + 'च्चों': 3, + 'च्छा': 3, + 'च्छि': 3, + 'च्या': 3, + 'च्यां': 3, + 'च्यो': 3, + 'ज्ञा': 3, + 'ज्या': 3, + 'ज्या‌': 3, + 'ज्रा': 3, + 'ञ्चा': 3, + 'ञ्चि': 3, + 'ट्टि': 3, + 'ट्टी': 3, + 'ट्या': 3, + 'ट्रा': 3, + 'ण्डः': 3, + 'ण्डि': 3, + 'ण्या': 3, + 'ण्यां': 3, + 'ताः': 3, + 'त्का': 3, + 'त्ता': 3, + 'त्ति': 3, + 'त्त्थि': 4, + 'त्त्व': 3, + 'त्त्वा': 4, + 'त्त्वे': 3, + 'त्नी': 3, + 'त्नों': 3, + 'त्पा': 3, + 'त्पी': 3, + 'त्मा': 3, + 'त्या': 3, + 'त्यां': 3, + 'त्यि': 3, + 'त्रा': 3, + 'त्राा': 4, + 'त्राि': 4, + 'त्रि': 3, + 'त्री': 3, + 'त्र्त': 3, + 'त्र्य': 3, + 'त्र्या': 4, + 'त्र्ये': 3, + 'त्वा': 3, + 'त्वां': 3, + 'त्सा': 3, + 'त्सो': 3, + 'त्स्वा': 4, + 'द्घि': 3, + 'द्घो': 3, + 'द्दा': 3, + 'द्दि': 3, + 'द्दी': 3, + 'द्धः': 3, + 'द्धा': 3, + 'द्धां': 3, + 'द्धि': 3, + 'द्धिं': 3, + 'द्धी': 3, + 'द्धीं': 3, + 'द्धैः': 3, + 'द्भा': 3, + 'द्या': 3, + 'द्रो': 3, + 'द्वा': 3, + 'द्वि': 3, + 'धाः': 3, + 'ध्या': 3, + 'नाः': 3, + 'निः': 3, + 'न्का': 3, + 'न्चि': 3, + 'न्ञ्या': 4, + 'न्तः': 3, + 'न्ता': 3, + 'न्ति': 3, + 'न्तो': 3, + 'न्तों': 3, + 'न्त्र': 3, + 'न्त्रा': 4, + 'न्त्राः': 5, + 'न्त्रि': 4, + 'न्त्री': 4, + 'न्त्र्य': 4, + 'न्त्र्यं': 4, + 'न्त्र्या': 5, + 'न्त्र्ये': 4, + 'न्दा': 3, + 'न्दी': 3, + 'न्दो': 3, + 'न्धा': 3, + 'न्धि': 3, + 'न्धी': 3, + 'न्धों': 3, + 'न्ना': 3, + 'न्नाः': 4, + 'न्नि': 3, + 'न्मा': 3, + 'न्या': 3, + 'न्यो': 3, + 'न्हा': 3, + 'न्ह्यां': 4, + 'प्ति': 3, + 'प्तौ': 3, + 'प्या': 3, + 'प्रा': 3, + 'फ्ता': 3, + 'फ्ना': 3, + 'फ्नो': 3, + 'फ्रां': 3, + 'ब्धि': 3, + 'भिः': 3, + 'भ्यः': 3, + 'भ्या': 3, + 'भ्यां': 3, + 'भ्यो': 3, + 'म्ति': 3, + 'म्नि': 3, + 'म्पा': 3, + 'म्प्र': 3, + 'म्भि': 3, + 'म्मा': 3, + 'म्मि': 3, + 'म्या': 3, + 'म्ही': 3, + 'म्हो': 3, + 'याः': 3, + 'य्यो': 3, + 'राः': 3, + 'र्कि': 3, + 'र्गी': 3, + 'र्चि': 3, + 'र्जा': 3, + 'र्जि': 3, + 'र्जी': 3, + 'र्णां': 3, + 'र्णी': 3, + 'र्ता': 3, + 'र्ति': 3, + 'र्तिः': 4, + 'र्ती': 3, + 'र्त्त': 3, + 'र्त्ति': 4, + 'र्थि': 3, + 'र्थी': 3, + 'र्दा': 3, + 'र्दि': 3, + 'र्दो': 3, + 'र्द्ध': 3, + 'र्धा': 3, + 'र्धि': 3, + 'र्नि': 3, + 'र्बा': 3, + 'र्भा': 3, + 'र्मा': 3, + 'र्मि': 3, + 'र्या': 3, + 'र्यां': 3, + 'र्यों': 3, + 'र्रा': 3, + 'र्वा': 3, + 'र्वां': 3, + 'र्वो': 3, + 'र्सा': 3, + 'र्हाः': 4, + 'र्हि': 3, + 'र्हो': 3, + 'र्‍या': 3, + 'लाः': 3, + 'ल्का': 3, + 'ल्पि': 3, + 'ल्या': 3, + 'ल्यां': 3, + 'ल्याः': 4, + 'ल्ला': 3, + 'ल्लि': 3, + 'वाः': 3, + 'व्या': 3, + 'व्यों': 3, + 'शाः': 3, + 'श्चि': 3, + 'श्या': 3, + 'श्यि': 3, + 'श्यों': 3, + 'श्रा': 3, + 'श्रां': 3, + 'श्वा': 3, + 'श्वि': 3, + 'षाः': 3, + 'ष्का': 3, + 'ष्टः': 3, + 'ष्टा': 3, + 'ष्टां': 3, + 'ष्टाः': 4, + 'ष्टि': 3, + 'ष्टी': 3, + 'ष्टीं': 3, + 'ष्ट्र': 3, + 'ष्ट्रा': 4, + 'ष्ट्रां': 4, + 'ष्ट्रि': 4, + 'ष्ट्री': 4, + 'ष्ट्रे': 3, + 'ष्ट्रो': 4, + 'ष्ट्रों': 4, + 'ष्ठा': 3, + 'ष्ठों': 3, + 'ष्प्र': 3, + 'ष्यः': 3, + 'ष्यों': 3, + 'स्का': 3, + 'स्काः': 4, + 'स्ट्या': 4, + 'स्ता': 3, + 'स्ति': 3, + 'स्ती': 3, + 'स्तो': 3, + 'स्त्र': 3, + 'स्त्रा': 4, + 'स्त्रि': 4, + 'स्त्री': 4, + 'स्था': 3, + 'स्थां': 3, + 'स्थि': 3, + 'स्थी': 3, + 'स्थ्य': 3, + 'स्धी': 3, + 'स्मि': 3, + 'स्मिं': 3, + 'स्या': 3, + 'स्यां': 3, + 'स्याः': 4, + 'स्युः': 3, + 'स्यों': 3, + 'स्रो': 3, + 'स्वा': 3, + 'स्वी': 3, + 'स्सा': 3, + 'ह्या': 3, + 'ह्रा': 3, + 'फ़्ता': 3, + 'কিং': 3, + 'ক্তি': 3, + 'ক্রী': 3, + 'ক্ষা': 3, + 'ক্ষি': 3, + 'ক্ষে': 3, + 'ক্ষ্য': 3, + 'ক্ষ্যে': 4, + 'খ্যা': 3, + 'গ্রা': 3, + 'গ্রে': 3, + 'ঘো': 3, + 'ঙ্খা': 3, + 'ঙ্গী': 3, + 'ঙ্গে': 3, + 'চ্ছা': 3, + 'চ্ছা‌': 3, + 'চ্ছে': 3, + 'জ্ঞা': 3, + 'ঞ্চি': 3, + 'ঞ্ছি': 3, + 'ট্রে': 3, + 'ণ্ডে': 3, + 'ত্তা': 3, + 'ত্তি': 3, + 'ত্বে': 3, + 'ত্যা': 3, + 'ত্যি': 3, + 'ত্যে': 3, + 'ত্রা': 3, + 'ত্রে': 3, + 'ত্‍পী': 3, + 'ত্‍সা': 3, + 'দ্দি': 3, + 'দ্দে': 3, + 'দ্ধা': 3, + 'দ্ধি': 3, + 'দ্ধে': 3, + 'দ্বা': 3, + 'দ্রো': 3, + 'ধ্যে': 3, + 'ন্তা': 3, + 'ন্তি': 3, + 'ন্তে': 3, + 'ন্ত্রি': 4, + 'ন্ত্রে': 4, + 'ন্থী': 3, + 'ন্ধা': 3, + 'ন্মা': 3, + 'ন্যা': 3, + 'ন্যে': 3, + 'প্তা': 3, + 'প্রা': 3, + 'ব্ধি': 3, + 'ব্যা': 3, + 'ভ্রা': 3, + 'ম্পা': 3, + 'ম্মা': 3, + 'রাং': 3, + 'র্জা': 3, + 'র্থে': 3, + 'র্দো': 3, + 'র্ধা': 3, + 'র্নী': 3, + 'র্বা': 3, + 'র্বি': 3, + 'র্বো': 3, + 'র্ব্য': 3, + 'র্মে': 3, + 'র্যা': 3, + 'ল্যা': 3, + 'ল্যে': 3, + 'ল্লে': 3, + 'শ্চি': 3, + 'শ্বা': 3, + 'শ্বে': 3, + 'শ্যে': 3, + 'শ্রা': 3, + 'ষ্টা': 3, + 'ষ্টি': 3, + 'ষ্ট্র': 3, + 'ষ্ট্রী': 4, + 'ষ্ট্রে': 4, + 'ষ্ঠা': 3, + 'ষ্ঠি': 3, + 'ষ্ঠী': 3, + 'সাং': 3, + 'স্তি': 3, + 'স্তি‌': 3, + 'স্ত্র': 3, + 'স্থা': 3, + 'স্থ্য': 3, + 'স্বা': 3, + 'স্বী': 3, + 'স্যা': 3, + 'স্যে': 3, + 'ક્કા': 3, + 'ક્કો': 3, + 'ક્તિ': 3, + 'ક્ષા': 3, + 'ચ્ચા': 3, + 'ચ્છા': 3, + 'જ્ઞા': 3, + 'જ્યો': 3, + 'ત્તા': 3, + 'ત્તિ': 3, + 'ત્ત્વ': 3, + 'ત્ત્વા': 4, + 'ત્યા': 3, + 'ત્યાં': 3, + 'ત્યિ': 3, + 'ત્યો': 3, + 'ત્રી': 3, + 'ત્ર્ય': 3, + 'દ્ધા': 3, + 'દ્ધાં': 3, + 'દ્ધિ': 3, + 'દ્વા': 3, + 'ધ્યા': 3, + 'ન્તો': 3, + 'ન્મા': 3, + 'ન્યા': 3, + 'પ્રા': 3, + 'મ્યાં': 3, + 'ર્તા': 3, + 'ર્થિ': 3, + 'ર્દો': 3, + 'ર્મિ': 3, + 'ર્યા': 3, + 'ર્યો': 3, + 'વ્યા': 3, + 'વ્યો': 3, + 'ષ્ટિ': 3, + 'ષ્ટ્ર': 3, + 'ષ્ટ્રી': 4, + 'ષ્ટ્રો': 4, + 'ષ્ઠા': 3, + 'સ્તિ': 3, + 'સ્તી': 3, + 'સ્ત્રી': 4, + 'સ્થા': 3, + 'સ્થિ': 3, + 'સ્રી': 3, + 'સ્વા': 3, + 'સ્વી': 3, + 'સ્સા': 3, + 'కుం': 3, + 'క్కు': 3, + 'క్తు': 3, + 'క్రాం': 3, + 'క్రూ': 3, + 'క్షిం': 3, + 'క్స్వా': 3, + 'చ్చు': 3, + 'టుం': 3, + 'ట్లు': 3, + 'డ్రు': 3, + 'త్తు': 3, + 'త్నిం': 3, + 'త్యం': 3, + 'త్రు': 3, + 'త్ర్య': 3, + 'దుం': 3, + 'ద్దు': 3, + 'ద్ధిం': 3, + 'ద్ర్య': 3, + 'నుం': 3, + 'న్ను': 3, + 'భ్యు': 3, + 'యుం': 3, + 'ర్చు': 3, + 'ర్ణాం': 3, + 'ర్ణు': 3, + 'ర్తిం': 3, + 'ర్తృ': 3, + 'ర్థిం': 3, + 'ర్బం': 3, + 'ర్హాం': 3, + 'ర్హు': 3, + 'శ్రాం': 3, + 'ష్టు': 3, + 'ష్ట్ర': 3, + 'ష్ట్రీ': 3, + 'ష్ఠు': 3, + 'స్కృ': 3, + 'స్త్ర': 3, + 'స్త్రీ': 3, + 'స్థ్య': 3, + 'ಕಾಂ': 3, + 'ಕುಂ': 3, + 'ಕೊಂ': 3, + 'ಖಾಂ': 3, + 'ಗಾಂ': 3, + 'ಗೊಂ': 3, + 'ಟುಂ': 3, + 'ನಾಂ': 3, + 'ಯುಂ': 3, + 'ರಾಂ': 3, + 'ವುಂ': 3, + 'ಶಾಂ': 3, + 'ಸಾಂ': 3, + 'ಹೊಂ': 3, + 'ക്കാ': 3, + 'ക്കി': 3, + 'ക്കും': 3, + 'ക്കെ': 3, + 'ക്കേ': 3, + 'ക്കൊ': 3, + 'ക്കോ': 3, + 'ക്തി': 3, + 'ക്യം': 3, + 'ക്ഷാ': 3, + 'ക്ഷി': 3, + 'ക്ഷേ': 3, + 'ഖ്യാ': 3, + 'ഗ്ഗം': 3, + 'ഗ്ദാ': 3, + 'ഗ്യം': 3, + 'ങ്കി': 3, + 'ങ്കെ': 3, + 'ങ്കേ': 3, + 'ങ്ങി': 3, + 'ച്ചി': 3, + 'ച്ചും': 3, + 'ച്ചെ': 3, + 'ച്ചേ': 3, + 'ജ്യാ': 3, + 'ഞ്ഞി': 3, + 'ഞ്ഞെ': 3, + 'ട്ടാ': 3, + 'ട്ടി': 3, + 'ട്ടോ': 3, + 'ണ്ടാ': 3, + 'ണ്ടി': 3, + 'ണ്ടും': 3, + 'ണ്ടെ': 3, + 'ത്താ': 3, + 'ത്തി': 3, + 'ത്തും': 3, + 'ത്തെ': 3, + 'ത്തേ': 3, + 'ത്തോ': 3, + 'ത്നം': 3, + 'ത്നി': 3, + 'ത്യാ': 3, + 'ത്യേ': 3, + 'ത്വം': 3, + 'ദ്ധി': 3, + 'ദ്യാ': 3, + 'ന്തം': 3, + 'ന്തെ': 3, + 'ന്ത്ര': 3, + 'ന്ത്ര്യ': 4, + 'ന്ത്ര്യം': 5, + 'ന്ധി': 3, + 'ന്നാ': 3, + 'ന്നി': 3, + 'ന്നീ': 3, + 'ന്നും': 3, + 'ന്നെ': 3, + 'ന്നേ': 3, + 'ന്നോ': 3, + 'ന്മാ': 3, + 'ന്യം': 3, + 'ന്യാ': 3, + 'ന്യേ': 3, + 'ന്യോ': 3, + 'ന്റെ': 3, + 'ന്‍പി': 3, + 'പ്പി': 3, + 'പ്പെ': 3, + 'പ്പോ': 3, + 'പ്രാ': 3, + 'ബ്ലി': 3, + 'ഭ്യാ': 3, + 'ഭ്രാ': 3, + 'മ്പാ': 3, + 'മ്പ്ര': 3, + 'മ്മി': 3, + 'യ്ക്കു': 3, + 'യ്തി': 3, + 'യ്യാ': 3, + 'യ്യി': 3, + 'ര്യം': 3, + 'ര്‍ക്കു': 3, + 'ര്‍ക്കും': 4, + 'ര്‍ക്ക്‌': 3, + 'ര്‍ഗ്ഗം': 4, + 'ര്‍ച്ച': 3, + 'ര്‍ണ്ണ': 3, + 'ര്‍ത്ത': 3, + 'ര്‍ത്തി': 4, + 'ര്‍ത്തു': 3, + 'ര്‍ത്തേ': 4, + 'ര്‍ദേ': 3, + 'ര്‍ദ്ദ': 3, + 'ര്‍പ്പെ': 4, + 'ര്‍മ്മി': 4, + 'ര്‍രാ': 3, + 'ര്‍വ്വ': 3, + 'ര്‍ഹി': 3, + 'റ്റം': 3, + 'റ്റേ': 3, + 'ല്യാ': 3, + 'ല്ലാ': 3, + 'ല്ലാം': 4, + 'ല്ലെ': 3, + 'ല്‍കി': 3, + 'ല്‍കേ': 3, + 'ല്‍നി': 3, + 'ല്‍പ്പ': 3, + 'ള്ളാ': 3, + 'ള്ളി': 3, + 'ള്‍കൊ': 3, + 'ള്‍ക്ക': 3, + 'ള്‍ക്കി': 4, + 'ള്‍ക്കു': 3, + 'ള്‍ക്കും': 4, + 'ള്‍ക്കെ': 4, + 'ള്‍ക്ക്‌': 3, + 'വ്യം': 3, + 'വ്യാ': 3, + 'ശ്വാ': 3, + 'ഷ്ട്യാ': 4, + 'ഷ്ട്ര': 3, + 'ഷ്ട്രീ': 4, + 'ഷ്യാ': 3, + 'സാം': 3, + 'സ്കാ': 3, + 'സ്ത്രം': 4, + 'സ്ത്രീ': 4, + 'സ്ഥാ': 3, + 'സ്ഥി': 3, + 'സ്റ്റ്‌': 3, + 'സ്വാ': 3, + 'സ്വീ': 3, + 'സ്സാ': 3, + 'സ്സി': 3, + 'സ്സും': 3, + 'സ്സോ': 3, + 'ഹിം': 3, + 'ൻ്റെ': 3, + 'ကျေ': 3, + 'ကြေ': 3, + 'ကြွေ': 3, + 'ချေ': 3, + 'ခြေ': 3, + 'ဇြေ': 3, + 'ဒ္ဂေ': 3, + 'ပျေ': 3, + 'ပြေ': 3, + 'ဖျေံ': 3, + 'ဗ္တေ': 3, + 'ဗ္ၜေ': 3, + 'ဗြေ': 3, + 'မြေ': 3, + 'လျေ': 3, + 'လျှေ': 3, + 'သ္ဂေ': 3, + 'ក្ដៅ': 3, + 'ក្រោ': 3, + 'ក្សា': 3, + 'ខ្ជា': 3, + 'ខ្លា': 3, + 'គ្នា': 3, + 'គ្មា': 3, + 'គ្រា': 3, + 'គ្រឹះ': 3, + 'ង្កើ': 3, + 'ង្រៀ': 3, + 'ង្ហា': 3, + 'ច្ចេ': 3, + 'ច្បា': 3, + 'ឆ្នាំ': 3, + 'ឆ្នោ': 3, + 'ឆ្លើ': 3, + 'ជ្ជា': 3, + 'ជ្ញា': 3, + 'ជ្រើ': 3, + 'ជ្រៀ': 3, + 'ជ្រែ': 3, + 'ឈ្មោះ': 4, + 'ញ្ជា': 3, + 'ញ្ញា': 3, + 'ញ្ញៈ': 3, + 'ដ្ឋា': 3, + 'ណោះ': 3, + 'ណ្ដា': 3, + 'ណ្ដុះ': 3, + 'ណ្ណោះ': 4, + 'ត្រា': 3, + 'ថ្ងៃ': 3, + 'ថ្នា': 3, + 'ថ្លៃ': 3, + 'ទោះ': 3, + 'ទ្យា': 3, + 'ធ្នា': 3, + 'ធ្យា': 3, + 'ធ្យោ': 3, + 'ធ្វើ': 3, + 'នេះ': 3, + 'នោះ': 3, + 'ន្ថែ': 3, + 'ន្ថោ': 3, + 'ន្ទា': 3, + 'ន្ទៈ': 3, + 'ន្យា': 3, + 'ន្លែ': 3, + 'បោះ': 3, + 'ប្ដេ': 3, + 'ប្រា': 3, + 'ប្រើ': 3, + 'ប្រែ': 3, + 'ផ្ដា': 3, + 'ផ្ទា': 3, + 'ផ្ទេ': 3, + 'ផ្នែ': 3, + 'ផ្លា': 3, + 'ផ្សា': 3, + 'ផ្សេ': 3, + 'ផ្សៃ': 3, + 'ពោះ': 3, + 'ព្យា': 3, + 'ព្រៀ': 3, + 'ព្រៃ': 3, + 'ម្ងា': 3, + 'ម្ចា': 3, + 'ម្ដា': 3, + 'ម្ដែ': 3, + 'ម្នា': 3, + 'ម្នេ': 3, + 'ម្ភា': 3, + 'ម្រា': 3, + 'ម្រើ': 3, + 'ម្រេ': 3, + 'ម្លៀ': 3, + 'ម្លៃ': 3, + 'ល្បៈ': 3, + 'ល្មើ': 3, + 'ស្គា': 3, + 'ស្ដ្រី': 3, + 'ស្ត្រ': 3, + 'ស្ថា': 3, + 'ស្នា': 3, + 'ស្មា': 3, + 'ស្មើ': 3, + 'ស្រា': 3, + 'ស្លា': 3, + 'ស្វែ': 3, + 'ᨠᩮ᩠ᨯᩨ': 3, + 'ᨠᩯ᩠ᨯ': 3, + 'ᨠᩯ᩠ᨶ᩵': 3, + 'ᨡᩮ᩠ᨲ': 3, + 'ᨡᩯ᩠ᨠ': 3, + 'ᨡᩯ᩠ᨦ': 3, + 'ᨣᩕ᩠ᩋ': 3, + 'ᨣᩕᩮ᩠ᨦᩨ᩵': 4, + 'ᨣᩯ᩠ᨶᩢ': 3, + 'ᨣᩯ᩠ᩅ': 3, + 'ᨧᩮ᩠ᨷ': 3, + 'ᨧᩱ᩠ᨿ': 3, + 'ᨩᩮ᩠ᩋᩨ': 3, + 'ᨩᩮ᩠ᩋᩨ᩵': 3, + 'ᨩᩮ᩠ᩋᩨ᩶': 3, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 3, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 3, + 'ᨯᩯ᩠ᨦ': 3, + 'ᨯᩯ᩠ᨶ': 3, + 'ᨯᩰ᩠ᨿ': 3, + 'ᨲᩮ᩠ᨠ': 3, + 'ᨲᩮ᩠ᨦ': 3, + 'ᨲᩮ᩠ᨾ': 3, + 'ᨲᩮ᩠ᨾᩨ᩵': 3, + 'ᨲᩯ᩠ᨠ': 3, + 'ᨲᩯ᩠ᨦ᩵': 3, + 'ᨲᩯ᩠ᨾᩢ': 3, + 'ᨲᩱ᩠ᨿ': 3, + 'ᨳᩮ᩠ᨶᩨ᩵': 3, + 'ᨳᩯ᩠ᨦᩢ': 3, + 'ᨳᩯ᩠ᨾ': 3, + 'ᨴᩮ᩠ᩈ': 3, + 'ᨴᩮ᩠ᩈᩱ': 4, + 'ᨴᩯ᩠ᨶ': 3, + 'ᨴᩰ᩠ᩈ': 3, + 'ᨶᩯ᩠ᨶ': 3, + 'ᨷᩮ᩠ᨦᩨ᩶': 3, + 'ᨸᩮ᩠ᨦᩨ': 3, + 'ᨸᩮ᩠ᨶ': 3, + 'ᨹᩮᩨ᩠ᨿ': 3, + 'ᨻᩕ᩠ᩋᩢ': 3, + 'ᨻᩮ᩠ᩋᩨ᩵': 3, + 'ᨽᩱ᩠ᨿ': 3, + 'ᨾᩮ᩠ᨠᩨ': 3, + 'ᨾᩮ᩠ᨦᩨ': 3, + 'ᨾᩮ᩠ᩋᩨ᩵': 3, + 'ᨿᩮ᩠ᨶ': 3, + 'ᨿᩮ᩠ᨾᩨ': 3, + 'ᩁᩮ᩠ᨦᩨ᩵': 3, + 'ᩁᩮ᩠ᨧ': 3, + 'ᩁᩮ᩠ᨶᩨ': 3, + 'ᩁᩮᩨ᩠ᨬ': 3, + 'ᩁᩯ᩠ᨦ': 3, + 'ᩃᩮ᩠ᨠᩨ': 3, + 'ᩃᩮ᩠ᨦᩨ': 3, + 'ᩃᩰ᩠ᨠ': 3, + 'ᩅᩮ᩠ᨶ': 3, + 'ᩅᩮ᩠ᨶᩢ': 3, + 'ᩈᩮ᩠ᩈ': 3, + 'ᩈᩯ᩠ᩅ': 3, + 'ᩈᩱ᩠ᨿ': 3, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 3, + 'ᩉᩮ᩠ᨦᩢᩢ': 3, + 'ᩉᩮ᩠ᨯ': 3, + 'ᩉᩮ᩠ᨲᩩ': 3, + 'ᩉᩮ᩠ᨶᩨ': 3, + 'ᩉᩮ᩠ᨾᩨ': 3, + 'ᩉᩮ᩠ᨾᩨᩨ': 3, + 'ᩉᩯ᩠ᨦ᩵': 3, + 'ᩉᩯ᩠ᨶᩢ': 3, + 'ᩉᩯ᩠ᨾ': 3, + 'ᩉᩱ᩠ᨾ᩵': 3, + 'ᩉᩱ᩠ᨿ᩵': 3, + 'ᩣ᩠ᨲᩱ': 3, + 'ꦏꦺꦴ': 3, + 'ꦏ꧀': 2, + 'ꦏ꧀ꦏ': 3, + 'ꦏ꧀ꦏꦁ': 3, + 'ꦏ꧀ꦏꦺ': 4, + 'ꦏ꧀ꦏꦼ': 3, + 'ꦏ꧀ꦔ': 3, + 'ꦏ꧀ꦔꦸ': 3, + 'ꦏ꧀ꦔꦿ': 4, + 'ꦏ꧀ꦕ': 3, + 'ꦏ꧀ꦠ': 3, + 'ꦏ꧀ꦠꦶ': 3, + 'ꦏ꧀ꦠꦸ': 3, + 'ꦏ꧀ꦠꦺ': 4, + 'ꦏ꧀ꦢ': 3, + 'ꦏ꧀ꦢꦂ': 3, + 'ꦏ꧀ꦢꦶ': 3, + 'ꦏ꧀ꦤ': 3, + 'ꦏ꧀ꦤꦶꦁ': 3, + 'ꦏ꧀ꦥ': 3, + 'ꦏ꧀ꦥꦶ': 3, + 'ꦏ꧀ꦥꦿꦶ': 4, + 'ꦏ꧀ꦧ': 3, + 'ꦏ꧀ꦧꦶ': 3, + 'ꦏ꧀ꦧꦺ': 4, + 'ꦏ꧀ꦩ': 3, + 'ꦏ꧀ꦩꦸ': 3, + 'ꦏ꧀ꦪ': 3, + 'ꦏ꧀ꦭ': 3, + 'ꦏ꧀ꦮ': 3, + 'ꦏ꧀ꦱ': 3, + 'ꦏ꧀ꦱꦂ': 3, + 'ꦏ꧀ꦱꦶ': 3, + 'ꦏ꧀ꦱꦸ': 3, + 'ꦏ꧀ꦱꦺ': 4, + 'ꦏ꧀ꦲ': 3, + 'ꦏ꧀ꦲꦁ': 3, + 'ꦏ꧀ꦲꦶꦁ': 3, + 'ꦏ꧀ꦲꦸ': 3, + 'ꦏ꧀ꦲꦺ': 4, + 'ꦏ꧀ꦲꦺꦴ': 5, + 'ꦒꦺꦴ': 3, + 'ꦒꦿꦺ': 3, + 'ꦒ꧀ꦒ': 3, + 'ꦔꦺꦴ': 3, + 'ꦔ꧀ꦒꦼ': 3, + 'ꦔ꧀ꦒꦿꦼꦁ': 4, + 'ꦔ꧀ꦭ': 3, + 'ꦔ꧀ꦭꦁ': 3, + 'ꦔ꧀ꦭꦸ': 3, + 'ꦔ꧀ꦭꦼ': 3, + 'ꦕꦺꦴ': 3, + 'ꦗꦿꦺꦴ': 4, + 'ꦚ꧀ꦕ': 3, + 'ꦚ꧀ꦕꦶ': 3, + 'ꦚ꧀ꦗ': 3, + 'ꦚ꧀ꦗꦶ': 3, + 'ꦚ꧀ꦗꦸꦁ': 3, + 'ꦚ꧀ꦗꦸꦂ': 3, + 'ꦝꦺꦴ': 3, + 'ꦝꦺꦴꦂ': 3, + 'ꦠꦺꦃ': 3, + 'ꦠꦺꦴ': 3, + 'ꦠ꧀': 2, + 'ꦠ꧀ꦏꦁ': 3, + 'ꦠ꧀ꦏꦸ': 3, + 'ꦠ꧀ꦒ': 3, + 'ꦠ꧀ꦔꦸ': 3, + 'ꦠ꧀ꦚ': 3, + 'ꦠ꧀ꦠ': 3, + 'ꦠ꧀ꦠꦶ': 3, + 'ꦠ꧀ꦠꦶꦁ': 3, + 'ꦠ꧀ꦠꦸ': 3, + 'ꦠ꧀ꦠꦺ': 4, + 'ꦠ꧀ꦤ': 3, + 'ꦠ꧀ꦤꦶ': 3, + 'ꦠ꧀ꦩ': 3, + 'ꦠ꧀ꦩꦼ': 3, + 'ꦠ꧀ꦭ': 3, + 'ꦠ꧀ꦭꦺ': 4, + 'ꦠ꧀ꦱ': 3, + 'ꦠ꧀ꦱꦶꦁ': 3, + 'ꦠ꧀ꦱꦶꦃ': 4, + 'ꦠ꧀ꦱꦾ': 4, + 'ꦠ꧀ꦱ꧀ꦮ': 5, + 'ꦠ꧀ꦲ': 3, + 'ꦠ꧀ꦲꦶꦁ': 3, + 'ꦠ꧀ꦲꦺꦴ': 5, + 'ꦢꦺꦴ': 3, + 'ꦢ꧀': 2, + 'ꦢ꧀ꦏ': 3, + 'ꦢ꧀ꦠ': 3, + 'ꦢ꧀ꦠꦶꦁ': 3, + 'ꦢ꧀ꦢ': 3, + 'ꦢ꧀ꦥ': 3, + 'ꦢ꧀ꦩꦺꦴ': 5, + 'ꦢ꧀ꦲ': 3, + 'ꦤꦺꦃ': 3, + 'ꦤꦺꦴ': 3, + 'ꦤ꧀': 2, + 'ꦤ꧀ꦏ': 3, + 'ꦤ꧀ꦏꦁ': 3, + 'ꦤ꧀ꦏꦸ': 3, + 'ꦤ꧀ꦏꦼ': 3, + 'ꦤ꧀ꦒ': 3, + 'ꦤ꧀ꦔ': 3, + 'ꦤ꧀ꦔꦁ': 3, + 'ꦤ꧀ꦔꦶ': 3, + 'ꦤ꧀ꦔꦸ': 3, + 'ꦤ꧀ꦔꦸꦂ': 3, + 'ꦤ꧀ꦔꦺ': 4, + 'ꦤ꧀ꦔꦼ': 3, + 'ꦤ꧀ꦔꦿꦸ': 4, + 'ꦤ꧀ꦗ': 3, + 'ꦤ꧀ꦗꦸ': 3, + 'ꦤ꧀ꦗꦼ': 3, + 'ꦤ꧀ꦚꦶ': 3, + 'ꦤ꧀ꦛꦃ': 4, + 'ꦤ꧀ꦛꦶ': 3, + 'ꦤ꧀ꦝ': 3, + 'ꦤ꧀ꦝꦁ': 3, + 'ꦤ꧀ꦝꦶ': 3, + 'ꦤ꧀ꦝꦸ': 3, + 'ꦤ꧀ꦝꦸꦁ': 3, + 'ꦤ꧀ꦝꦺꦁ': 4, + 'ꦤ꧀ꦝꦺꦴꦁ': 5, + 'ꦤ꧀ꦝꦼ': 3, + 'ꦤ꧀ꦠ': 3, + 'ꦤ꧀ꦠꦂ': 3, + 'ꦤ꧀ꦠꦃ': 4, + 'ꦤ꧀ꦠꦶ': 3, + 'ꦤ꧀ꦠꦸ': 3, + 'ꦤ꧀ꦠꦸꦁ': 3, + 'ꦤ꧀ꦠꦺ': 4, + 'ꦤ꧀ꦠꦼ': 3, + 'ꦤ꧀ꦠꦼꦂ': 3, + 'ꦤ꧀ꦠꦽ': 3, + 'ꦤ꧀ꦢ': 3, + 'ꦤ꧀ꦢꦁ': 3, + 'ꦤ꧀ꦢꦂ': 3, + 'ꦤ꧀ꦢꦶ': 3, + 'ꦤ꧀ꦢꦸ': 3, + 'ꦤ꧀ꦢꦺ': 4, + 'ꦤ꧀ꦢꦼ': 3, + 'ꦤ꧀ꦤ': 3, + 'ꦤ꧀ꦤꦶ': 3, + 'ꦤ꧀ꦤꦶꦁ': 3, + 'ꦤ꧀ꦤꦺ': 4, + 'ꦤ꧀ꦤꦼ': 3, + 'ꦤ꧀ꦥ': 3, + 'ꦤ꧀ꦥꦁ': 3, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 5, + 'ꦤ꧀ꦥꦶ': 3, + 'ꦤ꧀ꦥꦸ': 3, + 'ꦤ꧀ꦥꦼ': 3, + 'ꦤ꧀ꦥꦿ': 4, + 'ꦤ꧀ꦥꦿꦶ': 4, + 'ꦤ꧀ꦧ': 3, + 'ꦤ꧀ꦧꦁ': 3, + 'ꦤ꧀ꦧꦶ': 3, + 'ꦤ꧀ꦧꦸ': 3, + 'ꦤ꧀ꦧꦺ': 4, + 'ꦤ꧀ꦧꦺꦴ': 5, + 'ꦤ꧀ꦧꦼ': 3, + 'ꦤ꧀ꦩ': 3, + 'ꦤ꧀ꦩꦂ': 3, + 'ꦤ꧀ꦩꦶ': 3, + 'ꦤ꧀ꦩꦸꦂ': 3, + 'ꦤ꧀ꦩꦼ': 3, + 'ꦤ꧀ꦭ': 3, + 'ꦤ꧀ꦭꦶ': 3, + 'ꦤ꧀ꦭꦸ': 3, + 'ꦤ꧀ꦮ': 3, + 'ꦤ꧀ꦮꦂ': 3, + 'ꦤ꧀ꦮꦶ': 3, + 'ꦤ꧀ꦮꦸ': 3, + 'ꦤ꧀ꦮꦼ': 3, + 'ꦤ꧀ꦱ': 3, + 'ꦤ꧀ꦱꦂ': 3, + 'ꦤ꧀ꦱꦃ': 4, + 'ꦤ꧀ꦱꦶ': 3, + 'ꦤ꧀ꦱꦶꦁ': 3, + 'ꦤ꧀ꦱꦸ': 3, + 'ꦤ꧀ꦱꦺꦴ': 5, + 'ꦤ꧀ꦱꦼ': 3, + 'ꦤ꧀ꦲ': 3, + 'ꦤ꧀ꦲꦁ': 3, + 'ꦤ꧀ꦲꦶ': 3, + 'ꦤ꧀ꦲꦶꦁ': 3, + 'ꦤ꧀ꦲꦸ': 3, + 'ꦤ꧀ꦲꦺꦴ': 5, + 'ꦥ꦳꧀': 2, + 'ꦥꦺꦴ': 3, + 'ꦥꦿꦃ': 3, + 'ꦥꦿꦺꦴ': 4, + 'ꦥ꧀': 2, + 'ꦥ꧀ꦏ': 3, + 'ꦥ꧀ꦏꦁ': 3, + 'ꦥ꧀ꦠ': 3, + 'ꦥ꧀ꦠꦶ': 3, + 'ꦥ꧀ꦢꦸ': 3, + 'ꦥ꧀ꦤ': 3, + 'ꦥ꧀ꦤꦶ': 3, + 'ꦥ꧀ꦥ': 3, + 'ꦥ꧀ꦥꦶ': 3, + 'ꦥ꧀ꦥꦺ': 4, + 'ꦥ꧀ꦧꦺ': 4, + 'ꦥ꧀ꦩ': 3, + 'ꦥ꧀ꦩꦂ': 3, + 'ꦥ꧀ꦫꦺ': 4, + 'ꦥ꧀ꦭ': 3, + 'ꦥ꧀ꦭꦸ': 3, + 'ꦥ꧀ꦱ': 3, + 'ꦥ꧀ꦱꦶꦂ': 3, + 'ꦥ꧀ꦱꦼ': 3, + 'ꦥ꧀ꦲ': 3, + 'ꦧꦺꦃ': 3, + 'ꦧꦺꦴ': 3, + 'ꦧ꧀': 2, + 'ꦧ꧀ꦏ': 3, + 'ꦧ꧀ꦠꦸ': 3, + 'ꦧ꧀ꦥ': 3, + 'ꦧ꧀ꦧ': 3, + 'ꦧ꧀ꦧꦺ': 4, + 'ꦧ꧀ꦲ': 3, + 'ꦧ꧀ꦲꦶ': 3, + 'ꦩꦺꦃ': 3, + 'ꦩꦺꦴ': 3, + 'ꦩꦿꦃ': 3, + 'ꦩꦿꦶꦃ': 3, + 'ꦩ꧀': 2, + 'ꦩ꧀ꦏꦁ': 3, + 'ꦩ꧀ꦔꦼ': 3, + 'ꦩ꧀ꦠꦸ': 3, + 'ꦩ꧀ꦠꦺꦴ': 5, + 'ꦩ꧀ꦤꦶꦁ': 3, + 'ꦩ꧀ꦥ': 3, + 'ꦩ꧀ꦥꦶ': 3, + 'ꦩ꧀ꦥꦸ': 3, + 'ꦩ꧀ꦥꦼ': 3, + 'ꦩ꧀ꦧ': 3, + 'ꦩ꧀ꦧꦁ': 3, + 'ꦩ꧀ꦧꦂ': 3, + 'ꦩ꧀ꦧꦃ': 4, + 'ꦩ꧀ꦧꦶ': 3, + 'ꦩ꧀ꦧꦸ': 3, + 'ꦩ꧀ꦧꦸꦁ': 3, + 'ꦩ꧀ꦧꦺ': 4, + 'ꦩ꧀ꦧꦺꦂ': 4, + 'ꦩ꧀ꦧꦼꦂ': 3, + 'ꦩ꧀ꦧꦾꦸꦂ': 4, + 'ꦩ꧀ꦩ': 3, + 'ꦩ꧀ꦩꦶ': 3, + 'ꦩ꧀ꦫ': 3, + 'ꦩ꧀ꦫꦃ': 4, + 'ꦩ꧀ꦭ': 3, + 'ꦩ꧀ꦲꦶ': 3, + 'ꦪꦺꦴ': 3, + 'ꦫꦺꦴ': 3, + 'ꦭꦺꦃ': 3, + 'ꦭꦺꦴ': 3, + 'ꦭꦺꦴꦁ': 3, + 'ꦭ꧀': 2, + 'ꦭ꧀ꦏꦁ': 3, + 'ꦭ꧀ꦚꦼꦁ': 3, + 'ꦭ꧀ꦠꦸ': 3, + 'ꦭ꧀ꦧꦸ': 3, + 'ꦭ꧀ꦩꦸ': 3, + 'ꦭ꧀ꦭ': 3, + 'ꦭ꧀ꦭꦶ': 3, + 'ꦭ꧀ꦭꦶꦁ': 3, + 'ꦭ꧀ꦭꦺ': 4, + 'ꦭ꧀ꦮ': 3, + 'ꦭ꧀ꦱ': 3, + 'ꦭ꧀ꦱꦂ': 3, + 'ꦭ꧀ꦱꦶꦁ': 3, + 'ꦭ꧀ꦱꦸ': 3, + 'ꦭ꧀ꦲ': 3, + 'ꦭ꧀ꦲꦁ': 3, + 'ꦭ꧀ꦲꦶꦁ': 3, + 'ꦭ꧀ꦲꦸ': 3, + 'ꦮꦺꦴ': 3, + 'ꦮꦺꦴꦁ': 3, + 'ꦮꦺꦴꦃ': 4, + 'ꦮꦿꦸꦃ': 3, + 'ꦱꦺꦴ': 3, + 'ꦱꦿꦃ': 3, + 'ꦱ꧀': 2, + 'ꦱ꧀ꦏ': 3, + 'ꦱ꧀ꦏꦁ': 3, + 'ꦱ꧀ꦏꦿꦶ': 4, + 'ꦱ꧀ꦒ': 3, + 'ꦱ꧀ꦔꦸ': 3, + 'ꦱ꧀ꦔꦿ': 4, + 'ꦱ꧀ꦛꦶ': 3, + 'ꦱ꧀ꦠ': 3, + 'ꦱ꧀ꦠꦿ': 4, + 'ꦱ꧀ꦢꦂ': 3, + 'ꦱ꧀ꦢꦶ': 3, + 'ꦱ꧀ꦢꦸ': 3, + 'ꦱ꧀ꦥ': 3, + 'ꦱ꧀ꦧ': 3, + 'ꦱ꧀ꦧꦁ': 3, + 'ꦱ꧀ꦩ': 3, + 'ꦱ꧀ꦩꦶ': 3, + 'ꦱ꧀ꦩꦼ': 3, + 'ꦱ꧀ꦩꦿ': 4, + 'ꦱ꧀ꦭ': 3, + 'ꦱ꧀ꦮ': 3, + 'ꦱ꧀ꦱ': 3, + 'ꦱ꧀ꦱꦂ': 3, + 'ꦱ꧀ꦱꦶ': 3, + 'ꦱ꧀ꦱꦶꦁ': 3, + 'ꦱ꧀ꦱꦸ': 3, + 'ꦱ꧀ꦱꦺ': 4, + 'ꦱ꧀ꦲ': 3, + 'ꦱ꧀ꦲꦁ': 3, + 'ꦱ꧀ꦲꦶ': 3, + 'ꦱ꧀ꦲꦶꦁ': 3, + 'ꦱ꧀ꦲꦸ': 3, + 'ꦲꦺꦴ': 3, + '𑄇𑄳𑄠𑄬': 3, + '𑄈𑄳𑄠𑄬': 3, + '𑄌𑄳𑄠𑄬': 3, + '𑄎𑄳𑄠𑄬': 3, + '𑄑𑄳𑄢𑄬': 3, + '𑄖𑄳𑄠𑄬': 3, + '𑄖𑄳𑄢𑄬': 3, + '𑄘𑄳𑄠𑄬': 3, + '𑄚𑄳𑄠𑄬': 3, + '𑄝𑄳𑄢𑄬': 3, + '𑄟𑄳𑄠𑄬': 3, + '𑄡𑄳𑄠𑄬': 3, + '𑄣𑄳𑄦𑄬': 3, + '𑌕𑌾𑌂': 3, + '𑌕𑌾𑌃': 3, + '𑌕𑍍': 2, + '𑌗𑍍': 2, + '𑌚𑍍': 2, + '𑌜𑍍': 2, + '𑌞𑍍': 2, + '𑌟𑌾𑌂': 3, + '𑌟𑌾𑌃': 3, + '𑌟𑍍': 2, + '𑌠𑍈𑌃': 3, + '𑌣𑌾𑌂': 3, + '𑌣𑍍': 2, + '𑌤𑌾𑌂': 3, + '𑌤𑌾𑌃': 3, + '𑌤𑌿𑌂': 3, + '𑌤𑌿𑌃': 3, + '𑌤𑍁𑌂': 3, + '𑌤𑍇𑌃': 3, + '𑌤𑍍': 2, + '𑌥𑌾𑌂': 3, + '𑌦𑍍': 2, + '𑌧𑌾𑌃': 3, + '𑌧𑌿𑌂': 3, + '𑌧𑍇𑌃': 3, + '𑌧𑍈𑌃': 3, + '𑌧𑍍': 2, + '𑌨𑌾𑌂': 3, + '𑌨𑌾𑌃': 3, + '𑌨𑌿𑌃': 3, + '𑌨𑍈𑌃': 3, + '𑌨𑍍': 2, + '𑌪𑍍': 2, + '𑌬𑍍': 2, + '𑌭𑌿𑌃': 3, + '𑌭𑍍': 2, + '𑌮𑌿𑌂': 3, + '𑌮𑍍': 2, + '𑌯𑌾𑌂': 3, + '𑌯𑌾𑌃': 3, + '𑌯𑍁𑌃': 3, + '𑌯𑍈𑌃': 3, + '𑌯𑍋𑌃': 3, + '𑌯𑍍': 2, + '𑌰𑌾𑌃': 3, + '𑌰𑌿𑌂': 3, + '𑌰𑍍': 2, + '𑌲𑌾𑌃': 3, + '𑌲𑌿𑌂': 3, + '𑌲𑍍': 2, + '𑌵𑌾𑌂': 3, + '𑌵𑌾𑌃': 3, + '𑌵𑍍': 2, + '𑌶𑌾𑌃': 3, + '𑌶𑍍': 2, + '𑌷𑌾𑌂': 3, + '𑌷𑌾𑌃': 3, + '𑌷𑍍': 2, + '𑌸𑌾𑌂': 3, + '𑌸𑍍': 2, + '𑌹𑌾𑌃': 3, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_59180a0d.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_59180a0d.py new file mode 100644 index 0000000000000000000000000000000000000000..06da76a827514bbaa3ae64dff9786ba3e0a9c7b6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_59180a0d.py @@ -0,0 +1,2669 @@ +""" +Grapheme overrides for _known_59180a0d. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: iterm2 +""" +# pylint: skip-file +GRAPHEMES = { + 'क्का': 3, + 'क्कां': 3, + 'क्को': 3, + 'क्घ्घि्': 4, + 'क्ता': 3, + 'क्ति': 3, + 'क्ती': 3, + 'क्तीं': 3, + 'क्तेः': 3, + 'क्त्योः': 5, + 'क्ना': 3, + 'क्नि': 3, + 'क्या': 3, + 'क्रा': 3, + 'क्रि': 3, + 'क्षा': 3, + 'क्षां': 3, + 'क्षाः': 4, + 'क्षि': 3, + 'क्षो': 3, + 'क्ष्ण': 3, + 'क्ष्य': 3, + 'क्ष्या': 4, + 'क्सा': 3, + 'ख्यः': 3, + 'ख्या': 3, + 'ख्‍ने': 1, + 'ग्या': 3, + 'ग्यैः': 3, + 'ग्र्य': 3, + 'घ्का': 3, + 'घ्र्व्य': 4, + 'घ्लि': 3, + 'घ्श्य': 3, + 'घ्स्ट': 3, + 'च्चा': 3, + 'च्चों': 3, + 'च्छा': 3, + 'च्छि': 3, + 'च्या': 3, + 'च्यां': 3, + 'च्यो': 3, + 'ज्ञा': 3, + 'ज्या': 3, + 'ज्या‌': 3, + 'ज्रा': 3, + 'ञ्चा': 3, + 'ञ्चि': 3, + 'ट्टि': 3, + 'ट्टी': 3, + 'ट्या': 3, + 'ट्रा': 3, + 'ण्डः': 3, + 'ण्डि': 3, + 'ण्या': 3, + 'ण्यां': 3, + 'ताः': 3, + 'त्का': 3, + 'त्ता': 3, + 'त्ति': 3, + 'त्त्थि': 4, + 'त्त्व': 3, + 'त्त्वा': 4, + 'त्त्वे': 3, + 'त्नी': 3, + 'त्नों': 3, + 'त्पा': 3, + 'त्पी': 3, + 'त्मा': 3, + 'त्या': 3, + 'त्यां': 3, + 'त्यि': 3, + 'त्रा': 3, + 'त्राा': 4, + 'त्राि': 4, + 'त्रि': 3, + 'त्री': 3, + 'त्र्त': 3, + 'त्र्य': 3, + 'त्र्या': 4, + 'त्र्ये': 3, + 'त्वा': 3, + 'त्वां': 3, + 'त्सा': 3, + 'त्सो': 3, + 'त्स्वा': 4, + 'द्घि': 3, + 'द्घो': 3, + 'द्दा': 3, + 'द्दि': 3, + 'द्दी': 3, + 'द्धः': 3, + 'द्धा': 3, + 'द्धां': 3, + 'द्धि': 3, + 'द्धिं': 3, + 'द्धी': 3, + 'द्धीं': 3, + 'द्धैः': 3, + 'द्भा': 3, + 'द्या': 3, + 'द्रो': 3, + 'द्वा': 3, + 'द्वि': 3, + 'धाः': 3, + 'ध्या': 3, + 'नाः': 3, + 'निः': 3, + 'न्का': 3, + 'न्चि': 3, + 'न्ञ्या': 4, + 'न्तः': 3, + 'न्ता': 3, + 'न्ति': 3, + 'न्तो': 3, + 'न्तों': 3, + 'न्त्र': 3, + 'न्त्रा': 4, + 'न्त्राः': 5, + 'न्त्रि': 4, + 'न्त्री': 4, + 'न्त्र्य': 4, + 'न्त्र्यं': 4, + 'न्त्र्या': 5, + 'न्त्र्ये': 4, + 'न्दा': 3, + 'न्दी': 3, + 'न्दो': 3, + 'न्धा': 3, + 'न्धि': 3, + 'न्धी': 3, + 'न्धों': 3, + 'न्ना': 3, + 'न्नाः': 4, + 'न्नि': 3, + 'न्मा': 3, + 'न्या': 3, + 'न्यो': 3, + 'न्हा': 3, + 'न्ह्यां': 4, + 'प्ति': 3, + 'प्तौ': 3, + 'प्या': 3, + 'प्रा': 3, + 'फ्ता': 3, + 'फ्ना': 3, + 'फ्नो': 3, + 'फ्रां': 3, + 'ब्धि': 3, + 'भिः': 3, + 'भ्यः': 3, + 'भ्या': 3, + 'भ्यां': 3, + 'भ्यो': 3, + 'म्ति': 3, + 'म्नि': 3, + 'म्पा': 3, + 'म्प्र': 3, + 'म्भि': 3, + 'म्मा': 3, + 'म्मि': 3, + 'म्या': 3, + 'म्ही': 3, + 'म्हो': 3, + 'याः': 3, + 'य्यो': 3, + 'राः': 3, + 'र्कि': 3, + 'र्गी': 3, + 'र्चि': 3, + 'र्जा': 3, + 'र्जि': 3, + 'र्जी': 3, + 'र्णां': 3, + 'र्णी': 3, + 'र्ता': 3, + 'र्ति': 3, + 'र्तिः': 4, + 'र्ती': 3, + 'र्त्त': 3, + 'र्त्ति': 4, + 'र्थि': 3, + 'र्थी': 3, + 'र्दा': 3, + 'र्दि': 3, + 'र्दो': 3, + 'र्द्ध': 3, + 'र्धा': 3, + 'र्धि': 3, + 'र्नि': 3, + 'र्बा': 3, + 'र्भा': 3, + 'र्मा': 3, + 'र्मि': 3, + 'र्या': 3, + 'र्यां': 3, + 'र्यों': 3, + 'र्रा': 3, + 'र्वा': 3, + 'र्वां': 3, + 'र्वो': 3, + 'र्सा': 3, + 'र्हाः': 4, + 'र्हि': 3, + 'र्हो': 3, + 'र्‍या': 1, + 'लाः': 3, + 'ल्का': 3, + 'ल्पि': 3, + 'ल्या': 3, + 'ल्यां': 3, + 'ल्याः': 4, + 'ल्ला': 3, + 'ल्लि': 3, + 'वाः': 3, + 'व्या': 3, + 'व्यों': 3, + 'शाः': 3, + 'श्चि': 3, + 'श्या': 3, + 'श्यि': 3, + 'श्यों': 3, + 'श्रा': 3, + 'श्रां': 3, + 'श्वा': 3, + 'श्वि': 3, + 'षाः': 3, + 'ष्का': 3, + 'ष्टः': 3, + 'ष्टा': 3, + 'ष्टां': 3, + 'ष्टाः': 4, + 'ष्टि': 3, + 'ष्टी': 3, + 'ष्टीं': 3, + 'ष्ट्र': 3, + 'ष्ट्रा': 4, + 'ष्ट्रां': 4, + 'ष्ट्रि': 4, + 'ष्ट्री': 4, + 'ष्ट्रे': 3, + 'ष्ट्रो': 4, + 'ष्ट्रों': 4, + 'ष्ठा': 3, + 'ष्ठों': 3, + 'ष्प्र': 3, + 'ष्यः': 3, + 'ष्यों': 3, + 'स्का': 3, + 'स्काः': 4, + 'स्ट्या': 4, + 'स्ता': 3, + 'स्ति': 3, + 'स्ती': 3, + 'स्तो': 3, + 'स्त्र': 3, + 'स्त्रा': 4, + 'स्त्रि': 4, + 'स्त्री': 4, + 'स्था': 3, + 'स्थां': 3, + 'स्थि': 3, + 'स्थी': 3, + 'स्थ्य': 3, + 'स्धी': 3, + 'स्मि': 3, + 'स्मिं': 3, + 'स्या': 3, + 'स्यां': 3, + 'स्याः': 4, + 'स्युः': 3, + 'स्यों': 3, + 'स्रो': 3, + 'स्वा': 3, + 'स्वी': 3, + 'स्सा': 3, + 'ह्या': 3, + 'ह्रा': 3, + 'फ़्ता': 3, + 'কিং': 3, + 'ক্তি': 3, + 'ক্রী': 3, + 'ক্ষা': 3, + 'ক্ষি': 3, + 'ক্ষে': 3, + 'ক্ষ্য': 3, + 'ক্ষ্যে': 4, + 'খ্যা': 3, + 'গ্রা': 3, + 'গ্রে': 3, + 'ঘো': 3, + 'ঙ্খা': 3, + 'ঙ্গী': 3, + 'ঙ্গে': 3, + 'চ্ছা': 3, + 'চ্ছা‌': 3, + 'চ্ছে': 3, + 'জ্ঞা': 3, + 'ঞ্চি': 3, + 'ঞ্ছি': 3, + 'ট্রে': 3, + 'ণ্ডে': 3, + 'ত্তা': 3, + 'ত্তি': 3, + 'ত্বে': 3, + 'ত্যা': 3, + 'ত্যি': 3, + 'ত্যে': 3, + 'ত্রা': 3, + 'ত্রে': 3, + 'ত্‍প': 1, + 'ত্‍পী': 1, + 'ত্‍সা': 1, + 'দ্দি': 3, + 'দ্দে': 3, + 'দ্ধা': 3, + 'দ্ধি': 3, + 'দ্ধে': 3, + 'দ্বা': 3, + 'দ্রো': 3, + 'ধ্যে': 3, + 'ন্তা': 3, + 'ন্তি': 3, + 'ন্তে': 3, + 'ন্ত্রি': 4, + 'ন্ত্রে': 4, + 'ন্থী': 3, + 'ন্ধা': 3, + 'ন্মা': 3, + 'ন্যা': 3, + 'ন্যে': 3, + 'প্তা': 3, + 'প্রা': 3, + 'ব্ধি': 3, + 'ব্যা': 3, + 'ভ্রা': 3, + 'ম্পা': 3, + 'ম্মা': 3, + 'রাং': 3, + 'র্জা': 3, + 'র্থে': 3, + 'র্দো': 3, + 'র্ধা': 3, + 'র্নী': 3, + 'র্বা': 3, + 'র্বি': 3, + 'র্বো': 3, + 'র্ব্য': 3, + 'র্মে': 3, + 'র্যা': 3, + 'ল্যা': 3, + 'ল্যে': 3, + 'ল্লে': 3, + 'শ্চি': 3, + 'শ্বা': 3, + 'শ্বে': 3, + 'শ্যে': 3, + 'শ্রা': 3, + 'ষ্টা': 3, + 'ষ্টি': 3, + 'ষ্ট্র': 3, + 'ষ্ট্রী': 4, + 'ষ্ট্রে': 4, + 'ষ্ঠা': 3, + 'ষ্ঠি': 3, + 'ষ্ঠী': 3, + 'সাং': 3, + 'স্তি': 3, + 'স্তি‌': 3, + 'স্ত্র': 3, + 'স্থা': 3, + 'স্থ্য': 3, + 'স্বা': 3, + 'স্বী': 3, + 'স্যা': 3, + 'স্যে': 3, + 'ક્કા': 3, + 'ક્કો': 3, + 'ક્તિ': 3, + 'ક્ષા': 3, + 'ચ્ચા': 3, + 'ચ્છા': 3, + 'જ્ઞા': 3, + 'જ્યો': 3, + 'ત્તા': 3, + 'ત્તિ': 3, + 'ત્ત્વ': 3, + 'ત્ત્વા': 4, + 'ત્યા': 3, + 'ત્યાં': 3, + 'ત્યિ': 3, + 'ત્યો': 3, + 'ત્રી': 3, + 'ત્ર્ય': 3, + 'દ્ધા': 3, + 'દ્ધાં': 3, + 'દ્ધિ': 3, + 'દ્વા': 3, + 'ધ્યા': 3, + 'ન્તો': 3, + 'ન્મા': 3, + 'ન્યા': 3, + 'પ્રા': 3, + 'મ્યાં': 3, + 'ર્તા': 3, + 'ર્થિ': 3, + 'ર્દો': 3, + 'ર્મિ': 3, + 'ર્યા': 3, + 'ર્યો': 3, + 'વ્યા': 3, + 'વ્યો': 3, + 'ષ્ટિ': 3, + 'ષ્ટ્ર': 3, + 'ષ્ટ્રી': 4, + 'ષ્ટ્રો': 4, + 'ષ્ઠા': 3, + 'સ્તિ': 3, + 'સ્તી': 3, + 'સ્ત્રી': 4, + 'સ્થા': 3, + 'સ્થિ': 3, + 'સ્રી': 3, + 'સ્વા': 3, + 'સ્વી': 3, + 'સ્સા': 3, + 'కుం': 3, + 'క్కు': 3, + 'క్తు': 3, + 'క్రాం': 3, + 'క్రూ': 3, + 'క్షిం': 3, + 'క్స్వా': 3, + 'చ్చు': 3, + 'టుం': 3, + 'ట్లు': 3, + 'డ్రు': 3, + 'త్తు': 3, + 'త్నిం': 3, + 'త్యం': 3, + 'త్రు': 3, + 'త్ర్య': 3, + 'దుం': 3, + 'ద్దు': 3, + 'ద్ధిం': 3, + 'ద్ర్య': 3, + 'నుం': 3, + 'న్ను': 3, + 'భ్యు': 3, + 'యుం': 3, + 'ర్చు': 3, + 'ర్ణాం': 3, + 'ర్ణు': 3, + 'ర్తిం': 3, + 'ర్తృ': 3, + 'ర్థిం': 3, + 'ర్బం': 3, + 'ర్హాం': 3, + 'ర్హు': 3, + 'శ్రాం': 3, + 'ష్టు': 3, + 'ష్ట్ర': 3, + 'ష్ట్రీ': 3, + 'ష్ఠు': 3, + 'స్కృ': 3, + 'స్త్ర': 3, + 'స్త్రీ': 3, + 'స్థ్య': 3, + 'ಕಾಂ': 3, + 'ಕುಂ': 3, + 'ಕೊಂ': 3, + 'ಖಾಂ': 3, + 'ಗಾಂ': 3, + 'ಗೊಂ': 3, + 'ಟುಂ': 3, + 'ನಾಂ': 3, + 'ಯುಂ': 3, + 'ರಾಂ': 3, + 'ವುಂ': 3, + 'ಶಾಂ': 3, + 'ಸಾಂ': 3, + 'ಹೊಂ': 3, + 'ക്കാ': 3, + 'ക്കി': 3, + 'ക്കും': 3, + 'ക്കെ': 3, + 'ക്കേ': 3, + 'ക്കൊ': 3, + 'ക്കോ': 3, + 'ക്തി': 3, + 'ക്യം': 3, + 'ക്ഷാ': 3, + 'ക്ഷി': 3, + 'ക്ഷേ': 3, + 'ഖ്യാ': 3, + 'ഗ്ഗം': 3, + 'ഗ്ദാ': 3, + 'ഗ്യം': 3, + 'ങ്കി': 3, + 'ങ്കെ': 3, + 'ങ്കേ': 3, + 'ങ്ങി': 3, + 'ച്ചി': 3, + 'ച്ചും': 3, + 'ച്ചെ': 3, + 'ച്ചേ': 3, + 'ജ്യാ': 3, + 'ഞ്ഞി': 3, + 'ഞ്ഞെ': 3, + 'ട്ടാ': 3, + 'ട്ടി': 3, + 'ട്ടോ': 3, + 'ണ്ടാ': 3, + 'ണ്ടി': 3, + 'ണ്ടും': 3, + 'ണ്ടെ': 3, + 'ത്താ': 3, + 'ത്തി': 3, + 'ത്തും': 3, + 'ത്തെ': 3, + 'ത്തേ': 3, + 'ത്തോ': 3, + 'ത്നം': 3, + 'ത്നി': 3, + 'ത്യാ': 3, + 'ത്യേ': 3, + 'ത്വം': 3, + 'ദ്ധി': 3, + 'ദ്യാ': 3, + 'ന്തം': 3, + 'ന്തെ': 3, + 'ന്ത്ര': 3, + 'ന്ത്ര്യ': 4, + 'ന്ത്ര്യം': 5, + 'ന്ധി': 3, + 'ന്നാ': 3, + 'ന്നി': 3, + 'ന്നീ': 3, + 'ന്നും': 3, + 'ന്നെ': 3, + 'ന്നേ': 3, + 'ന്നോ': 3, + 'ന്മാ': 3, + 'ന്യം': 3, + 'ന്യാ': 3, + 'ന്യേ': 3, + 'ന്യോ': 3, + 'ന്റെ': 3, + 'ന്‍കൂ': 1, + 'ന്‍പി': 1, + 'പ്പി': 3, + 'പ്പെ': 3, + 'പ്പോ': 3, + 'പ്രാ': 3, + 'ബ്ലി': 3, + 'ഭ്യാ': 3, + 'ഭ്രാ': 3, + 'മ്പാ': 3, + 'മ്പ്ര': 3, + 'മ്മി': 3, + 'യ്ക്കു': 3, + 'യ്തി': 3, + 'യ്യാ': 3, + 'യ്യി': 3, + 'ര്യം': 3, + 'ര്‍ക്കു': 1, + 'ര്‍ക്കും': 1, + 'ര്‍ക്ക്‌': 1, + 'ര്‍ഗ്ഗം': 1, + 'ര്‍ച്ച': 1, + 'ര്‍ണ്ണ': 1, + 'ര്‍ത്ത': 1, + 'ര്‍ത്തി': 1, + 'ര്‍ത്തു': 1, + 'ര്‍ത്തേ': 1, + 'ര്‍ദേ': 1, + 'ര്‍ദ്ദ': 1, + 'ര്‍പ്പെ': 1, + 'ര്‍ബ': 1, + 'ര്‍ഭ': 1, + 'ര്‍മ്മി': 1, + 'ര്‍രാ': 1, + 'ര്‍വ്വ': 1, + 'ര്‍ഹ': 1, + 'ര്‍ഹി': 1, + 'റ്റം': 3, + 'റ്റേ': 3, + 'ല്യാ': 3, + 'ല്ലാ': 3, + 'ല്ലാം': 4, + 'ല്ലെ': 3, + 'ല്‍കി': 1, + 'ല്‍കു': 1, + 'ല്‍കേ': 1, + 'ല്‍ത': 1, + 'ല്‍നി': 1, + 'ല്‍പ്പ': 1, + 'ള്ളാ': 3, + 'ള്ളി': 3, + 'ള്‍കൊ': 1, + 'ള്‍ക്ക': 1, + 'ള്‍ക്കി': 1, + 'ള്‍ക്കു': 1, + 'ള്‍ക്കും': 1, + 'ള്‍ക്കെ': 1, + 'ള്‍ക്ക്‌': 1, + 'വ്യം': 3, + 'വ്യാ': 3, + 'ശ്വാ': 3, + 'ഷ്ട്യാ': 4, + 'ഷ്ട്ര': 3, + 'ഷ്ട്രീ': 4, + 'ഷ്യാ': 3, + 'സാം': 3, + 'സ്കാ': 3, + 'സ്ത്രം': 4, + 'സ്ത്രീ': 4, + 'സ്ഥാ': 3, + 'സ്ഥി': 3, + 'സ്റ്റ്‌': 3, + 'സ്വാ': 3, + 'സ്വീ': 3, + 'സ്സാ': 3, + 'സ്സി': 3, + 'സ്സും': 3, + 'സ്സോ': 3, + 'ഹിം': 3, + 'ൻ്റെ': 3, + 'ကျေ': 3, + 'ကြေ': 3, + 'ကြွေ': 3, + 'ချေ': 3, + 'ခြေ': 3, + 'ဇြေ': 3, + 'ဒ္ဂေ': 3, + 'ပျေ': 3, + 'ပြေ': 3, + 'ဖျေံ': 3, + 'ဗ္တေ': 3, + 'ဗ္ၜေ': 3, + 'ဗြေ': 3, + 'မြေ': 3, + 'လျေ': 3, + 'လျှေ': 3, + 'သ္ဂေ': 3, + 'ក្ដៅ': 3, + 'ក្រោ': 3, + 'ក្សា': 3, + 'ខ្ជា': 3, + 'ខ្លា': 3, + 'គ្នា': 3, + 'គ្មា': 3, + 'គ្រា': 3, + 'គ្រឹះ': 3, + 'ង្កើ': 3, + 'ង្រៀ': 3, + 'ង្ហា': 3, + 'ច្ចេ': 3, + 'ច្បា': 3, + 'ឆ្នាំ': 3, + 'ឆ្នោ': 3, + 'ឆ្លើ': 3, + 'ជ្ជា': 3, + 'ជ្ញា': 3, + 'ជ្រើ': 3, + 'ជ្រៀ': 3, + 'ជ្រែ': 3, + 'ឈ្មោះ': 4, + 'ញ្ជា': 3, + 'ញ្ញា': 3, + 'ញ្ញៈ': 3, + 'ដ្ឋា': 3, + 'ណោះ': 3, + 'ណ្ដា': 3, + 'ណ្ដុះ': 3, + 'ណ្ណោះ': 4, + 'ត្រា': 3, + 'ថ្ងៃ': 3, + 'ថ្នា': 3, + 'ថ្លៃ': 3, + 'ទោះ': 3, + 'ទ្យា': 3, + 'ធ្នា': 3, + 'ធ្យា': 3, + 'ធ្យោ': 3, + 'ធ្វើ': 3, + 'នេះ': 3, + 'នោះ': 3, + 'ន្ថែ': 3, + 'ន្ថោ': 3, + 'ន្ទា': 3, + 'ន្ទៈ': 3, + 'ន្យា': 3, + 'ន្លែ': 3, + 'បោះ': 3, + 'ប្ដេ': 3, + 'ប្រា': 3, + 'ប្រើ': 3, + 'ប្រែ': 3, + 'ផ្ដា': 3, + 'ផ្ទា': 3, + 'ផ្ទេ': 3, + 'ផ្នែ': 3, + 'ផ្លា': 3, + 'ផ្សា': 3, + 'ផ្សេ': 3, + 'ផ្សៃ': 3, + 'ពោះ': 3, + 'ព្យា': 3, + 'ព្រៀ': 3, + 'ព្រៃ': 3, + 'ម្ងា': 3, + 'ម្ចា': 3, + 'ម្ដា': 3, + 'ម្ដែ': 3, + 'ម្នា': 3, + 'ម្នេ': 3, + 'ម្ភា': 3, + 'ម្រា': 3, + 'ម្រើ': 3, + 'ម្រេ': 3, + 'ម្លៀ': 3, + 'ម្លៃ': 3, + 'ល្បៈ': 3, + 'ល្មើ': 3, + 'ស្គា': 3, + 'ស្ដ្រី': 3, + 'ស្ត្រ': 3, + 'ស្ថា': 3, + 'ស្នា': 3, + 'ស្មា': 3, + 'ស្មើ': 3, + 'ស្រា': 3, + 'ស្លា': 3, + 'ស្វែ': 3, + 'ᨠᩮ᩠ᨯᩨ': 3, + 'ᨠᩯ᩠ᨯ': 3, + 'ᨠᩯ᩠ᨶ᩵': 3, + 'ᨡᩮ᩠ᨲ': 3, + 'ᨡᩯ᩠ᨠ': 3, + 'ᨡᩯ᩠ᨦ': 3, + 'ᨣᩕ᩠ᩋ': 3, + 'ᨣᩕᩮ᩠ᨦᩨ᩵': 4, + 'ᨣᩯ᩠ᨶᩢ': 3, + 'ᨣᩯ᩠ᩅ': 3, + 'ᨧᩮ᩠ᨷ': 3, + 'ᨧᩱ᩠ᨿ': 3, + 'ᨩᩮ᩠ᩋᩨ': 3, + 'ᨩᩮ᩠ᩋᩨ᩵': 3, + 'ᨩᩮ᩠ᩋᩨ᩶': 3, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 3, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 3, + 'ᨯᩯ᩠ᨦ': 3, + 'ᨯᩯ᩠ᨶ': 3, + 'ᨯᩰ᩠ᨿ': 3, + 'ᨲᩮ᩠ᨠ': 3, + 'ᨲᩮ᩠ᨦ': 3, + 'ᨲᩮ᩠ᨾ': 3, + 'ᨲᩮ᩠ᨾᩨ᩵': 3, + 'ᨲᩯ᩠ᨠ': 3, + 'ᨲᩯ᩠ᨦ᩵': 3, + 'ᨲᩯ᩠ᨾᩢ': 3, + 'ᨲᩱ᩠ᨿ': 3, + 'ᨳᩮ᩠ᨶᩨ᩵': 3, + 'ᨳᩯ᩠ᨦᩢ': 3, + 'ᨳᩯ᩠ᨾ': 3, + 'ᨴᩮ᩠ᩈ': 3, + 'ᨴᩮ᩠ᩈᩱ': 4, + 'ᨴᩯ᩠ᨶ': 3, + 'ᨴᩰ᩠ᩈ': 3, + 'ᨶᩯ᩠ᨶ': 3, + 'ᨷᩮ᩠ᨦᩨ᩶': 3, + 'ᨸᩮ᩠ᨦᩨ': 3, + 'ᨸᩮ᩠ᨶ': 3, + 'ᨹᩮᩨ᩠ᨿ': 3, + 'ᨻᩕ᩠ᩋᩢ': 3, + 'ᨻᩮ᩠ᩋᩨ᩵': 3, + 'ᨽᩱ᩠ᨿ': 3, + 'ᨾᩮ᩠ᨠᩨ': 3, + 'ᨾᩮ᩠ᨦᩨ': 3, + 'ᨾᩮ᩠ᩋᩨ᩵': 3, + 'ᨿᩮ᩠ᨶ': 3, + 'ᨿᩮ᩠ᨾᩨ': 3, + 'ᩁᩮ᩠ᨦᩨ᩵': 3, + 'ᩁᩮ᩠ᨧ': 3, + 'ᩁᩮ᩠ᨶᩨ': 3, + 'ᩁᩮᩨ᩠ᨬ': 3, + 'ᩁᩯ᩠ᨦ': 3, + 'ᩃᩮ᩠ᨠᩨ': 3, + 'ᩃᩮ᩠ᨦᩨ': 3, + 'ᩃᩰ᩠ᨠ': 3, + 'ᩅᩮ᩠ᨶ': 3, + 'ᩅᩮ᩠ᨶᩢ': 3, + 'ᩈᩮ᩠ᩈ': 3, + 'ᩈᩯ᩠ᩅ': 3, + 'ᩈᩱ᩠ᨿ': 3, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 3, + 'ᩉᩮ᩠ᨦᩢᩢ': 3, + 'ᩉᩮ᩠ᨯ': 3, + 'ᩉᩮ᩠ᨲᩩ': 3, + 'ᩉᩮ᩠ᨶᩨ': 3, + 'ᩉᩮ᩠ᨾᩨ': 3, + 'ᩉᩮ᩠ᨾᩨᩨ': 3, + 'ᩉᩯ᩠ᨦ᩵': 3, + 'ᩉᩯ᩠ᨶᩢ': 3, + 'ᩉᩯ᩠ᨾ': 3, + 'ᩉᩱ᩠ᨾ᩵': 3, + 'ᩉᩱ᩠ᨿ᩵': 3, + 'ᩣ᩠ᨲᩱ': 3, + '⛹🏻‍♀️': 3, + '⛹🏻‍♂️': 3, + '⛹🏼‍♀️': 3, + '⛹🏼‍♂️': 3, + '⛹🏽‍♀️': 3, + '⛹🏽‍♂️': 3, + '⛹🏾‍♀️': 3, + '⛹🏾‍♂️': 3, + '⛹🏿‍♀️': 3, + '⛹🏿‍♂️': 3, + 'ꦏꦺꦴ': 3, + 'ꦏ꧀': 2, + 'ꦏ꧀ꦏ': 3, + 'ꦏ꧀ꦏꦁ': 3, + 'ꦏ꧀ꦏꦺ': 4, + 'ꦏ꧀ꦏꦼ': 3, + 'ꦏ꧀ꦔ': 3, + 'ꦏ꧀ꦔꦸ': 3, + 'ꦏ꧀ꦔꦿ': 4, + 'ꦏ꧀ꦕ': 3, + 'ꦏ꧀ꦠ': 3, + 'ꦏ꧀ꦠꦶ': 3, + 'ꦏ꧀ꦠꦸ': 3, + 'ꦏ꧀ꦠꦺ': 4, + 'ꦏ꧀ꦢ': 3, + 'ꦏ꧀ꦢꦂ': 3, + 'ꦏ꧀ꦢꦶ': 3, + 'ꦏ꧀ꦤ': 3, + 'ꦏ꧀ꦤꦶꦁ': 3, + 'ꦏ꧀ꦥ': 3, + 'ꦏ꧀ꦥꦶ': 3, + 'ꦏ꧀ꦥꦿꦶ': 4, + 'ꦏ꧀ꦧ': 3, + 'ꦏ꧀ꦧꦶ': 3, + 'ꦏ꧀ꦧꦺ': 4, + 'ꦏ꧀ꦩ': 3, + 'ꦏ꧀ꦩꦸ': 3, + 'ꦏ꧀ꦪ': 3, + 'ꦏ꧀ꦭ': 3, + 'ꦏ꧀ꦮ': 3, + 'ꦏ꧀ꦱ': 3, + 'ꦏ꧀ꦱꦂ': 3, + 'ꦏ꧀ꦱꦶ': 3, + 'ꦏ꧀ꦱꦸ': 3, + 'ꦏ꧀ꦱꦺ': 4, + 'ꦏ꧀ꦲ': 3, + 'ꦏ꧀ꦲꦁ': 3, + 'ꦏ꧀ꦲꦶꦁ': 3, + 'ꦏ꧀ꦲꦸ': 3, + 'ꦏ꧀ꦲꦺ': 4, + 'ꦏ꧀ꦲꦺꦴ': 5, + 'ꦒꦺꦴ': 3, + 'ꦒꦿꦺ': 3, + 'ꦒ꧀ꦒ': 3, + 'ꦔꦺꦴ': 3, + 'ꦔ꧀ꦒꦼ': 3, + 'ꦔ꧀ꦒꦿꦼꦁ': 4, + 'ꦔ꧀ꦭ': 3, + 'ꦔ꧀ꦭꦁ': 3, + 'ꦔ꧀ꦭꦸ': 3, + 'ꦔ꧀ꦭꦼ': 3, + 'ꦕꦺꦴ': 3, + 'ꦗꦿꦺꦴ': 4, + 'ꦚ꧀ꦕ': 3, + 'ꦚ꧀ꦕꦶ': 3, + 'ꦚ꧀ꦗ': 3, + 'ꦚ꧀ꦗꦶ': 3, + 'ꦚ꧀ꦗꦸꦁ': 3, + 'ꦚ꧀ꦗꦸꦂ': 3, + 'ꦝꦺꦴ': 3, + 'ꦝꦺꦴꦂ': 3, + 'ꦠꦺꦃ': 3, + 'ꦠꦺꦴ': 3, + 'ꦠ꧀': 2, + 'ꦠ꧀ꦏꦁ': 3, + 'ꦠ꧀ꦏꦸ': 3, + 'ꦠ꧀ꦒ': 3, + 'ꦠ꧀ꦔꦸ': 3, + 'ꦠ꧀ꦚ': 3, + 'ꦠ꧀ꦠ': 3, + 'ꦠ꧀ꦠꦶ': 3, + 'ꦠ꧀ꦠꦶꦁ': 3, + 'ꦠ꧀ꦠꦸ': 3, + 'ꦠ꧀ꦠꦺ': 4, + 'ꦠ꧀ꦤ': 3, + 'ꦠ꧀ꦤꦶ': 3, + 'ꦠ꧀ꦩ': 3, + 'ꦠ꧀ꦩꦼ': 3, + 'ꦠ꧀ꦭ': 3, + 'ꦠ꧀ꦭꦺ': 4, + 'ꦠ꧀ꦱ': 3, + 'ꦠ꧀ꦱꦶꦁ': 3, + 'ꦠ꧀ꦱꦶꦃ': 4, + 'ꦠ꧀ꦱꦾ': 4, + 'ꦠ꧀ꦱ꧀ꦮ': 5, + 'ꦠ꧀ꦲ': 3, + 'ꦠ꧀ꦲꦶꦁ': 3, + 'ꦠ꧀ꦲꦺꦴ': 5, + 'ꦢꦺꦴ': 3, + 'ꦢ꧀': 2, + 'ꦢ꧀ꦏ': 3, + 'ꦢ꧀ꦠ': 3, + 'ꦢ꧀ꦠꦶꦁ': 3, + 'ꦢ꧀ꦢ': 3, + 'ꦢ꧀ꦥ': 3, + 'ꦢ꧀ꦩꦺꦴ': 5, + 'ꦢ꧀ꦲ': 3, + 'ꦤꦺꦃ': 3, + 'ꦤꦺꦴ': 3, + 'ꦤ꧀': 2, + 'ꦤ꧀ꦏ': 3, + 'ꦤ꧀ꦏꦁ': 3, + 'ꦤ꧀ꦏꦸ': 3, + 'ꦤ꧀ꦏꦼ': 3, + 'ꦤ꧀ꦒ': 3, + 'ꦤ꧀ꦔ': 3, + 'ꦤ꧀ꦔꦁ': 3, + 'ꦤ꧀ꦔꦶ': 3, + 'ꦤ꧀ꦔꦸ': 3, + 'ꦤ꧀ꦔꦸꦂ': 3, + 'ꦤ꧀ꦔꦺ': 4, + 'ꦤ꧀ꦔꦼ': 3, + 'ꦤ꧀ꦔꦿꦸ': 4, + 'ꦤ꧀ꦗ': 3, + 'ꦤ꧀ꦗꦸ': 3, + 'ꦤ꧀ꦗꦼ': 3, + 'ꦤ꧀ꦚꦶ': 3, + 'ꦤ꧀ꦛꦃ': 4, + 'ꦤ꧀ꦛꦶ': 3, + 'ꦤ꧀ꦝ': 3, + 'ꦤ꧀ꦝꦁ': 3, + 'ꦤ꧀ꦝꦶ': 3, + 'ꦤ꧀ꦝꦸ': 3, + 'ꦤ꧀ꦝꦸꦁ': 3, + 'ꦤ꧀ꦝꦺꦁ': 4, + 'ꦤ꧀ꦝꦺꦴꦁ': 5, + 'ꦤ꧀ꦝꦼ': 3, + 'ꦤ꧀ꦠ': 3, + 'ꦤ꧀ꦠꦂ': 3, + 'ꦤ꧀ꦠꦃ': 4, + 'ꦤ꧀ꦠꦶ': 3, + 'ꦤ꧀ꦠꦸ': 3, + 'ꦤ꧀ꦠꦸꦁ': 3, + 'ꦤ꧀ꦠꦺ': 4, + 'ꦤ꧀ꦠꦼ': 3, + 'ꦤ꧀ꦠꦼꦂ': 3, + 'ꦤ꧀ꦠꦽ': 3, + 'ꦤ꧀ꦢ': 3, + 'ꦤ꧀ꦢꦁ': 3, + 'ꦤ꧀ꦢꦂ': 3, + 'ꦤ꧀ꦢꦶ': 3, + 'ꦤ꧀ꦢꦸ': 3, + 'ꦤ꧀ꦢꦺ': 4, + 'ꦤ꧀ꦢꦼ': 3, + 'ꦤ꧀ꦤ': 3, + 'ꦤ꧀ꦤꦶ': 3, + 'ꦤ꧀ꦤꦶꦁ': 3, + 'ꦤ꧀ꦤꦺ': 4, + 'ꦤ꧀ꦤꦼ': 3, + 'ꦤ꧀ꦥ': 3, + 'ꦤ꧀ꦥꦁ': 3, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 5, + 'ꦤ꧀ꦥꦶ': 3, + 'ꦤ꧀ꦥꦸ': 3, + 'ꦤ꧀ꦥꦼ': 3, + 'ꦤ꧀ꦥꦿ': 4, + 'ꦤ꧀ꦥꦿꦶ': 4, + 'ꦤ꧀ꦧ': 3, + 'ꦤ꧀ꦧꦁ': 3, + 'ꦤ꧀ꦧꦶ': 3, + 'ꦤ꧀ꦧꦸ': 3, + 'ꦤ꧀ꦧꦺ': 4, + 'ꦤ꧀ꦧꦺꦴ': 5, + 'ꦤ꧀ꦧꦼ': 3, + 'ꦤ꧀ꦩ': 3, + 'ꦤ꧀ꦩꦂ': 3, + 'ꦤ꧀ꦩꦶ': 3, + 'ꦤ꧀ꦩꦸꦂ': 3, + 'ꦤ꧀ꦩꦼ': 3, + 'ꦤ꧀ꦭ': 3, + 'ꦤ꧀ꦭꦶ': 3, + 'ꦤ꧀ꦭꦸ': 3, + 'ꦤ꧀ꦮ': 3, + 'ꦤ꧀ꦮꦂ': 3, + 'ꦤ꧀ꦮꦶ': 3, + 'ꦤ꧀ꦮꦸ': 3, + 'ꦤ꧀ꦮꦼ': 3, + 'ꦤ꧀ꦱ': 3, + 'ꦤ꧀ꦱꦂ': 3, + 'ꦤ꧀ꦱꦃ': 4, + 'ꦤ꧀ꦱꦶ': 3, + 'ꦤ꧀ꦱꦶꦁ': 3, + 'ꦤ꧀ꦱꦸ': 3, + 'ꦤ꧀ꦱꦺꦴ': 5, + 'ꦤ꧀ꦱꦼ': 3, + 'ꦤ꧀ꦲ': 3, + 'ꦤ꧀ꦲꦁ': 3, + 'ꦤ꧀ꦲꦶ': 3, + 'ꦤ꧀ꦲꦶꦁ': 3, + 'ꦤ꧀ꦲꦸ': 3, + 'ꦤ꧀ꦲꦺꦴ': 5, + 'ꦥ꦳꧀': 2, + 'ꦥꦺꦴ': 3, + 'ꦥꦿꦃ': 3, + 'ꦥꦿꦺꦴ': 4, + 'ꦥ꧀': 2, + 'ꦥ꧀ꦏ': 3, + 'ꦥ꧀ꦏꦁ': 3, + 'ꦥ꧀ꦠ': 3, + 'ꦥ꧀ꦠꦶ': 3, + 'ꦥ꧀ꦢꦸ': 3, + 'ꦥ꧀ꦤ': 3, + 'ꦥ꧀ꦤꦶ': 3, + 'ꦥ꧀ꦥ': 3, + 'ꦥ꧀ꦥꦶ': 3, + 'ꦥ꧀ꦥꦺ': 4, + 'ꦥ꧀ꦧꦺ': 4, + 'ꦥ꧀ꦩ': 3, + 'ꦥ꧀ꦩꦂ': 3, + 'ꦥ꧀ꦫꦺ': 4, + 'ꦥ꧀ꦭ': 3, + 'ꦥ꧀ꦭꦸ': 3, + 'ꦥ꧀ꦱ': 3, + 'ꦥ꧀ꦱꦶꦂ': 3, + 'ꦥ꧀ꦱꦼ': 3, + 'ꦥ꧀ꦲ': 3, + 'ꦧꦺꦃ': 3, + 'ꦧꦺꦴ': 3, + 'ꦧ꧀': 2, + 'ꦧ꧀ꦏ': 3, + 'ꦧ꧀ꦠꦸ': 3, + 'ꦧ꧀ꦥ': 3, + 'ꦧ꧀ꦧ': 3, + 'ꦧ꧀ꦧꦺ': 4, + 'ꦧ꧀ꦲ': 3, + 'ꦧ꧀ꦲꦶ': 3, + 'ꦩꦺꦃ': 3, + 'ꦩꦺꦴ': 3, + 'ꦩꦿꦃ': 3, + 'ꦩꦿꦶꦃ': 3, + 'ꦩ꧀': 2, + 'ꦩ꧀ꦏꦁ': 3, + 'ꦩ꧀ꦔꦼ': 3, + 'ꦩ꧀ꦠꦸ': 3, + 'ꦩ꧀ꦠꦺꦴ': 5, + 'ꦩ꧀ꦤꦶꦁ': 3, + 'ꦩ꧀ꦥ': 3, + 'ꦩ꧀ꦥꦶ': 3, + 'ꦩ꧀ꦥꦸ': 3, + 'ꦩ꧀ꦥꦼ': 3, + 'ꦩ꧀ꦧ': 3, + 'ꦩ꧀ꦧꦁ': 3, + 'ꦩ꧀ꦧꦂ': 3, + 'ꦩ꧀ꦧꦃ': 4, + 'ꦩ꧀ꦧꦶ': 3, + 'ꦩ꧀ꦧꦸ': 3, + 'ꦩ꧀ꦧꦸꦁ': 3, + 'ꦩ꧀ꦧꦺ': 4, + 'ꦩ꧀ꦧꦺꦂ': 4, + 'ꦩ꧀ꦧꦼꦂ': 3, + 'ꦩ꧀ꦧꦾꦸꦂ': 4, + 'ꦩ꧀ꦩ': 3, + 'ꦩ꧀ꦩꦶ': 3, + 'ꦩ꧀ꦫ': 3, + 'ꦩ꧀ꦫꦃ': 4, + 'ꦩ꧀ꦭ': 3, + 'ꦩ꧀ꦲꦶ': 3, + 'ꦪꦺꦴ': 3, + 'ꦫꦺꦴ': 3, + 'ꦭꦺꦃ': 3, + 'ꦭꦺꦴ': 3, + 'ꦭꦺꦴꦁ': 3, + 'ꦭ꧀': 2, + 'ꦭ꧀ꦏꦁ': 3, + 'ꦭ꧀ꦚꦼꦁ': 3, + 'ꦭ꧀ꦠꦸ': 3, + 'ꦭ꧀ꦧꦸ': 3, + 'ꦭ꧀ꦩꦸ': 3, + 'ꦭ꧀ꦭ': 3, + 'ꦭ꧀ꦭꦶ': 3, + 'ꦭ꧀ꦭꦶꦁ': 3, + 'ꦭ꧀ꦭꦺ': 4, + 'ꦭ꧀ꦮ': 3, + 'ꦭ꧀ꦱ': 3, + 'ꦭ꧀ꦱꦂ': 3, + 'ꦭ꧀ꦱꦶꦁ': 3, + 'ꦭ꧀ꦱꦸ': 3, + 'ꦭ꧀ꦲ': 3, + 'ꦭ꧀ꦲꦁ': 3, + 'ꦭ꧀ꦲꦶꦁ': 3, + 'ꦭ꧀ꦲꦸ': 3, + 'ꦮꦺꦴ': 3, + 'ꦮꦺꦴꦁ': 3, + 'ꦮꦺꦴꦃ': 4, + 'ꦮꦿꦸꦃ': 3, + 'ꦱꦺꦴ': 3, + 'ꦱꦿꦃ': 3, + 'ꦱ꧀': 2, + 'ꦱ꧀ꦏ': 3, + 'ꦱ꧀ꦏꦁ': 3, + 'ꦱ꧀ꦏꦿꦶ': 4, + 'ꦱ꧀ꦒ': 3, + 'ꦱ꧀ꦔꦸ': 3, + 'ꦱ꧀ꦔꦿ': 4, + 'ꦱ꧀ꦛꦶ': 3, + 'ꦱ꧀ꦠ': 3, + 'ꦱ꧀ꦠꦿ': 4, + 'ꦱ꧀ꦢꦂ': 3, + 'ꦱ꧀ꦢꦶ': 3, + 'ꦱ꧀ꦢꦸ': 3, + 'ꦱ꧀ꦥ': 3, + 'ꦱ꧀ꦧ': 3, + 'ꦱ꧀ꦧꦁ': 3, + 'ꦱ꧀ꦩ': 3, + 'ꦱ꧀ꦩꦶ': 3, + 'ꦱ꧀ꦩꦼ': 3, + 'ꦱ꧀ꦩꦿ': 4, + 'ꦱ꧀ꦭ': 3, + 'ꦱ꧀ꦮ': 3, + 'ꦱ꧀ꦱ': 3, + 'ꦱ꧀ꦱꦂ': 3, + 'ꦱ꧀ꦱꦶ': 3, + 'ꦱ꧀ꦱꦶꦁ': 3, + 'ꦱ꧀ꦱꦸ': 3, + 'ꦱ꧀ꦱꦺ': 4, + 'ꦱ꧀ꦲ': 3, + 'ꦱ꧀ꦲꦁ': 3, + 'ꦱ꧀ꦲꦶ': 3, + 'ꦱ꧀ꦲꦶꦁ': 3, + 'ꦱ꧀ꦲꦸ': 3, + 'ꦲꦺꦴ': 3, + '𑄇𑄳𑄠𑄬': 3, + '𑄈𑄳𑄠𑄬': 3, + '𑄌𑄳𑄠𑄬': 3, + '𑄎𑄳𑄠𑄬': 3, + '𑄑𑄳𑄢𑄬': 3, + '𑄖𑄳𑄠𑄬': 3, + '𑄖𑄳𑄢𑄬': 3, + '𑄘𑄳𑄠𑄬': 3, + '𑄚𑄳𑄠𑄬': 3, + '𑄝𑄳𑄢𑄬': 3, + '𑄟𑄳𑄠𑄬': 3, + '𑄡𑄳𑄠𑄬': 3, + '𑄣𑄳𑄦𑄬': 3, + '𑌕𑌾𑌂': 3, + '𑌕𑌾𑌃': 3, + '𑌕𑍍': 2, + '𑌗𑍍': 2, + '𑌚𑍍': 2, + '𑌜𑍍': 2, + '𑌞𑍍': 2, + '𑌟𑌾𑌂': 3, + '𑌟𑌾𑌃': 3, + '𑌟𑍍': 2, + '𑌠𑍈𑌃': 3, + '𑌣𑌾𑌂': 3, + '𑌣𑍍': 2, + '𑌤𑌾𑌂': 3, + '𑌤𑌾𑌃': 3, + '𑌤𑌿𑌂': 3, + '𑌤𑌿𑌃': 3, + '𑌤𑍁𑌂': 3, + '𑌤𑍇𑌃': 3, + '𑌤𑍍': 2, + '𑌥𑌾𑌂': 3, + '𑌦𑍍': 2, + '𑌧𑌾𑌃': 3, + '𑌧𑌿𑌂': 3, + '𑌧𑍇𑌃': 3, + '𑌧𑍈𑌃': 3, + '𑌧𑍍': 2, + '𑌨𑌾𑌂': 3, + '𑌨𑌾𑌃': 3, + '𑌨𑌿𑌃': 3, + '𑌨𑍈𑌃': 3, + '𑌨𑍍': 2, + '𑌪𑍍': 2, + '𑌬𑍍': 2, + '𑌭𑌿𑌃': 3, + '𑌭𑍍': 2, + '𑌮𑌿𑌂': 3, + '𑌮𑍍': 2, + '𑌯𑌾𑌂': 3, + '𑌯𑌾𑌃': 3, + '𑌯𑍁𑌃': 3, + '𑌯𑍈𑌃': 3, + '𑌯𑍋𑌃': 3, + '𑌯𑍍': 2, + '𑌰𑌾𑌃': 3, + '𑌰𑌿𑌂': 3, + '𑌰𑍍': 2, + '𑌲𑌾𑌃': 3, + '𑌲𑌿𑌂': 3, + '𑌲𑍍': 2, + '𑌵𑌾𑌂': 3, + '𑌵𑌾𑌃': 3, + '𑌵𑍍': 2, + '𑌶𑌾𑌃': 3, + '𑌶𑍍': 2, + '𑌷𑌾𑌂': 3, + '𑌷𑌾𑌃': 3, + '𑌷𑍍': 2, + '𑌸𑌾𑌂': 3, + '𑌸𑍍': 2, + '𑌹𑌾𑌃': 3, + '🇦🇨': 4, + '🇦🇩': 4, + '🇦🇪': 4, + '🇦🇫': 4, + '🇦🇬': 4, + '🇦🇮': 4, + '🇦🇱': 4, + '🇦🇲': 4, + '🇦🇴': 4, + '🇦🇶': 4, + '🇦🇷': 4, + '🇦🇸': 4, + '🇦🇹': 4, + '🇦🇺': 4, + '🇦🇼': 4, + '🇦🇽': 4, + '🇦🇿': 4, + '🇧🇦': 4, + '🇧🇧': 4, + '🇧🇩': 4, + '🇧🇪': 4, + '🇧🇫': 4, + '🇧🇬': 4, + '🇧🇭': 4, + '🇧🇮': 4, + '🇧🇯': 4, + '🇧🇱': 4, + '🇧🇲': 4, + '🇧🇳': 4, + '🇧🇴': 4, + '🇧🇶': 4, + '🇧🇷': 4, + '🇧🇸': 4, + '🇧🇹': 4, + '🇧🇻': 4, + '🇧🇼': 4, + '🇧🇾': 4, + '🇧🇿': 4, + '🇨🇦': 4, + '🇨🇨': 4, + '🇨🇩': 4, + '🇨🇫': 4, + '🇨🇬': 4, + '🇨🇭': 4, + '🇨🇮': 4, + '🇨🇰': 4, + '🇨🇱': 4, + '🇨🇲': 4, + '🇨🇳': 4, + '🇨🇴': 4, + '🇨🇵': 4, + '🇨🇶': 4, + '🇨🇷': 4, + '🇨🇺': 4, + '🇨🇻': 4, + '🇨🇼': 4, + '🇨🇽': 4, + '🇨🇾': 4, + '🇨🇿': 4, + '🇩🇪': 4, + '🇩🇬': 4, + '🇩🇯': 4, + '🇩🇰': 4, + '🇩🇲': 4, + '🇩🇴': 4, + '🇩🇿': 4, + '🇪🇦': 4, + '🇪🇨': 4, + '🇪🇪': 4, + '🇪🇬': 4, + '🇪🇭': 4, + '🇪🇷': 4, + '🇪🇸': 4, + '🇪🇹': 4, + '🇪🇺': 4, + '🇫🇮': 4, + '🇫🇯': 4, + '🇫🇰': 4, + '🇫🇲': 4, + '🇫🇴': 4, + '🇫🇷': 4, + '🇬🇦': 4, + '🇬🇧': 4, + '🇬🇩': 4, + '🇬🇪': 4, + '🇬🇫': 4, + '🇬🇬': 4, + '🇬🇭': 4, + '🇬🇮': 4, + '🇬🇱': 4, + '🇬🇲': 4, + '🇬🇳': 4, + '🇬🇵': 4, + '🇬🇶': 4, + '🇬🇷': 4, + '🇬🇸': 4, + '🇬🇹': 4, + '🇬🇺': 4, + '🇬🇼': 4, + '🇬🇾': 4, + '🇭🇰': 4, + '🇭🇲': 4, + '🇭🇳': 4, + '🇭🇷': 4, + '🇭🇹': 4, + '🇭🇺': 4, + '🇮🇨': 4, + '🇮🇩': 4, + '🇮🇪': 4, + '🇮🇱': 4, + '🇮🇲': 4, + '🇮🇳': 4, + '🇮🇴': 4, + '🇮🇶': 4, + '🇮🇷': 4, + '🇮🇸': 4, + '🇮🇹': 4, + '🇯🇪': 4, + '🇯🇲': 4, + '🇯🇴': 4, + '🇯🇵': 4, + '🇰🇪': 4, + '🇰🇬': 4, + '🇰🇭': 4, + '🇰🇮': 4, + '🇰🇲': 4, + '🇰🇳': 4, + '🇰🇵': 4, + '🇰🇷': 4, + '🇰🇼': 4, + '🇰🇾': 4, + '🇰🇿': 4, + '🇱🇦': 4, + '🇱🇧': 4, + '🇱🇨': 4, + '🇱🇮': 4, + '🇱🇰': 4, + '🇱🇷': 4, + '🇱🇸': 4, + '🇱🇹': 4, + '🇱🇺': 4, + '🇱🇻': 4, + '🇱🇾': 4, + '🇲🇦': 4, + '🇲🇨': 4, + '🇲🇩': 4, + '🇲🇪': 4, + '🇲🇫': 4, + '🇲🇬': 4, + '🇲🇭': 4, + '🇲🇰': 4, + '🇲🇱': 4, + '🇲🇲': 4, + '🇲🇳': 4, + '🇲🇴': 4, + '🇲🇵': 4, + '🇲🇶': 4, + '🇲🇷': 4, + '🇲🇸': 4, + '🇲🇹': 4, + '🇲🇺': 4, + '🇲🇻': 4, + '🇲🇼': 4, + '🇲🇽': 4, + '🇲🇾': 4, + '🇲🇿': 4, + '🇳🇦': 4, + '🇳🇨': 4, + '🇳🇪': 4, + '🇳🇫': 4, + '🇳🇬': 4, + '🇳🇮': 4, + '🇳🇱': 4, + '🇳🇴': 4, + '🇳🇵': 4, + '🇳🇷': 4, + '🇳🇺': 4, + '🇳🇿': 4, + '🇴🇲': 4, + '🇵🇦': 4, + '🇵🇪': 4, + '🇵🇫': 4, + '🇵🇬': 4, + '🇵🇭': 4, + '🇵🇰': 4, + '🇵🇱': 4, + '🇵🇲': 4, + '🇵🇳': 4, + '🇵🇷': 4, + '🇵🇸': 4, + '🇵🇹': 4, + '🇵🇼': 4, + '🇵🇾': 4, + '🇶🇦': 4, + '🇷🇪': 4, + '🇷🇴': 4, + '🇷🇸': 4, + '🇷🇺': 4, + '🇷🇼': 4, + '🇸🇦': 4, + '🇸🇧': 4, + '🇸🇨': 4, + '🇸🇩': 4, + '🇸🇪': 4, + '🇸🇬': 4, + '🇸🇭': 4, + '🇸🇮': 4, + '🇸🇯': 4, + '🇸🇰': 4, + '🇸🇱': 4, + '🇸🇲': 4, + '🇸🇳': 4, + '🇸🇴': 4, + '🇸🇷': 4, + '🇸🇸': 4, + '🇸🇹': 4, + '🇸🇻': 4, + '🇸🇽': 4, + '🇸🇾': 4, + '🇸🇿': 4, + '🇹🇦': 4, + '🇹🇨': 4, + '🇹🇩': 4, + '🇹🇫': 4, + '🇹🇬': 4, + '🇹🇭': 4, + '🇹🇯': 4, + '🇹🇰': 4, + '🇹🇱': 4, + '🇹🇲': 4, + '🇹🇳': 4, + '🇹🇴': 4, + '🇹🇷': 4, + '🇹🇹': 4, + '🇹🇻': 4, + '🇹🇼': 4, + '🇹🇿': 4, + '🇺🇦': 4, + '🇺🇬': 4, + '🇺🇲': 4, + '🇺🇳': 4, + '🇺🇸': 4, + '🇺🇾': 4, + '🇺🇿': 4, + '🇻🇦': 4, + '🇻🇨': 4, + '🇻🇪': 4, + '🇻🇬': 4, + '🇻🇮': 4, + '🇻🇳': 4, + '🇻🇺': 4, + '🇼🇫': 4, + '🇼🇸': 4, + '🇽🇰': 4, + '🇾🇪': 4, + '🇾🇹': 4, + '🇿🇦': 4, + '🇿🇲': 4, + '🇿🇼': 4, + '🏃🏻‍♀️': 4, + '🏃🏻‍♀️‍➡️': 4, + '🏃🏻‍♂️': 4, + '🏃🏻‍♂️‍➡️': 4, + '🏃🏻‍➡️': 4, + '🏃🏼‍♀️': 4, + '🏃🏼‍♀️‍➡️': 4, + '🏃🏼‍♂️': 4, + '🏃🏼‍♂️‍➡️': 4, + '🏃🏼‍➡️': 4, + '🏃🏽‍♀️': 4, + '🏃🏽‍♀️‍➡️': 4, + '🏃🏽‍♂️': 4, + '🏃🏽‍♂️‍➡️': 4, + '🏃🏽‍➡️': 4, + '🏃🏾‍♀️': 4, + '🏃🏾‍♀️‍➡️': 4, + '🏃🏾‍♂️': 4, + '🏃🏾‍♂️‍➡️': 4, + '🏃🏾‍➡️': 4, + '🏃🏿‍♀️': 4, + '🏃🏿‍♀️‍➡️': 4, + '🏃🏿‍♂️': 4, + '🏃🏿‍♂️‍➡️': 4, + '🏃🏿‍➡️': 4, + '🏄🏻‍♀️': 4, + '🏄🏻‍♂️': 4, + '🏄🏼‍♀️': 4, + '🏄🏼‍♂️': 4, + '🏄🏽‍♀️': 4, + '🏄🏽‍♂️': 4, + '🏄🏾‍♀️': 4, + '🏄🏾‍♂️': 4, + '🏄🏿‍♀️': 4, + '🏄🏿‍♂️': 4, + '🏊🏻‍♀️': 4, + '🏊🏻‍♂️': 4, + '🏊🏼‍♀️': 4, + '🏊🏼‍♂️': 4, + '🏊🏽‍♀️': 4, + '🏊🏽‍♂️': 4, + '🏊🏾‍♀️': 4, + '🏊🏾‍♂️': 4, + '🏊🏿‍♀️': 4, + '🏊🏿‍♂️': 4, + '🏋🏻‍♀️': 3, + '🏋🏻‍♂️': 3, + '🏋🏼‍♀️': 3, + '🏋🏼‍♂️': 3, + '🏋🏽‍♀️': 3, + '🏋🏽‍♂️': 3, + '🏋🏾‍♀️': 3, + '🏋🏾‍♂️': 3, + '🏋🏿‍♀️': 3, + '🏋🏿‍♂️': 3, + '🏌🏻‍♀️': 3, + '🏌🏻‍♂️': 3, + '🏌🏼‍♀️': 3, + '🏌🏼‍♂️': 3, + '🏌🏽‍♀️': 3, + '🏌🏽‍♂️': 3, + '🏌🏾‍♀️': 3, + '🏌🏾‍♂️': 3, + '🏌🏿‍♀️': 3, + '🏌🏿‍♂️': 3, + '👨🏻‍⚕️': 4, + '👨🏻‍⚖️': 4, + '👨🏻‍✈️': 4, + '👨🏻‍❤️‍👨🏻': 4, + '👨🏻‍❤️‍👨🏽': 4, + '👨🏻‍❤️‍👨🏿': 4, + '👨🏻‍❤️‍💋‍👨🏻': 4, + '👨🏻‍❤️‍💋‍👨🏽': 4, + '👨🏻‍❤️‍💋‍👨🏾': 4, + '👨🏻‍❤️‍💋‍👨🏿': 4, + '👨🏻‍🌾': 4, + '👨🏻‍🍳': 4, + '👨🏻‍🍼': 4, + '👨🏻‍🎓': 4, + '👨🏻‍🎤': 4, + '👨🏻‍🎨': 4, + '👨🏻‍🏫': 4, + '👨🏻‍🏭': 4, + '👨🏻‍🐰‍👨🏼': 4, + '👨🏻‍🐰‍👨🏽': 4, + '👨🏻‍🐰‍👨🏾': 4, + '👨🏻‍🐰‍👨🏿': 4, + '👨🏻‍💻': 4, + '👨🏻‍💼': 4, + '👨🏻‍🔧': 4, + '👨🏻‍🔬': 4, + '👨🏻‍🚀': 4, + '👨🏻‍🚒': 4, + '👨🏻‍🤝‍👨🏼': 4, + '👨🏻‍🤝‍👨🏽': 4, + '👨🏻‍🤝‍👨🏾': 4, + '👨🏻‍🤝‍👨🏿': 4, + '👨🏻‍🦯': 4, + '👨🏻‍🦯‍➡️': 4, + '👨🏻‍🦰': 4, + '👨🏻‍🦱': 4, + '👨🏻‍🦲': 4, + '👨🏻‍🦳': 4, + '👨🏻‍🦼': 4, + '👨🏻‍🦼‍➡️': 4, + '👨🏻‍🦽': 4, + '👨🏻‍🦽‍➡️': 4, + '👨🏻‍🫯‍👨🏼': 4, + '👨🏻‍🫯‍👨🏽': 4, + '👨🏻‍🫯‍👨🏾': 4, + '👨🏻‍🫯‍👨🏿': 4, + '👨🏼‍⚕️': 4, + '👨🏼‍⚖️': 4, + '👨🏼‍✈️': 4, + '👨🏼‍❤️‍👨🏼': 4, + '👨🏼‍❤️‍💋‍👨🏼': 4, + '👨🏼‍❤️‍💋‍👨🏿': 4, + '👨🏼‍🌾': 4, + '👨🏼‍🍳': 4, + '👨🏼‍🍼': 4, + '👨🏼‍🎓': 4, + '👨🏼‍🎤': 4, + '👨🏼‍🎨': 4, + '👨🏼‍🏫': 4, + '👨🏼‍🏭': 4, + '👨🏼‍🐰‍👨🏻': 4, + '👨🏼‍🐰‍👨🏽': 4, + '👨🏼‍🐰‍👨🏿': 4, + '👨🏼‍💻': 4, + '👨🏼‍💼': 4, + '👨🏼‍🔧': 4, + '👨🏼‍🔬': 4, + '👨🏼‍🚀': 4, + '👨🏼‍🚒': 4, + '👨🏼‍🤝‍👨🏻': 4, + '👨🏼‍🤝‍👨🏽': 4, + '👨🏼‍🤝‍👨🏿': 4, + '👨🏼‍🦯': 4, + '👨🏼‍🦯‍➡️': 4, + '👨🏼‍🦰': 4, + '👨🏼‍🦱': 4, + '👨🏼‍🦲': 4, + '👨🏼‍🦳': 4, + '👨🏼‍🦼': 4, + '👨🏼‍🦽': 4, + '👨🏼‍🦽‍➡️': 4, + '👨🏼‍🫯‍👨🏻': 4, + '👨🏼‍🫯‍👨🏽': 4, + '👨🏼‍🫯‍👨🏾': 4, + '👨🏼‍🫯‍👨🏿': 4, + '👨🏽‍⚕️': 4, + '👨🏽‍⚖️': 4, + '👨🏽‍✈️': 4, + '👨🏽‍❤️‍👨🏻': 4, + '👨🏽‍❤️‍👨🏽': 4, + '👨🏽‍❤️‍👨🏿': 4, + '👨🏽‍❤️‍💋‍👨🏻': 4, + '👨🏽‍❤️‍💋‍👨🏽': 4, + '👨🏽‍❤️‍💋‍👨🏿': 4, + '👨🏽‍🌾': 4, + '👨🏽‍🍳': 4, + '👨🏽‍🍼': 4, + '👨🏽‍🎓': 4, + '👨🏽‍🎤': 4, + '👨🏽‍🎨': 4, + '👨🏽‍🏫': 4, + '👨🏽‍🏭': 4, + '👨🏽‍🐰‍👨🏻': 4, + '👨🏽‍🐰‍👨🏼': 4, + '👨🏽‍🐰‍👨🏾': 4, + '👨🏽‍🐰‍👨🏿': 4, + '👨🏽‍💻': 4, + '👨🏽‍💼': 4, + '👨🏽‍🔧': 4, + '👨🏽‍🔬': 4, + '👨🏽‍🚀': 4, + '👨🏽‍🚒': 4, + '👨🏽‍🤝‍👨🏻': 4, + '👨🏽‍🤝‍👨🏼': 4, + '👨🏽‍🤝‍👨🏾': 4, + '👨🏽‍🤝‍👨🏿': 4, + '👨🏽‍🦯': 4, + '👨🏽‍🦯‍➡️': 4, + '👨🏽‍🦰': 4, + '👨🏽‍🦱': 4, + '👨🏽‍🦲': 4, + '👨🏽‍🦳': 4, + '👨🏽‍🦼': 4, + '👨🏽‍🦼‍➡️': 4, + '👨🏽‍🦽': 4, + '👨🏽‍🦽‍➡️': 4, + '👨🏽‍🫯‍👨🏻': 4, + '👨🏽‍🫯‍👨🏼': 4, + '👨🏽‍🫯‍👨🏾': 4, + '👨🏽‍🫯‍👨🏿': 4, + '👨🏾‍⚕️': 4, + '👨🏾‍⚖️': 4, + '👨🏾‍✈️': 4, + '👨🏾‍❤️‍👨🏾': 4, + '👨🏾‍❤️‍💋‍👨🏻': 4, + '👨🏾‍❤️‍💋‍👨🏾': 4, + '👨🏾‍❤️‍💋‍👨🏿': 4, + '👨🏾‍🌾': 4, + '👨🏾‍🍳': 4, + '👨🏾‍🍼': 4, + '👨🏾‍🎓': 4, + '👨🏾‍🎤': 4, + '👨🏾‍🎨': 4, + '👨🏾‍🏫': 4, + '👨🏾‍🏭': 4, + '👨🏾‍🐰‍👨🏻': 4, + '👨🏾‍🐰‍👨🏽': 4, + '👨🏾‍🐰‍👨🏿': 4, + '👨🏾‍💻': 4, + '👨🏾‍💼': 4, + '👨🏾‍🔧': 4, + '👨🏾‍🔬': 4, + '👨🏾‍🚀': 4, + '👨🏾‍🚒': 4, + '👨🏾‍🤝‍👨🏻': 4, + '👨🏾‍🤝‍👨🏽': 4, + '👨🏾‍🤝‍👨🏿': 4, + '👨🏾‍🦯': 4, + '👨🏾‍🦯‍➡️': 4, + '👨🏾‍🦰': 4, + '👨🏾‍🦱': 4, + '👨🏾‍🦲': 4, + '👨🏾‍🦳': 4, + '👨🏾‍🦼': 4, + '👨🏾‍🦽': 4, + '👨🏾‍🦽‍➡️': 4, + '👨🏾‍🫯‍👨🏻': 4, + '👨🏾‍🫯‍👨🏼': 4, + '👨🏾‍🫯‍👨🏽': 4, + '👨🏾‍🫯‍👨🏿': 4, + '👨🏿‍⚕️': 4, + '👨🏿‍⚖️': 4, + '👨🏿‍✈️': 4, + '👨🏿‍❤️‍👨🏻': 4, + '👨🏿‍❤️‍👨🏽': 4, + '👨🏿‍❤️‍👨🏿': 4, + '👨🏿‍❤️‍💋‍👨🏻': 4, + '👨🏿‍❤️‍💋‍👨🏼': 4, + '👨🏿‍❤️‍💋‍👨🏽': 4, + '👨🏿‍❤️‍💋‍👨🏾': 4, + '👨🏿‍❤️‍💋‍👨🏿': 4, + '👨🏿‍🌾': 4, + '👨🏿‍🍳': 4, + '👨🏿‍🍼': 4, + '👨🏿‍🎓': 4, + '👨🏿‍🎤': 4, + '👨🏿‍🎨': 4, + '👨🏿‍🏫': 4, + '👨🏿‍🏭': 4, + '👨🏿‍🐰‍👨🏻': 4, + '👨🏿‍🐰‍👨🏼': 4, + '👨🏿‍🐰‍👨🏽': 4, + '👨🏿‍🐰‍👨🏾': 4, + '👨🏿‍💻': 4, + '👨🏿‍💼': 4, + '👨🏿‍🔧': 4, + '👨🏿‍🔬': 4, + '👨🏿‍🚀': 4, + '👨🏿‍🚒': 4, + '👨🏿‍🤝‍👨🏻': 4, + '👨🏿‍🤝‍👨🏼': 4, + '👨🏿‍🤝‍👨🏽': 4, + '👨🏿‍🤝‍👨🏾': 4, + '👨🏿‍🦯': 4, + '👨🏿‍🦯‍➡️': 4, + '👨🏿‍🦰': 4, + '👨🏿‍🦱': 4, + '👨🏿‍🦲': 4, + '👨🏿‍🦳': 4, + '👨🏿‍🦼': 4, + '👨🏿‍🦼‍➡️': 4, + '👨🏿‍🦽': 4, + '👨🏿‍🦽‍➡️': 4, + '👨🏿‍🫯‍👨🏻': 4, + '👨🏿‍🫯‍👨🏼': 4, + '👨🏿‍🫯‍👨🏽': 4, + '👨🏿‍🫯‍👨🏾': 4, + '👩🏻‍⚕️': 4, + '👩🏻‍⚖️': 4, + '👩🏻‍✈️': 4, + '👩🏻‍❤️‍👨🏻': 4, + '👩🏻‍❤️‍👨🏿': 4, + '👩🏻‍❤️‍👩🏻': 4, + '👩🏻‍❤️‍💋‍👨🏻': 4, + '👩🏻‍❤️‍💋‍👨🏽': 4, + '👩🏻‍❤️‍💋‍👨🏿': 4, + '👩🏻‍❤️‍💋‍👩🏻': 4, + '👩🏻‍❤️‍💋‍👩🏽': 4, + '👩🏻‍❤️‍💋‍👩🏿': 4, + '👩🏻‍🌾': 4, + '👩🏻‍🍳': 4, + '👩🏻‍🍼': 4, + '👩🏻‍🎓': 4, + '👩🏻‍🎤': 4, + '👩🏻‍🎨': 4, + '👩🏻‍🏫': 4, + '👩🏻‍🏭': 4, + '👩🏻‍🐰‍👩🏼': 4, + '👩🏻‍🐰‍👩🏽': 4, + '👩🏻‍🐰‍👩🏾': 4, + '👩🏻‍🐰‍👩🏿': 4, + '👩🏻‍💻': 4, + '👩🏻‍💼': 4, + '👩🏻‍🔧': 4, + '👩🏻‍🔬': 4, + '👩🏻‍🚀': 4, + '👩🏻‍🚒': 4, + '👩🏻‍🤝‍👨🏽': 4, + '👩🏻‍🤝‍👨🏿': 4, + '👩🏻‍🤝‍👩🏼': 4, + '👩🏻‍🤝‍👩🏽': 4, + '👩🏻‍🤝‍👩🏾': 4, + '👩🏻‍🤝‍👩🏿': 4, + '👩🏻‍🦯': 4, + '👩🏻‍🦯‍➡️': 4, + '👩🏻‍🦰': 4, + '👩🏻‍🦱': 4, + '👩🏻‍🦲': 4, + '👩🏻‍🦳': 4, + '👩🏻‍🦼': 4, + '👩🏻‍🦼‍➡️': 4, + '👩🏻‍🦽': 4, + '👩🏻‍🦽‍➡️': 4, + '👩🏻‍🫯‍👩🏼': 4, + '👩🏻‍🫯‍👩🏽': 4, + '👩🏻‍🫯‍👩🏾': 4, + '👩🏻‍🫯‍👩🏿': 4, + '👩🏼‍⚕️': 4, + '👩🏼‍⚖️': 4, + '👩🏼‍✈️': 4, + '👩🏼‍❤️‍👨🏼': 4, + '👩🏼‍❤️‍👩🏼': 4, + '👩🏼‍❤️‍💋‍👨🏼': 4, + '👩🏼‍❤️‍💋‍👩🏼': 4, + '👩🏼‍🌾': 4, + '👩🏼‍🍳': 4, + '👩🏼‍🍼': 4, + '👩🏼‍🎓': 4, + '👩🏼‍🎤': 4, + '👩🏼‍🎨': 4, + '👩🏼‍🏫': 4, + '👩🏼‍🏭': 4, + '👩🏼‍🐰‍👩🏻': 4, + '👩🏼‍🐰‍👩🏿': 4, + '👩🏼‍💻': 4, + '👩🏼‍💼': 4, + '👩🏼‍🔧': 4, + '👩🏼‍🔬': 4, + '👩🏼‍🚀': 4, + '👩🏼‍🚒': 4, + '👩🏼‍🤝‍👩🏻': 4, + '👩🏼‍🤝‍👩🏽': 4, + '👩🏼‍🤝‍👩🏿': 4, + '👩🏼‍🦯': 4, + '👩🏼‍🦯‍➡️': 4, + '👩🏼‍🦰': 4, + '👩🏼‍🦱': 4, + '👩🏼‍🦲': 4, + '👩🏼‍🦳': 4, + '👩🏼‍🦼': 4, + '👩🏼‍🦽': 4, + '👩🏼‍🫯‍👩🏻': 4, + '👩🏼‍🫯‍👩🏽': 4, + '👩🏼‍🫯‍👩🏾': 4, + '👩🏼‍🫯‍👩🏿': 4, + '👩🏽‍⚕️': 4, + '👩🏽‍⚖️': 4, + '👩🏽‍✈️': 4, + '👩🏽‍❤️‍👨🏽': 4, + '👩🏽‍❤️‍👩🏽': 4, + '👩🏽‍❤️‍💋‍👨🏻': 4, + '👩🏽‍❤️‍💋‍👨🏽': 4, + '👩🏽‍❤️‍💋‍👨🏿': 4, + '👩🏽‍❤️‍💋‍👩🏻': 4, + '👩🏽‍❤️‍💋‍👩🏽': 4, + '👩🏽‍❤️‍💋‍👩🏿': 4, + '👩🏽‍🌾': 4, + '👩🏽‍🍳': 4, + '👩🏽‍🍼': 4, + '👩🏽‍🎓': 4, + '👩🏽‍🎤': 4, + '👩🏽‍🎨': 4, + '👩🏽‍🏫': 4, + '👩🏽‍🏭': 4, + '👩🏽‍🐰‍👩🏻': 4, + '👩🏽‍🐰‍👩🏾': 4, + '👩🏽‍🐰‍👩🏿': 4, + '👩🏽‍💻': 4, + '👩🏽‍💼': 4, + '👩🏽‍🔧': 4, + '👩🏽‍🔬': 4, + '👩🏽‍🚀': 4, + '👩🏽‍🚒': 4, + '👩🏽‍🤝‍👨🏻': 4, + '👩🏽‍🤝‍👨🏿': 4, + '👩🏽‍🤝‍👩🏻': 4, + '👩🏽‍🤝‍👩🏼': 4, + '👩🏽‍🤝‍👩🏾': 4, + '👩🏽‍🤝‍👩🏿': 4, + '👩🏽‍🦯': 4, + '👩🏽‍🦯‍➡️': 4, + '👩🏽‍🦰': 4, + '👩🏽‍🦱': 4, + '👩🏽‍🦲': 4, + '👩🏽‍🦳': 4, + '👩🏽‍🦼': 4, + '👩🏽‍🦼‍➡️': 4, + '👩🏽‍🦽': 4, + '👩🏽‍🦽‍➡️': 4, + '👩🏽‍🫯‍👩🏻': 4, + '👩🏽‍🫯‍👩🏼': 4, + '👩🏽‍🫯‍👩🏾': 4, + '👩🏽‍🫯‍👩🏿': 4, + '👩🏾‍⚕️': 4, + '👩🏾‍⚖️': 4, + '👩🏾‍✈️': 4, + '👩🏾‍❤️‍👨🏾': 4, + '👩🏾‍❤️‍👩🏾': 4, + '👩🏾‍❤️‍💋‍👨🏾': 4, + '👩🏾‍❤️‍💋‍👩🏾': 4, + '👩🏾‍🌾': 4, + '👩🏾‍🍳': 4, + '👩🏾‍🍼': 4, + '👩🏾‍🎓': 4, + '👩🏾‍🎤': 4, + '👩🏾‍🎨': 4, + '👩🏾‍🏫': 4, + '👩🏾‍🏭': 4, + '👩🏾‍🐰‍👩🏻': 4, + '👩🏾‍🐰‍👩🏽': 4, + '👩🏾‍🐰‍👩🏿': 4, + '👩🏾‍💻': 4, + '👩🏾‍💼': 4, + '👩🏾‍🔧': 4, + '👩🏾‍🔬': 4, + '👩🏾‍🚀': 4, + '👩🏾‍🚒': 4, + '👩🏾‍🤝‍👩🏻': 4, + '👩🏾‍🤝‍👩🏽': 4, + '👩🏾‍🤝‍👩🏿': 4, + '👩🏾‍🦯': 4, + '👩🏾‍🦯‍➡️': 4, + '👩🏾‍🦰': 4, + '👩🏾‍🦱': 4, + '👩🏾‍🦲': 4, + '👩🏾‍🦳': 4, + '👩🏾‍🦼': 4, + '👩🏾‍🦽': 4, + '👩🏾‍🦽‍➡️': 4, + '👩🏾‍🫯‍👩🏻': 4, + '👩🏾‍🫯‍👩🏼': 4, + '👩🏾‍🫯‍👩🏽': 4, + '👩🏾‍🫯‍👩🏿': 4, + '👩🏿‍⚕️': 4, + '👩🏿‍⚖️': 4, + '👩🏿‍✈️': 4, + '👩🏿‍❤️‍👨🏻': 4, + '👩🏿‍❤️‍👨🏿': 4, + '👩🏿‍❤️‍👩🏿': 4, + '👩🏿‍❤️‍💋‍👨🏻': 4, + '👩🏿‍❤️‍💋‍👨🏽': 4, + '👩🏿‍❤️‍💋‍👨🏿': 4, + '👩🏿‍❤️‍💋‍👩🏻': 4, + '👩🏿‍❤️‍💋‍👩🏽': 4, + '👩🏿‍❤️‍💋‍👩🏿': 4, + '👩🏿‍🌾': 4, + '👩🏿‍🍳': 4, + '👩🏿‍🍼': 4, + '👩🏿‍🎓': 4, + '👩🏿‍🎤': 4, + '👩🏿‍🎨': 4, + '👩🏿‍🏫': 4, + '👩🏿‍🏭': 4, + '👩🏿‍🐰‍👩🏻': 4, + '👩🏿‍🐰‍👩🏼': 4, + '👩🏿‍🐰‍👩🏽': 4, + '👩🏿‍🐰‍👩🏾': 4, + '👩🏿‍💻': 4, + '👩🏿‍💼': 4, + '👩🏿‍🔧': 4, + '👩🏿‍🔬': 4, + '👩🏿‍🚀': 4, + '👩🏿‍🚒': 4, + '👩🏿‍🤝‍👨🏻': 4, + '👩🏿‍🤝‍👨🏽': 4, + '👩🏿‍🤝‍👩🏻': 4, + '👩🏿‍🤝‍👩🏼': 4, + '👩🏿‍🤝‍👩🏽': 4, + '👩🏿‍🤝‍👩🏾': 4, + '👩🏿‍🦯': 4, + '👩🏿‍🦯‍➡️': 4, + '👩🏿‍🦰': 4, + '👩🏿‍🦱': 4, + '👩🏿‍🦲': 4, + '👩🏿‍🦳': 4, + '👩🏿‍🦼': 4, + '👩🏿‍🦼‍➡️': 4, + '👩🏿‍🦽': 4, + '👩🏿‍🦽‍➡️': 4, + '👩🏿‍🫯‍👩🏻': 4, + '👩🏿‍🫯‍👩🏼': 4, + '👩🏿‍🫯‍👩🏽': 4, + '👩🏿‍🫯‍👩🏾': 4, + '👮🏻‍♀️': 4, + '👮🏻‍♂️': 4, + '👮🏼‍♀️': 4, + '👮🏼‍♂️': 4, + '👮🏽‍♀️': 4, + '👮🏽‍♂️': 4, + '👮🏾‍♀️': 4, + '👮🏾‍♂️': 4, + '👮🏿‍♀️': 4, + '👮🏿‍♂️': 4, + '👯🏻‍♀️': 4, + '👯🏻‍♂️': 4, + '👯🏼‍♀️': 4, + '👯🏼‍♂️': 4, + '👯🏽‍♀️': 4, + '👯🏽‍♂️': 4, + '👯🏾‍♀️': 4, + '👯🏾‍♂️': 4, + '👯🏿‍♀️': 4, + '👯🏿‍♂️': 4, + '👰🏻‍♀️': 4, + '👰🏻‍♂️': 4, + '👰🏼‍♀️': 4, + '👰🏼‍♂️': 4, + '👰🏽‍♀️': 4, + '👰🏽‍♂️': 4, + '👰🏾‍♀️': 4, + '👰🏾‍♂️': 4, + '👰🏿‍♀️': 4, + '👰🏿‍♂️': 4, + '👱🏻‍♀️': 4, + '👱🏻‍♂️': 4, + '👱🏼‍♀️': 4, + '👱🏼‍♂️': 4, + '👱🏽‍♀️': 4, + '👱🏽‍♂️': 4, + '👱🏾‍♀️': 4, + '👱🏾‍♂️': 4, + '👱🏿‍♀️': 4, + '👱🏿‍♂️': 4, + '👳🏻‍♀️': 4, + '👳🏻‍♂️': 4, + '👳🏼‍♀️': 4, + '👳🏼‍♂️': 4, + '👳🏽‍♀️': 4, + '👳🏽‍♂️': 4, + '👳🏾‍♀️': 4, + '👳🏾‍♂️': 4, + '👳🏿‍♀️': 4, + '👳🏿‍♂️': 4, + '👷🏻‍♀️': 4, + '👷🏻‍♂️': 4, + '👷🏼‍♀️': 4, + '👷🏼‍♂️': 4, + '👷🏽‍♀️': 4, + '👷🏽‍♂️': 4, + '👷🏾‍♀️': 4, + '👷🏾‍♂️': 4, + '👷🏿‍♀️': 4, + '👷🏿‍♂️': 4, + '💁🏻‍♀️': 4, + '💁🏻‍♂️': 4, + '💁🏼‍♀️': 4, + '💁🏼‍♂️': 4, + '💁🏽‍♀️': 4, + '💁🏽‍♂️': 4, + '💁🏾‍♀️': 4, + '💁🏾‍♂️': 4, + '💁🏿‍♀️': 4, + '💁🏿‍♂️': 4, + '💂🏻‍♀️': 4, + '💂🏻‍♂️': 4, + '💂🏼‍♀️': 4, + '💂🏼‍♂️': 4, + '💂🏽‍♀️': 4, + '💂🏽‍♂️': 4, + '💂🏾‍♀️': 4, + '💂🏾‍♂️': 4, + '💂🏿‍♀️': 4, + '💂🏿‍♂️': 4, + '💆🏻‍♀️': 4, + '💆🏻‍♂️': 4, + '💆🏼‍♀️': 4, + '💆🏼‍♂️': 4, + '💆🏽‍♀️': 4, + '💆🏽‍♂️': 4, + '💆🏾‍♀️': 4, + '💆🏾‍♂️': 4, + '💆🏿‍♀️': 4, + '💆🏿‍♂️': 4, + '💇🏻‍♀️': 4, + '💇🏻‍♂️': 4, + '💇🏼‍♀️': 4, + '💇🏼‍♂️': 4, + '💇🏽‍♀️': 4, + '💇🏽‍♂️': 4, + '💇🏾‍♀️': 4, + '💇🏾‍♂️': 4, + '💇🏿‍♀️': 4, + '💇🏿‍♂️': 4, + '🕵🏻‍♀️': 3, + '🕵🏻‍♂️': 3, + '🕵🏼‍♀️': 3, + '🕵🏼‍♂️': 3, + '🕵🏽‍♀️': 3, + '🕵🏽‍♂️': 3, + '🕵🏾‍♀️': 3, + '🕵🏾‍♂️': 3, + '🕵🏿‍♀️': 3, + '🕵🏿‍♂️': 3, + '🙅🏻‍♀️': 4, + '🙅🏻‍♂️': 4, + '🙅🏼‍♀️': 4, + '🙅🏼‍♂️': 4, + '🙅🏽‍♀️': 4, + '🙅🏽‍♂️': 4, + '🙅🏾‍♀️': 4, + '🙅🏾‍♂️': 4, + '🙅🏿‍♀️': 4, + '🙅🏿‍♂️': 4, + '🙆🏻‍♀️': 4, + '🙆🏻‍♂️': 4, + '🙆🏼‍♀️': 4, + '🙆🏼‍♂️': 4, + '🙆🏽‍♀️': 4, + '🙆🏽‍♂️': 4, + '🙆🏾‍♀️': 4, + '🙆🏾‍♂️': 4, + '🙆🏿‍♀️': 4, + '🙆🏿‍♂️': 4, + '🙇🏻‍♀️': 4, + '🙇🏻‍♂️': 4, + '🙇🏼‍♀️': 4, + '🙇🏼‍♂️': 4, + '🙇🏽‍♀️': 4, + '🙇🏽‍♂️': 4, + '🙇🏾‍♀️': 4, + '🙇🏾‍♂️': 4, + '🙇🏿‍♀️': 4, + '🙇🏿‍♂️': 4, + '🙋🏻‍♀️': 4, + '🙋🏻‍♂️': 4, + '🙋🏼‍♀️': 4, + '🙋🏼‍♂️': 4, + '🙋🏽‍♀️': 4, + '🙋🏽‍♂️': 4, + '🙋🏾‍♀️': 4, + '🙋🏾‍♂️': 4, + '🙋🏿‍♀️': 4, + '🙋🏿‍♂️': 4, + '🙍🏻‍♀️': 4, + '🙍🏻‍♂️': 4, + '🙍🏼‍♀️': 4, + '🙍🏼‍♂️': 4, + '🙍🏽‍♀️': 4, + '🙍🏽‍♂️': 4, + '🙍🏾‍♀️': 4, + '🙍🏾‍♂️': 4, + '🙍🏿‍♀️': 4, + '🙍🏿‍♂️': 4, + '🙎🏻‍♀️': 4, + '🙎🏻‍♂️': 4, + '🙎🏼‍♀️': 4, + '🙎🏼‍♂️': 4, + '🙎🏽‍♀️': 4, + '🙎🏽‍♂️': 4, + '🙎🏾‍♀️': 4, + '🙎🏾‍♂️': 4, + '🙎🏿‍♀️': 4, + '🙎🏿‍♂️': 4, + '🚣🏻‍♀️': 4, + '🚣🏻‍♂️': 4, + '🚣🏼‍♀️': 4, + '🚣🏼‍♂️': 4, + '🚣🏽‍♀️': 4, + '🚣🏽‍♂️': 4, + '🚣🏾‍♀️': 4, + '🚣🏾‍♂️': 4, + '🚣🏿‍♀️': 4, + '🚣🏿‍♂️': 4, + '🚴🏻‍♀️': 4, + '🚴🏻‍♂️': 4, + '🚴🏼‍♀️': 4, + '🚴🏼‍♂️': 4, + '🚴🏽‍♀️': 4, + '🚴🏽‍♂️': 4, + '🚴🏾‍♀️': 4, + '🚴🏾‍♂️': 4, + '🚴🏿‍♀️': 4, + '🚴🏿‍♂️': 4, + '🚵🏻‍♀️': 4, + '🚵🏻‍♂️': 4, + '🚵🏼‍♀️': 4, + '🚵🏼‍♂️': 4, + '🚵🏽‍♀️': 4, + '🚵🏽‍♂️': 4, + '🚵🏾‍♀️': 4, + '🚵🏾‍♂️': 4, + '🚵🏿‍♀️': 4, + '🚵🏿‍♂️': 4, + '🚶🏻‍♀️': 4, + '🚶🏻‍♀️‍➡️': 4, + '🚶🏻‍♂️': 4, + '🚶🏻‍♂️‍➡️': 4, + '🚶🏻‍➡️': 4, + '🚶🏼‍♀️': 4, + '🚶🏼‍♀️‍➡️': 4, + '🚶🏼‍♂️': 4, + '🚶🏼‍♂️‍➡️': 4, + '🚶🏼‍➡️': 4, + '🚶🏽‍♀️': 4, + '🚶🏽‍♀️‍➡️': 4, + '🚶🏽‍♂️': 4, + '🚶🏽‍♂️‍➡️': 4, + '🚶🏽‍➡️': 4, + '🚶🏾‍♀️': 4, + '🚶🏾‍♀️‍➡️': 4, + '🚶🏾‍♂️': 4, + '🚶🏾‍♂️‍➡️': 4, + '🚶🏾‍➡️': 4, + '🚶🏿‍♀️': 4, + '🚶🏿‍♀️‍➡️': 4, + '🚶🏿‍♂️': 4, + '🚶🏿‍♂️‍➡️': 4, + '🚶🏿‍➡️': 4, + '🤦🏻‍♀️': 4, + '🤦🏻‍♂️': 4, + '🤦🏼‍♀️': 4, + '🤦🏼‍♂️': 4, + '🤦🏽‍♀️': 4, + '🤦🏽‍♂️': 4, + '🤦🏾‍♀️': 4, + '🤦🏾‍♂️': 4, + '🤦🏿‍♀️': 4, + '🤦🏿‍♂️': 4, + '🤵🏻‍♀️': 4, + '🤵🏻‍♂️': 4, + '🤵🏼‍♀️': 4, + '🤵🏼‍♂️': 4, + '🤵🏽‍♀️': 4, + '🤵🏽‍♂️': 4, + '🤵🏾‍♀️': 4, + '🤵🏾‍♂️': 4, + '🤵🏿‍♀️': 4, + '🤵🏿‍♂️': 4, + '🤷🏻‍♀️': 4, + '🤷🏻‍♂️': 4, + '🤷🏼‍♀️': 4, + '🤷🏼‍♂️': 4, + '🤷🏽‍♀️': 4, + '🤷🏽‍♂️': 4, + '🤷🏾‍♀️': 4, + '🤷🏾‍♂️': 4, + '🤷🏿‍♀️': 4, + '🤷🏿‍♂️': 4, + '🤸🏻‍♀️': 4, + '🤸🏻‍♂️': 4, + '🤸🏼‍♀️': 4, + '🤸🏼‍♂️': 4, + '🤸🏽‍♀️': 4, + '🤸🏽‍♂️': 4, + '🤸🏾‍♀️': 4, + '🤸🏾‍♂️': 4, + '🤸🏿‍♀️': 4, + '🤸🏿‍♂️': 4, + '🤹🏻‍♀️': 4, + '🤹🏻‍♂️': 4, + '🤹🏼‍♀️': 4, + '🤹🏼‍♂️': 4, + '🤹🏽‍♀️': 4, + '🤹🏽‍♂️': 4, + '🤹🏾‍♀️': 4, + '🤹🏾‍♂️': 4, + '🤹🏿‍♀️': 4, + '🤹🏿‍♂️': 4, + '🤼🏻‍♀️': 4, + '🤼🏻‍♂️': 4, + '🤼🏼‍♀️': 4, + '🤼🏼‍♂️': 4, + '🤼🏽‍♀️': 4, + '🤼🏽‍♂️': 4, + '🤼🏾‍♀️': 4, + '🤼🏾‍♂️': 4, + '🤼🏿‍♀️': 4, + '🤼🏿‍♂️': 4, + '🤽🏻‍♀️': 4, + '🤽🏻‍♂️': 4, + '🤽🏼‍♀️': 4, + '🤽🏼‍♂️': 4, + '🤽🏽‍♀️': 4, + '🤽🏽‍♂️': 4, + '🤽🏾‍♀️': 4, + '🤽🏾‍♂️': 4, + '🤽🏿‍♀️': 4, + '🤽🏿‍♂️': 4, + '🤾🏻‍♀️': 4, + '🤾🏻‍♂️': 4, + '🤾🏼‍♀️': 4, + '🤾🏼‍♂️': 4, + '🤾🏽‍♀️': 4, + '🤾🏽‍♂️': 4, + '🤾🏾‍♀️': 4, + '🤾🏾‍♂️': 4, + '🤾🏿‍♀️': 4, + '🤾🏿‍♂️': 4, + '🦸🏻‍♀️': 4, + '🦸🏻‍♂️': 4, + '🦸🏼‍♀️': 4, + '🦸🏼‍♂️': 4, + '🦸🏽‍♀️': 4, + '🦸🏽‍♂️': 4, + '🦸🏾‍♀️': 4, + '🦸🏾‍♂️': 4, + '🦸🏿‍♀️': 4, + '🦸🏿‍♂️': 4, + '🦹🏻‍♀️': 4, + '🦹🏻‍♂️': 4, + '🦹🏼‍♀️': 4, + '🦹🏼‍♂️': 4, + '🦹🏽‍♀️': 4, + '🦹🏽‍♂️': 4, + '🦹🏾‍♀️': 4, + '🦹🏾‍♂️': 4, + '🦹🏿‍♀️': 4, + '🦹🏿‍♂️': 4, + '🧍🏻‍♀️': 4, + '🧍🏻‍♂️': 4, + '🧍🏼‍♀️': 4, + '🧍🏼‍♂️': 4, + '🧍🏽‍♀️': 4, + '🧍🏽‍♂️': 4, + '🧍🏾‍♀️': 4, + '🧍🏾‍♂️': 4, + '🧍🏿‍♀️': 4, + '🧍🏿‍♂️': 4, + '🧎🏻‍♀️': 4, + '🧎🏻‍♀️‍➡️': 4, + '🧎🏻‍♂️': 4, + '🧎🏻‍♂️‍➡️': 4, + '🧎🏻‍➡️': 4, + '🧎🏼‍♀️': 4, + '🧎🏼‍♀️‍➡️': 4, + '🧎🏼‍♂️': 4, + '🧎🏼‍♂️‍➡️': 4, + '🧎🏼‍➡️': 4, + '🧎🏽‍♀️': 4, + '🧎🏽‍♀️‍➡️': 4, + '🧎🏽‍♂️': 4, + '🧎🏽‍♂️‍➡️': 4, + '🧎🏽‍➡️': 4, + '🧎🏾‍♀️': 4, + '🧎🏾‍♀️‍➡️': 4, + '🧎🏾‍♂️': 4, + '🧎🏾‍♂️‍➡️': 4, + '🧎🏾‍➡️': 4, + '🧎🏿‍♀️': 4, + '🧎🏿‍♀️‍➡️': 4, + '🧎🏿‍♂️': 4, + '🧎🏿‍♂️‍➡️': 4, + '🧎🏿‍➡️': 4, + '🧏🏻‍♀️': 4, + '🧏🏻‍♂️': 4, + '🧏🏼‍♀️': 4, + '🧏🏼‍♂️': 4, + '🧏🏽‍♀️': 4, + '🧏🏽‍♂️': 4, + '🧏🏾‍♀️': 4, + '🧏🏾‍♂️': 4, + '🧏🏿‍♀️': 4, + '🧏🏿‍♂️': 4, + '🧑🏻‍⚕️': 4, + '🧑🏻‍⚖️': 4, + '🧑🏻‍✈️': 4, + '🧑🏻‍❤️‍💋‍🧑🏿': 4, + '🧑🏻‍🌾': 4, + '🧑🏻‍🍳': 4, + '🧑🏻‍🍼': 4, + '🧑🏻‍🎄': 4, + '🧑🏻‍🎓': 4, + '🧑🏻‍🎤': 4, + '🧑🏻‍🎨': 4, + '🧑🏻‍🏫': 4, + '🧑🏻‍🏭': 4, + '🧑🏻‍🐰‍🧑🏽': 4, + '🧑🏻‍🐰‍🧑🏾': 4, + '🧑🏻‍🐰‍🧑🏿': 4, + '🧑🏻‍💻': 4, + '🧑🏻‍💼': 4, + '🧑🏻‍🔧': 4, + '🧑🏻‍🔬': 4, + '🧑🏻‍🚀': 4, + '🧑🏻‍🚒': 4, + '🧑🏻‍🤝‍🧑🏻': 4, + '🧑🏻‍🤝‍🧑🏼': 4, + '🧑🏻‍🤝‍🧑🏽': 4, + '🧑🏻‍🤝‍🧑🏾': 4, + '🧑🏻‍🤝‍🧑🏿': 4, + '🧑🏻‍🦯': 4, + '🧑🏻‍🦯‍➡️': 4, + '🧑🏻‍🦰': 4, + '🧑🏻‍🦱': 4, + '🧑🏻‍🦲': 4, + '🧑🏻‍🦳': 4, + '🧑🏻‍🦼': 4, + '🧑🏻‍🦼‍➡️': 4, + '🧑🏻‍🦽': 4, + '🧑🏻‍🦽‍➡️': 4, + '🧑🏻‍🩰': 4, + '🧑🏻‍🫯‍🧑🏼': 4, + '🧑🏻‍🫯‍🧑🏽': 4, + '🧑🏻‍🫯‍🧑🏾': 4, + '🧑🏻‍🫯‍🧑🏿': 4, + '🧑🏼‍⚕️': 4, + '🧑🏼‍⚖️': 4, + '🧑🏼‍✈️': 4, + '🧑🏼‍🌾': 4, + '🧑🏼‍🍳': 4, + '🧑🏼‍🍼': 4, + '🧑🏼‍🎄': 4, + '🧑🏼‍🎓': 4, + '🧑🏼‍🎤': 4, + '🧑🏼‍🎨': 4, + '🧑🏼‍🏫': 4, + '🧑🏼‍🏭': 4, + '🧑🏼‍🐰‍🧑🏿': 4, + '🧑🏼‍💻': 4, + '🧑🏼‍💼': 4, + '🧑🏼‍🔧': 4, + '🧑🏼‍🔬': 4, + '🧑🏼‍🚀': 4, + '🧑🏼‍🚒': 4, + '🧑🏼‍🤝‍🧑🏻': 4, + '🧑🏼‍🤝‍🧑🏼': 4, + '🧑🏼‍🤝‍🧑🏽': 4, + '🧑🏼‍🤝‍🧑🏿': 4, + '🧑🏼‍🦯': 4, + '🧑🏼‍🦯‍➡️': 4, + '🧑🏼‍🦰': 4, + '🧑🏼‍🦱': 4, + '🧑🏼‍🦲': 4, + '🧑🏼‍🦳': 4, + '🧑🏼‍🦼': 4, + '🧑🏼‍🦽': 4, + '🧑🏼‍🩰': 4, + '🧑🏼‍🫯‍🧑🏻': 4, + '🧑🏼‍🫯‍🧑🏽': 4, + '🧑🏼‍🫯‍🧑🏿': 4, + '🧑🏽‍⚕️': 4, + '🧑🏽‍⚖️': 4, + '🧑🏽‍✈️': 4, + '🧑🏽‍❤️‍💋‍🧑🏿': 4, + '🧑🏽‍🌾': 4, + '🧑🏽‍🍳': 4, + '🧑🏽‍🍼': 4, + '🧑🏽‍🎄': 4, + '🧑🏽‍🎓': 4, + '🧑🏽‍🎤': 4, + '🧑🏽‍🎨': 4, + '🧑🏽‍🏫': 4, + '🧑🏽‍🏭': 4, + '🧑🏽‍🐰‍🧑🏻': 4, + '🧑🏽‍🐰‍🧑🏿': 4, + '🧑🏽‍💻': 4, + '🧑🏽‍💼': 4, + '🧑🏽‍🔧': 4, + '🧑🏽‍🔬': 4, + '🧑🏽‍🚀': 4, + '🧑🏽‍🚒': 4, + '🧑🏽‍🤝‍🧑🏻': 4, + '🧑🏽‍🤝‍🧑🏼': 4, + '🧑🏽‍🤝‍🧑🏽': 4, + '🧑🏽‍🤝‍🧑🏾': 4, + '🧑🏽‍🤝‍🧑🏿': 4, + '🧑🏽‍🦯': 4, + '🧑🏽‍🦯‍➡️': 4, + '🧑🏽‍🦰': 4, + '🧑🏽‍🦱': 4, + '🧑🏽‍🦲': 4, + '🧑🏽‍🦳': 4, + '🧑🏽‍🦼': 4, + '🧑🏽‍🦼‍➡️': 4, + '🧑🏽‍🦽': 4, + '🧑🏽‍🦽‍➡️': 4, + '🧑🏽‍🩰': 4, + '🧑🏽‍🫯‍🧑🏻': 4, + '🧑🏽‍🫯‍🧑🏼': 4, + '🧑🏽‍🫯‍🧑🏾': 4, + '🧑🏽‍🫯‍🧑🏿': 4, + '🧑🏾‍⚕️': 4, + '🧑🏾‍⚖️': 4, + '🧑🏾‍✈️': 4, + '🧑🏾‍🌾': 4, + '🧑🏾‍🍳': 4, + '🧑🏾‍🍼': 4, + '🧑🏾‍🎄': 4, + '🧑🏾‍🎓': 4, + '🧑🏾‍🎤': 4, + '🧑🏾‍🎨': 4, + '🧑🏾‍🏫': 4, + '🧑🏾‍🏭': 4, + '🧑🏾‍🐰‍🧑🏻': 4, + '🧑🏾‍🐰‍🧑🏿': 4, + '🧑🏾‍💻': 4, + '🧑🏾‍💼': 4, + '🧑🏾‍🔧': 4, + '🧑🏾‍🔬': 4, + '🧑🏾‍🚀': 4, + '🧑🏾‍🚒': 4, + '🧑🏾‍🤝‍🧑🏻': 4, + '🧑🏾‍🤝‍🧑🏽': 4, + '🧑🏾‍🤝‍🧑🏾': 4, + '🧑🏾‍🤝‍🧑🏿': 4, + '🧑🏾‍🦯': 4, + '🧑🏾‍🦯‍➡️': 4, + '🧑🏾‍🦰': 4, + '🧑🏾‍🦱': 4, + '🧑🏾‍🦲': 4, + '🧑🏾‍🦳': 4, + '🧑🏾‍🦼': 4, + '🧑🏾‍🦽': 4, + '🧑🏾‍🩰': 4, + '🧑🏾‍🫯‍🧑🏻': 4, + '🧑🏾‍🫯‍🧑🏽': 4, + '🧑🏾‍🫯‍🧑🏿': 4, + '🧑🏿‍⚕️': 4, + '🧑🏿‍⚖️': 4, + '🧑🏿‍✈️': 4, + '🧑🏿‍❤️‍💋‍🧑🏻': 4, + '🧑🏿‍❤️‍💋‍🧑🏽': 4, + '🧑🏿‍🌾': 4, + '🧑🏿‍🍳': 4, + '🧑🏿‍🍼': 4, + '🧑🏿‍🎄': 4, + '🧑🏿‍🎓': 4, + '🧑🏿‍🎤': 4, + '🧑🏿‍🎨': 4, + '🧑🏿‍🏫': 4, + '🧑🏿‍🏭': 4, + '🧑🏿‍🐰‍🧑🏻': 4, + '🧑🏿‍🐰‍🧑🏼': 4, + '🧑🏿‍🐰‍🧑🏽': 4, + '🧑🏿‍🐰‍🧑🏾': 4, + '🧑🏿‍💻': 4, + '🧑🏿‍💼': 4, + '🧑🏿‍🔧': 4, + '🧑🏿‍🔬': 4, + '🧑🏿‍🚀': 4, + '🧑🏿‍🚒': 4, + '🧑🏿‍🤝‍🧑🏻': 4, + '🧑🏿‍🤝‍🧑🏼': 4, + '🧑🏿‍🤝‍🧑🏽': 4, + '🧑🏿‍🤝‍🧑🏾': 4, + '🧑🏿‍🤝‍🧑🏿': 4, + '🧑🏿‍🦯': 4, + '🧑🏿‍🦯‍➡️': 4, + '🧑🏿‍🦰': 4, + '🧑🏿‍🦱': 4, + '🧑🏿‍🦲': 4, + '🧑🏿‍🦳': 4, + '🧑🏿‍🦼': 4, + '🧑🏿‍🦼‍➡️': 4, + '🧑🏿‍🦽': 4, + '🧑🏿‍🦽‍➡️': 4, + '🧑🏿‍🩰': 4, + '🧑🏿‍🫯‍🧑🏻': 4, + '🧑🏿‍🫯‍🧑🏼': 4, + '🧑🏿‍🫯‍🧑🏽': 4, + '🧑🏿‍🫯‍🧑🏾': 4, + '🧔🏻‍♀️': 4, + '🧔🏻‍♂️': 4, + '🧔🏼‍♀️': 4, + '🧔🏼‍♂️': 4, + '🧔🏽‍♀️': 4, + '🧔🏽‍♂️': 4, + '🧔🏾‍♀️': 4, + '🧔🏾‍♂️': 4, + '🧔🏿‍♀️': 4, + '🧔🏿‍♂️': 4, + '🧖🏻‍♀️': 4, + '🧖🏻‍♂️': 4, + '🧖🏼‍♀️': 4, + '🧖🏼‍♂️': 4, + '🧖🏽‍♀️': 4, + '🧖🏽‍♂️': 4, + '🧖🏾‍♀️': 4, + '🧖🏾‍♂️': 4, + '🧖🏿‍♀️': 4, + '🧖🏿‍♂️': 4, + '🧗🏻‍♀️': 4, + '🧗🏻‍♂️': 4, + '🧗🏼‍♀️': 4, + '🧗🏼‍♂️': 4, + '🧗🏽‍♀️': 4, + '🧗🏽‍♂️': 4, + '🧗🏾‍♀️': 4, + '🧗🏾‍♂️': 4, + '🧗🏿‍♀️': 4, + '🧗🏿‍♂️': 4, + '🧘🏻‍♀️': 4, + '🧘🏻‍♂️': 4, + '🧘🏼‍♀️': 4, + '🧘🏼‍♂️': 4, + '🧘🏽‍♀️': 4, + '🧘🏽‍♂️': 4, + '🧘🏾‍♀️': 4, + '🧘🏾‍♂️': 4, + '🧘🏿‍♀️': 4, + '🧘🏿‍♂️': 4, + '🧙🏻‍♀️': 4, + '🧙🏻‍♂️': 4, + '🧙🏼‍♀️': 4, + '🧙🏼‍♂️': 4, + '🧙🏽‍♀️': 4, + '🧙🏽‍♂️': 4, + '🧙🏾‍♀️': 4, + '🧙🏾‍♂️': 4, + '🧙🏿‍♀️': 4, + '🧙🏿‍♂️': 4, + '🧚🏻‍♀️': 4, + '🧚🏻‍♂️': 4, + '🧚🏼‍♀️': 4, + '🧚🏼‍♂️': 4, + '🧚🏽‍♀️': 4, + '🧚🏽‍♂️': 4, + '🧚🏾‍♀️': 4, + '🧚🏾‍♂️': 4, + '🧚🏿‍♀️': 4, + '🧚🏿‍♂️': 4, + '🧛🏻‍♀️': 4, + '🧛🏻‍♂️': 4, + '🧛🏼‍♀️': 4, + '🧛🏼‍♂️': 4, + '🧛🏽‍♀️': 4, + '🧛🏽‍♂️': 4, + '🧛🏾‍♀️': 4, + '🧛🏾‍♂️': 4, + '🧛🏿‍♀️': 4, + '🧛🏿‍♂️': 4, + '🧜🏻‍♀️': 4, + '🧜🏻‍♂️': 4, + '🧜🏼‍♀️': 4, + '🧜🏼‍♂️': 4, + '🧜🏽‍♀️': 4, + '🧜🏽‍♂️': 4, + '🧜🏾‍♀️': 4, + '🧜🏾‍♂️': 4, + '🧜🏿‍♀️': 4, + '🧜🏿‍♂️': 4, + '🧝🏻‍♀️': 4, + '🧝🏻‍♂️': 4, + '🧝🏼‍♀️': 4, + '🧝🏼‍♂️': 4, + '🧝🏽‍♀️': 4, + '🧝🏽‍♂️': 4, + '🧝🏾‍♀️': 4, + '🧝🏾‍♂️': 4, + '🧝🏿‍♀️': 4, + '🧝🏿‍♂️': 4, + '🫱🏻‍🫲🏼': 4, + '🫱🏻‍🫲🏽': 4, + '🫱🏻‍🫲🏾': 4, + '🫱🏻‍🫲🏿': 4, + '🫱🏼‍🫲🏻': 4, + '🫱🏼‍🫲🏽': 4, + '🫱🏼‍🫲🏾': 4, + '🫱🏼‍🫲🏿': 4, + '🫱🏽‍🫲🏻': 4, + '🫱🏽‍🫲🏼': 4, + '🫱🏽‍🫲🏾': 4, + '🫱🏽‍🫲🏿': 4, + '🫱🏾‍🫲🏻': 4, + '🫱🏾‍🫲🏼': 4, + '🫱🏾‍🫲🏽': 4, + '🫱🏾‍🫲🏿': 4, + '🫱🏿‍🫲🏻': 4, + '🫱🏿‍🫲🏼': 4, + '🫱🏿‍🫲🏽': 4, + '🫱🏿‍🫲🏾': 4, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_65c6beb5.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_65c6beb5.py new file mode 100644 index 0000000000000000000000000000000000000000..26032e157e4e854216bb52f7f9a7ccf0122172eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_65c6beb5.py @@ -0,0 +1,2748 @@ +""" +Grapheme overrides for _known_65c6beb5. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: warp +""" +# pylint: skip-file +GRAPHEMES = { + 'क्का': 3, + 'क्कां': 3, + 'क्को': 3, + 'क्घ्घि्': 4, + 'क्ता': 3, + 'क्ति': 3, + 'क्ती': 3, + 'क्तीं': 3, + 'क्तेः': 3, + 'क्त्योः': 5, + 'क्ना': 3, + 'क्नि': 3, + 'क्या': 3, + 'क्रा': 3, + 'क्रि': 3, + 'क्षा': 3, + 'क्षां': 3, + 'क्षाः': 4, + 'क्षि': 3, + 'क्षो': 3, + 'क्ष्ण': 3, + 'क्ष्य': 3, + 'क्ष्या': 4, + 'क्सा': 3, + 'ख्यः': 3, + 'ख्या': 3, + 'ग्या': 3, + 'ग्यैः': 3, + 'ग्र्य': 3, + 'घ्का': 3, + 'घ्र्व्य': 4, + 'घ्लि': 3, + 'घ्श्य': 3, + 'घ्स्ट': 3, + 'च्चा': 3, + 'च्चों': 3, + 'च्छा': 3, + 'च्छि': 3, + 'च्या': 3, + 'च्यां': 3, + 'च्यो': 3, + 'ज्ञा': 3, + 'ज्या': 3, + 'ज्या‌': 3, + 'ज्रा': 3, + 'ञ्चा': 3, + 'ञ्चि': 3, + 'ट्टि': 3, + 'ट्टी': 3, + 'ट्या': 3, + 'ट्रा': 3, + 'ण्डः': 3, + 'ण्डि': 3, + 'ण्या': 3, + 'ण्यां': 3, + 'ताः': 3, + 'त्का': 3, + 'त्ता': 3, + 'त्ति': 3, + 'त्त्थि': 4, + 'त्त्व': 3, + 'त्त्वा': 4, + 'त्त्वे': 3, + 'त्नी': 3, + 'त्नों': 3, + 'त्पा': 3, + 'त्पी': 3, + 'त्मा': 3, + 'त्या': 3, + 'त्यां': 3, + 'त्यि': 3, + 'त्रा': 3, + 'त्राा': 4, + 'त्राि': 4, + 'त्रि': 3, + 'त्री': 3, + 'त्र्त': 3, + 'त्र्य': 3, + 'त्र्या': 4, + 'त्र्ये': 3, + 'त्वा': 3, + 'त्वां': 3, + 'त्सा': 3, + 'त्सो': 3, + 'त्स्वा': 4, + 'द्घि': 3, + 'द्घो': 3, + 'द्दा': 3, + 'द्दि': 3, + 'द्दी': 3, + 'द्धः': 3, + 'द्धा': 3, + 'द्धां': 3, + 'द्धि': 3, + 'द्धिं': 3, + 'द्धी': 3, + 'द्धीं': 3, + 'द्धैः': 3, + 'द्भा': 3, + 'द्या': 3, + 'द्रो': 3, + 'द्वा': 3, + 'द्वि': 3, + 'धाः': 3, + 'ध्या': 3, + 'नाः': 3, + 'निः': 3, + 'न्का': 3, + 'न्चि': 3, + 'न्ञ्या': 4, + 'न्तः': 3, + 'न्ता': 3, + 'न्ति': 3, + 'न्तो': 3, + 'न्तों': 3, + 'न्त्र': 3, + 'न्त्रा': 4, + 'न्त्राः': 5, + 'न्त्रि': 4, + 'न्त्री': 4, + 'न्त्र्य': 4, + 'न्त्र्यं': 4, + 'न्त्र्या': 5, + 'न्त्र्ये': 4, + 'न्दा': 3, + 'न्दी': 3, + 'न्दो': 3, + 'न्धा': 3, + 'न्धि': 3, + 'न्धी': 3, + 'न्धों': 3, + 'न्ना': 3, + 'न्नाः': 4, + 'न्नि': 3, + 'न्मा': 3, + 'न्या': 3, + 'न्यो': 3, + 'न्हा': 3, + 'न्ह्यां': 4, + 'प्ति': 3, + 'प्तौ': 3, + 'प्या': 3, + 'प्रा': 3, + 'फ्ता': 3, + 'फ्ना': 3, + 'फ्नो': 3, + 'फ्रां': 3, + 'ब्धि': 3, + 'भिः': 3, + 'भ्यः': 3, + 'भ्या': 3, + 'भ्यां': 3, + 'भ्यो': 3, + 'म्ति': 3, + 'म्नि': 3, + 'म्पा': 3, + 'म्प्र': 3, + 'म्भि': 3, + 'म्मा': 3, + 'म्मि': 3, + 'म्या': 3, + 'म्ही': 3, + 'म्हो': 3, + 'याः': 3, + 'य्यो': 3, + 'राः': 3, + 'र्कि': 3, + 'र्गी': 3, + 'र्चि': 3, + 'र्जा': 3, + 'र्जि': 3, + 'र्जी': 3, + 'र्णां': 3, + 'र्णी': 3, + 'र्ता': 3, + 'र्ति': 3, + 'र्तिः': 4, + 'र्ती': 3, + 'र्त्त': 3, + 'र्त्ति': 4, + 'र्थि': 3, + 'र्थी': 3, + 'र्दा': 3, + 'र्दि': 3, + 'र्दो': 3, + 'र्द्ध': 3, + 'र्धा': 3, + 'र्धि': 3, + 'र्नि': 3, + 'र्बा': 3, + 'र्भा': 3, + 'र्मा': 3, + 'र्मि': 3, + 'र्या': 3, + 'र्यां': 3, + 'र्यों': 3, + 'र्रा': 3, + 'र्वा': 3, + 'र्वां': 3, + 'र्वो': 3, + 'र्सा': 3, + 'र्हाः': 4, + 'र्हि': 3, + 'र्हो': 3, + 'र्‍या': 3, + 'लाः': 3, + 'ल्का': 3, + 'ल्पि': 3, + 'ल्या': 3, + 'ल्यां': 3, + 'ल्याः': 4, + 'ल्ला': 3, + 'ल्लि': 3, + 'वाः': 3, + 'व्या': 3, + 'व्यों': 3, + 'शाः': 3, + 'श्चि': 3, + 'श्या': 3, + 'श्यि': 3, + 'श्यों': 3, + 'श्रा': 3, + 'श्रां': 3, + 'श्वा': 3, + 'श्वि': 3, + 'षाः': 3, + 'ष्का': 3, + 'ष्टः': 3, + 'ष्टा': 3, + 'ष्टां': 3, + 'ष्टाः': 4, + 'ष्टि': 3, + 'ष्टी': 3, + 'ष्टीं': 3, + 'ष्ट्र': 3, + 'ष्ट्रा': 4, + 'ष्ट्रां': 4, + 'ष्ट्रि': 4, + 'ष्ट्री': 4, + 'ष्ट्रे': 3, + 'ष्ट्रो': 4, + 'ष्ट्रों': 4, + 'ष्ठा': 3, + 'ष्ठों': 3, + 'ष्प्र': 3, + 'ष्यः': 3, + 'ष्यों': 3, + 'स्का': 3, + 'स्काः': 4, + 'स्ट्या': 4, + 'स्ता': 3, + 'स्ति': 3, + 'स्ती': 3, + 'स्तो': 3, + 'स्त्र': 3, + 'स्त्रा': 4, + 'स्त्रि': 4, + 'स्त्री': 4, + 'स्था': 3, + 'स्थां': 3, + 'स्थि': 3, + 'स्थी': 3, + 'स्थ्य': 3, + 'स्धी': 3, + 'स्मि': 3, + 'स्मिं': 3, + 'स्या': 3, + 'स्यां': 3, + 'स्याः': 4, + 'स्युः': 3, + 'स्यों': 3, + 'स्रो': 3, + 'स्वा': 3, + 'स्वी': 3, + 'स्सा': 3, + 'ह्या': 3, + 'ह्रा': 3, + 'फ़्ता': 3, + 'কা': 1, + 'কা‌': 1, + 'কিং': 3, + 'ক্তি': 3, + 'ক্রী': 3, + 'ক্ষি': 3, + 'ক্ষে': 3, + 'ক্ষ্য': 3, + 'ক্ষ্যে': 4, + 'খা': 1, + 'গ্রে': 3, + 'ঘা': 1, + 'ঙ্গী': 3, + 'ঙ্গে': 3, + 'চা': 1, + 'চ্ছে': 3, + 'ছা': 1, + 'জা': 1, + 'ঞ্চি': 3, + 'ঞ্ছি': 3, + 'টা': 1, + 'ট্রে': 3, + 'ড়া': 1, + 'ণা': 1, + 'ণ্ডে': 3, + 'তা': 1, + 'তাঁ': 1, + 'তা‌': 1, + 'ত্তি': 3, + 'ত্বে': 3, + 'ত্যি': 3, + 'ত্যে': 3, + 'ত্রে': 3, + 'ত্‍পী': 3, + 'থা': 1, + 'দা': 1, + 'দ্দি': 3, + 'দ্দে': 3, + 'দ্ধি': 3, + 'দ্ধে': 3, + 'দ্রো': 3, + 'ধা': 1, + 'ধ্যে': 3, + 'না': 1, + 'না‌': 1, + 'ন্তি': 3, + 'ন্তে': 3, + 'ন্ত্রি': 4, + 'ন্ত্রে': 4, + 'ন্থী': 3, + 'ন্যে': 3, + 'পা': 1, + 'পা‌': 1, + 'বা': 1, + 'বা‌': 1, + 'ব্ধি': 3, + 'ভা': 1, + 'মা': 1, + 'মা‌': 1, + 'য়া': 1, + 'যা': 1, + 'রা': 1, + 'র্থে': 3, + 'র্দো': 3, + 'র্নী': 3, + 'র্বি': 3, + 'র্বো': 3, + 'র্ব্য': 3, + 'র্মে': 3, + 'লা': 1, + 'ল্যে': 3, + 'ল্লে': 3, + 'শা': 1, + 'শ্চি': 3, + 'শ্বে': 3, + 'শ্যে': 3, + 'ষা': 1, + 'ষ্টি': 3, + 'ষ্ট্র': 3, + 'ষ্ট্রী': 4, + 'ষ্ট্রে': 4, + 'ষ্ঠি': 3, + 'ষ্ঠী': 3, + 'সা': 1, + 'স্তি': 3, + 'স্তি‌': 3, + 'স্ত্র': 3, + 'স্থ্য': 3, + 'স্বী': 3, + 'স্যে': 3, + 'হা': 1, + 'ક્કા': 3, + 'ક્કો': 3, + 'ક્તિ': 3, + 'ક્ષા': 3, + 'ચ્ચા': 3, + 'ચ્છા': 3, + 'જ્ઞા': 3, + 'જ્યો': 3, + 'ત્તા': 3, + 'ત્તિ': 3, + 'ત્ત્વ': 3, + 'ત્ત્વા': 4, + 'ત્યા': 3, + 'ત્યાં': 3, + 'ત્યિ': 3, + 'ત્યો': 3, + 'ત્રી': 3, + 'ત્ર્ય': 3, + 'દ્ધા': 3, + 'દ્ધાં': 3, + 'દ્ધિ': 3, + 'દ્વા': 3, + 'ધ્યા': 3, + 'ન્તો': 3, + 'ન્મા': 3, + 'ન્યા': 3, + 'પ્રા': 3, + 'મ્યાં': 3, + 'ર્તા': 3, + 'ર્થિ': 3, + 'ર્દો': 3, + 'ર્મિ': 3, + 'ર્યા': 3, + 'ર્યો': 3, + 'વ્યા': 3, + 'વ્યો': 3, + 'ષ્ટિ': 3, + 'ષ્ટ્ર': 3, + 'ષ્ટ્રી': 4, + 'ષ્ટ્રો': 4, + 'ષ્ઠા': 3, + 'સ્તિ': 3, + 'સ્તી': 3, + 'સ્ત્રી': 4, + 'સ્થા': 3, + 'સ્થિ': 3, + 'સ્રી': 3, + 'સ્વા': 3, + 'સ્વી': 3, + 'સ્સા': 3, + 'கா': 1, + 'சா': 1, + 'டா': 1, + 'ணா': 1, + 'தா': 1, + 'நா': 1, + 'னா': 1, + 'பா': 1, + 'மா': 1, + 'யா': 1, + 'ரா': 1, + 'றா': 1, + 'லா': 1, + 'ளா': 1, + 'வா': 1, + 'కుం': 3, + 'క్కు': 3, + 'క్తు': 3, + 'క్రాం': 3, + 'క్రూ': 3, + 'క్షిం': 3, + 'క్స్వా': 3, + 'చ్చు': 3, + 'టుం': 3, + 'ట్లు': 3, + 'డ్రు': 3, + 'త్తు': 3, + 'త్నిం': 3, + 'త్యం': 3, + 'త్రు': 3, + 'త్ర్య': 3, + 'దుం': 3, + 'ద్దు': 3, + 'ద్ధిం': 3, + 'ద్ర్య': 3, + 'నుం': 3, + 'న్ను': 3, + 'భ్యు': 3, + 'యుం': 3, + 'ర్చు': 3, + 'ర్ణాం': 3, + 'ర్ణు': 3, + 'ర్తిం': 3, + 'ర్తృ': 3, + 'ర్థిం': 3, + 'ర్బం': 3, + 'ర్హాం': 3, + 'ర్హు': 3, + 'శ్రాం': 3, + 'ష్టు': 3, + 'ష్ట్ర': 3, + 'ష్ట్రీ': 3, + 'ష్ఠు': 3, + 'స్కృ': 3, + 'స్త్ర': 3, + 'స్త్రీ': 3, + 'స్థ్య': 3, + 'ಕಾಂ': 3, + 'ಕೀ': 1, + 'ಕುಂ': 3, + 'ಕೂ': 1, + 'ಕೇ': 1, + 'ಕೈ': 1, + 'ಕೊ': 1, + 'ಖಾಂ': 3, + 'ಗಾಂ': 3, + 'ಗೀ': 1, + 'ಗೂ': 1, + 'ಗೈ': 1, + 'ಗೊ': 1, + 'ಗೋ': 1, + 'ಚೀ': 1, + 'ಜೀ': 1, + 'ಟುಂ': 3, + 'ಟೇ': 1, + 'ಡೂ': 1, + 'ಢೀ': 1, + 'ಣೈ': 1, + 'ತೀ': 1, + 'ತೊ': 1, + 'ತೋ': 1, + 'ದೂ': 1, + 'ದೇ': 1, + 'ದೊ': 1, + 'ದೋ': 1, + 'ಧೀ': 1, + 'ಧೂ': 1, + 'ನಾಂ': 3, + 'ನೂ': 1, + 'ನೇ': 1, + 'ನೈ': 1, + 'ನೊ': 1, + 'ಪೂ': 1, + 'ಪೇ': 1, + 'ಬೇ': 1, + 'ಬೋ': 1, + 'ಭೀ': 1, + 'ಭೇ': 1, + 'ಭೋ': 1, + 'ಮೀ': 1, + 'ಮೂ': 1, + 'ಮೇ': 1, + 'ಮೈ': 1, + 'ಯುಂ': 3, + 'ಯೂ': 1, + 'ಯೇ': 1, + 'ಯೊ': 1, + 'ಯೋ': 1, + 'ರಾಂ': 3, + 'ರೀ': 1, + 'ರೂ': 1, + 'ರೊ': 1, + 'ರೋ': 1, + 'ಲೀ': 1, + 'ಲೂ': 1, + 'ಲೇ': 1, + 'ಲೋ': 1, + 'ಳೂ': 1, + 'ವೀ': 1, + 'ವುಂ': 3, + 'ವೂ': 1, + 'ವೇ': 1, + 'ವೈ': 1, + 'ವೋ': 1, + 'ಶಾಂ': 3, + 'ಶೀ': 1, + 'ಶೇ': 1, + 'ಷೇ': 1, + 'ಸಾಂ': 3, + 'ಸೂ': 1, + 'ಸೇ': 1, + 'ಹೇ': 1, + 'ಹೊ': 1, + 'ಹೋ': 1, + 'കാ': 1, + 'ക്കി': 3, + 'ക്കും': 3, + 'ക്കെ': 3, + 'ക്കേ': 3, + 'ക്കൊ': 3, + 'ക്കോ': 3, + 'ക്തി': 3, + 'ക്യം': 3, + 'ക്ഷി': 3, + 'ക്ഷേ': 3, + 'ഗ്ഗം': 3, + 'ഗ്യം': 3, + 'ങ്കി': 3, + 'ങ്കെ': 3, + 'ങ്കേ': 3, + 'ങ്ങി': 3, + 'ചാ': 1, + 'ച്ചി': 3, + 'ച്ചും': 3, + 'ച്ചെ': 3, + 'ച്ചേ': 3, + 'ജാ': 1, + 'ഞ്ഞി': 3, + 'ഞ്ഞെ': 3, + 'ടാ': 1, + 'ട്ടി': 3, + 'ട്ടോ': 3, + 'ണാ': 1, + 'ണ്ടി': 3, + 'ണ്ടും': 3, + 'ണ്ടെ': 3, + 'താ': 1, + 'ത്തി': 3, + 'ത്തും': 3, + 'ത്തെ': 3, + 'ത്തേ': 3, + 'ത്തോ': 3, + 'ത്നം': 3, + 'ത്നി': 3, + 'ത്യേ': 3, + 'ത്വം': 3, + 'ദാ': 1, + 'ദ്ധി': 3, + 'ധാ': 1, + 'നാ': 1, + 'ന്തം': 3, + 'ന്തെ': 3, + 'ന്ത്ര': 3, + 'ന്ത്ര്യ': 4, + 'ന്ത്ര്യം': 5, + 'ന്ധി': 3, + 'ന്നി': 3, + 'ന്നീ': 3, + 'ന്നും': 3, + 'ന്നെ': 3, + 'ന്നേ': 3, + 'ന്നോ': 3, + 'ന്യം': 3, + 'ന്യേ': 3, + 'ന്യോ': 3, + 'ന്റെ': 3, + 'ന്‍പി': 3, + 'പാ': 1, + 'പ്പി': 3, + 'പ്പെ': 3, + 'പ്പോ': 3, + 'ബാ': 1, + 'ബ്ലി': 3, + 'ഭാ': 1, + 'മാ': 1, + 'മ്പ്ര': 3, + 'മ്മി': 3, + 'യാ': 1, + 'യ്ക്കു': 3, + 'യ്തി': 3, + 'യ്യി': 3, + 'രാ': 1, + 'ര്യം': 3, + 'ര്‍ക്കു': 3, + 'ര്‍ക്കും': 4, + 'ര്‍ക്ക്‌': 3, + 'ര്‍ഗ്ഗം': 4, + 'ര്‍ച്ച': 3, + 'ര്‍ണ്ണ': 3, + 'ര്‍ത്ത': 3, + 'ര്‍ത്തി': 4, + 'ര്‍ത്തു': 3, + 'ര്‍ത്തേ': 4, + 'ര്‍ദേ': 3, + 'ര്‍ദ്ദ': 3, + 'ര്‍പ്പെ': 4, + 'ര്‍മ്മി': 4, + 'ര്‍വ്വ': 3, + 'ര്‍ഹി': 3, + 'റ്റം': 3, + 'റ്റേ': 3, + 'ലാ': 1, + 'ല്ലാം': 3, + 'ല്ലെ': 3, + 'ല്‍കി': 3, + 'ല്‍കേ': 3, + 'ല്‍നി': 3, + 'ല്‍പ്പ': 3, + 'ളാ': 1, + 'ള്ളി': 3, + 'ള്‍കൊ': 3, + 'ള്‍ക്ക': 3, + 'ള്‍ക്കി': 4, + 'ള്‍ക്കു': 3, + 'ള്‍ക്കും': 4, + 'ള്‍ക്കെ': 4, + 'ള്‍ക്ക്‌': 3, + 'വാ': 1, + 'വ്യം': 3, + 'ശാ': 1, + 'ഷ്ട്യാ': 3, + 'ഷ്ട്ര': 3, + 'ഷ്ട്രീ': 4, + 'സാ': 1, + 'സ്ത്രം': 4, + 'സ്ത്രീ': 4, + 'സ്ഥി': 3, + 'സ്റ്റ്‌': 3, + 'സ്വീ': 3, + 'സ്സി': 3, + 'സ്സും': 3, + 'സ്സോ': 3, + 'ഹാ': 1, + 'ഹിം': 3, + 'ൻ്റെ': 3, + 'කා': 1, + 'ගා': 1, + 'චා': 1, + 'ජා': 1, + 'ඥා': 1, + 'ටා': 1, + 'ඨා': 1, + 'ඩා': 1, + 'තා': 1, + 'ථා': 1, + 'දා': 1, + 'ධා': 1, + 'නා': 1, + 'ඳා': 1, + 'පා': 1, + 'බා': 1, + 'භා': 1, + 'මා': 1, + 'යා': 1, + 'රා': 1, + 'ලා': 1, + 'වා': 1, + 'ෂා': 1, + 'සා': 1, + 'හා': 1, + 'ကျေ': 3, + 'ကြေ': 3, + 'ကြွေ': 3, + 'ချေ': 3, + 'ခြေ': 3, + 'ဇြေ': 3, + 'ဒ္ဂေ': 3, + 'ပျေ': 3, + 'ပြေ': 3, + 'ဖျေံ': 3, + 'ဗ္တေ': 3, + 'ဗ္ၜေ': 3, + 'ဗြေ': 3, + 'မြေ': 3, + 'လျေ': 3, + 'လျှေ': 3, + 'သ္ဂေ': 3, + 'ក្ដៅ': 3, + 'ក្រោ': 3, + 'ក្សា': 3, + 'ខ្ជា': 3, + 'ខ្លា': 3, + 'គ្នា': 3, + 'គ្មា': 3, + 'គ្រា': 3, + 'គ្រឹះ': 3, + 'ង្កើ': 3, + 'ង្រៀ': 3, + 'ង្ហា': 3, + 'ច្ចេ': 3, + 'ច្បា': 3, + 'ឆ្នាំ': 3, + 'ឆ្នោ': 3, + 'ឆ្លើ': 3, + 'ជ្ជា': 3, + 'ជ្ញា': 3, + 'ជ្រើ': 3, + 'ជ្រៀ': 3, + 'ជ្រែ': 3, + 'ឈ្មោះ': 4, + 'ញ្ជា': 3, + 'ញ្ញា': 3, + 'ញ្ញៈ': 3, + 'ដ្ឋា': 3, + 'ណោះ': 3, + 'ណ្ដា': 3, + 'ណ្ដុះ': 3, + 'ណ្ណោះ': 4, + 'ត្រា': 3, + 'ថ្ងៃ': 3, + 'ថ្នា': 3, + 'ថ្លៃ': 3, + 'ទោះ': 3, + 'ទ្យា': 3, + 'ធ្នា': 3, + 'ធ្យា': 3, + 'ធ្យោ': 3, + 'ធ្វើ': 3, + 'នេះ': 3, + 'នោះ': 3, + 'ន្ថែ': 3, + 'ន្ថោ': 3, + 'ន្ទា': 3, + 'ន្ទៈ': 3, + 'ន្យា': 3, + 'ន្លែ': 3, + 'បោះ': 3, + 'ប្ដេ': 3, + 'ប្រា': 3, + 'ប្រើ': 3, + 'ប្រែ': 3, + 'ផ្ដា': 3, + 'ផ្ទា': 3, + 'ផ្ទេ': 3, + 'ផ្នែ': 3, + 'ផ្លា': 3, + 'ផ្សា': 3, + 'ផ្សេ': 3, + 'ផ្សៃ': 3, + 'ពោះ': 3, + 'ព្យា': 3, + 'ព្រៀ': 3, + 'ព្រៃ': 3, + 'ម្ងា': 3, + 'ម្ចា': 3, + 'ម្ដា': 3, + 'ម្ដែ': 3, + 'ម្នា': 3, + 'ម្នេ': 3, + 'ម្ភា': 3, + 'ម្រា': 3, + 'ម្រើ': 3, + 'ម្រេ': 3, + 'ម្លៀ': 3, + 'ម្លៃ': 3, + 'ល្បៈ': 3, + 'ល្មើ': 3, + 'ស្គា': 3, + 'ស្ដ្រី': 3, + 'ស្ត្រ': 3, + 'ស្ថា': 3, + 'ស្នា': 3, + 'ស្មា': 3, + 'ស្មើ': 3, + 'ស្រា': 3, + 'ស្លា': 3, + 'ស្វែ': 3, + 'ᨠᩮ᩠ᨯᩨ': 3, + 'ᨠᩯ᩠ᨯ': 3, + 'ᨠᩯ᩠ᨶ᩵': 3, + 'ᨡᩮ᩠ᨲ': 3, + 'ᨡᩯ᩠ᨠ': 3, + 'ᨡᩯ᩠ᨦ': 3, + 'ᨣᩕ᩠ᩋ': 3, + 'ᨣᩕᩮ᩠ᨦᩨ᩵': 4, + 'ᨣᩯ᩠ᨶᩢ': 3, + 'ᨣᩯ᩠ᩅ': 3, + 'ᨧᩮ᩠ᨷ': 3, + 'ᨧᩱ᩠ᨿ': 3, + 'ᨩᩮ᩠ᩋᩨ': 3, + 'ᨩᩮ᩠ᩋᩨ᩵': 3, + 'ᨩᩮ᩠ᩋᩨ᩶': 3, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 3, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 3, + 'ᨯᩯ᩠ᨦ': 3, + 'ᨯᩯ᩠ᨶ': 3, + 'ᨯᩰ᩠ᨿ': 3, + 'ᨲᩮ᩠ᨠ': 3, + 'ᨲᩮ᩠ᨦ': 3, + 'ᨲᩮ᩠ᨾ': 3, + 'ᨲᩮ᩠ᨾᩨ᩵': 3, + 'ᨲᩯ᩠ᨠ': 3, + 'ᨲᩯ᩠ᨦ᩵': 3, + 'ᨲᩯ᩠ᨾᩢ': 3, + 'ᨲᩱ᩠ᨿ': 3, + 'ᨳᩮ᩠ᨶᩨ᩵': 3, + 'ᨳᩯ᩠ᨦᩢ': 3, + 'ᨳᩯ᩠ᨾ': 3, + 'ᨴᩮ᩠ᩈ': 3, + 'ᨴᩮ᩠ᩈᩱ': 4, + 'ᨴᩯ᩠ᨶ': 3, + 'ᨴᩰ᩠ᩈ': 3, + 'ᨶᩯ᩠ᨶ': 3, + 'ᨷᩮ᩠ᨦᩨ᩶': 3, + 'ᨸᩮ᩠ᨦᩨ': 3, + 'ᨸᩮ᩠ᨶ': 3, + 'ᨹᩮᩨ᩠ᨿ': 3, + 'ᨻᩕ᩠ᩋᩢ': 3, + 'ᨻᩮ᩠ᩋᩨ᩵': 3, + 'ᨽᩱ᩠ᨿ': 3, + 'ᨾᩮ᩠ᨠᩨ': 3, + 'ᨾᩮ᩠ᨦᩨ': 3, + 'ᨾᩮ᩠ᩋᩨ᩵': 3, + 'ᨿᩮ᩠ᨶ': 3, + 'ᨿᩮ᩠ᨾᩨ': 3, + 'ᩁᩮ᩠ᨦᩨ᩵': 3, + 'ᩁᩮ᩠ᨧ': 3, + 'ᩁᩮ᩠ᨶᩨ': 3, + 'ᩁᩮᩨ᩠ᨬ': 3, + 'ᩁᩯ᩠ᨦ': 3, + 'ᩃᩮ᩠ᨠᩨ': 3, + 'ᩃᩮ᩠ᨦᩨ': 3, + 'ᩃᩰ᩠ᨠ': 3, + 'ᩅᩮ᩠ᨶ': 3, + 'ᩅᩮ᩠ᨶᩢ': 3, + 'ᩈᩮ᩠ᩈ': 3, + 'ᩈᩯ᩠ᩅ': 3, + 'ᩈᩱ᩠ᨿ': 3, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 3, + 'ᩉᩮ᩠ᨦᩢᩢ': 3, + 'ᩉᩮ᩠ᨯ': 3, + 'ᩉᩮ᩠ᨲᩩ': 3, + 'ᩉᩮ᩠ᨶᩨ': 3, + 'ᩉᩮ᩠ᨾᩨ': 3, + 'ᩉᩮ᩠ᨾᩨᩨ': 3, + 'ᩉᩯ᩠ᨦ᩵': 3, + 'ᩉᩯ᩠ᨶᩢ': 3, + 'ᩉᩯ᩠ᨾ': 3, + 'ᩉᩱ᩠ᨾ᩵': 3, + 'ᩉᩱ᩠ᨿ᩵': 3, + 'ᩣ᩠ᨲᩱ': 3, + '⛓️‍💥': 5, + '⛹️‍♀️': 5, + '⛹️‍♂️': 5, + '⛹🏻‍♀️': 6, + '⛹🏻‍♂️': 6, + '⛹🏼‍♀️': 6, + '⛹🏼‍♂️': 6, + '⛹🏽‍♀️': 6, + '⛹🏽‍♂️': 6, + '⛹🏾‍♀️': 6, + '⛹🏾‍♂️': 6, + '⛹🏿‍♀️': 6, + '⛹🏿‍♂️': 6, + '❤️‍🔥': 5, + '❤️‍🩹': 5, + 'ꦏꦺꦴ': 3, + 'ꦏ꧀': 2, + 'ꦏ꧀ꦏ': 3, + 'ꦏ꧀ꦏꦁ': 3, + 'ꦏ꧀ꦏꦺ': 4, + 'ꦏ꧀ꦏꦼ': 3, + 'ꦏ꧀ꦔ': 3, + 'ꦏ꧀ꦔꦸ': 3, + 'ꦏ꧀ꦔꦿ': 4, + 'ꦏ꧀ꦕ': 3, + 'ꦏ꧀ꦠ': 3, + 'ꦏ꧀ꦠꦶ': 3, + 'ꦏ꧀ꦠꦸ': 3, + 'ꦏ꧀ꦠꦺ': 4, + 'ꦏ꧀ꦢ': 3, + 'ꦏ꧀ꦢꦂ': 3, + 'ꦏ꧀ꦢꦶ': 3, + 'ꦏ꧀ꦤ': 3, + 'ꦏ꧀ꦤꦶꦁ': 3, + 'ꦏ꧀ꦥ': 3, + 'ꦏ꧀ꦥꦶ': 3, + 'ꦏ꧀ꦥꦿꦶ': 4, + 'ꦏ꧀ꦧ': 3, + 'ꦏ꧀ꦧꦶ': 3, + 'ꦏ꧀ꦧꦺ': 4, + 'ꦏ꧀ꦩ': 3, + 'ꦏ꧀ꦩꦸ': 3, + 'ꦏ꧀ꦪ': 3, + 'ꦏ꧀ꦭ': 3, + 'ꦏ꧀ꦮ': 3, + 'ꦏ꧀ꦱ': 3, + 'ꦏ꧀ꦱꦂ': 3, + 'ꦏ꧀ꦱꦶ': 3, + 'ꦏ꧀ꦱꦸ': 3, + 'ꦏ꧀ꦱꦺ': 4, + 'ꦏ꧀ꦲ': 3, + 'ꦏ꧀ꦲꦁ': 3, + 'ꦏ꧀ꦲꦶꦁ': 3, + 'ꦏ꧀ꦲꦸ': 3, + 'ꦏ꧀ꦲꦺ': 4, + 'ꦏ꧀ꦲꦺꦴ': 5, + 'ꦒꦺꦴ': 3, + 'ꦒꦿꦺ': 3, + 'ꦒ꧀ꦒ': 3, + 'ꦔꦺꦴ': 3, + 'ꦔ꧀ꦒꦼ': 3, + 'ꦔ꧀ꦒꦿꦼꦁ': 4, + 'ꦔ꧀ꦭ': 3, + 'ꦔ꧀ꦭꦁ': 3, + 'ꦔ꧀ꦭꦸ': 3, + 'ꦔ꧀ꦭꦼ': 3, + 'ꦕꦺꦴ': 3, + 'ꦗꦿꦺꦴ': 4, + 'ꦚ꧀ꦕ': 3, + 'ꦚ꧀ꦕꦶ': 3, + 'ꦚ꧀ꦗ': 3, + 'ꦚ꧀ꦗꦶ': 3, + 'ꦚ꧀ꦗꦸꦁ': 3, + 'ꦚ꧀ꦗꦸꦂ': 3, + 'ꦝꦺꦴ': 3, + 'ꦝꦺꦴꦂ': 3, + 'ꦠꦺꦃ': 3, + 'ꦠꦺꦴ': 3, + 'ꦠ꧀': 2, + 'ꦠ꧀ꦏꦁ': 3, + 'ꦠ꧀ꦏꦸ': 3, + 'ꦠ꧀ꦒ': 3, + 'ꦠ꧀ꦔꦸ': 3, + 'ꦠ꧀ꦚ': 3, + 'ꦠ꧀ꦠ': 3, + 'ꦠ꧀ꦠꦶ': 3, + 'ꦠ꧀ꦠꦶꦁ': 3, + 'ꦠ꧀ꦠꦸ': 3, + 'ꦠ꧀ꦠꦺ': 4, + 'ꦠ꧀ꦤ': 3, + 'ꦠ꧀ꦤꦶ': 3, + 'ꦠ꧀ꦩ': 3, + 'ꦠ꧀ꦩꦼ': 3, + 'ꦠ꧀ꦭ': 3, + 'ꦠ꧀ꦭꦺ': 4, + 'ꦠ꧀ꦱ': 3, + 'ꦠ꧀ꦱꦶꦁ': 3, + 'ꦠ꧀ꦱꦶꦃ': 4, + 'ꦠ꧀ꦱꦾ': 4, + 'ꦠ꧀ꦱ꧀ꦮ': 5, + 'ꦠ꧀ꦲ': 3, + 'ꦠ꧀ꦲꦶꦁ': 3, + 'ꦠ꧀ꦲꦺꦴ': 5, + 'ꦢꦺꦴ': 3, + 'ꦢ꧀': 2, + 'ꦢ꧀ꦏ': 3, + 'ꦢ꧀ꦠ': 3, + 'ꦢ꧀ꦠꦶꦁ': 3, + 'ꦢ꧀ꦢ': 3, + 'ꦢ꧀ꦥ': 3, + 'ꦢ꧀ꦩꦺꦴ': 5, + 'ꦢ꧀ꦲ': 3, + 'ꦤꦺꦃ': 3, + 'ꦤꦺꦴ': 3, + 'ꦤ꧀': 2, + 'ꦤ꧀ꦏ': 3, + 'ꦤ꧀ꦏꦁ': 3, + 'ꦤ꧀ꦏꦸ': 3, + 'ꦤ꧀ꦏꦼ': 3, + 'ꦤ꧀ꦒ': 3, + 'ꦤ꧀ꦔ': 3, + 'ꦤ꧀ꦔꦁ': 3, + 'ꦤ꧀ꦔꦶ': 3, + 'ꦤ꧀ꦔꦸ': 3, + 'ꦤ꧀ꦔꦸꦂ': 3, + 'ꦤ꧀ꦔꦺ': 4, + 'ꦤ꧀ꦔꦼ': 3, + 'ꦤ꧀ꦔꦿꦸ': 4, + 'ꦤ꧀ꦗ': 3, + 'ꦤ꧀ꦗꦸ': 3, + 'ꦤ꧀ꦗꦼ': 3, + 'ꦤ꧀ꦚꦶ': 3, + 'ꦤ꧀ꦛꦃ': 4, + 'ꦤ꧀ꦛꦶ': 3, + 'ꦤ꧀ꦝ': 3, + 'ꦤ꧀ꦝꦁ': 3, + 'ꦤ꧀ꦝꦶ': 3, + 'ꦤ꧀ꦝꦸ': 3, + 'ꦤ꧀ꦝꦸꦁ': 3, + 'ꦤ꧀ꦝꦺꦁ': 4, + 'ꦤ꧀ꦝꦺꦴꦁ': 5, + 'ꦤ꧀ꦝꦼ': 3, + 'ꦤ꧀ꦠ': 3, + 'ꦤ꧀ꦠꦂ': 3, + 'ꦤ꧀ꦠꦃ': 4, + 'ꦤ꧀ꦠꦶ': 3, + 'ꦤ꧀ꦠꦸ': 3, + 'ꦤ꧀ꦠꦸꦁ': 3, + 'ꦤ꧀ꦠꦺ': 4, + 'ꦤ꧀ꦠꦼ': 3, + 'ꦤ꧀ꦠꦼꦂ': 3, + 'ꦤ꧀ꦠꦽ': 3, + 'ꦤ꧀ꦢ': 3, + 'ꦤ꧀ꦢꦁ': 3, + 'ꦤ꧀ꦢꦂ': 3, + 'ꦤ꧀ꦢꦶ': 3, + 'ꦤ꧀ꦢꦸ': 3, + 'ꦤ꧀ꦢꦺ': 4, + 'ꦤ꧀ꦢꦼ': 3, + 'ꦤ꧀ꦤ': 3, + 'ꦤ꧀ꦤꦶ': 3, + 'ꦤ꧀ꦤꦶꦁ': 3, + 'ꦤ꧀ꦤꦺ': 4, + 'ꦤ꧀ꦤꦼ': 3, + 'ꦤ꧀ꦥ': 3, + 'ꦤ꧀ꦥꦁ': 3, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 5, + 'ꦤ꧀ꦥꦶ': 3, + 'ꦤ꧀ꦥꦸ': 3, + 'ꦤ꧀ꦥꦼ': 3, + 'ꦤ꧀ꦥꦿ': 4, + 'ꦤ꧀ꦥꦿꦶ': 4, + 'ꦤ꧀ꦧ': 3, + 'ꦤ꧀ꦧꦁ': 3, + 'ꦤ꧀ꦧꦶ': 3, + 'ꦤ꧀ꦧꦸ': 3, + 'ꦤ꧀ꦧꦺ': 4, + 'ꦤ꧀ꦧꦺꦴ': 5, + 'ꦤ꧀ꦧꦼ': 3, + 'ꦤ꧀ꦩ': 3, + 'ꦤ꧀ꦩꦂ': 3, + 'ꦤ꧀ꦩꦶ': 3, + 'ꦤ꧀ꦩꦸꦂ': 3, + 'ꦤ꧀ꦩꦼ': 3, + 'ꦤ꧀ꦭ': 3, + 'ꦤ꧀ꦭꦶ': 3, + 'ꦤ꧀ꦭꦸ': 3, + 'ꦤ꧀ꦮ': 3, + 'ꦤ꧀ꦮꦂ': 3, + 'ꦤ꧀ꦮꦶ': 3, + 'ꦤ꧀ꦮꦸ': 3, + 'ꦤ꧀ꦮꦼ': 3, + 'ꦤ꧀ꦱ': 3, + 'ꦤ꧀ꦱꦂ': 3, + 'ꦤ꧀ꦱꦃ': 4, + 'ꦤ꧀ꦱꦶ': 3, + 'ꦤ꧀ꦱꦶꦁ': 3, + 'ꦤ꧀ꦱꦸ': 3, + 'ꦤ꧀ꦱꦺꦴ': 5, + 'ꦤ꧀ꦱꦼ': 3, + 'ꦤ꧀ꦲ': 3, + 'ꦤ꧀ꦲꦁ': 3, + 'ꦤ꧀ꦲꦶ': 3, + 'ꦤ꧀ꦲꦶꦁ': 3, + 'ꦤ꧀ꦲꦸ': 3, + 'ꦤ꧀ꦲꦺꦴ': 5, + 'ꦥ꦳꧀': 2, + 'ꦥꦺꦴ': 3, + 'ꦥꦿꦃ': 3, + 'ꦥꦿꦺꦴ': 4, + 'ꦥ꧀': 2, + 'ꦥ꧀ꦏ': 3, + 'ꦥ꧀ꦏꦁ': 3, + 'ꦥ꧀ꦠ': 3, + 'ꦥ꧀ꦠꦶ': 3, + 'ꦥ꧀ꦢꦸ': 3, + 'ꦥ꧀ꦤ': 3, + 'ꦥ꧀ꦤꦶ': 3, + 'ꦥ꧀ꦥ': 3, + 'ꦥ꧀ꦥꦶ': 3, + 'ꦥ꧀ꦥꦺ': 4, + 'ꦥ꧀ꦧꦺ': 4, + 'ꦥ꧀ꦩ': 3, + 'ꦥ꧀ꦩꦂ': 3, + 'ꦥ꧀ꦫꦺ': 4, + 'ꦥ꧀ꦭ': 3, + 'ꦥ꧀ꦭꦸ': 3, + 'ꦥ꧀ꦱ': 3, + 'ꦥ꧀ꦱꦶꦂ': 3, + 'ꦥ꧀ꦱꦼ': 3, + 'ꦥ꧀ꦲ': 3, + 'ꦧꦺꦃ': 3, + 'ꦧꦺꦴ': 3, + 'ꦧ꧀': 2, + 'ꦧ꧀ꦏ': 3, + 'ꦧ꧀ꦠꦸ': 3, + 'ꦧ꧀ꦥ': 3, + 'ꦧ꧀ꦧ': 3, + 'ꦧ꧀ꦧꦺ': 4, + 'ꦧ꧀ꦲ': 3, + 'ꦧ꧀ꦲꦶ': 3, + 'ꦩꦺꦃ': 3, + 'ꦩꦺꦴ': 3, + 'ꦩꦿꦃ': 3, + 'ꦩꦿꦶꦃ': 3, + 'ꦩ꧀': 2, + 'ꦩ꧀ꦏꦁ': 3, + 'ꦩ꧀ꦔꦼ': 3, + 'ꦩ꧀ꦠꦸ': 3, + 'ꦩ꧀ꦠꦺꦴ': 5, + 'ꦩ꧀ꦤꦶꦁ': 3, + 'ꦩ꧀ꦥ': 3, + 'ꦩ꧀ꦥꦶ': 3, + 'ꦩ꧀ꦥꦸ': 3, + 'ꦩ꧀ꦥꦼ': 3, + 'ꦩ꧀ꦧ': 3, + 'ꦩ꧀ꦧꦁ': 3, + 'ꦩ꧀ꦧꦂ': 3, + 'ꦩ꧀ꦧꦃ': 4, + 'ꦩ꧀ꦧꦶ': 3, + 'ꦩ꧀ꦧꦸ': 3, + 'ꦩ꧀ꦧꦸꦁ': 3, + 'ꦩ꧀ꦧꦺ': 4, + 'ꦩ꧀ꦧꦺꦂ': 4, + 'ꦩ꧀ꦧꦼꦂ': 3, + 'ꦩ꧀ꦧꦾꦸꦂ': 4, + 'ꦩ꧀ꦩ': 3, + 'ꦩ꧀ꦩꦶ': 3, + 'ꦩ꧀ꦫ': 3, + 'ꦩ꧀ꦫꦃ': 4, + 'ꦩ꧀ꦭ': 3, + 'ꦩ꧀ꦲꦶ': 3, + 'ꦪꦺꦴ': 3, + 'ꦫꦺꦴ': 3, + 'ꦭꦺꦃ': 3, + 'ꦭꦺꦴ': 3, + 'ꦭꦺꦴꦁ': 3, + 'ꦭ꧀': 2, + 'ꦭ꧀ꦏꦁ': 3, + 'ꦭ꧀ꦚꦼꦁ': 3, + 'ꦭ꧀ꦠꦸ': 3, + 'ꦭ꧀ꦧꦸ': 3, + 'ꦭ꧀ꦩꦸ': 3, + 'ꦭ꧀ꦭ': 3, + 'ꦭ꧀ꦭꦶ': 3, + 'ꦭ꧀ꦭꦶꦁ': 3, + 'ꦭ꧀ꦭꦺ': 4, + 'ꦭ꧀ꦮ': 3, + 'ꦭ꧀ꦱ': 3, + 'ꦭ꧀ꦱꦂ': 3, + 'ꦭ꧀ꦱꦶꦁ': 3, + 'ꦭ꧀ꦱꦸ': 3, + 'ꦭ꧀ꦲ': 3, + 'ꦭ꧀ꦲꦁ': 3, + 'ꦭ꧀ꦲꦶꦁ': 3, + 'ꦭ꧀ꦲꦸ': 3, + 'ꦮꦺꦴ': 3, + 'ꦮꦺꦴꦁ': 3, + 'ꦮꦺꦴꦃ': 4, + 'ꦮꦿꦸꦃ': 3, + 'ꦱꦺꦴ': 3, + 'ꦱꦿꦃ': 3, + 'ꦱ꧀': 2, + 'ꦱ꧀ꦏ': 3, + 'ꦱ꧀ꦏꦁ': 3, + 'ꦱ꧀ꦏꦿꦶ': 4, + 'ꦱ꧀ꦒ': 3, + 'ꦱ꧀ꦔꦸ': 3, + 'ꦱ꧀ꦔꦿ': 4, + 'ꦱ꧀ꦛꦶ': 3, + 'ꦱ꧀ꦠ': 3, + 'ꦱ꧀ꦠꦿ': 4, + 'ꦱ꧀ꦢꦂ': 3, + 'ꦱ꧀ꦢꦶ': 3, + 'ꦱ꧀ꦢꦸ': 3, + 'ꦱ꧀ꦥ': 3, + 'ꦱ꧀ꦧ': 3, + 'ꦱ꧀ꦧꦁ': 3, + 'ꦱ꧀ꦩ': 3, + 'ꦱ꧀ꦩꦶ': 3, + 'ꦱ꧀ꦩꦼ': 3, + 'ꦱ꧀ꦩꦿ': 4, + 'ꦱ꧀ꦭ': 3, + 'ꦱ꧀ꦮ': 3, + 'ꦱ꧀ꦱ': 3, + 'ꦱ꧀ꦱꦂ': 3, + 'ꦱ꧀ꦱꦶ': 3, + 'ꦱ꧀ꦱꦶꦁ': 3, + 'ꦱ꧀ꦱꦸ': 3, + 'ꦱ꧀ꦱꦺ': 4, + 'ꦱ꧀ꦲ': 3, + 'ꦱ꧀ꦲꦁ': 3, + 'ꦱ꧀ꦲꦶ': 3, + 'ꦱ꧀ꦲꦶꦁ': 3, + 'ꦱ꧀ꦲꦸ': 3, + 'ꦲꦺꦴ': 3, + '𑄇𑄳𑄠𑄬': 3, + '𑄈𑄳𑄠𑄬': 3, + '𑄌𑄳𑄠𑄬': 3, + '𑄎𑄳𑄠𑄬': 3, + '𑄑𑄳𑄢𑄬': 3, + '𑄖𑄳𑄠𑄬': 3, + '𑄖𑄳𑄢𑄬': 3, + '𑄘𑄳𑄠𑄬': 3, + '𑄚𑄳𑄠𑄬': 3, + '𑄝𑄳𑄢𑄬': 3, + '𑄟𑄳𑄠𑄬': 3, + '𑄡𑄳𑄠𑄬': 3, + '𑄣𑄳𑄦𑄬': 3, + '𑌕𑌾': 1, + '𑌕𑍍': 2, + '𑌗𑌾': 1, + '𑌗𑍍': 2, + '𑌘𑌾': 1, + '𑌚𑌾': 1, + '𑌚𑍍': 2, + '𑌛𑌾': 1, + '𑌜𑌾': 1, + '𑌜𑍍': 2, + '𑌞𑌾': 1, + '𑌞𑍍': 2, + '𑌟𑌾': 1, + '𑌟𑍍': 2, + '𑌠𑌾': 1, + '𑌠𑍈𑌃': 3, + '𑌣𑌾': 1, + '𑌣𑍍': 2, + '𑌤𑌾': 1, + '𑌤𑌿𑌂': 3, + '𑌤𑌿𑌃': 3, + '𑌤𑍁𑌂': 3, + '𑌤𑍇𑌃': 3, + '𑌤𑍍': 2, + '𑌥𑌾': 1, + '𑌦𑌾': 1, + '𑌦𑍍': 2, + '𑌧𑌾': 1, + '𑌧𑌿𑌂': 3, + '𑌧𑍇𑌃': 3, + '𑌧𑍈𑌃': 3, + '𑌧𑍍': 2, + '𑌨𑌾': 1, + '𑌨𑌿𑌃': 3, + '𑌨𑍈𑌃': 3, + '𑌨𑍍': 2, + '𑌪𑌾': 1, + '𑌪𑍍': 2, + '𑌬𑌾': 1, + '𑌬𑍍': 2, + '𑌭𑌾': 1, + '𑌭𑌿𑌃': 3, + '𑌭𑍍': 2, + '𑌮𑌾': 1, + '𑌮𑌿𑌂': 3, + '𑌮𑍍': 2, + '𑌯𑌾': 1, + '𑌯𑍁𑌃': 3, + '𑌯𑍈𑌃': 3, + '𑌯𑍋𑌃': 3, + '𑌯𑍍': 2, + '𑌰𑌾': 1, + '𑌰𑌿𑌂': 3, + '𑌰𑍍': 2, + '𑌲𑌾': 1, + '𑌲𑌿𑌂': 3, + '𑌲𑍍': 2, + '𑌵𑌾': 1, + '𑌵𑍍': 2, + '𑌶𑌾': 1, + '𑌶𑍍': 2, + '𑌷𑌾': 1, + '𑌷𑍍': 2, + '𑌸𑌾': 1, + '𑌸𑍍': 2, + '𑌹𑌾': 1, + '🍄‍🟫': 5, + '🍋‍🟩': 5, + '🏃‍♀️': 5, + '🏃‍♀️‍➡️': 8, + '🏃‍♂️': 5, + '🏃‍♂️‍➡️': 8, + '🏃‍➡️': 5, + '🏃🏻‍♀️': 7, + '🏃🏻‍♀️‍➡️': 10, + '🏃🏻‍♂️': 7, + '🏃🏻‍♂️‍➡️': 10, + '🏃🏻‍➡️': 7, + '🏃🏼‍♀️': 7, + '🏃🏼‍♀️‍➡️': 10, + '🏃🏼‍♂️': 7, + '🏃🏼‍♂️‍➡️': 10, + '🏃🏼‍➡️': 7, + '🏃🏽‍♀️': 7, + '🏃🏽‍♀️‍➡️': 10, + '🏃🏽‍♂️': 7, + '🏃🏽‍♂️‍➡️': 10, + '🏃🏽‍➡️': 7, + '🏃🏾‍♀️': 7, + '🏃🏾‍♀️‍➡️': 10, + '🏃🏾‍♂️': 7, + '🏃🏾‍♂️‍➡️': 10, + '🏃🏾‍➡️': 7, + '🏃🏿‍♀️': 7, + '🏃🏿‍♀️‍➡️': 10, + '🏃🏿‍♂️': 7, + '🏃🏿‍♂️‍➡️': 10, + '🏃🏿‍➡️': 7, + '🏄‍♀️': 5, + '🏄‍♂️': 5, + '🏄🏻‍♀️': 7, + '🏄🏻‍♂️': 7, + '🏄🏼‍♀️': 7, + '🏄🏼‍♂️': 7, + '🏄🏽‍♀️': 7, + '🏄🏽‍♂️': 7, + '🏄🏾‍♀️': 7, + '🏄🏾‍♂️': 7, + '🏄🏿‍♀️': 7, + '🏄🏿‍♂️': 7, + '🏊‍♀️': 5, + '🏊‍♂️': 5, + '🏊🏻‍♀️': 7, + '🏊🏻‍♂️': 7, + '🏊🏼‍♀️': 7, + '🏊🏼‍♂️': 7, + '🏊🏽‍♀️': 7, + '🏊🏽‍♂️': 7, + '🏊🏾‍♀️': 7, + '🏊🏾‍♂️': 7, + '🏊🏿‍♀️': 7, + '🏊🏿‍♂️': 7, + '🏋️‍♀️': 5, + '🏋️‍♂️': 5, + '🏋🏻‍♀️': 6, + '🏋🏻‍♂️': 6, + '🏋🏼‍♀️': 6, + '🏋🏼‍♂️': 6, + '🏋🏽‍♀️': 6, + '🏋🏽‍♂️': 6, + '🏋🏾‍♀️': 6, + '🏋🏾‍♂️': 6, + '🏋🏿‍♀️': 6, + '🏋🏿‍♂️': 6, + '🏌️‍♀️': 5, + '🏌️‍♂️': 5, + '🏌🏻‍♀️': 6, + '🏌🏻‍♂️': 6, + '🏌🏼‍♀️': 6, + '🏌🏼‍♂️': 6, + '🏌🏽‍♀️': 6, + '🏌🏽‍♂️': 6, + '🏌🏾‍♀️': 6, + '🏌🏾‍♂️': 6, + '🏌🏿‍♀️': 6, + '🏌🏿‍♂️': 6, + '🏳️‍⚧️': 5, + '🏳️‍🌈': 5, + '🏴‍☠️': 5, + '🏴󠁧󠁢󠁥󠁮󠁧󠁿': 3, + '🏴󠁧󠁢󠁳󠁣󠁴󠁿': 3, + '🏴󠁧󠁢󠁷󠁬󠁳󠁿': 3, + '🐈‍⬛': 5, + '🐕‍🦺': 5, + '🐦‍⬛': 5, + '🐦‍🔥': 5, + '🐻‍❄️': 5, + '👁️‍🗨️': 5, + '👨‍⚕️': 5, + '👨‍⚖️': 5, + '👨‍✈️': 5, + '👨‍❤️‍👨': 8, + '👨‍❤️‍💋‍👨': 11, + '👨‍🌾': 5, + '👨‍🍳': 5, + '👨‍🍼': 5, + '👨‍🎓': 5, + '👨‍🎤': 5, + '👨‍🎨': 5, + '👨‍🏫': 5, + '👨‍🏭': 5, + '👨‍👦': 5, + '👨‍👦‍👦': 8, + '👨‍👧': 5, + '👨‍👧‍👦': 8, + '👨‍👧‍👧': 8, + '👨‍👨‍👦': 8, + '👨‍👨‍👦‍👦': 11, + '👨‍👨‍👧': 8, + '👨‍👨‍👧‍👦': 11, + '👨‍👨‍👧‍👧': 11, + '👨‍👩‍👦': 8, + '👨‍👩‍👦‍👦': 11, + '👨‍👩‍👧': 8, + '👨‍👩‍👧‍👦': 11, + '👨‍👩‍👧‍👧': 11, + '👨‍💻': 5, + '👨‍💼': 5, + '👨‍🔧': 5, + '👨‍🔬': 5, + '👨‍🚀': 5, + '👨‍🚒': 5, + '👨‍🦯': 5, + '👨‍🦯‍➡️': 8, + '👨‍🦰': 5, + '👨‍🦱': 5, + '👨‍🦲': 5, + '👨‍🦳': 5, + '👨‍🦼': 5, + '👨‍🦼‍➡️': 8, + '👨‍🦽': 5, + '👨‍🦽‍➡️': 8, + '👨🏻‍⚕️': 7, + '👨🏻‍⚖️': 7, + '👨🏻‍✈️': 7, + '👨🏻‍❤️‍👨🏻': 12, + '👨🏻‍❤️‍👨🏽': 12, + '👨🏻‍❤️‍👨🏿': 12, + '👨🏻‍❤️‍💋‍👨🏻': 15, + '👨🏻‍❤️‍💋‍👨🏽': 15, + '👨🏻‍❤️‍💋‍👨🏾': 15, + '👨🏻‍❤️‍💋‍👨🏿': 15, + '👨🏻‍🌾': 7, + '👨🏻‍🍳': 7, + '👨🏻‍🍼': 7, + '👨🏻‍🎓': 7, + '👨🏻‍🎤': 7, + '👨🏻‍🎨': 7, + '👨🏻‍🏫': 7, + '👨🏻‍🏭': 7, + '👨🏻‍🐰‍👨🏼': 12, + '👨🏻‍🐰‍👨🏽': 12, + '👨🏻‍🐰‍👨🏾': 12, + '👨🏻‍🐰‍👨🏿': 12, + '👨🏻‍💻': 7, + '👨🏻‍💼': 7, + '👨🏻‍🔧': 7, + '👨🏻‍🔬': 7, + '👨🏻‍🚀': 7, + '👨🏻‍🚒': 7, + '👨🏻‍🤝‍👨🏼': 12, + '👨🏻‍🤝‍👨🏽': 12, + '👨🏻‍🤝‍👨🏾': 12, + '👨🏻‍🤝‍👨🏿': 12, + '👨🏻‍🦯': 7, + '👨🏻‍🦯‍➡️': 10, + '👨🏻‍🦰': 7, + '👨🏻‍🦱': 7, + '👨🏻‍🦲': 7, + '👨🏻‍🦳': 7, + '👨🏻‍🦼': 7, + '👨🏻‍🦼‍➡️': 10, + '👨🏻‍🦽': 7, + '👨🏻‍🦽‍➡️': 10, + '👨🏻‍🫯‍👨🏼': 10, + '👨🏻‍🫯‍👨🏽': 10, + '👨🏻‍🫯‍👨🏾': 10, + '👨🏻‍🫯‍👨🏿': 10, + '👨🏼‍⚕️': 7, + '👨🏼‍⚖️': 7, + '👨🏼‍✈️': 7, + '👨🏼‍❤️‍👨🏼': 12, + '👨🏼‍❤️‍💋‍👨🏼': 15, + '👨🏼‍❤️‍💋‍👨🏿': 15, + '👨🏼‍🌾': 7, + '👨🏼‍🍳': 7, + '👨🏼‍🍼': 7, + '👨🏼‍🎓': 7, + '👨🏼‍🎤': 7, + '👨🏼‍🎨': 7, + '👨🏼‍🏫': 7, + '👨🏼‍🏭': 7, + '👨🏼‍🐰‍👨🏻': 12, + '👨🏼‍🐰‍👨🏽': 12, + '👨🏼‍🐰‍👨🏿': 12, + '👨🏼‍💻': 7, + '👨🏼‍💼': 7, + '👨🏼‍🔧': 7, + '👨🏼‍🔬': 7, + '👨🏼‍🚀': 7, + '👨🏼‍🚒': 7, + '👨🏼‍🤝‍👨🏻': 12, + '👨🏼‍🤝‍👨🏽': 12, + '👨🏼‍🤝‍👨🏿': 12, + '👨🏼‍🦯': 7, + '👨🏼‍🦯‍➡️': 10, + '👨🏼‍🦰': 7, + '👨🏼‍🦱': 7, + '👨🏼‍🦲': 7, + '👨🏼‍🦳': 7, + '👨🏼‍🦼': 7, + '👨🏼‍🦽': 7, + '👨🏼‍🦽‍➡️': 10, + '👨🏼‍🫯‍👨🏻': 10, + '👨🏼‍🫯‍👨🏽': 10, + '👨🏼‍🫯‍👨🏾': 10, + '👨🏼‍🫯‍👨🏿': 10, + '👨🏽‍⚕️': 7, + '👨🏽‍⚖️': 7, + '👨🏽‍✈️': 7, + '👨🏽‍❤️‍👨🏻': 12, + '👨🏽‍❤️‍👨🏽': 12, + '👨🏽‍❤️‍👨🏿': 12, + '👨🏽‍❤️‍💋‍👨🏻': 15, + '👨🏽‍❤️‍💋‍👨🏽': 15, + '👨🏽‍❤️‍💋‍👨🏿': 15, + '👨🏽‍🌾': 7, + '👨🏽‍🍳': 7, + '👨🏽‍🍼': 7, + '👨🏽‍🎓': 7, + '👨🏽‍🎤': 7, + '👨🏽‍🎨': 7, + '👨🏽‍🏫': 7, + '👨🏽‍🏭': 7, + '👨🏽‍🐰‍👨🏻': 12, + '👨🏽‍🐰‍👨🏼': 12, + '👨🏽‍🐰‍👨🏾': 12, + '👨🏽‍🐰‍👨🏿': 12, + '👨🏽‍💻': 7, + '👨🏽‍💼': 7, + '👨🏽‍🔧': 7, + '👨🏽‍🔬': 7, + '👨🏽‍🚀': 7, + '👨🏽‍🚒': 7, + '👨🏽‍🤝‍👨🏻': 12, + '👨🏽‍🤝‍👨🏼': 12, + '👨🏽‍🤝‍👨🏾': 12, + '👨🏽‍🤝‍👨🏿': 12, + '👨🏽‍🦯': 7, + '👨🏽‍🦯‍➡️': 10, + '👨🏽‍🦰': 7, + '👨🏽‍🦱': 7, + '👨🏽‍🦲': 7, + '👨🏽‍🦳': 7, + '👨🏽‍🦼': 7, + '👨🏽‍🦼‍➡️': 10, + '👨🏽‍🦽': 7, + '👨🏽‍🦽‍➡️': 10, + '👨🏽‍🫯‍👨🏻': 10, + '👨🏽‍🫯‍👨🏼': 10, + '👨🏽‍🫯‍👨🏾': 10, + '👨🏽‍🫯‍👨🏿': 10, + '👨🏾‍⚕️': 7, + '👨🏾‍⚖️': 7, + '👨🏾‍✈️': 7, + '👨🏾‍❤️‍👨🏾': 12, + '👨🏾‍❤️‍💋‍👨🏻': 15, + '👨🏾‍❤️‍💋‍👨🏾': 15, + '👨🏾‍❤️‍💋‍👨🏿': 15, + '👨🏾‍🌾': 7, + '👨🏾‍🍳': 7, + '👨🏾‍🍼': 7, + '👨🏾‍🎓': 7, + '👨🏾‍🎤': 7, + '👨🏾‍🎨': 7, + '👨🏾‍🏫': 7, + '👨🏾‍🏭': 7, + '👨🏾‍🐰‍👨🏻': 12, + '👨🏾‍🐰‍👨🏽': 12, + '👨🏾‍🐰‍👨🏿': 12, + '👨🏾‍💻': 7, + '👨🏾‍💼': 7, + '👨🏾‍🔧': 7, + '👨🏾‍🔬': 7, + '👨🏾‍🚀': 7, + '👨🏾‍🚒': 7, + '👨🏾‍🤝‍👨🏻': 12, + '👨🏾‍🤝‍👨🏽': 12, + '👨🏾‍🤝‍👨🏿': 12, + '👨🏾‍🦯': 7, + '👨🏾‍🦯‍➡️': 10, + '👨🏾‍🦰': 7, + '👨🏾‍🦱': 7, + '👨🏾‍🦲': 7, + '👨🏾‍🦳': 7, + '👨🏾‍🦼': 7, + '👨🏾‍🦽': 7, + '👨🏾‍🦽‍➡️': 10, + '👨🏾‍🫯‍👨🏻': 10, + '👨🏾‍🫯‍👨🏼': 10, + '👨🏾‍🫯‍👨🏽': 10, + '👨🏾‍🫯‍👨🏿': 10, + '👨🏿‍⚕️': 7, + '👨🏿‍⚖️': 7, + '👨🏿‍✈️': 7, + '👨🏿‍❤️‍👨🏻': 12, + '👨🏿‍❤️‍👨🏽': 12, + '👨🏿‍❤️‍👨🏿': 12, + '👨🏿‍❤️‍💋‍👨🏻': 15, + '👨🏿‍❤️‍💋‍👨🏼': 15, + '👨🏿‍❤️‍💋‍👨🏽': 15, + '👨🏿‍❤️‍💋‍👨🏾': 15, + '👨🏿‍❤️‍💋‍👨🏿': 15, + '👨🏿‍🌾': 7, + '👨🏿‍🍳': 7, + '👨🏿‍🍼': 7, + '👨🏿‍🎓': 7, + '👨🏿‍🎤': 7, + '👨🏿‍🎨': 7, + '👨🏿‍🏫': 7, + '👨🏿‍🏭': 7, + '👨🏿‍🐰‍👨🏻': 12, + '👨🏿‍🐰‍👨🏼': 12, + '👨🏿‍🐰‍👨🏽': 12, + '👨🏿‍🐰‍👨🏾': 12, + '👨🏿‍💻': 7, + '👨🏿‍💼': 7, + '👨🏿‍🔧': 7, + '👨🏿‍🔬': 7, + '👨🏿‍🚀': 7, + '👨🏿‍🚒': 7, + '👨🏿‍🤝‍👨🏻': 12, + '👨🏿‍🤝‍👨🏼': 12, + '👨🏿‍🤝‍👨🏽': 12, + '👨🏿‍🤝‍👨🏾': 12, + '👨🏿‍🦯': 7, + '👨🏿‍🦯‍➡️': 10, + '👨🏿‍🦰': 7, + '👨🏿‍🦱': 7, + '👨🏿‍🦲': 7, + '👨🏿‍🦳': 7, + '👨🏿‍🦼': 7, + '👨🏿‍🦼‍➡️': 10, + '👨🏿‍🦽': 7, + '👨🏿‍🦽‍➡️': 10, + '👨🏿‍🫯‍👨🏻': 10, + '👨🏿‍🫯‍👨🏼': 10, + '👨🏿‍🫯‍👨🏽': 10, + '👨🏿‍🫯‍👨🏾': 10, + '👩‍⚕️': 5, + '👩‍⚖️': 5, + '👩‍✈️': 5, + '👩‍❤️‍👨': 8, + '👩‍❤️‍👩': 8, + '👩‍❤️‍💋‍👨': 11, + '👩‍❤️‍💋‍👩': 11, + '👩‍🌾': 5, + '👩‍🍳': 5, + '👩‍🍼': 5, + '👩‍🎓': 5, + '👩‍🎤': 5, + '👩‍🎨': 5, + '👩‍🏫': 5, + '👩‍🏭': 5, + '👩‍👦': 5, + '👩‍👦‍👦': 8, + '👩‍👧': 5, + '👩‍👧‍👦': 8, + '👩‍👧‍👧': 8, + '👩‍👩‍👦': 8, + '👩‍👩‍👦‍👦': 11, + '👩‍👩‍👧': 8, + '👩‍👩‍👧‍👦': 11, + '👩‍👩‍👧‍👧': 11, + '👩‍💻': 5, + '👩‍💼': 5, + '👩‍🔧': 5, + '👩‍🔬': 5, + '👩‍🚀': 5, + '👩‍🚒': 5, + '👩‍🦯': 5, + '👩‍🦯‍➡️': 8, + '👩‍🦰': 5, + '👩‍🦱': 5, + '👩‍🦲': 5, + '👩‍🦳': 5, + '👩‍🦼': 5, + '👩‍🦼‍➡️': 8, + '👩‍🦽': 5, + '👩‍🦽‍➡️': 8, + '👩🏻‍⚕️': 7, + '👩🏻‍⚖️': 7, + '👩🏻‍✈️': 7, + '👩🏻‍❤️‍👨🏻': 12, + '👩🏻‍❤️‍👨🏿': 12, + '👩🏻‍❤️‍👩🏻': 12, + '👩🏻‍❤️‍💋‍👨🏻': 15, + '👩🏻‍❤️‍💋‍👨🏽': 15, + '👩🏻‍❤️‍💋‍👨🏿': 15, + '👩🏻‍❤️‍💋‍👩🏻': 15, + '👩🏻‍❤️‍💋‍👩🏽': 15, + '👩🏻‍❤️‍💋‍👩🏿': 15, + '👩🏻‍🌾': 7, + '👩🏻‍🍳': 7, + '👩🏻‍🍼': 7, + '👩🏻‍🎓': 7, + '👩🏻‍🎤': 7, + '👩🏻‍🎨': 7, + '👩🏻‍🏫': 7, + '👩🏻‍🏭': 7, + '👩🏻‍🐰‍👩🏼': 12, + '👩🏻‍🐰‍👩🏽': 12, + '👩🏻‍🐰‍👩🏾': 12, + '👩🏻‍🐰‍👩🏿': 12, + '👩🏻‍💻': 7, + '👩🏻‍💼': 7, + '👩🏻‍🔧': 7, + '👩🏻‍🔬': 7, + '👩🏻‍🚀': 7, + '👩🏻‍🚒': 7, + '👩🏻‍🤝‍👨🏽': 12, + '👩🏻‍🤝‍👨🏿': 12, + '👩🏻‍🤝‍👩🏼': 12, + '👩🏻‍🤝‍👩🏽': 12, + '👩🏻‍🤝‍👩🏾': 12, + '👩🏻‍🤝‍👩🏿': 12, + '👩🏻‍🦯': 7, + '👩🏻‍🦯‍➡️': 10, + '👩🏻‍🦰': 7, + '👩🏻‍🦱': 7, + '👩🏻‍🦲': 7, + '👩🏻‍🦳': 7, + '👩🏻‍🦼': 7, + '👩🏻‍🦼‍➡️': 10, + '👩🏻‍🦽': 7, + '👩🏻‍🦽‍➡️': 10, + '👩🏻‍🫯‍👩🏼': 10, + '👩🏻‍🫯‍👩🏽': 10, + '👩🏻‍🫯‍👩🏾': 10, + '👩🏻‍🫯‍👩🏿': 10, + '👩🏼‍⚕️': 7, + '👩🏼‍⚖️': 7, + '👩🏼‍✈️': 7, + '👩🏼‍❤️‍👨🏼': 12, + '👩🏼‍❤️‍👩🏼': 12, + '👩🏼‍❤️‍💋‍👨🏼': 15, + '👩🏼‍❤️‍💋‍👩🏼': 15, + '👩🏼‍🌾': 7, + '👩🏼‍🍳': 7, + '👩🏼‍🍼': 7, + '👩🏼‍🎓': 7, + '👩🏼‍🎤': 7, + '👩🏼‍🎨': 7, + '👩🏼‍🏫': 7, + '👩🏼‍🏭': 7, + '👩🏼‍🐰‍👩🏻': 12, + '👩🏼‍🐰‍👩🏿': 12, + '👩🏼‍💻': 7, + '👩🏼‍💼': 7, + '👩🏼‍🔧': 7, + '👩🏼‍🔬': 7, + '👩🏼‍🚀': 7, + '👩🏼‍🚒': 7, + '👩🏼‍🤝‍👩🏻': 12, + '👩🏼‍🤝‍👩🏽': 12, + '👩🏼‍🤝‍👩🏿': 12, + '👩🏼‍🦯': 7, + '👩🏼‍🦯‍➡️': 10, + '👩🏼‍🦰': 7, + '👩🏼‍🦱': 7, + '👩🏼‍🦲': 7, + '👩🏼‍🦳': 7, + '👩🏼‍🦼': 7, + '👩🏼‍🦽': 7, + '👩🏼‍🫯‍👩🏻': 10, + '👩🏼‍🫯‍👩🏽': 10, + '👩🏼‍🫯‍👩🏾': 10, + '👩🏼‍🫯‍👩🏿': 10, + '👩🏽‍⚕️': 7, + '👩🏽‍⚖️': 7, + '👩🏽‍✈️': 7, + '👩🏽‍❤️‍👨🏽': 12, + '👩🏽‍❤️‍👩🏽': 12, + '👩🏽‍❤️‍💋‍👨🏻': 15, + '👩🏽‍❤️‍💋‍👨🏽': 15, + '👩🏽‍❤️‍💋‍👨🏿': 15, + '👩🏽‍❤️‍💋‍👩🏻': 15, + '👩🏽‍❤️‍💋‍👩🏽': 15, + '👩🏽‍❤️‍💋‍👩🏿': 15, + '👩🏽‍🌾': 7, + '👩🏽‍🍳': 7, + '👩🏽‍🍼': 7, + '👩🏽‍🎓': 7, + '👩🏽‍🎤': 7, + '👩🏽‍🎨': 7, + '👩🏽‍🏫': 7, + '👩🏽‍🏭': 7, + '👩🏽‍🐰‍👩🏻': 12, + '👩🏽‍🐰‍👩🏾': 12, + '👩🏽‍🐰‍👩🏿': 12, + '👩🏽‍💻': 7, + '👩🏽‍💼': 7, + '👩🏽‍🔧': 7, + '👩🏽‍🔬': 7, + '👩🏽‍🚀': 7, + '👩🏽‍🚒': 7, + '👩🏽‍🤝‍👨🏻': 12, + '👩🏽‍🤝‍👨🏿': 12, + '👩🏽‍🤝‍👩🏻': 12, + '👩🏽‍🤝‍👩🏼': 12, + '👩🏽‍🤝‍👩🏾': 12, + '👩🏽‍🤝‍👩🏿': 12, + '👩🏽‍🦯': 7, + '👩🏽‍🦯‍➡️': 10, + '👩🏽‍🦰': 7, + '👩🏽‍🦱': 7, + '👩🏽‍🦲': 7, + '👩🏽‍🦳': 7, + '👩🏽‍🦼': 7, + '👩🏽‍🦼‍➡️': 10, + '👩🏽‍🦽': 7, + '👩🏽‍🦽‍➡️': 10, + '👩🏽‍🫯‍👩🏻': 10, + '👩🏽‍🫯‍👩🏼': 10, + '👩🏽‍🫯‍👩🏾': 10, + '👩🏽‍🫯‍👩🏿': 10, + '👩🏾‍⚕️': 7, + '👩🏾‍⚖️': 7, + '👩🏾‍✈️': 7, + '👩🏾‍❤️‍👨🏾': 12, + '👩🏾‍❤️‍👩🏾': 12, + '👩🏾‍❤️‍💋‍👨🏾': 15, + '👩🏾‍❤️‍💋‍👩🏾': 15, + '👩🏾‍🌾': 7, + '👩🏾‍🍳': 7, + '👩🏾‍🍼': 7, + '👩🏾‍🎓': 7, + '👩🏾‍🎤': 7, + '👩🏾‍🎨': 7, + '👩🏾‍🏫': 7, + '👩🏾‍🏭': 7, + '👩🏾‍🐰‍👩🏻': 12, + '👩🏾‍🐰‍👩🏽': 12, + '👩🏾‍🐰‍👩🏿': 12, + '👩🏾‍💻': 7, + '👩🏾‍💼': 7, + '👩🏾‍🔧': 7, + '👩🏾‍🔬': 7, + '👩🏾‍🚀': 7, + '👩🏾‍🚒': 7, + '👩🏾‍🤝‍👩🏻': 12, + '👩🏾‍🤝‍👩🏽': 12, + '👩🏾‍🤝‍👩🏿': 12, + '👩🏾‍🦯': 7, + '👩🏾‍🦯‍➡️': 10, + '👩🏾‍🦰': 7, + '👩🏾‍🦱': 7, + '👩🏾‍🦲': 7, + '👩🏾‍🦳': 7, + '👩🏾‍🦼': 7, + '👩🏾‍🦽': 7, + '👩🏾‍🦽‍➡️': 10, + '👩🏾‍🫯‍👩🏻': 10, + '👩🏾‍🫯‍👩🏼': 10, + '👩🏾‍🫯‍👩🏽': 10, + '👩🏾‍🫯‍👩🏿': 10, + '👩🏿‍⚕️': 7, + '👩🏿‍⚖️': 7, + '👩🏿‍✈️': 7, + '👩🏿‍❤️‍👨🏻': 12, + '👩🏿‍❤️‍👨🏿': 12, + '👩🏿‍❤️‍👩🏿': 12, + '👩🏿‍❤️‍💋‍👨🏻': 15, + '👩🏿‍❤️‍💋‍👨🏽': 15, + '👩🏿‍❤️‍💋‍👨🏿': 15, + '👩🏿‍❤️‍💋‍👩🏻': 15, + '👩🏿‍❤️‍💋‍👩🏽': 15, + '👩🏿‍❤️‍💋‍👩🏿': 15, + '👩🏿‍🌾': 7, + '👩🏿‍🍳': 7, + '👩🏿‍🍼': 7, + '👩🏿‍🎓': 7, + '👩🏿‍🎤': 7, + '👩🏿‍🎨': 7, + '👩🏿‍🏫': 7, + '👩🏿‍🏭': 7, + '👩🏿‍🐰‍👩🏻': 12, + '👩🏿‍🐰‍👩🏼': 12, + '👩🏿‍🐰‍👩🏽': 12, + '👩🏿‍🐰‍👩🏾': 12, + '👩🏿‍💻': 7, + '👩🏿‍💼': 7, + '👩🏿‍🔧': 7, + '👩🏿‍🔬': 7, + '👩🏿‍🚀': 7, + '👩🏿‍🚒': 7, + '👩🏿‍🤝‍👨🏻': 12, + '👩🏿‍🤝‍👨🏽': 12, + '👩🏿‍🤝‍👩🏻': 12, + '👩🏿‍🤝‍👩🏼': 12, + '👩🏿‍🤝‍👩🏽': 12, + '👩🏿‍🤝‍👩🏾': 12, + '👩🏿‍🦯': 7, + '👩🏿‍🦯‍➡️': 10, + '👩🏿‍🦰': 7, + '👩🏿‍🦱': 7, + '👩🏿‍🦲': 7, + '👩🏿‍🦳': 7, + '👩🏿‍🦼': 7, + '👩🏿‍🦼‍➡️': 10, + '👩🏿‍🦽': 7, + '👩🏿‍🦽‍➡️': 10, + '👩🏿‍🫯‍👩🏻': 10, + '👩🏿‍🫯‍👩🏼': 10, + '👩🏿‍🫯‍👩🏽': 10, + '👩🏿‍🫯‍👩🏾': 10, + '👮‍♀️': 5, + '👮‍♂️': 5, + '👮🏻‍♀️': 7, + '👮🏻‍♂️': 7, + '👮🏼‍♀️': 7, + '👮🏼‍♂️': 7, + '👮🏽‍♀️': 7, + '👮🏽‍♂️': 7, + '👮🏾‍♀️': 7, + '👮🏾‍♂️': 7, + '👮🏿‍♀️': 7, + '👮🏿‍♂️': 7, + '👯‍♀️': 5, + '👯‍♂️': 5, + '👯🏻‍♀️': 7, + '👯🏻‍♂️': 7, + '👯🏼‍♀️': 7, + '👯🏼‍♂️': 7, + '👯🏽‍♀️': 7, + '👯🏽‍♂️': 7, + '👯🏾‍♀️': 7, + '👯🏾‍♂️': 7, + '👯🏿‍♀️': 7, + '👯🏿‍♂️': 7, + '👰‍♀️': 5, + '👰‍♂️': 5, + '👰🏻‍♀️': 7, + '👰🏻‍♂️': 7, + '👰🏼‍♀️': 7, + '👰🏼‍♂️': 7, + '👰🏽‍♀️': 7, + '👰🏽‍♂️': 7, + '👰🏾‍♀️': 7, + '👰🏾‍♂️': 7, + '👰🏿‍♀️': 7, + '👰🏿‍♂️': 7, + '👱‍♀️': 5, + '👱‍♂️': 5, + '👱🏻‍♀️': 7, + '👱🏻‍♂️': 7, + '👱🏼‍♀️': 7, + '👱🏼‍♂️': 7, + '👱🏽‍♀️': 7, + '👱🏽‍♂️': 7, + '👱🏾‍♀️': 7, + '👱🏾‍♂️': 7, + '👱🏿‍♀️': 7, + '👱🏿‍♂️': 7, + '👳‍♀️': 5, + '👳‍♂️': 5, + '👳🏻‍♀️': 7, + '👳🏻‍♂️': 7, + '👳🏼‍♀️': 7, + '👳🏼‍♂️': 7, + '👳🏽‍♀️': 7, + '👳🏽‍♂️': 7, + '👳🏾‍♀️': 7, + '👳🏾‍♂️': 7, + '👳🏿‍♀️': 7, + '👳🏿‍♂️': 7, + '👷‍♀️': 5, + '👷‍♂️': 5, + '👷🏻‍♀️': 7, + '👷🏻‍♂️': 7, + '👷🏼‍♀️': 7, + '👷🏼‍♂️': 7, + '👷🏽‍♀️': 7, + '👷🏽‍♂️': 7, + '👷🏾‍♀️': 7, + '👷🏾‍♂️': 7, + '👷🏿‍♀️': 7, + '👷🏿‍♂️': 7, + '💁‍♀️': 5, + '💁‍♂️': 5, + '💁🏻‍♀️': 7, + '💁🏻‍♂️': 7, + '💁🏼‍♀️': 7, + '💁🏼‍♂️': 7, + '💁🏽‍♀️': 7, + '💁🏽‍♂️': 7, + '💁🏾‍♀️': 7, + '💁🏾‍♂️': 7, + '💁🏿‍♀️': 7, + '💁🏿‍♂️': 7, + '💂‍♀️': 5, + '💂‍♂️': 5, + '💂🏻‍♀️': 7, + '💂🏻‍♂️': 7, + '💂🏼‍♀️': 7, + '💂🏼‍♂️': 7, + '💂🏽‍♀️': 7, + '💂🏽‍♂️': 7, + '💂🏾‍♀️': 7, + '💂🏾‍♂️': 7, + '💂🏿‍♀️': 7, + '💂🏿‍♂️': 7, + '💆‍♀️': 5, + '💆‍♂️': 5, + '💆🏻‍♀️': 7, + '💆🏻‍♂️': 7, + '💆🏼‍♀️': 7, + '💆🏼‍♂️': 7, + '💆🏽‍♀️': 7, + '💆🏽‍♂️': 7, + '💆🏾‍♀️': 7, + '💆🏾‍♂️': 7, + '💆🏿‍♀️': 7, + '💆🏿‍♂️': 7, + '💇‍♀️': 5, + '💇‍♂️': 5, + '💇🏻‍♀️': 7, + '💇🏻‍♂️': 7, + '💇🏼‍♀️': 7, + '💇🏼‍♂️': 7, + '💇🏽‍♀️': 7, + '💇🏽‍♂️': 7, + '💇🏾‍♀️': 7, + '💇🏾‍♂️': 7, + '💇🏿‍♀️': 7, + '💇🏿‍♂️': 7, + '🕵️‍♀️': 5, + '🕵️‍♂️': 5, + '🕵🏻‍♀️': 6, + '🕵🏻‍♂️': 6, + '🕵🏼‍♀️': 6, + '🕵🏼‍♂️': 6, + '🕵🏽‍♀️': 6, + '🕵🏽‍♂️': 6, + '🕵🏾‍♀️': 6, + '🕵🏾‍♂️': 6, + '🕵🏿‍♀️': 6, + '🕵🏿‍♂️': 6, + '😮‍💨': 5, + '😵‍💫': 5, + '😶‍🌫️': 5, + '🙂‍↔️': 5, + '🙂‍↕️': 5, + '🙅‍♀️': 5, + '🙅‍♂️': 5, + '🙅🏻‍♀️': 7, + '🙅🏻‍♂️': 7, + '🙅🏼‍♀️': 7, + '🙅🏼‍♂️': 7, + '🙅🏽‍♀️': 7, + '🙅🏽‍♂️': 7, + '🙅🏾‍♀️': 7, + '🙅🏾‍♂️': 7, + '🙅🏿‍♀️': 7, + '🙅🏿‍♂️': 7, + '🙆‍♀️': 5, + '🙆‍♂️': 5, + '🙆🏻‍♀️': 7, + '🙆🏻‍♂️': 7, + '🙆🏼‍♀️': 7, + '🙆🏼‍♂️': 7, + '🙆🏽‍♀️': 7, + '🙆🏽‍♂️': 7, + '🙆🏾‍♀️': 7, + '🙆🏾‍♂️': 7, + '🙆🏿‍♀️': 7, + '🙆🏿‍♂️': 7, + '🙇‍♀️': 5, + '🙇‍♂️': 5, + '🙇🏻‍♀️': 7, + '🙇🏻‍♂️': 7, + '🙇🏼‍♀️': 7, + '🙇🏼‍♂️': 7, + '🙇🏽‍♀️': 7, + '🙇🏽‍♂️': 7, + '🙇🏾‍♀️': 7, + '🙇🏾‍♂️': 7, + '🙇🏿‍♀️': 7, + '🙇🏿‍♂️': 7, + '🙋‍♀️': 5, + '🙋‍♂️': 5, + '🙋🏻‍♀️': 7, + '🙋🏻‍♂️': 7, + '🙋🏼‍♀️': 7, + '🙋🏼‍♂️': 7, + '🙋🏽‍♀️': 7, + '🙋🏽‍♂️': 7, + '🙋🏾‍♀️': 7, + '🙋🏾‍♂️': 7, + '🙋🏿‍♀️': 7, + '🙋🏿‍♂️': 7, + '🙍‍♀️': 5, + '🙍‍♂️': 5, + '🙍🏻‍♀️': 7, + '🙍🏻‍♂️': 7, + '🙍🏼‍♀️': 7, + '🙍🏼‍♂️': 7, + '🙍🏽‍♀️': 7, + '🙍🏽‍♂️': 7, + '🙍🏾‍♀️': 7, + '🙍🏾‍♂️': 7, + '🙍🏿‍♀️': 7, + '🙍🏿‍♂️': 7, + '🙎‍♀️': 5, + '🙎‍♂️': 5, + '🙎🏻‍♀️': 7, + '🙎🏻‍♂️': 7, + '🙎🏼‍♀️': 7, + '🙎🏼‍♂️': 7, + '🙎🏽‍♀️': 7, + '🙎🏽‍♂️': 7, + '🙎🏾‍♀️': 7, + '🙎🏾‍♂️': 7, + '🙎🏿‍♀️': 7, + '🙎🏿‍♂️': 7, + '🚣‍♀️': 5, + '🚣‍♂️': 5, + '🚣🏻‍♀️': 7, + '🚣🏻‍♂️': 7, + '🚣🏼‍♀️': 7, + '🚣🏼‍♂️': 7, + '🚣🏽‍♀️': 7, + '🚣🏽‍♂️': 7, + '🚣🏾‍♀️': 7, + '🚣🏾‍♂️': 7, + '🚣🏿‍♀️': 7, + '🚣🏿‍♂️': 7, + '🚴‍♀️': 5, + '🚴‍♂️': 5, + '🚴🏻‍♀️': 7, + '🚴🏻‍♂️': 7, + '🚴🏼‍♀️': 7, + '🚴🏼‍♂️': 7, + '🚴🏽‍♀️': 7, + '🚴🏽‍♂️': 7, + '🚴🏾‍♀️': 7, + '🚴🏾‍♂️': 7, + '🚴🏿‍♀️': 7, + '🚴🏿‍♂️': 7, + '🚵‍♀️': 5, + '🚵‍♂️': 5, + '🚵🏻‍♀️': 7, + '🚵🏻‍♂️': 7, + '🚵🏼‍♀️': 7, + '🚵🏼‍♂️': 7, + '🚵🏽‍♀️': 7, + '🚵🏽‍♂️': 7, + '🚵🏾‍♀️': 7, + '🚵🏾‍♂️': 7, + '🚵🏿‍♀️': 7, + '🚵🏿‍♂️': 7, + '🚶‍♀️': 5, + '🚶‍♀️‍➡️': 8, + '🚶‍♂️': 5, + '🚶‍♂️‍➡️': 8, + '🚶‍➡️': 5, + '🚶🏻‍♀️': 7, + '🚶🏻‍♀️‍➡️': 10, + '🚶🏻‍♂️': 7, + '🚶🏻‍♂️‍➡️': 10, + '🚶🏻‍➡️': 7, + '🚶🏼‍♀️': 7, + '🚶🏼‍♀️‍➡️': 10, + '🚶🏼‍♂️': 7, + '🚶🏼‍♂️‍➡️': 10, + '🚶🏼‍➡️': 7, + '🚶🏽‍♀️': 7, + '🚶🏽‍♀️‍➡️': 10, + '🚶🏽‍♂️': 7, + '🚶🏽‍♂️‍➡️': 10, + '🚶🏽‍➡️': 7, + '🚶🏾‍♀️': 7, + '🚶🏾‍♀️‍➡️': 10, + '🚶🏾‍♂️': 7, + '🚶🏾‍♂️‍➡️': 10, + '🚶🏾‍➡️': 7, + '🚶🏿‍♀️': 7, + '🚶🏿‍♀️‍➡️': 10, + '🚶🏿‍♂️': 7, + '🚶🏿‍♂️‍➡️': 10, + '🚶🏿‍➡️': 7, + '🤦‍♀️': 5, + '🤦‍♂️': 5, + '🤦🏻‍♀️': 7, + '🤦🏻‍♂️': 7, + '🤦🏼‍♀️': 7, + '🤦🏼‍♂️': 7, + '🤦🏽‍♀️': 7, + '🤦🏽‍♂️': 7, + '🤦🏾‍♀️': 7, + '🤦🏾‍♂️': 7, + '🤦🏿‍♀️': 7, + '🤦🏿‍♂️': 7, + '🤵‍♀️': 5, + '🤵‍♂️': 5, + '🤵🏻‍♀️': 7, + '🤵🏻‍♂️': 7, + '🤵🏼‍♀️': 7, + '🤵🏼‍♂️': 7, + '🤵🏽‍♀️': 7, + '🤵🏽‍♂️': 7, + '🤵🏾‍♀️': 7, + '🤵🏾‍♂️': 7, + '🤵🏿‍♀️': 7, + '🤵🏿‍♂️': 7, + '🤷‍♀️': 5, + '🤷‍♂️': 5, + '🤷🏻‍♀️': 7, + '🤷🏻‍♂️': 7, + '🤷🏼‍♀️': 7, + '🤷🏼‍♂️': 7, + '🤷🏽‍♀️': 7, + '🤷🏽‍♂️': 7, + '🤷🏾‍♀️': 7, + '🤷🏾‍♂️': 7, + '🤷🏿‍♀️': 7, + '🤷🏿‍♂️': 7, + '🤸‍♀️': 5, + '🤸‍♂️': 5, + '🤸🏻‍♀️': 7, + '🤸🏻‍♂️': 7, + '🤸🏼‍♀️': 7, + '🤸🏼‍♂️': 7, + '🤸🏽‍♀️': 7, + '🤸🏽‍♂️': 7, + '🤸🏾‍♀️': 7, + '🤸🏾‍♂️': 7, + '🤸🏿‍♀️': 7, + '🤸🏿‍♂️': 7, + '🤹‍♀️': 5, + '🤹‍♂️': 5, + '🤹🏻‍♀️': 7, + '🤹🏻‍♂️': 7, + '🤹🏼‍♀️': 7, + '🤹🏼‍♂️': 7, + '🤹🏽‍♀️': 7, + '🤹🏽‍♂️': 7, + '🤹🏾‍♀️': 7, + '🤹🏾‍♂️': 7, + '🤹🏿‍♀️': 7, + '🤹🏿‍♂️': 7, + '🤼‍♀️': 5, + '🤼‍♂️': 5, + '🤼🏻‍♀️': 7, + '🤼🏻‍♂️': 7, + '🤼🏼‍♀️': 7, + '🤼🏼‍♂️': 7, + '🤼🏽‍♀️': 7, + '🤼🏽‍♂️': 7, + '🤼🏾‍♀️': 7, + '🤼🏾‍♂️': 7, + '🤼🏿‍♀️': 7, + '🤼🏿‍♂️': 7, + '🤽‍♀️': 5, + '🤽‍♂️': 5, + '🤽🏻‍♀️': 7, + '🤽🏻‍♂️': 7, + '🤽🏼‍♀️': 7, + '🤽🏼‍♂️': 7, + '🤽🏽‍♀️': 7, + '🤽🏽‍♂️': 7, + '🤽🏾‍♀️': 7, + '🤽🏾‍♂️': 7, + '🤽🏿‍♀️': 7, + '🤽🏿‍♂️': 7, + '🤾‍♀️': 5, + '🤾‍♂️': 5, + '🤾🏻‍♀️': 7, + '🤾🏻‍♂️': 7, + '🤾🏼‍♀️': 7, + '🤾🏼‍♂️': 7, + '🤾🏽‍♀️': 7, + '🤾🏽‍♂️': 7, + '🤾🏾‍♀️': 7, + '🤾🏾‍♂️': 7, + '🤾🏿‍♀️': 7, + '🤾🏿‍♂️': 7, + '🦸‍♀️': 5, + '🦸‍♂️': 5, + '🦸🏻‍♀️': 7, + '🦸🏻‍♂️': 7, + '🦸🏼‍♀️': 7, + '🦸🏼‍♂️': 7, + '🦸🏽‍♀️': 7, + '🦸🏽‍♂️': 7, + '🦸🏾‍♀️': 7, + '🦸🏾‍♂️': 7, + '🦸🏿‍♀️': 7, + '🦸🏿‍♂️': 7, + '🦹‍♀️': 5, + '🦹‍♂️': 5, + '🦹🏻‍♀️': 7, + '🦹🏻‍♂️': 7, + '🦹🏼‍♀️': 7, + '🦹🏼‍♂️': 7, + '🦹🏽‍♀️': 7, + '🦹🏽‍♂️': 7, + '🦹🏾‍♀️': 7, + '🦹🏾‍♂️': 7, + '🦹🏿‍♀️': 7, + '🦹🏿‍♂️': 7, + '🧍‍♀️': 5, + '🧍‍♂️': 5, + '🧍🏻‍♀️': 7, + '🧍🏻‍♂️': 7, + '🧍🏼‍♀️': 7, + '🧍🏼‍♂️': 7, + '🧍🏽‍♀️': 7, + '🧍🏽‍♂️': 7, + '🧍🏾‍♀️': 7, + '🧍🏾‍♂️': 7, + '🧍🏿‍♀️': 7, + '🧍🏿‍♂️': 7, + '🧎‍♀️': 5, + '🧎‍♀️‍➡️': 8, + '🧎‍♂️': 5, + '🧎‍♂️‍➡️': 8, + '🧎‍➡️': 5, + '🧎🏻‍♀️': 7, + '🧎🏻‍♀️‍➡️': 10, + '🧎🏻‍♂️': 7, + '🧎🏻‍♂️‍➡️': 10, + '🧎🏻‍➡️': 7, + '🧎🏼‍♀️': 7, + '🧎🏼‍♀️‍➡️': 10, + '🧎🏼‍♂️': 7, + '🧎🏼‍♂️‍➡️': 10, + '🧎🏼‍➡️': 7, + '🧎🏽‍♀️': 7, + '🧎🏽‍♀️‍➡️': 10, + '🧎🏽‍♂️': 7, + '🧎🏽‍♂️‍➡️': 10, + '🧎🏽‍➡️': 7, + '🧎🏾‍♀️': 7, + '🧎🏾‍♀️‍➡️': 10, + '🧎🏾‍♂️': 7, + '🧎🏾‍♂️‍➡️': 10, + '🧎🏾‍➡️': 7, + '🧎🏿‍♀️': 7, + '🧎🏿‍♀️‍➡️': 10, + '🧎🏿‍♂️': 7, + '🧎🏿‍♂️‍➡️': 10, + '🧎🏿‍➡️': 7, + '🧏‍♀️': 5, + '🧏‍♂️': 5, + '🧏🏻‍♀️': 7, + '🧏🏻‍♂️': 7, + '🧏🏼‍♀️': 7, + '🧏🏼‍♂️': 7, + '🧏🏽‍♀️': 7, + '🧏🏽‍♂️': 7, + '🧏🏾‍♀️': 7, + '🧏🏾‍♂️': 7, + '🧏🏿‍♀️': 7, + '🧏🏿‍♂️': 7, + '🧑‍⚕️': 5, + '🧑‍⚖️': 5, + '🧑‍✈️': 5, + '🧑‍🌾': 5, + '🧑‍🍳': 5, + '🧑‍🍼': 5, + '🧑‍🎄': 5, + '🧑‍🎓': 5, + '🧑‍🎤': 5, + '🧑‍🎨': 5, + '🧑‍🏫': 5, + '🧑‍🏭': 5, + '🧑‍💻': 5, + '🧑‍💼': 5, + '🧑‍🔧': 5, + '🧑‍🔬': 5, + '🧑‍🚀': 5, + '🧑‍🚒': 5, + '🧑‍🤝‍🧑': 8, + '🧑‍🦯': 5, + '🧑‍🦯‍➡️': 8, + '🧑‍🦰': 5, + '🧑‍🦱': 5, + '🧑‍🦲': 5, + '🧑‍🦳': 5, + '🧑‍🦼': 5, + '🧑‍🦼‍➡️': 8, + '🧑‍🦽': 5, + '🧑‍🦽‍➡️': 8, + '🧑‍🧑‍🧒': 8, + '🧑‍🧑‍🧒‍🧒': 11, + '🧑‍🧒': 5, + '🧑‍🧒‍🧒': 8, + '🧑‍🩰': 5, + '🧑🏻‍⚕️': 7, + '🧑🏻‍⚖️': 7, + '🧑🏻‍✈️': 7, + '🧑🏻‍❤️‍💋‍🧑🏿': 15, + '🧑🏻‍🌾': 7, + '🧑🏻‍🍳': 7, + '🧑🏻‍🍼': 7, + '🧑🏻‍🎄': 7, + '🧑🏻‍🎓': 7, + '🧑🏻‍🎤': 7, + '🧑🏻‍🎨': 7, + '🧑🏻‍🏫': 7, + '🧑🏻‍🏭': 7, + '🧑🏻‍🐰‍🧑🏽': 12, + '🧑🏻‍🐰‍🧑🏾': 12, + '🧑🏻‍🐰‍🧑🏿': 12, + '🧑🏻‍💻': 7, + '🧑🏻‍💼': 7, + '🧑🏻‍🔧': 7, + '🧑🏻‍🔬': 7, + '🧑🏻‍🚀': 7, + '🧑🏻‍🚒': 7, + '🧑🏻‍🤝‍🧑🏻': 12, + '🧑🏻‍🤝‍🧑🏼': 12, + '🧑🏻‍🤝‍🧑🏽': 12, + '🧑🏻‍🤝‍🧑🏾': 12, + '🧑🏻‍🤝‍🧑🏿': 12, + '🧑🏻‍🦯': 7, + '🧑🏻‍🦯‍➡️': 10, + '🧑🏻‍🦰': 7, + '🧑🏻‍🦱': 7, + '🧑🏻‍🦲': 7, + '🧑🏻‍🦳': 7, + '🧑🏻‍🦼': 7, + '🧑🏻‍🦼‍➡️': 10, + '🧑🏻‍🦽': 7, + '🧑🏻‍🦽‍➡️': 10, + '🧑🏻‍🩰': 7, + '🧑🏻‍🫯‍🧑🏼': 10, + '🧑🏻‍🫯‍🧑🏽': 10, + '🧑🏻‍🫯‍🧑🏾': 10, + '🧑🏻‍🫯‍🧑🏿': 10, + '🧑🏼‍⚕️': 7, + '🧑🏼‍⚖️': 7, + '🧑🏼‍✈️': 7, + '🧑🏼‍🌾': 7, + '🧑🏼‍🍳': 7, + '🧑🏼‍🍼': 7, + '🧑🏼‍🎄': 7, + '🧑🏼‍🎓': 7, + '🧑🏼‍🎤': 7, + '🧑🏼‍🎨': 7, + '🧑🏼‍🏫': 7, + '🧑🏼‍🏭': 7, + '🧑🏼‍🐰‍🧑🏿': 12, + '🧑🏼‍💻': 7, + '🧑🏼‍💼': 7, + '🧑🏼‍🔧': 7, + '🧑🏼‍🔬': 7, + '🧑🏼‍🚀': 7, + '🧑🏼‍🚒': 7, + '🧑🏼‍🤝‍🧑🏻': 12, + '🧑🏼‍🤝‍🧑🏼': 12, + '🧑🏼‍🤝‍🧑🏽': 12, + '🧑🏼‍🤝‍🧑🏿': 12, + '🧑🏼‍🦯': 7, + '🧑🏼‍🦯‍➡️': 10, + '🧑🏼‍🦰': 7, + '🧑🏼‍🦱': 7, + '🧑🏼‍🦲': 7, + '🧑🏼‍🦳': 7, + '🧑🏼‍🦼': 7, + '🧑🏼‍🦽': 7, + '🧑🏼‍🩰': 7, + '🧑🏼‍🫯‍🧑🏻': 10, + '🧑🏼‍🫯‍🧑🏽': 10, + '🧑🏼‍🫯‍🧑🏿': 10, + '🧑🏽‍⚕️': 7, + '🧑🏽‍⚖️': 7, + '🧑🏽‍✈️': 7, + '🧑🏽‍❤️‍💋‍🧑🏿': 15, + '🧑🏽‍🌾': 7, + '🧑🏽‍🍳': 7, + '🧑🏽‍🍼': 7, + '🧑🏽‍🎄': 7, + '🧑🏽‍🎓': 7, + '🧑🏽‍🎤': 7, + '🧑🏽‍🎨': 7, + '🧑🏽‍🏫': 7, + '🧑🏽‍🏭': 7, + '🧑🏽‍🐰‍🧑🏻': 12, + '🧑🏽‍🐰‍🧑🏿': 12, + '🧑🏽‍💻': 7, + '🧑🏽‍💼': 7, + '🧑🏽‍🔧': 7, + '🧑🏽‍🔬': 7, + '🧑🏽‍🚀': 7, + '🧑🏽‍🚒': 7, + '🧑🏽‍🤝‍🧑🏻': 12, + '🧑🏽‍🤝‍🧑🏼': 12, + '🧑🏽‍🤝‍🧑🏽': 12, + '🧑🏽‍🤝‍🧑🏾': 12, + '🧑🏽‍🤝‍🧑🏿': 12, + '🧑🏽‍🦯': 7, + '🧑🏽‍🦯‍➡️': 10, + '🧑🏽‍🦰': 7, + '🧑🏽‍🦱': 7, + '🧑🏽‍🦲': 7, + '🧑🏽‍🦳': 7, + '🧑🏽‍🦼': 7, + '🧑🏽‍🦼‍➡️': 10, + '🧑🏽‍🦽': 7, + '🧑🏽‍🦽‍➡️': 10, + '🧑🏽‍🩰': 7, + '🧑🏽‍🫯‍🧑🏻': 10, + '🧑🏽‍🫯‍🧑🏼': 10, + '🧑🏽‍🫯‍🧑🏾': 10, + '🧑🏽‍🫯‍🧑🏿': 10, + '🧑🏾‍⚕️': 7, + '🧑🏾‍⚖️': 7, + '🧑🏾‍✈️': 7, + '🧑🏾‍🌾': 7, + '🧑🏾‍🍳': 7, + '🧑🏾‍🍼': 7, + '🧑🏾‍🎄': 7, + '🧑🏾‍🎓': 7, + '🧑🏾‍🎤': 7, + '🧑🏾‍🎨': 7, + '🧑🏾‍🏫': 7, + '🧑🏾‍🏭': 7, + '🧑🏾‍🐰‍🧑🏻': 12, + '🧑🏾‍🐰‍🧑🏿': 12, + '🧑🏾‍💻': 7, + '🧑🏾‍💼': 7, + '🧑🏾‍🔧': 7, + '🧑🏾‍🔬': 7, + '🧑🏾‍🚀': 7, + '🧑🏾‍🚒': 7, + '🧑🏾‍🤝‍🧑🏻': 12, + '🧑🏾‍🤝‍🧑🏽': 12, + '🧑🏾‍🤝‍🧑🏾': 12, + '🧑🏾‍🤝‍🧑🏿': 12, + '🧑🏾‍🦯': 7, + '🧑🏾‍🦯‍➡️': 10, + '🧑🏾‍🦰': 7, + '🧑🏾‍🦱': 7, + '🧑🏾‍🦲': 7, + '🧑🏾‍🦳': 7, + '🧑🏾‍🦼': 7, + '🧑🏾‍🦽': 7, + '🧑🏾‍🩰': 7, + '🧑🏾‍🫯‍🧑🏻': 10, + '🧑🏾‍🫯‍🧑🏽': 10, + '🧑🏾‍🫯‍🧑🏿': 10, + '🧑🏿‍⚕️': 7, + '🧑🏿‍⚖️': 7, + '🧑🏿‍✈️': 7, + '🧑🏿‍❤️‍💋‍🧑🏻': 15, + '🧑🏿‍❤️‍💋‍🧑🏽': 15, + '🧑🏿‍🌾': 7, + '🧑🏿‍🍳': 7, + '🧑🏿‍🍼': 7, + '🧑🏿‍🎄': 7, + '🧑🏿‍🎓': 7, + '🧑🏿‍🎤': 7, + '🧑🏿‍🎨': 7, + '🧑🏿‍🏫': 7, + '🧑🏿‍🏭': 7, + '🧑🏿‍🐰‍🧑🏻': 12, + '🧑🏿‍🐰‍🧑🏼': 12, + '🧑🏿‍🐰‍🧑🏽': 12, + '🧑🏿‍🐰‍🧑🏾': 12, + '🧑🏿‍💻': 7, + '🧑🏿‍💼': 7, + '🧑🏿‍🔧': 7, + '🧑🏿‍🔬': 7, + '🧑🏿‍🚀': 7, + '🧑🏿‍🚒': 7, + '🧑🏿‍🤝‍🧑🏻': 12, + '🧑🏿‍🤝‍🧑🏼': 12, + '🧑🏿‍🤝‍🧑🏽': 12, + '🧑🏿‍🤝‍🧑🏾': 12, + '🧑🏿‍🤝‍🧑🏿': 12, + '🧑🏿‍🦯': 7, + '🧑🏿‍🦯‍➡️': 10, + '🧑🏿‍🦰': 7, + '🧑🏿‍🦱': 7, + '🧑🏿‍🦲': 7, + '🧑🏿‍🦳': 7, + '🧑🏿‍🦼': 7, + '🧑🏿‍🦼‍➡️': 10, + '🧑🏿‍🦽': 7, + '🧑🏿‍🦽‍➡️': 10, + '🧑🏿‍🩰': 7, + '🧑🏿‍🫯‍🧑🏻': 10, + '🧑🏿‍🫯‍🧑🏼': 10, + '🧑🏿‍🫯‍🧑🏽': 10, + '🧑🏿‍🫯‍🧑🏾': 10, + '🧔‍♀️': 5, + '🧔‍♂️': 5, + '🧔🏻‍♀️': 7, + '🧔🏻‍♂️': 7, + '🧔🏼‍♀️': 7, + '🧔🏼‍♂️': 7, + '🧔🏽‍♀️': 7, + '🧔🏽‍♂️': 7, + '🧔🏾‍♀️': 7, + '🧔🏾‍♂️': 7, + '🧔🏿‍♀️': 7, + '🧔🏿‍♂️': 7, + '🧖‍♀️': 5, + '🧖‍♂️': 5, + '🧖🏻‍♀️': 7, + '🧖🏻‍♂️': 7, + '🧖🏼‍♀️': 7, + '🧖🏼‍♂️': 7, + '🧖🏽‍♀️': 7, + '🧖🏽‍♂️': 7, + '🧖🏾‍♀️': 7, + '🧖🏾‍♂️': 7, + '🧖🏿‍♀️': 7, + '🧖🏿‍♂️': 7, + '🧗‍♀️': 5, + '🧗‍♂️': 5, + '🧗🏻‍♀️': 7, + '🧗🏻‍♂️': 7, + '🧗🏼‍♀️': 7, + '🧗🏼‍♂️': 7, + '🧗🏽‍♀️': 7, + '🧗🏽‍♂️': 7, + '🧗🏾‍♀️': 7, + '🧗🏾‍♂️': 7, + '🧗🏿‍♀️': 7, + '🧗🏿‍♂️': 7, + '🧘‍♀️': 5, + '🧘‍♂️': 5, + '🧘🏻‍♀️': 7, + '🧘🏻‍♂️': 7, + '🧘🏼‍♀️': 7, + '🧘🏼‍♂️': 7, + '🧘🏽‍♀️': 7, + '🧘🏽‍♂️': 7, + '🧘🏾‍♀️': 7, + '🧘🏾‍♂️': 7, + '🧘🏿‍♀️': 7, + '🧘🏿‍♂️': 7, + '🧙‍♀️': 5, + '🧙‍♂️': 5, + '🧙🏻‍♀️': 7, + '🧙🏻‍♂️': 7, + '🧙🏼‍♀️': 7, + '🧙🏼‍♂️': 7, + '🧙🏽‍♀️': 7, + '🧙🏽‍♂️': 7, + '🧙🏾‍♀️': 7, + '🧙🏾‍♂️': 7, + '🧙🏿‍♀️': 7, + '🧙🏿‍♂️': 7, + '🧚‍♀️': 5, + '🧚‍♂️': 5, + '🧚🏻‍♀️': 7, + '🧚🏻‍♂️': 7, + '🧚🏼‍♀️': 7, + '🧚🏼‍♂️': 7, + '🧚🏽‍♀️': 7, + '🧚🏽‍♂️': 7, + '🧚🏾‍♀️': 7, + '🧚🏾‍♂️': 7, + '🧚🏿‍♀️': 7, + '🧚🏿‍♂️': 7, + '🧛‍♀️': 5, + '🧛‍♂️': 5, + '🧛🏻‍♀️': 7, + '🧛🏻‍♂️': 7, + '🧛🏼‍♀️': 7, + '🧛🏼‍♂️': 7, + '🧛🏽‍♀️': 7, + '🧛🏽‍♂️': 7, + '🧛🏾‍♀️': 7, + '🧛🏾‍♂️': 7, + '🧛🏿‍♀️': 7, + '🧛🏿‍♂️': 7, + '🧜‍♀️': 5, + '🧜‍♂️': 5, + '🧜🏻‍♀️': 7, + '🧜🏻‍♂️': 7, + '🧜🏼‍♀️': 7, + '🧜🏼‍♂️': 7, + '🧜🏽‍♀️': 7, + '🧜🏽‍♂️': 7, + '🧜🏾‍♀️': 7, + '🧜🏾‍♂️': 7, + '🧜🏿‍♀️': 7, + '🧜🏿‍♂️': 7, + '🧝‍♀️': 5, + '🧝‍♂️': 5, + '🧝🏻‍♀️': 7, + '🧝🏻‍♂️': 7, + '🧝🏼‍♀️': 7, + '🧝🏼‍♂️': 7, + '🧝🏽‍♀️': 7, + '🧝🏽‍♂️': 7, + '🧝🏾‍♀️': 7, + '🧝🏾‍♂️': 7, + '🧝🏿‍♀️': 7, + '🧝🏿‍♂️': 7, + '🧞‍♀️': 5, + '🧞‍♂️': 5, + '🧟‍♀️': 5, + '🧟‍♂️': 5, + '🫱🏻‍🫲🏼': 9, + '🫱🏻‍🫲🏽': 9, + '🫱🏻‍🫲🏾': 9, + '🫱🏻‍🫲🏿': 9, + '🫱🏼‍🫲🏻': 9, + '🫱🏼‍🫲🏽': 9, + '🫱🏼‍🫲🏾': 9, + '🫱🏼‍🫲🏿': 9, + '🫱🏽‍🫲🏻': 9, + '🫱🏽‍🫲🏼': 9, + '🫱🏽‍🫲🏾': 9, + '🫱🏽‍🫲🏿': 9, + '🫱🏾‍🫲🏻': 9, + '🫱🏾‍🫲🏼': 9, + '🫱🏾‍🫲🏽': 9, + '🫱🏾‍🫲🏿': 9, + '🫱🏿‍🫲🏻': 9, + '🫱🏿‍🫲🏼': 9, + '🫱🏿‍🫲🏽': 9, + '🫱🏿‍🫲🏾': 9, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_78f828e8.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_78f828e8.py new file mode 100644 index 0000000000000000000000000000000000000000..6e15a7b081491d6eae22e39ef7f91c6b80d7f0bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_78f828e8.py @@ -0,0 +1,1225 @@ +""" +Grapheme overrides for _known_78f828e8. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: konsole +""" +# pylint: skip-file +GRAPHEMES = { + '؁۱': 1, + 'केा': 1, + 'क्का': 3, + 'क्कां': 3, + 'क्को': 3, + 'क्घ्घि्': 4, + 'क्ता': 3, + 'क्ति': 3, + 'क्ती': 3, + 'क्तीं': 3, + 'क्त्योः': 4, + 'क्ना': 3, + 'क्नि': 3, + 'क्या': 3, + 'क्रा': 3, + 'क्रि': 3, + 'क्षा': 3, + 'क्षां': 3, + 'क्षाः': 3, + 'क्षि': 3, + 'क्षो': 3, + 'क्ष्ण': 3, + 'क्ष्य': 3, + 'क्ष्या': 4, + 'क्सा': 3, + 'ख्यः': 3, + 'ख्या': 3, + 'ग़ा': 1, + 'ग्या': 3, + 'ग्र्य': 3, + 'घेि': 1, + 'घ्का': 3, + 'घ्र्व्य': 4, + 'घ्लि': 3, + 'घ्श्य': 3, + 'घ्स्ट': 3, + 'च्चा': 3, + 'च्चों': 3, + 'च्छा': 3, + 'च्छि': 3, + 'च्या': 3, + 'च्यां': 3, + 'च्यो': 3, + 'छुी': 1, + 'ज्ञा': 3, + 'ज्या': 3, + 'ज्या‌': 3, + 'ज्रा': 3, + 'ञ्चा': 3, + 'ञ्चि': 3, + 'ट्टि': 3, + 'ट्टी': 3, + 'ट्या': 3, + 'ट्रा': 3, + 'ठैः': 1, + 'ड़ा': 1, + 'ढ़ा': 1, + 'ढ़ि': 1, + 'ढ़ी': 1, + 'ढ़ो': 1, + 'ण्डः': 3, + 'ण्डि': 3, + 'ण्या': 3, + 'ण्यां': 3, + 'त्का': 3, + 'त्ता': 3, + 'त्ति': 3, + 'त्त्थि': 4, + 'त्त्व': 3, + 'त्त्वा': 4, + 'त्त्वे': 3, + 'त्नी': 3, + 'त्नों': 3, + 'त्पा': 3, + 'त्पी': 3, + 'त्मा': 3, + 'त्या': 3, + 'त्यां': 3, + 'त्यि': 3, + 'त्रा': 3, + 'त्राा': 3, + 'त्राि': 3, + 'त्रि': 3, + 'त्री': 3, + 'त्र्त': 3, + 'त्र्य': 3, + 'त्र्या': 4, + 'त्र्ये': 3, + 'त्वा': 3, + 'त्वां': 3, + 'त्सा': 3, + 'त्सो': 3, + 'त्स्वा': 4, + 'द्घि': 3, + 'द्घो': 3, + 'द्दा': 3, + 'द्दि': 3, + 'द्दी': 3, + 'द्धः': 3, + 'द्धा': 3, + 'द्धां': 3, + 'द्धि': 3, + 'द्धिं': 3, + 'द्धी': 3, + 'द्धीं': 3, + 'द्भा': 3, + 'द्या': 3, + 'द्रो': 3, + 'द्वा': 3, + 'द्वि': 3, + 'धेः': 1, + 'ध्या': 3, + 'नैः': 1, + 'न्का': 3, + 'न्चि': 3, + 'न्ञ्या': 4, + 'न्तः': 3, + 'न्ता': 3, + 'न्ति': 3, + 'न्तो': 3, + 'न्तों': 3, + 'न्त्र': 3, + 'न्त्रा': 4, + 'न्त्राः': 4, + 'न्त्रि': 4, + 'न्त्री': 4, + 'न्त्र्य': 4, + 'न्त्र्यं': 4, + 'न्त्र्या': 5, + 'न्त्र्ये': 4, + 'न्दा': 3, + 'न्दी': 3, + 'न्दो': 3, + 'न्धा': 3, + 'न्धि': 3, + 'न्धी': 3, + 'न्धों': 3, + 'न्ना': 3, + 'न्नाः': 3, + 'न्नि': 3, + 'न्मा': 3, + 'न्या': 3, + 'न्यो': 3, + 'न्हा': 3, + 'न्ह्यां': 4, + 'प्ति': 3, + 'प्तौ': 3, + 'प्या': 3, + 'प्रा': 3, + 'फ्ता': 3, + 'फ्ना': 3, + 'फ्नो': 3, + 'फ्रां': 3, + 'ब्धि': 3, + 'भ्यः': 3, + 'भ्या': 3, + 'भ्यां': 3, + 'भ्यो': 3, + 'म्ति': 3, + 'म्नि': 3, + 'म्पा': 3, + 'म्प्र': 3, + 'म्भि': 3, + 'म्मा': 3, + 'म्मि': 3, + 'म्या': 3, + 'म्ही': 3, + 'म्हो': 3, + 'यैः': 1, + 'य्यो': 3, + 'र्कि': 3, + 'र्गी': 3, + 'र्चि': 3, + 'र्जा': 3, + 'र्जि': 3, + 'र्जी': 3, + 'र्णां': 3, + 'र्णी': 3, + 'र्ता': 3, + 'र्ति': 3, + 'र्तिः': 3, + 'र्ती': 3, + 'र्त्त': 3, + 'र्त्ति': 4, + 'र्थि': 3, + 'र्थी': 3, + 'र्दा': 3, + 'र्दि': 3, + 'र्दो': 3, + 'र्द्ध': 3, + 'र्धा': 3, + 'र्धि': 3, + 'र्नि': 3, + 'र्बा': 3, + 'र्भा': 3, + 'र्मा': 3, + 'र्मि': 3, + 'र्या': 3, + 'र्यां': 3, + 'र्यों': 3, + 'र्रा': 3, + 'र्वा': 3, + 'र्वां': 3, + 'र्वो': 3, + 'र्सा': 3, + 'र्हाः': 3, + 'र्हि': 3, + 'र्हो': 3, + 'र्‍या': 3, + 'ल्का': 3, + 'ल्पि': 3, + 'ल्या': 3, + 'ल्यां': 3, + 'ल्याः': 3, + 'ल्ला': 3, + 'ल्लि': 3, + 'व्या': 3, + 'व्यों': 3, + 'श्चि': 3, + 'श्या': 3, + 'श्यि': 3, + 'श्यों': 3, + 'श्रा': 3, + 'श्रां': 3, + 'श्वा': 3, + 'श्वि': 3, + 'ष्का': 3, + 'ष्टः': 3, + 'ष्टा': 3, + 'ष्टां': 3, + 'ष्टाः': 3, + 'ष्टि': 3, + 'ष्टी': 3, + 'ष्टीं': 3, + 'ष्ट्र': 3, + 'ष्ट्रा': 4, + 'ष्ट्रां': 4, + 'ष्ट्रि': 4, + 'ष्ट्री': 4, + 'ष्ट्रे': 3, + 'ष्ट्रो': 4, + 'ष्ट्रों': 4, + 'ष्ठा': 3, + 'ष्ठों': 3, + 'ष्प्र': 3, + 'ष्यः': 3, + 'ष्यों': 3, + 'स्का': 3, + 'स्काः': 3, + 'स्ट्या': 4, + 'स्ता': 3, + 'स्ति': 3, + 'स्ती': 3, + 'स्तो': 3, + 'स्त्र': 3, + 'स्त्रा': 4, + 'स्त्रि': 4, + 'स्त्री': 4, + 'स्था': 3, + 'स्थां': 3, + 'स्थि': 3, + 'स्थी': 3, + 'स्थ्य': 3, + 'स्धी': 3, + 'स्मि': 3, + 'स्मिं': 3, + 'स्या': 3, + 'स्यां': 3, + 'स्याः': 3, + 'स्यों': 3, + 'स्रो': 3, + 'स्वा': 3, + 'स्वी': 3, + 'स्सा': 3, + 'हैः': 1, + 'ह्या': 3, + 'ह्रा': 3, + 'फ़्ता': 3, + 'ক্তি': 3, + 'ক্রী': 3, + 'ক্ষা': 3, + 'ক্ষি': 3, + 'ক্ষে': 3, + 'ক্ষ্য': 3, + 'ক্ষ্যে': 4, + 'খ্যা': 3, + 'গ্রা': 3, + 'গ্রে': 3, + 'ঙ্খা': 3, + 'ঙ্গী': 3, + 'ঙ্গে': 3, + 'চ্ছা': 3, + 'চ্ছা‌': 3, + 'চ্ছে': 3, + 'জ্ঞা': 3, + 'ঞ্চি': 3, + 'ঞ্ছি': 3, + 'ট্রে': 3, + 'ড়া': 1, + 'ণ্ডে': 3, + 'ত্তা': 3, + 'ত্তি': 3, + 'ত্বে': 3, + 'ত্যা': 3, + 'ত্যি': 3, + 'ত্যে': 3, + 'ত্রা': 3, + 'ত্রে': 3, + 'ত্‍পী': 3, + 'ত্‍সা': 3, + 'দ্দি': 3, + 'দ্দে': 3, + 'দ্ধা': 3, + 'দ্ধি': 3, + 'দ্ধে': 3, + 'দ্বা': 3, + 'দ্রো': 3, + 'ধ্যে': 3, + 'ন্তা': 3, + 'ন্তি': 3, + 'ন্তে': 3, + 'ন্ত্রি': 4, + 'ন্ত্রে': 4, + 'ন্থী': 3, + 'ন্ধা': 3, + 'ন্মা': 3, + 'ন্যা': 3, + 'ন্যে': 3, + 'প্তা': 3, + 'প্রা': 3, + 'ব্ধি': 3, + 'ব্যা': 3, + 'ভ্রা': 3, + 'ম্পা': 3, + 'ম্মা': 3, + 'য়া': 1, + 'য়ি': 1, + 'য়ে': 1, + 'য়ো': 1, + 'র্জা': 3, + 'র্থে': 3, + 'র্দো': 3, + 'র্ধা': 3, + 'র্নী': 3, + 'র্বা': 3, + 'র্বি': 3, + 'র্বো': 3, + 'র্ব্য': 3, + 'র্মে': 3, + 'র্যা': 3, + 'ল্যা': 3, + 'ল্যে': 3, + 'ল্লে': 3, + 'শৃং': 1, + 'শ্চি': 3, + 'শ্বা': 3, + 'শ্বে': 3, + 'শ্যে': 3, + 'শ্রা': 3, + 'ষ্টা': 3, + 'ষ্টি': 3, + 'ষ্ট্র': 3, + 'ষ্ট্রী': 4, + 'ষ্ট্রে': 4, + 'ষ্ঠা': 3, + 'ষ্ঠি': 3, + 'ষ্ঠী': 3, + 'স্তি': 3, + 'স্তি‌': 3, + 'স্ত্র': 3, + 'স্থা': 3, + 'স্থ্য': 3, + 'স্বা': 3, + 'স্বী': 3, + 'স্যা': 3, + 'স্যে': 3, + 'ક્કા': 3, + 'ક્કો': 3, + 'ક્તિ': 3, + 'ક્ષા': 3, + 'ચ્ચા': 3, + 'ચ્છા': 3, + 'જ્ઞા': 3, + 'જ્યો': 3, + 'ત્તા': 3, + 'ત્તિ': 3, + 'ત્ત્વ': 3, + 'ત્ત્વા': 4, + 'ત્યા': 3, + 'ત્યાં': 3, + 'ત્યિ': 3, + 'ત્યો': 3, + 'ત્રી': 3, + 'ત્ર્ય': 3, + 'દ્ધા': 3, + 'દ્ધાં': 3, + 'દ્ધિ': 3, + 'દ્વા': 3, + 'ધ્યા': 3, + 'ન્તો': 3, + 'ન્મા': 3, + 'ન્યા': 3, + 'પ્રા': 3, + 'મ્યાં': 3, + 'ર્તા': 3, + 'ર્થિ': 3, + 'ર્દો': 3, + 'ર્મિ': 3, + 'ર્યા': 3, + 'ર્યો': 3, + 'વ્યા': 3, + 'વ્યો': 3, + 'ષ્ટિ': 3, + 'ષ્ટ્ર': 3, + 'ષ્ટ્રી': 4, + 'ષ્ટ્રો': 4, + 'ષ્ઠા': 3, + 'સ્તિ': 3, + 'સ્તી': 3, + 'સ્ત્રી': 4, + 'સ્થા': 3, + 'સ્થિ': 3, + 'સ્રી': 3, + 'સ્વા': 3, + 'સ્વી': 3, + 'સ્સા': 3, + 'కాం': 1, + 'కెం': 1, + 'క్కు': 3, + 'క్తు': 3, + 'క్రూ': 3, + 'క్స్వా': 3, + 'గిం': 1, + 'చెం': 1, + 'చ్చు': 3, + 'టిం': 1, + 'ట్లు': 3, + 'డ్రు': 3, + 'ణిం': 1, + 'త్తు': 3, + 'త్యం': 3, + 'త్రు': 3, + 'త్ర్య': 3, + 'దిం': 1, + 'ద్దు': 3, + 'ద్ర్య': 3, + 'ధిం': 1, + 'నాం': 1, + 'నిం': 1, + 'నొం': 1, + 'న్ను': 3, + 'పిం': 1, + 'పెం': 1, + 'పొం': 1, + 'భ్యు': 3, + 'మిం': 1, + 'యిం': 1, + 'రిం': 1, + 'ర్చు': 3, + 'ర్ణు': 3, + 'ర్తృ': 3, + 'ర్బం': 3, + 'ర్హు': 3, + 'లిం': 1, + 'విం': 1, + 'శాం': 1, + 'శిం': 1, + 'షిం': 1, + 'ష్టు': 3, + 'ష్ట్ర': 3, + 'ష్ట్రీ': 3, + 'ష్ఠు': 3, + 'సాం': 1, + 'స్కృ': 3, + 'స్త్ర': 3, + 'స్త్రీ': 3, + 'స్థ్య': 3, + 'హిం': 1, + 'ಕಿಂ': 1, + 'ಕೆಂ': 1, + 'ದಿಂ': 1, + 'ನಿಂ': 1, + 'ಯಿಂ': 1, + 'ಯೆಂ': 1, + 'ರಿಂ': 1, + 'ರೆಂ': 1, + 'ಲೆಂ': 1, + 'ಳಿಂ': 1, + 'ವೆಂ': 1, + 'ക്കാ': 3, + 'ക്കി': 3, + 'ക്കെ': 3, + 'ക്കേ': 3, + 'ക്കൊ': 3, + 'ക്കോ': 3, + 'ക്തി': 3, + 'ക്യം': 3, + 'ക്ഷാ': 3, + 'ക്ഷി': 3, + 'ക്ഷേ': 3, + 'ഖ്യാ': 3, + 'ഗ്ഗം': 3, + 'ഗ്ദാ': 3, + 'ഗ്യം': 3, + 'ങ്കി': 3, + 'ങ്കെ': 3, + 'ങ്കേ': 3, + 'ങ്ങി': 3, + 'ച്ചി': 3, + 'ച്ചെ': 3, + 'ച്ചേ': 3, + 'ജ്യാ': 3, + 'ഞ്ഞി': 3, + 'ഞ്ഞെ': 3, + 'ടും': 1, + 'ട്ടാ': 3, + 'ട്ടി': 3, + 'ട്ടോ': 3, + 'ണ്ടാ': 3, + 'ണ്ടി': 3, + 'ണ്ടെ': 3, + 'തും': 1, + 'ത്താ': 3, + 'ത്തി': 3, + 'ത്തെ': 3, + 'ത്തേ': 3, + 'ത്തോ': 3, + 'ത്നം': 3, + 'ത്നി': 3, + 'ത്യാ': 3, + 'ത്യേ': 3, + 'ത്വം': 3, + 'ദ്ധി': 3, + 'ദ്യാ': 3, + 'നും': 1, + 'ന്തം': 3, + 'ന്തെ': 3, + 'ന്ത്ര': 3, + 'ന്ത്ര്യ': 4, + 'ന്ത്ര്യം': 5, + 'ന്ധി': 3, + 'ന്നാ': 3, + 'ന്നി': 3, + 'ന്നീ': 3, + 'ന്നെ': 3, + 'ന്നേ': 3, + 'ന്നോ': 3, + 'ന്മാ': 3, + 'ന്യം': 3, + 'ന്യാ': 3, + 'ന്യേ': 3, + 'ന്യോ': 3, + 'ന്റെ': 3, + 'ന്‍പി': 3, + 'പ്പി': 3, + 'പ്പെ': 3, + 'പ്പോ': 3, + 'പ്രാ': 3, + 'ബ്ലി': 3, + 'ഭ്യാ': 3, + 'ഭ്രാ': 3, + 'മ്പാ': 3, + 'മ്പ്ര': 3, + 'മ്മി': 3, + 'യും': 1, + 'യ്ക്കു': 3, + 'യ്തി': 3, + 'യ്യാ': 3, + 'യ്യി': 3, + 'രും': 1, + 'ര്യം': 3, + 'ര്‍ക്കു': 3, + 'ര്‍ക്കും': 3, + 'ര്‍ക്ക്‌': 3, + 'ര്‍ഗ്ഗം': 4, + 'ര്‍ച്ച': 3, + 'ര്‍ണ്ണ': 3, + 'ര്‍ത്ത': 3, + 'ര്‍ത്തി': 4, + 'ര്‍ത്തു': 3, + 'ര്‍ത്തേ': 4, + 'ര്‍ദേ': 3, + 'ര്‍ദ്ദ': 3, + 'ര്‍പ്പെ': 4, + 'ര്‍മ്മി': 4, + 'ര്‍രാ': 3, + 'ര്‍വ്വ': 3, + 'ര്‍ഹി': 3, + 'റ്റം': 3, + 'റ്റേ': 3, + 'ലും': 1, + 'ല്യാ': 3, + 'ല്ലാ': 3, + 'ല്ലാം': 3, + 'ല്ലെ': 3, + 'ല്‍കി': 3, + 'ല്‍കേ': 3, + 'ല്‍നി': 3, + 'ല്‍പ്പ': 3, + 'ളും': 1, + 'ള്ളാ': 3, + 'ള്ളി': 3, + 'ള്‍കൊ': 3, + 'ള്‍ക്ക': 3, + 'ള്‍ക്കി': 4, + 'ള്‍ക്കു': 3, + 'ള്‍ക്കും': 3, + 'ള്‍ക്കെ': 4, + 'ള്‍ക്ക്‌': 3, + 'വും': 1, + 'വ്യം': 3, + 'വ്യാ': 3, + 'ശ്വാ': 3, + 'ഷ്ട്യാ': 4, + 'ഷ്ട്ര': 3, + 'ഷ്ട്രീ': 4, + 'ഷ്യാ': 3, + 'സ്കാ': 3, + 'സ്ത്രം': 4, + 'സ്ത്രീ': 4, + 'സ്ഥാ': 3, + 'സ്ഥി': 3, + 'സ്റ്റ്‌': 3, + 'സ്വാ': 3, + 'സ്വീ': 3, + 'സ്സാ': 3, + 'സ്സി': 3, + 'സ്സോ': 3, + 'ൻ്റെ': 3, + 'දිං': 1, + 'හිං': 1, + 'က်ျ': 1, + 'ကၠေ': 1, + 'ကၠေံ': 1, + 'ဂၠေ': 1, + 'ငွေ': 1, + 'စှ်ေ': 1, + 'စၞေ': 1, + 'စၠေ': 1, + 'ဇၞေ': 1, + 'တွေ': 1, + 'တှ်ေ': 1, + 'တၟေ': 1, + 'ထွေ': 1, + 'ဒ္ဂေ': 3, + 'နှေ': 1, + 'ဗ္တေ': 3, + 'ဗ္ၜေ': 3, + 'ဗၠေ': 1, + 'မွေ': 1, + 'မွေ့': 1, + 'မှေ': 1, + 'မၠေ': 1, + 'ရွေ': 1, + 'ရွှေ့': 1, + 'ရှေ': 1, + 'ရှေ့': 1, + 'ရှ်ေ': 1, + 'လၟေ': 1, + 'သ္ဂေ': 3, + 'သှ်ေ': 1, + 'သၞေ': 1, + 'ក្ដៅ': 3, + 'ក្រោ': 3, + 'ក្សា': 3, + 'ខ្ជា': 3, + 'ខ្លា': 3, + 'គ្នា': 3, + 'គ្មា': 3, + 'គ្រា': 3, + 'ង្កើ': 3, + 'ង្រៀ': 3, + 'ង្ហា': 3, + 'ច្ចេ': 3, + 'ច្បា': 3, + 'ឆ្នាំ': 3, + 'ឆ្នោ': 3, + 'ឆ្លើ': 3, + 'ជ្ជា': 3, + 'ជ្ញា': 3, + 'ជ្រើ': 3, + 'ជ្រៀ': 3, + 'ជ្រែ': 3, + 'ឈ្មោះ': 3, + 'ញុះ': 1, + 'ញ្ជា': 3, + 'ញ្ញា': 3, + 'ញ្ញៈ': 3, + 'ដ្ឋា': 3, + 'ណ្ដា': 3, + 'ណ្ណោះ': 3, + 'ត្រា': 3, + 'ថ្ងៃ': 3, + 'ថ្នា': 3, + 'ថ្លៃ': 3, + 'ទ្យា': 3, + 'ធ្នា': 3, + 'ធ្យា': 3, + 'ធ្យោ': 3, + 'ធ្វើ': 3, + 'ន្ថែ': 3, + 'ន្ថោ': 3, + 'ន្ទា': 3, + 'ន្ទៈ': 3, + 'ន្យា': 3, + 'ន្លែ': 3, + 'ប៉ះ': 1, + 'ប្ដេ': 3, + 'ប្រា': 3, + 'ប្រើ': 3, + 'ប្រែ': 3, + 'ផ្ដា': 3, + 'ផ្ទា': 3, + 'ផ្ទេ': 3, + 'ផ្នែ': 3, + 'ផ្លា': 3, + 'ផ្សា': 3, + 'ផ្សេ': 3, + 'ផ្សៃ': 3, + 'ព្យា': 3, + 'ព្រៀ': 3, + 'ព្រៃ': 3, + 'ម៉ា': 1, + 'ម៉ោ': 1, + 'ម្ងា': 3, + 'ម្ចា': 3, + 'ម្ដា': 3, + 'ម្ដែ': 3, + 'ម្នា': 3, + 'ម្នេ': 3, + 'ម្ភា': 3, + 'ម្រា': 3, + 'ម្រើ': 3, + 'ម្រេ': 3, + 'ម្លៀ': 3, + 'ម្លៃ': 3, + 'យ៉ា': 1, + 'លុះ': 1, + 'ល្បៈ': 3, + 'ល្មើ': 3, + 'ស្គា': 3, + 'ស្ដ្រី': 3, + 'ស្ត្រ': 3, + 'ស្ថា': 3, + 'ស្នា': 3, + 'ស្មា': 3, + 'ស្មើ': 3, + 'ស្រា': 3, + 'ស្លា': 3, + 'ស្វែ': 3, + 'ᨠᩮ᩠ᨯᩨ': 3, + 'ᨠᩯ᩠ᨯ': 3, + 'ᨠᩯ᩠ᨶ᩵': 3, + 'ᨡᩮ᩠ᨲ': 3, + 'ᨡᩯ᩠ᨠ': 3, + 'ᨡᩯ᩠ᨦ': 3, + 'ᨣᩕ᩠ᩋ': 3, + 'ᨣᩕᩮ᩠ᨦᩨ᩵': 3, + 'ᨣᩯ᩠ᨶᩢ': 3, + 'ᨣᩯ᩠ᩅ': 3, + 'ᨧᩮ᩠ᨷ': 3, + 'ᨧᩱ᩠ᨿ': 3, + 'ᨩᩮ᩠ᩋᩨ': 3, + 'ᨩᩮ᩠ᩋᩨ᩵': 3, + 'ᨩᩮ᩠ᩋᩨ᩶': 3, + 'ᨩ᩵ᩭ': 1, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 3, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 3, + 'ᨯᩪᩯ': 1, + 'ᨯᩯ᩠ᨦ': 3, + 'ᨯᩯ᩠ᨶ': 3, + 'ᨯᩰ᩠ᨿ': 3, + 'ᨲᩮ᩠ᨠ': 3, + 'ᨲᩮ᩠ᨦ': 3, + 'ᨲᩮ᩠ᨾ': 3, + 'ᨲᩮ᩠ᨾᩨ᩵': 3, + 'ᨲᩯ᩠ᨠ': 3, + 'ᨲᩯ᩠ᨦ᩵': 3, + 'ᨲᩯ᩠ᨾᩢ': 3, + 'ᨲᩱ᩠ᨿ': 3, + 'ᨳᩮ᩠ᨶᩨ᩵': 3, + 'ᨳᩯ᩠ᨦᩢ': 3, + 'ᨳᩯ᩠ᨾ': 3, + 'ᨴᩮ᩠ᩈ': 3, + 'ᨴᩮ᩠ᩈᩱ': 4, + 'ᨴᩯ᩠ᨶ': 3, + 'ᨴᩰ᩠ᩈ': 3, + 'ᨶᩯ᩠ᨶ': 3, + 'ᨷᩮ᩠ᨦᩨ᩶': 3, + 'ᨸᩮ᩠ᨦᩨ': 3, + 'ᨸᩮ᩠ᨶ': 3, + 'ᨹᩪᩢᩱ': 1, + 'ᨹᩮᩨ᩠ᨿ': 3, + 'ᨻᩕ᩠ᩋᩢ': 3, + 'ᨻᩮ᩠ᩋᩨ᩵': 3, + 'ᨽᩱ᩠ᨿ': 3, + 'ᨾᩮ᩠ᨠᩨ': 3, + 'ᨾᩮ᩠ᨦᩨ': 3, + 'ᨾᩮ᩠ᩋᩨ᩵': 3, + 'ᨿᩮ᩠ᨶ': 3, + 'ᨿᩮ᩠ᨾᩨ': 3, + 'ᩁᩢᩭ': 1, + 'ᩁᩮ᩠ᨦᩨ᩵': 3, + 'ᩁᩮ᩠ᨧ': 3, + 'ᩁᩮ᩠ᨶᩨ': 3, + 'ᩁᩮᩨ᩠ᨬ': 3, + 'ᩁᩯ᩠ᨦ': 3, + 'ᩃᩮ᩠ᨠᩨ': 3, + 'ᩃᩮ᩠ᨦᩨ': 3, + 'ᩃᩰ᩠ᨠ': 3, + 'ᩅᩮ᩠ᨶ': 3, + 'ᩅᩮ᩠ᨶᩢ': 3, + 'ᩈᩮ᩠ᩈ': 3, + 'ᩈᩯ᩠ᩅ': 3, + 'ᩈᩱ᩠ᨿ': 3, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 3, + 'ᩉᩮ᩠ᨦᩢᩢ': 3, + 'ᩉᩮ᩠ᨯ': 3, + 'ᩉᩮ᩠ᨲᩩ': 3, + 'ᩉᩮ᩠ᨶᩨ': 3, + 'ᩉᩮ᩠ᨾᩨ': 3, + 'ᩉᩮ᩠ᨾᩨᩨ': 3, + 'ᩉᩯ᩠ᨦ᩵': 3, + 'ᩉᩯ᩠ᨶᩢ': 3, + 'ᩉᩯ᩠ᨾ': 3, + 'ᩉᩱ᩠ᨾ᩵': 3, + 'ᩉᩱ᩠ᨿ᩵': 3, + 'ᩣ᩠ᨲᩱ': 3, + 'ꦏ꧀': 2, + 'ꦏ꧀ꦏ': 3, + 'ꦏ꧀ꦏꦁ': 3, + 'ꦏ꧀ꦏꦺ': 4, + 'ꦏ꧀ꦏꦼ': 3, + 'ꦏ꧀ꦔ': 3, + 'ꦏ꧀ꦔꦸ': 3, + 'ꦏ꧀ꦔꦿ': 4, + 'ꦏ꧀ꦕ': 3, + 'ꦏ꧀ꦠ': 3, + 'ꦏ꧀ꦠꦶ': 3, + 'ꦏ꧀ꦠꦸ': 3, + 'ꦏ꧀ꦠꦺ': 4, + 'ꦏ꧀ꦢ': 3, + 'ꦏ꧀ꦢꦂ': 3, + 'ꦏ꧀ꦢꦶ': 3, + 'ꦏ꧀ꦤ': 3, + 'ꦏ꧀ꦤꦶꦁ': 3, + 'ꦏ꧀ꦥ': 3, + 'ꦏ꧀ꦥꦶ': 3, + 'ꦏ꧀ꦥꦿꦶ': 4, + 'ꦏ꧀ꦧ': 3, + 'ꦏ꧀ꦧꦶ': 3, + 'ꦏ꧀ꦧꦺ': 4, + 'ꦏ꧀ꦩ': 3, + 'ꦏ꧀ꦩꦸ': 3, + 'ꦏ꧀ꦪ': 3, + 'ꦏ꧀ꦭ': 3, + 'ꦏ꧀ꦮ': 3, + 'ꦏ꧀ꦱ': 3, + 'ꦏ꧀ꦱꦂ': 3, + 'ꦏ꧀ꦱꦶ': 3, + 'ꦏ꧀ꦱꦸ': 3, + 'ꦏ꧀ꦱꦺ': 4, + 'ꦏ꧀ꦲ': 3, + 'ꦏ꧀ꦲꦁ': 3, + 'ꦏ꧀ꦲꦶꦁ': 3, + 'ꦏ꧀ꦲꦸ': 3, + 'ꦏ꧀ꦲꦺ': 4, + 'ꦏ꧀ꦲꦺꦴ': 4, + 'ꦒꦸꦃ': 1, + 'ꦒ꧀ꦒ': 3, + 'ꦔ꧀ꦒꦼ': 3, + 'ꦔ꧀ꦒꦿꦼꦁ': 4, + 'ꦔ꧀ꦭ': 3, + 'ꦔ꧀ꦭꦁ': 3, + 'ꦔ꧀ꦭꦸ': 3, + 'ꦔ꧀ꦭꦼ': 3, + 'ꦚ꧀ꦕ': 3, + 'ꦚ꧀ꦕꦶ': 3, + 'ꦚ꧀ꦗ': 3, + 'ꦚ꧀ꦗꦶ': 3, + 'ꦚ꧀ꦗꦸꦁ': 3, + 'ꦚ꧀ꦗꦸꦂ': 3, + 'ꦠꦸꦃ': 1, + 'ꦠ꧀': 2, + 'ꦠ꧀ꦏꦁ': 3, + 'ꦠ꧀ꦏꦸ': 3, + 'ꦠ꧀ꦒ': 3, + 'ꦠ꧀ꦔꦸ': 3, + 'ꦠ꧀ꦚ': 3, + 'ꦠ꧀ꦠ': 3, + 'ꦠ꧀ꦠꦶ': 3, + 'ꦠ꧀ꦠꦶꦁ': 3, + 'ꦠ꧀ꦠꦸ': 3, + 'ꦠ꧀ꦠꦺ': 4, + 'ꦠ꧀ꦤ': 3, + 'ꦠ꧀ꦤꦶ': 3, + 'ꦠ꧀ꦩ': 3, + 'ꦠ꧀ꦩꦼ': 3, + 'ꦠ꧀ꦭ': 3, + 'ꦠ꧀ꦭꦺ': 4, + 'ꦠ꧀ꦱ': 3, + 'ꦠ꧀ꦱꦶꦁ': 3, + 'ꦠ꧀ꦱꦶꦃ': 3, + 'ꦠ꧀ꦱꦾ': 4, + 'ꦠ꧀ꦱ꧀ꦮ': 5, + 'ꦠ꧀ꦲ': 3, + 'ꦠ꧀ꦲꦶꦁ': 3, + 'ꦠ꧀ꦲꦺꦴ': 4, + 'ꦢ꧀': 2, + 'ꦢ꧀ꦏ': 3, + 'ꦢ꧀ꦠ': 3, + 'ꦢ꧀ꦠꦶꦁ': 3, + 'ꦢ꧀ꦢ': 3, + 'ꦢ꧀ꦥ': 3, + 'ꦢ꧀ꦩꦺꦴ': 4, + 'ꦢ꧀ꦲ': 3, + 'ꦤ꧀': 2, + 'ꦤ꧀ꦏ': 3, + 'ꦤ꧀ꦏꦁ': 3, + 'ꦤ꧀ꦏꦸ': 3, + 'ꦤ꧀ꦏꦼ': 3, + 'ꦤ꧀ꦒ': 3, + 'ꦤ꧀ꦔ': 3, + 'ꦤ꧀ꦔꦁ': 3, + 'ꦤ꧀ꦔꦶ': 3, + 'ꦤ꧀ꦔꦸ': 3, + 'ꦤ꧀ꦔꦸꦂ': 3, + 'ꦤ꧀ꦔꦺ': 4, + 'ꦤ꧀ꦔꦼ': 3, + 'ꦤ꧀ꦔꦿꦸ': 4, + 'ꦤ꧀ꦗ': 3, + 'ꦤ꧀ꦗꦸ': 3, + 'ꦤ꧀ꦗꦼ': 3, + 'ꦤ꧀ꦚꦶ': 3, + 'ꦤ꧀ꦛꦃ': 4, + 'ꦤ꧀ꦛꦶ': 3, + 'ꦤ꧀ꦝ': 3, + 'ꦤ꧀ꦝꦁ': 3, + 'ꦤ꧀ꦝꦶ': 3, + 'ꦤ꧀ꦝꦸ': 3, + 'ꦤ꧀ꦝꦸꦁ': 3, + 'ꦤ꧀ꦝꦺꦁ': 4, + 'ꦤ꧀ꦝꦺꦴꦁ': 4, + 'ꦤ꧀ꦝꦼ': 3, + 'ꦤ꧀ꦠ': 3, + 'ꦤ꧀ꦠꦂ': 3, + 'ꦤ꧀ꦠꦃ': 4, + 'ꦤ꧀ꦠꦶ': 3, + 'ꦤ꧀ꦠꦸ': 3, + 'ꦤ꧀ꦠꦸꦁ': 3, + 'ꦤ꧀ꦠꦺ': 4, + 'ꦤ꧀ꦠꦼ': 3, + 'ꦤ꧀ꦠꦼꦂ': 3, + 'ꦤ꧀ꦠꦽ': 3, + 'ꦤ꧀ꦢ': 3, + 'ꦤ꧀ꦢꦁ': 3, + 'ꦤ꧀ꦢꦂ': 3, + 'ꦤ꧀ꦢꦶ': 3, + 'ꦤ꧀ꦢꦸ': 3, + 'ꦤ꧀ꦢꦺ': 4, + 'ꦤ꧀ꦢꦼ': 3, + 'ꦤ꧀ꦤ': 3, + 'ꦤ꧀ꦤꦶ': 3, + 'ꦤ꧀ꦤꦶꦁ': 3, + 'ꦤ꧀ꦤꦺ': 4, + 'ꦤ꧀ꦤꦼ': 3, + 'ꦤ꧀ꦥ': 3, + 'ꦤ꧀ꦥꦁ': 3, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 3, + 'ꦤ꧀ꦥꦶ': 3, + 'ꦤ꧀ꦥꦸ': 3, + 'ꦤ꧀ꦥꦼ': 3, + 'ꦤ꧀ꦥꦿ': 4, + 'ꦤ꧀ꦥꦿꦶ': 4, + 'ꦤ꧀ꦧ': 3, + 'ꦤ꧀ꦧꦁ': 3, + 'ꦤ꧀ꦧꦶ': 3, + 'ꦤ꧀ꦧꦸ': 3, + 'ꦤ꧀ꦧꦺ': 4, + 'ꦤ꧀ꦧꦺꦴ': 4, + 'ꦤ꧀ꦧꦼ': 3, + 'ꦤ꧀ꦩ': 3, + 'ꦤ꧀ꦩꦂ': 3, + 'ꦤ꧀ꦩꦶ': 3, + 'ꦤ꧀ꦩꦸꦂ': 3, + 'ꦤ꧀ꦩꦼ': 3, + 'ꦤ꧀ꦭ': 3, + 'ꦤ꧀ꦭꦶ': 3, + 'ꦤ꧀ꦭꦸ': 3, + 'ꦤ꧀ꦮ': 3, + 'ꦤ꧀ꦮꦂ': 3, + 'ꦤ꧀ꦮꦶ': 3, + 'ꦤ꧀ꦮꦸ': 3, + 'ꦤ꧀ꦮꦼ': 3, + 'ꦤ꧀ꦱ': 3, + 'ꦤ꧀ꦱꦂ': 3, + 'ꦤ꧀ꦱꦃ': 4, + 'ꦤ꧀ꦱꦶ': 3, + 'ꦤ꧀ꦱꦶꦁ': 3, + 'ꦤ꧀ꦱꦸ': 3, + 'ꦤ꧀ꦱꦺꦴ': 4, + 'ꦤ꧀ꦱꦼ': 3, + 'ꦤ꧀ꦲ': 3, + 'ꦤ꧀ꦲꦁ': 3, + 'ꦤ꧀ꦲꦶ': 3, + 'ꦤ꧀ꦲꦶꦁ': 3, + 'ꦤ꧀ꦲꦸ': 3, + 'ꦤ꧀ꦲꦺꦴ': 4, + 'ꦥ꧀': 2, + 'ꦥ꧀ꦏ': 3, + 'ꦥ꧀ꦏꦁ': 3, + 'ꦥ꧀ꦠ': 3, + 'ꦥ꧀ꦠꦶ': 3, + 'ꦥ꧀ꦢꦸ': 3, + 'ꦥ꧀ꦤ': 3, + 'ꦥ꧀ꦤꦶ': 3, + 'ꦥ꧀ꦥ': 3, + 'ꦥ꧀ꦥꦶ': 3, + 'ꦥ꧀ꦥꦺ': 4, + 'ꦥ꧀ꦧꦺ': 4, + 'ꦥ꧀ꦩ': 3, + 'ꦥ꧀ꦩꦂ': 3, + 'ꦥ꧀ꦫꦺ': 4, + 'ꦥ꧀ꦭ': 3, + 'ꦥ꧀ꦭꦸ': 3, + 'ꦥ꧀ꦱ': 3, + 'ꦥ꧀ꦱꦶꦂ': 3, + 'ꦥ꧀ꦱꦼ': 3, + 'ꦥ꧀ꦲ': 3, + 'ꦧ꧀': 2, + 'ꦧ꧀ꦏ': 3, + 'ꦧ꧀ꦠꦸ': 3, + 'ꦧ꧀ꦥ': 3, + 'ꦧ꧀ꦧ': 3, + 'ꦧ꧀ꦧꦺ': 4, + 'ꦧ꧀ꦲ': 3, + 'ꦧ꧀ꦲꦶ': 3, + 'ꦩ꧀': 2, + 'ꦩ꧀ꦏꦁ': 3, + 'ꦩ꧀ꦔꦼ': 3, + 'ꦩ꧀ꦠꦸ': 3, + 'ꦩ꧀ꦠꦺꦴ': 4, + 'ꦩ꧀ꦤꦶꦁ': 3, + 'ꦩ꧀ꦥ': 3, + 'ꦩ꧀ꦥꦶ': 3, + 'ꦩ꧀ꦥꦸ': 3, + 'ꦩ꧀ꦥꦼ': 3, + 'ꦩ꧀ꦧ': 3, + 'ꦩ꧀ꦧꦁ': 3, + 'ꦩ꧀ꦧꦂ': 3, + 'ꦩ꧀ꦧꦃ': 4, + 'ꦩ꧀ꦧꦶ': 3, + 'ꦩ꧀ꦧꦸ': 3, + 'ꦩ꧀ꦧꦸꦁ': 3, + 'ꦩ꧀ꦧꦺ': 4, + 'ꦩ꧀ꦧꦺꦂ': 4, + 'ꦩ꧀ꦧꦼꦂ': 3, + 'ꦩ꧀ꦧꦾꦸꦂ': 4, + 'ꦩ꧀ꦩ': 3, + 'ꦩ꧀ꦩꦶ': 3, + 'ꦩ꧀ꦫ': 3, + 'ꦩ꧀ꦫꦃ': 4, + 'ꦩ꧀ꦭ': 3, + 'ꦩ꧀ꦲꦶ': 3, + 'ꦪꦸꦃ': 1, + 'ꦫꦶꦃ': 1, + 'ꦭꦶꦃ': 1, + 'ꦭ꧀': 2, + 'ꦭ꧀ꦏꦁ': 3, + 'ꦭ꧀ꦚꦼꦁ': 3, + 'ꦭ꧀ꦠꦸ': 3, + 'ꦭ꧀ꦧꦸ': 3, + 'ꦭ꧀ꦩꦸ': 3, + 'ꦭ꧀ꦭ': 3, + 'ꦭ꧀ꦭꦶ': 3, + 'ꦭ꧀ꦭꦶꦁ': 3, + 'ꦭ꧀ꦭꦺ': 4, + 'ꦭ꧀ꦮ': 3, + 'ꦭ꧀ꦱ': 3, + 'ꦭ꧀ꦱꦂ': 3, + 'ꦭ꧀ꦱꦶꦁ': 3, + 'ꦭ꧀ꦱꦸ': 3, + 'ꦭ꧀ꦲ': 3, + 'ꦭ꧀ꦲꦁ': 3, + 'ꦭ꧀ꦲꦶꦁ': 3, + 'ꦭ꧀ꦲꦸ': 3, + 'ꦮꦶꦃ': 1, + 'ꦮꦸꦃ': 1, + 'ꦱꦶꦃ': 1, + 'ꦱ꧀': 2, + 'ꦱ꧀ꦏ': 3, + 'ꦱ꧀ꦏꦁ': 3, + 'ꦱ꧀ꦏꦿꦶ': 4, + 'ꦱ꧀ꦒ': 3, + 'ꦱ꧀ꦔꦸ': 3, + 'ꦱ꧀ꦔꦿ': 4, + 'ꦱ꧀ꦛꦶ': 3, + 'ꦱ꧀ꦠ': 3, + 'ꦱ꧀ꦠꦿ': 4, + 'ꦱ꧀ꦢꦂ': 3, + 'ꦱ꧀ꦢꦶ': 3, + 'ꦱ꧀ꦢꦸ': 3, + 'ꦱ꧀ꦥ': 3, + 'ꦱ꧀ꦧ': 3, + 'ꦱ꧀ꦧꦁ': 3, + 'ꦱ꧀ꦩ': 3, + 'ꦱ꧀ꦩꦶ': 3, + 'ꦱ꧀ꦩꦼ': 3, + 'ꦱ꧀ꦩꦿ': 4, + 'ꦱ꧀ꦭ': 3, + 'ꦱ꧀ꦮ': 3, + 'ꦱ꧀ꦱ': 3, + 'ꦱ꧀ꦱꦂ': 3, + 'ꦱ꧀ꦱꦶ': 3, + 'ꦱ꧀ꦱꦶꦁ': 3, + 'ꦱ꧀ꦱꦸ': 3, + 'ꦱ꧀ꦱꦺ': 4, + 'ꦱ꧀ꦲ': 3, + 'ꦱ꧀ꦲꦁ': 3, + 'ꦱ꧀ꦲꦶ': 3, + 'ꦱ꧀ꦲꦶꦁ': 3, + 'ꦱ꧀ꦲꦸ': 3, + '𑄇𑄳𑄠𑄬': 3, + '𑄈𑄳𑄠𑄬': 3, + '𑄌𑄳𑄠𑄬': 3, + '𑄎𑄳𑄠𑄬': 3, + '𑄑𑄳𑄢𑄬': 3, + '𑄖𑄳𑄠𑄬': 3, + '𑄖𑄳𑄢𑄬': 3, + '𑄘𑄳𑄠𑄬': 3, + '𑄚𑄳𑄠𑄬': 3, + '𑄝𑄳𑄢𑄬': 3, + '𑄟𑄳𑄠𑄬': 3, + '𑄡𑄳𑄠𑄬': 3, + '𑄣𑄳𑄦𑄬': 3, + '𑌕𑍍': 2, + '𑌗𑍍': 2, + '𑌚𑍍': 2, + '𑌜𑍍': 2, + '𑌞𑍍': 2, + '𑌟𑍍': 2, + '𑌣𑍍': 2, + '𑌤𑍍': 2, + '𑌦𑍍': 2, + '𑌧𑍍': 2, + '𑌨𑍍': 2, + '𑌪𑍍': 2, + '𑌬𑍍': 2, + '𑌭𑍍': 2, + '𑌮𑍍': 2, + '𑌯𑍍': 2, + '𑌰𑍍': 2, + '𑌲𑍍': 2, + '𑌵𑍍': 2, + '𑌶𑍍': 2, + '𑌷𑍍': 2, + '𑌸𑍍': 2, + '👨🏻‍🫯‍👨🏼': 3, + '👨🏻‍🫯‍👨🏽': 3, + '👨🏻‍🫯‍👨🏾': 3, + '👨🏻‍🫯‍👨🏿': 3, + '👨🏼‍🫯‍👨🏻': 3, + '👨🏼‍🫯‍👨🏽': 3, + '👨🏼‍🫯‍👨🏾': 3, + '👨🏼‍🫯‍👨🏿': 3, + '👨🏽‍🫯‍👨🏻': 3, + '👨🏽‍🫯‍👨🏼': 3, + '👨🏽‍🫯‍👨🏾': 3, + '👨🏽‍🫯‍👨🏿': 3, + '👨🏾‍🫯‍👨🏻': 3, + '👨🏾‍🫯‍👨🏼': 3, + '👨🏾‍🫯‍👨🏽': 3, + '👨🏾‍🫯‍👨🏿': 3, + '👨🏿‍🫯‍👨🏻': 3, + '👨🏿‍🫯‍👨🏼': 3, + '👨🏿‍🫯‍👨🏽': 3, + '👨🏿‍🫯‍👨🏾': 3, + '👩🏻‍🫯‍👩🏼': 3, + '👩🏻‍🫯‍👩🏽': 3, + '👩🏻‍🫯‍👩🏾': 3, + '👩🏻‍🫯‍👩🏿': 3, + '👩🏼‍🫯‍👩🏻': 3, + '👩🏼‍🫯‍👩🏽': 3, + '👩🏼‍🫯‍👩🏾': 3, + '👩🏼‍🫯‍👩🏿': 3, + '👩🏽‍🫯‍👩🏻': 3, + '👩🏽‍🫯‍👩🏼': 3, + '👩🏽‍🫯‍👩🏾': 3, + '👩🏽‍🫯‍👩🏿': 3, + '👩🏾‍🫯‍👩🏻': 3, + '👩🏾‍🫯‍👩🏼': 3, + '👩🏾‍🫯‍👩🏽': 3, + '👩🏾‍🫯‍👩🏿': 3, + '👩🏿‍🫯‍👩🏻': 3, + '👩🏿‍🫯‍👩🏼': 3, + '👩🏿‍🫯‍👩🏽': 3, + '👩🏿‍🫯‍👩🏾': 3, + '🧑🏻‍🫯‍🧑🏼': 3, + '🧑🏻‍🫯‍🧑🏽': 3, + '🧑🏻‍🫯‍🧑🏾': 3, + '🧑🏻‍🫯‍🧑🏿': 3, + '🧑🏼‍🫯‍🧑🏻': 3, + '🧑🏼‍🫯‍🧑🏽': 3, + '🧑🏼‍🫯‍🧑🏿': 3, + '🧑🏽‍🫯‍🧑🏻': 3, + '🧑🏽‍🫯‍🧑🏼': 3, + '🧑🏽‍🫯‍🧑🏾': 3, + '🧑🏽‍🫯‍🧑🏿': 3, + '🧑🏾‍🫯‍🧑🏻': 3, + '🧑🏾‍🫯‍🧑🏽': 3, + '🧑🏾‍🫯‍🧑🏿': 3, + '🧑🏿‍🫯‍🧑🏻': 3, + '🧑🏿‍🫯‍🧑🏼': 3, + '🧑🏿‍🫯‍🧑🏽': 3, + '🧑🏿‍🫯‍🧑🏾': 3, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_8c2ae14d.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_8c2ae14d.py new file mode 100644 index 0000000000000000000000000000000000000000..77f94e1ebd974a8b7241107ae1dbce355120e592 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_8c2ae14d.py @@ -0,0 +1,2712 @@ +""" +Grapheme overrides for _known_8c2ae14d. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: apple_terminal +""" +# pylint: skip-file +GRAPHEMES = { + 'ت‌': 2, + 'ن‌': 2, + 'ه‌': 2, + 'ی‌': 2, + 'ے‌': 2, + 'क्का': 3, + 'क्कां': 3, + 'क्को': 3, + 'क्घ्घि्': 4, + 'क्ता': 3, + 'क्ति': 3, + 'क्ती': 3, + 'क्तीं': 3, + 'क्तेः': 3, + 'क्त्योः': 5, + 'क्ना': 3, + 'क्नि': 3, + 'क्या': 3, + 'क्रा': 3, + 'क्रि': 3, + 'क्षा': 3, + 'क्षां': 3, + 'क्षाः': 4, + 'क्षि': 3, + 'क्षो': 3, + 'क्ष्ण': 3, + 'क्ष्य': 3, + 'क्ष्या': 4, + 'क्सा': 3, + 'ख्यः': 3, + 'ख्या': 3, + 'ख्‍ने': 3, + 'ग्या': 3, + 'ग्यैः': 3, + 'ग्र्य': 3, + 'घ्का': 3, + 'घ्र्व्य': 4, + 'घ्लि': 3, + 'घ्श्य': 3, + 'घ्स्ट': 3, + 'च्चा': 3, + 'च्चों': 3, + 'च्छा': 3, + 'च्छि': 3, + 'च्या': 3, + 'च्यां': 3, + 'च्यो': 3, + 'ज्ञा': 3, + 'ज्या': 3, + 'ज्या‌': 4, + 'ज्रा': 3, + 'ञ्चा': 3, + 'ञ्चि': 3, + 'ट्टि': 3, + 'ट्टी': 3, + 'ट्या': 3, + 'ट्रा': 3, + 'ण्डः': 3, + 'ण्डि': 3, + 'ण्या': 3, + 'ण्यां': 3, + 'ताः': 3, + 'त्का': 3, + 'त्ता': 3, + 'त्ति': 3, + 'त्त्थि': 4, + 'त्त्व': 3, + 'त्त्वा': 4, + 'त्त्वे': 3, + 'त्नी': 3, + 'त्नों': 3, + 'त्पा': 3, + 'त्पी': 3, + 'त्मा': 3, + 'त्या': 3, + 'त्यां': 3, + 'त्यि': 3, + 'त्रा': 3, + 'त्राा': 4, + 'त्राि': 4, + 'त्रि': 3, + 'त्री': 3, + 'त्र्त': 3, + 'त्र्य': 3, + 'त्र्या': 4, + 'त्र्ये': 3, + 'त्वा': 3, + 'त्वां': 3, + 'त्सा': 3, + 'त्सो': 3, + 'त्स्वा': 4, + 'द्घि': 3, + 'द्घो': 3, + 'द्दा': 3, + 'द्दि': 3, + 'द्दी': 3, + 'द्धः': 3, + 'द्धा': 3, + 'द्धां': 3, + 'द्धि': 3, + 'द्धिं': 3, + 'द्धी': 3, + 'द्धीं': 3, + 'द्धैः': 3, + 'द्भा': 3, + 'द्या': 3, + 'द्रो': 3, + 'द्वा': 3, + 'द्वि': 3, + 'द्‌': 2, + 'धाः': 3, + 'ध्या': 3, + 'नाः': 3, + 'ना‌': 3, + 'निः': 3, + 'न्का': 3, + 'न्चि': 3, + 'न्ञ्या': 4, + 'न्तः': 3, + 'न्ता': 3, + 'न्ति': 3, + 'न्तो': 3, + 'न्तों': 3, + 'न्त्र': 3, + 'न्त्रा': 4, + 'न्त्राः': 5, + 'न्त्रि': 4, + 'न्त्री': 4, + 'न्त्र्य': 4, + 'न्त्र्यं': 4, + 'न्त्र्या': 5, + 'न्त्र्ये': 4, + 'न्दा': 3, + 'न्दी': 3, + 'न्दो': 3, + 'न्धा': 3, + 'न्धि': 3, + 'न्धी': 3, + 'न्धों': 3, + 'न्ना': 3, + 'न्नाः': 4, + 'न्नि': 3, + 'न्मा': 3, + 'न्या': 3, + 'न्यो': 3, + 'न्हा': 3, + 'न्ह्यां': 4, + 'प्ति': 3, + 'प्तौ': 3, + 'प्या': 3, + 'प्रा': 3, + 'फ्ता': 3, + 'फ्ना': 3, + 'फ्नो': 3, + 'फ्रां': 3, + 'ब्धि': 3, + 'भिः': 3, + 'भ्यः': 3, + 'भ्या': 3, + 'भ्यां': 3, + 'भ्यो': 3, + 'म्ति': 3, + 'म्नि': 3, + 'म्पा': 3, + 'म्प्र': 3, + 'म्भि': 3, + 'म्मा': 3, + 'म्मि': 3, + 'म्या': 3, + 'म्ही': 3, + 'म्हो': 3, + 'याः': 3, + 'य्यो': 3, + 'राः': 3, + 'र्कि': 3, + 'र्गी': 3, + 'र्चि': 3, + 'र्जा': 3, + 'र्जि': 3, + 'र्जी': 3, + 'र्णां': 3, + 'र्णी': 3, + 'र्ता': 3, + 'र्ति': 3, + 'र्तिः': 4, + 'र्ती': 3, + 'र्त्त': 3, + 'र्त्ति': 4, + 'र्थि': 3, + 'र्थी': 3, + 'र्दा': 3, + 'र्दि': 3, + 'र्दो': 3, + 'र्द्ध': 3, + 'र्धा': 3, + 'र्धि': 3, + 'र्नि': 3, + 'र्बा': 3, + 'र्भा': 3, + 'र्मा': 3, + 'र्मि': 3, + 'र्या': 3, + 'र्यां': 3, + 'र्यों': 3, + 'र्रा': 3, + 'र्वा': 3, + 'र्वां': 3, + 'र्वो': 3, + 'र्सा': 3, + 'र्हाः': 4, + 'र्हि': 3, + 'र्हो': 3, + 'र्‍या': 4, + 'लाः': 3, + 'ल्का': 3, + 'ल्पि': 3, + 'ल्या': 3, + 'ल्यां': 3, + 'ल्याः': 4, + 'ल्ला': 3, + 'ल्लि': 3, + 'वाः': 3, + 'व्या': 3, + 'व्यों': 3, + 'शाः': 3, + 'श्चि': 3, + 'श्या': 3, + 'श्यि': 3, + 'श्यों': 3, + 'श्रा': 3, + 'श्रां': 3, + 'श्वा': 3, + 'श्वि': 3, + 'षाः': 3, + 'ष्का': 3, + 'ष्टः': 3, + 'ष्टा': 3, + 'ष्टां': 3, + 'ष्टाः': 4, + 'ष्टि': 3, + 'ष्टी': 3, + 'ष्टीं': 3, + 'ष्ट्र': 3, + 'ष्ट्रा': 4, + 'ष्ट्रां': 4, + 'ष्ट्रि': 4, + 'ष्ट्री': 4, + 'ष्ट्रे': 3, + 'ष्ट्रो': 4, + 'ष्ट्रों': 4, + 'ष्ठा': 3, + 'ष्ठों': 3, + 'ष्प्र': 3, + 'ष्यः': 3, + 'ष्यों': 3, + 'स्का': 3, + 'स्काः': 4, + 'स्ट्या': 4, + 'स्ता': 3, + 'स्ति': 3, + 'स्ती': 3, + 'स्तो': 3, + 'स्त्र': 3, + 'स्त्रा': 4, + 'स्त्रि': 4, + 'स्त्री': 4, + 'स्था': 3, + 'स्थां': 3, + 'स्थि': 3, + 'स्थी': 3, + 'स्थ्य': 3, + 'स्धी': 3, + 'स्मि': 3, + 'स्मिं': 3, + 'स्या': 3, + 'स्यां': 3, + 'स्याः': 4, + 'स्युः': 3, + 'स्यों': 3, + 'स्रो': 3, + 'स्वा': 3, + 'स्वी': 3, + 'स्सा': 3, + 'ह्या': 3, + 'ह्रा': 3, + 'फ़्ता': 3, + 'আ‌': 2, + 'ই‌': 2, + 'এ‌': 2, + 'কা‌': 3, + 'কিং': 3, + 'কে‌': 3, + 'ক্তি': 3, + 'ক্রী': 3, + 'ক্ষা': 3, + 'ক্ষি': 3, + 'ক্ষে': 3, + 'ক্ষ্য': 3, + 'ক্ষ্যে': 4, + 'খ্যা': 3, + 'গ্রা': 3, + 'গ্রে': 3, + 'ঘো': 3, + 'ঙ্খা': 3, + 'ঙ্গী': 3, + 'ঙ্গে': 3, + 'চ্ছা': 3, + 'চ্ছা‌': 4, + 'চ্ছে': 3, + 'জে‌': 3, + 'জ্ঞা': 3, + 'ঞ্চি': 3, + 'ঞ্ছি': 3, + 'ট্রে': 3, + 'ণ্ডে': 3, + 'তা‌': 3, + 'তি‌': 3, + 'তে‌': 3, + 'ত্তা': 3, + 'ত্তি': 3, + 'ত্বে': 3, + 'ত্যা': 3, + 'ত্যি': 3, + 'ত্যে': 3, + 'ত্রা': 3, + 'ত্রে': 3, + 'ত্‍': 2, + 'ত্‍প': 3, + 'ত্‍পী': 4, + 'ত্‍সা': 4, + 'দে‌': 3, + 'দ্দি': 3, + 'দ্দে': 3, + 'দ্ধা': 3, + 'দ্ধি': 3, + 'দ্ধে': 3, + 'দ্বা': 3, + 'দ্রো': 3, + 'ধ্যে': 3, + 'না‌': 3, + 'ন্তা': 3, + 'ন্তি': 3, + 'ন্তে': 3, + 'ন্ত্রি': 4, + 'ন্ত্রে': 4, + 'ন্থী': 3, + 'ন্ধা': 3, + 'ন্মা': 3, + 'ন্যা': 3, + 'ন্যে': 3, + 'ন‌': 2, + 'পা‌': 3, + 'প্তা': 3, + 'প্রা': 3, + 'বা‌': 3, + 'ব্ধি': 3, + 'ব্যা': 3, + 'ভ্রা': 3, + 'মা‌': 3, + 'ম্পা': 3, + 'ম্মা': 3, + 'রাং': 3, + 'র্জা': 3, + 'র্থে': 3, + 'র্দো': 3, + 'র্ধা': 3, + 'র্নী': 3, + 'র্বা': 3, + 'র্বি': 3, + 'র্বো': 3, + 'র্ব্য': 3, + 'র্মে': 3, + 'র্যা': 3, + 'র‌': 2, + 'লে‌': 3, + 'ল্যা': 3, + 'ল্যে': 3, + 'ল্লে': 3, + 'শ্চি': 3, + 'শ্বা': 3, + 'শ্বে': 3, + 'শ্যে': 3, + 'শ্রা': 3, + 'ষ্টা': 3, + 'ষ্টি': 3, + 'ষ্ট্র': 3, + 'ষ্ট্রী': 4, + 'ষ্ট্রে': 4, + 'ষ্ঠা': 3, + 'ষ্ঠি': 3, + 'ষ্ঠী': 3, + 'সাং': 3, + 'সে‌': 3, + 'স্তি': 3, + 'স্তি‌': 4, + 'স্ত্র': 3, + 'স্থা': 3, + 'স্থ্য': 3, + 'স্বা': 3, + 'স্বী': 3, + 'স্যা': 3, + 'স্যে': 3, + 'হ‌': 2, + 'ક્કા': 3, + 'ક્કો': 3, + 'ક્તિ': 3, + 'ક્ષા': 3, + 'ચ્ચા': 3, + 'ચ્છા': 3, + 'જ્ઞા': 3, + 'જ્યો': 3, + 'ત્તા': 3, + 'ત્તિ': 3, + 'ત્ત્વ': 3, + 'ત્ત્વા': 4, + 'ત્યા': 3, + 'ત્યાં': 3, + 'ત્યિ': 3, + 'ત્યો': 3, + 'ત્રી': 3, + 'ત્ર્ય': 3, + 'દ્ધા': 3, + 'દ્ધાં': 3, + 'દ્ધિ': 3, + 'દ્વા': 3, + 'ધ્યા': 3, + 'ન્તો': 3, + 'ન્મા': 3, + 'ન્યા': 3, + 'પ્રા': 3, + 'મ્યાં': 3, + 'ર્તા': 3, + 'ર્થિ': 3, + 'ર્દો': 3, + 'ર્મિ': 3, + 'ર્યા': 3, + 'ર્યો': 3, + 'વ્યા': 3, + 'વ્યો': 3, + 'ષ્ટિ': 3, + 'ષ્ટ્ર': 3, + 'ષ્ટ્રી': 4, + 'ષ્ટ્રો': 4, + 'ષ્ઠા': 3, + 'સ્તિ': 3, + 'સ્તી': 3, + 'સ્ત્રી': 4, + 'સ્થા': 3, + 'સ્થિ': 3, + 'સ્રી': 3, + 'સ્વા': 3, + 'સ્વી': 3, + 'સ્સા': 3, + 'కుం': 3, + 'క్కు': 3, + 'క్తు': 3, + 'క్రాం': 3, + 'క్రూ': 3, + 'క్షిం': 3, + 'క్స్వా': 3, + 'చ్చు': 3, + 'టుం': 3, + 'ట్లు': 3, + 'డ్రు': 3, + 'త్తు': 3, + 'త్నిం': 3, + 'త్యం': 3, + 'త్రు': 3, + 'త్ర్య': 3, + 'దుం': 3, + 'ద్దు': 3, + 'ద్ధిం': 3, + 'ద్ర్య': 3, + 'నుం': 3, + 'న్ను': 3, + 'భ్యు': 3, + 'యుం': 3, + 'ర్చు': 3, + 'ర్ణాం': 3, + 'ర్ణు': 3, + 'ర్తిం': 3, + 'ర్తృ': 3, + 'ర్థిం': 3, + 'ర్బం': 3, + 'ర్హాం': 3, + 'ర్హు': 3, + 'శ్రాం': 3, + 'ష్టు': 3, + 'ష్ట్ర': 3, + 'ష్ట్రీ': 3, + 'ష్ఠు': 3, + 'స్కృ': 3, + 'స్త్ర': 3, + 'స్త్రీ': 3, + 'స్థ్య': 3, + 'ಕಾಂ': 3, + 'ಕುಂ': 3, + 'ಕೊಂ': 3, + 'ಕ್‌': 2, + 'ಖಾಂ': 3, + 'ಗಾಂ': 3, + 'ಗೊಂ': 3, + 'ಟುಂ': 3, + 'ನಾಂ': 3, + 'ಯುಂ': 3, + 'ರಾಂ': 3, + 'ವುಂ': 3, + 'ಶಾಂ': 3, + 'ಸಾಂ': 3, + 'ಹೊಂ': 3, + 'ക്കാ': 3, + 'ക്കി': 3, + 'ക്കും': 3, + 'ക്കെ': 3, + 'ക്കേ': 3, + 'ക്കൊ': 3, + 'ക്കോ': 3, + 'ക്ക്‌': 3, + 'ക്തി': 3, + 'ക്യം': 3, + 'ക്ഷാ': 3, + 'ക്ഷി': 3, + 'ക്ഷേ': 3, + 'ഖ്യാ': 3, + 'ഗ്ഗം': 3, + 'ഗ്ദാ': 3, + 'ഗ്യം': 3, + 'ങ്കി': 3, + 'ങ്കെ': 3, + 'ങ്കേ': 3, + 'ങ്ങി': 3, + 'ച്ചി': 3, + 'ച്ചും': 3, + 'ച്ചെ': 3, + 'ച്ചേ': 3, + 'ജ്യാ': 3, + 'ഞ്ഞി': 3, + 'ഞ്ഞെ': 3, + 'ട്ടാ': 3, + 'ട്ടി': 3, + 'ട്ടോ': 3, + 'ട്‌': 2, + 'ണ്ടാ': 3, + 'ണ്ടി': 3, + 'ണ്ടും': 3, + 'ണ്ടെ': 3, + 'ണ്ട്‌': 3, + 'ണ്‌': 2, + 'ത്താ': 3, + 'ത്തി': 3, + 'ത്തും': 3, + 'ത്തെ': 3, + 'ത്തേ': 3, + 'ത്തോ': 3, + 'ത്ത്‌': 3, + 'ത്നം': 3, + 'ത്നി': 3, + 'ത്യാ': 3, + 'ത്യേ': 3, + 'ത്വം': 3, + 'ത്‌': 2, + 'ദ്ധി': 3, + 'ദ്യാ': 3, + 'ന്തം': 3, + 'ന്തെ': 3, + 'ന്ത്ര': 3, + 'ന്ത്ര്യ': 4, + 'ന്ത്ര്യം': 5, + 'ന്ധി': 3, + 'ന്നാ': 3, + 'ന്നി': 3, + 'ന്നീ': 3, + 'ന്നും': 3, + 'ന്നെ': 3, + 'ന്നേ': 3, + 'ന്നോ': 3, + 'ന്മാ': 3, + 'ന്യം': 3, + 'ന്യാ': 3, + 'ന്യേ': 3, + 'ന്യോ': 3, + 'ന്റെ': 3, + 'ന്‌': 2, + 'ന്‍': 2, + 'ന്‍കൂ': 3, + 'ന്‍പി': 4, + 'പ്പി': 3, + 'പ്പെ': 3, + 'പ്പോ': 3, + 'പ്പ്‌': 3, + 'പ്രാ': 3, + 'ബ്ലി': 3, + 'ഭ്യാ': 3, + 'ഭ്രാ': 3, + 'മ്പാ': 3, + 'മ്പ്ര': 3, + 'മ്മി': 3, + 'യ്ക്കു': 3, + 'യ്തി': 3, + 'യ്യാ': 3, + 'യ്യി': 3, + 'ര്യം': 3, + 'ര്‍ക്കു': 4, + 'ര്‍ക്കും': 5, + 'ര്‍ക്ക്‌': 5, + 'ര്‍ഗ്ഗം': 5, + 'ര്‍ച്ച': 4, + 'ര്‍ണ്ണ': 4, + 'ര്‍ത്ത': 4, + 'ര്‍ത്തി': 5, + 'ര്‍ത്തു': 4, + 'ര്‍ത്തേ': 5, + 'ര്‍ദേ': 4, + 'ര്‍ദ്ദ': 4, + 'ര്‍പ്പെ': 5, + 'ര്‍ബ': 3, + 'ര്‍ഭ': 3, + 'ര്‍മ്മി': 5, + 'ര്‍രാ': 4, + 'ര്‍വ്വ': 4, + 'ര്‍ഹ': 3, + 'ര്‍ഹി': 4, + 'റ്റം': 3, + 'റ്റേ': 3, + 'ല്യാ': 3, + 'ല്ലാ': 3, + 'ല്ലാം': 4, + 'ല്ലെ': 3, + 'ല്‍': 2, + 'ല്‍കി': 4, + 'ല്‍കു': 3, + 'ല്‍കേ': 4, + 'ല്‍ത': 3, + 'ല്‍നി': 4, + 'ല്‍പ്പ': 4, + 'ള്ളാ': 3, + 'ള്ളി': 3, + 'ള്‍': 2, + 'ള്‍കൊ': 4, + 'ള്‍ക്ക': 4, + 'ള്‍ക്കി': 5, + 'ള്‍ക്കു': 4, + 'ള്‍ക്കും': 5, + 'ള്‍ക്കെ': 5, + 'ള്‍ക്ക്‌': 5, + 'വ്യം': 3, + 'വ്യാ': 3, + 'ശ്വാ': 3, + 'ഷ്ട്യാ': 4, + 'ഷ്ട്ര': 3, + 'ഷ്ട്രീ': 4, + 'ഷ്യാ': 3, + 'സാം': 3, + 'സ്കാ': 3, + 'സ്ത്രം': 4, + 'സ്ത്രീ': 4, + 'സ്ഥാ': 3, + 'സ്ഥി': 3, + 'സ്റ്റ്‌': 4, + 'സ്വാ': 3, + 'സ്വീ': 3, + 'സ്സാ': 3, + 'സ്സി': 3, + 'സ്സും': 3, + 'സ്സോ': 3, + 'ഹിം': 3, + 'ൻ്റെ': 3, + 'ක්‍': 2, + 'ඛ්‍': 2, + 'ජ්‍': 2, + 'ත්‍': 2, + 'ද්‍': 2, + 'ධ්‍': 2, + 'න්‍': 2, + 'ප්‍': 2, + 'ව්‍': 2, + 'ශ්‍': 2, + 'ෂ්‍': 2, + 'ကျေ': 3, + 'ကြေ': 3, + 'ကြွေ': 3, + 'ချေ': 3, + 'ခြေ': 3, + 'ဇြေ': 3, + 'ဒ္ဂေ': 3, + 'ပျေ': 3, + 'ပြေ': 3, + 'ဖျေံ': 3, + 'ဗ္တေ': 3, + 'ဗ္ၜေ': 3, + 'ဗြေ': 3, + 'မြေ': 3, + 'လျေ': 3, + 'လျှေ': 3, + 'သ္ဂေ': 3, + 'ក្ដៅ': 3, + 'ក្រោ': 3, + 'ក្សា': 3, + 'ខ្ជា': 3, + 'ខ្លា': 3, + 'គ្នា': 3, + 'គ្មា': 3, + 'គ្រា': 3, + 'គ្រឹះ': 3, + 'ង្កើ': 3, + 'ង្រៀ': 3, + 'ង្ហា': 3, + 'ច្ចេ': 3, + 'ច្បា': 3, + 'ឆ្នាំ': 3, + 'ឆ្នោ': 3, + 'ឆ្លើ': 3, + 'ជ្ជា': 3, + 'ជ្ញា': 3, + 'ជ្រើ': 3, + 'ជ្រៀ': 3, + 'ជ្រែ': 3, + 'ឈ្មោះ': 4, + 'ញ្ជា': 3, + 'ញ្ញា': 3, + 'ញ្ញៈ': 3, + 'ដ្ឋា': 3, + 'ណោះ': 3, + 'ណ្ដា': 3, + 'ណ្ដុះ': 3, + 'ណ្ណោះ': 4, + 'ត្រា': 3, + 'ថ្ងៃ': 3, + 'ថ្នា': 3, + 'ថ្លៃ': 3, + 'ទោះ': 3, + 'ទ្យា': 3, + 'ធ្នា': 3, + 'ធ្យា': 3, + 'ធ្យោ': 3, + 'ធ្វើ': 3, + 'នេះ': 3, + 'នោះ': 3, + 'ន្ថែ': 3, + 'ន្ថោ': 3, + 'ន្ទា': 3, + 'ន្ទៈ': 3, + 'ន្យា': 3, + 'ន្លែ': 3, + 'បោះ': 3, + 'ប្ដេ': 3, + 'ប្រា': 3, + 'ប្រើ': 3, + 'ប្រែ': 3, + 'ផ្ដា': 3, + 'ផ្ទា': 3, + 'ផ្ទេ': 3, + 'ផ្នែ': 3, + 'ផ្លា': 3, + 'ផ្សា': 3, + 'ផ្សេ': 3, + 'ផ្សៃ': 3, + 'ពោះ': 3, + 'ព្យា': 3, + 'ព្រៀ': 3, + 'ព្រៃ': 3, + 'ម្ងា': 3, + 'ម្ចា': 3, + 'ម្ដា': 3, + 'ម្ដែ': 3, + 'ម្នា': 3, + 'ម្នេ': 3, + 'ម្ភា': 3, + 'ម្រា': 3, + 'ម្រើ': 3, + 'ម្រេ': 3, + 'ម្លៀ': 3, + 'ម្លៃ': 3, + 'ល្បៈ': 3, + 'ល្មើ': 3, + 'ស្គា': 3, + 'ស្ដ្រី': 3, + 'ស្ត្រ': 3, + 'ស្ថា': 3, + 'ស្នា': 3, + 'ស្មា': 3, + 'ស្មើ': 3, + 'ស្រា': 3, + 'ស្លា': 3, + 'ស្វែ': 3, + 'ᨠᩮ᩠ᨯᩨ': 3, + 'ᨠᩯ᩠ᨯ': 3, + 'ᨠᩯ᩠ᨶ᩵': 3, + 'ᨡᩮ᩠ᨲ': 3, + 'ᨡᩯ᩠ᨠ': 3, + 'ᨡᩯ᩠ᨦ': 3, + 'ᨣᩕ᩠ᩋ': 3, + 'ᨣᩕᩮ᩠ᨦᩨ᩵': 4, + 'ᨣᩯ᩠ᨶᩢ': 3, + 'ᨣᩯ᩠ᩅ': 3, + 'ᨧᩮ᩠ᨷ': 3, + 'ᨧᩱ᩠ᨿ': 3, + 'ᨩᩮ᩠ᩋᩨ': 3, + 'ᨩᩮ᩠ᩋᩨ᩵': 3, + 'ᨩᩮ᩠ᩋᩨ᩶': 3, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 3, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 3, + 'ᨯᩯ᩠ᨦ': 3, + 'ᨯᩯ᩠ᨶ': 3, + 'ᨯᩰ᩠ᨿ': 3, + 'ᨲᩮ᩠ᨠ': 3, + 'ᨲᩮ᩠ᨦ': 3, + 'ᨲᩮ᩠ᨾ': 3, + 'ᨲᩮ᩠ᨾᩨ᩵': 3, + 'ᨲᩯ᩠ᨠ': 3, + 'ᨲᩯ᩠ᨦ᩵': 3, + 'ᨲᩯ᩠ᨾᩢ': 3, + 'ᨲᩱ᩠ᨿ': 3, + 'ᨳᩮ᩠ᨶᩨ᩵': 3, + 'ᨳᩯ᩠ᨦᩢ': 3, + 'ᨳᩯ᩠ᨾ': 3, + 'ᨴᩮ᩠ᩈ': 3, + 'ᨴᩮ᩠ᩈᩱ': 4, + 'ᨴᩯ᩠ᨶ': 3, + 'ᨴᩰ᩠ᩈ': 3, + 'ᨶᩯ᩠ᨶ': 3, + 'ᨷᩮ᩠ᨦᩨ᩶': 3, + 'ᨸᩮ᩠ᨦᩨ': 3, + 'ᨸᩮ᩠ᨶ': 3, + 'ᨹᩮᩨ᩠ᨿ': 3, + 'ᨻᩕ᩠ᩋᩢ': 3, + 'ᨻᩮ᩠ᩋᩨ᩵': 3, + 'ᨽᩱ᩠ᨿ': 3, + 'ᨾᩮ᩠ᨠᩨ': 3, + 'ᨾᩮ᩠ᨦᩨ': 3, + 'ᨾᩮ᩠ᩋᩨ᩵': 3, + 'ᨿᩮ᩠ᨶ': 3, + 'ᨿᩮ᩠ᨾᩨ': 3, + 'ᩁᩮ᩠ᨦᩨ᩵': 3, + 'ᩁᩮ᩠ᨧ': 3, + 'ᩁᩮ᩠ᨶᩨ': 3, + 'ᩁᩮᩨ᩠ᨬ': 3, + 'ᩁᩯ᩠ᨦ': 3, + 'ᩃᩮ᩠ᨠᩨ': 3, + 'ᩃᩮ᩠ᨦᩨ': 3, + 'ᩃᩰ᩠ᨠ': 3, + 'ᩅᩮ᩠ᨶ': 3, + 'ᩅᩮ᩠ᨶᩢ': 3, + 'ᩈᩮ᩠ᩈ': 3, + 'ᩈᩯ᩠ᩅ': 3, + 'ᩈᩱ᩠ᨿ': 3, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 3, + 'ᩉᩮ᩠ᨦᩢᩢ': 3, + 'ᩉᩮ᩠ᨯ': 3, + 'ᩉᩮ᩠ᨲᩩ': 3, + 'ᩉᩮ᩠ᨶᩨ': 3, + 'ᩉᩮ᩠ᨾᩨ': 3, + 'ᩉᩮ᩠ᨾᩨᩨ': 3, + 'ᩉᩯ᩠ᨦ᩵': 3, + 'ᩉᩯ᩠ᨶᩢ': 3, + 'ᩉᩯ᩠ᨾ': 3, + 'ᩉᩱ᩠ᨾ᩵': 3, + 'ᩉᩱ᩠ᨿ᩵': 3, + 'ᩣ᩠ᨲᩱ': 3, + '⛓️‍💥': 4, + '⛹️‍♀️': 3, + '⛹️‍♂️': 3, + '⛹🏻‍♀️': 5, + '⛹🏻‍♂️': 5, + '⛹🏼‍♀️': 5, + '⛹🏼‍♂️': 5, + '⛹🏽‍♀️': 5, + '⛹🏽‍♂️': 5, + '⛹🏾‍♀️': 5, + '⛹🏾‍♂️': 5, + '⛹🏿‍♀️': 5, + '⛹🏿‍♂️': 5, + '❤️‍🔥': 4, + '❤️‍🩹': 4, + 'ꦏꦺꦴ': 3, + 'ꦏ꧀': 2, + 'ꦏ꧀ꦏ': 3, + 'ꦏ꧀ꦏꦁ': 3, + 'ꦏ꧀ꦏꦺ': 4, + 'ꦏ꧀ꦏꦼ': 3, + 'ꦏ꧀ꦔ': 3, + 'ꦏ꧀ꦔꦸ': 3, + 'ꦏ꧀ꦔꦿ': 4, + 'ꦏ꧀ꦕ': 3, + 'ꦏ꧀ꦠ': 3, + 'ꦏ꧀ꦠꦶ': 3, + 'ꦏ꧀ꦠꦸ': 3, + 'ꦏ꧀ꦠꦺ': 4, + 'ꦏ꧀ꦢ': 3, + 'ꦏ꧀ꦢꦂ': 3, + 'ꦏ꧀ꦢꦶ': 3, + 'ꦏ꧀ꦤ': 3, + 'ꦏ꧀ꦤꦶꦁ': 3, + 'ꦏ꧀ꦥ': 3, + 'ꦏ꧀ꦥꦶ': 3, + 'ꦏ꧀ꦥꦿꦶ': 4, + 'ꦏ꧀ꦧ': 3, + 'ꦏ꧀ꦧꦶ': 3, + 'ꦏ꧀ꦧꦺ': 4, + 'ꦏ꧀ꦩ': 3, + 'ꦏ꧀ꦩꦸ': 3, + 'ꦏ꧀ꦪ': 3, + 'ꦏ꧀ꦭ': 3, + 'ꦏ꧀ꦮ': 3, + 'ꦏ꧀ꦱ': 3, + 'ꦏ꧀ꦱꦂ': 3, + 'ꦏ꧀ꦱꦶ': 3, + 'ꦏ꧀ꦱꦸ': 3, + 'ꦏ꧀ꦱꦺ': 4, + 'ꦏ꧀ꦲ': 3, + 'ꦏ꧀ꦲꦁ': 3, + 'ꦏ꧀ꦲꦶꦁ': 3, + 'ꦏ꧀ꦲꦸ': 3, + 'ꦏ꧀ꦲꦺ': 4, + 'ꦏ꧀ꦲꦺꦴ': 5, + 'ꦒꦺꦴ': 3, + 'ꦒꦿꦺ': 3, + 'ꦒ꧀ꦒ': 3, + 'ꦔꦺꦴ': 3, + 'ꦔ꧀ꦒꦼ': 3, + 'ꦔ꧀ꦒꦿꦼꦁ': 4, + 'ꦔ꧀ꦭ': 3, + 'ꦔ꧀ꦭꦁ': 3, + 'ꦔ꧀ꦭꦸ': 3, + 'ꦔ꧀ꦭꦼ': 3, + 'ꦕꦺꦴ': 3, + 'ꦗꦿꦺꦴ': 4, + 'ꦚ꧀ꦕ': 3, + 'ꦚ꧀ꦕꦶ': 3, + 'ꦚ꧀ꦗ': 3, + 'ꦚ꧀ꦗꦶ': 3, + 'ꦚ꧀ꦗꦸꦁ': 3, + 'ꦚ꧀ꦗꦸꦂ': 3, + 'ꦝꦺꦴ': 3, + 'ꦝꦺꦴꦂ': 3, + 'ꦠꦺꦃ': 3, + 'ꦠꦺꦴ': 3, + 'ꦠ꧀': 2, + 'ꦠ꧀ꦏꦁ': 3, + 'ꦠ꧀ꦏꦸ': 3, + 'ꦠ꧀ꦒ': 3, + 'ꦠ꧀ꦔꦸ': 3, + 'ꦠ꧀ꦚ': 3, + 'ꦠ꧀ꦠ': 3, + 'ꦠ꧀ꦠꦶ': 3, + 'ꦠ꧀ꦠꦶꦁ': 3, + 'ꦠ꧀ꦠꦸ': 3, + 'ꦠ꧀ꦠꦺ': 4, + 'ꦠ꧀ꦤ': 3, + 'ꦠ꧀ꦤꦶ': 3, + 'ꦠ꧀ꦩ': 3, + 'ꦠ꧀ꦩꦼ': 3, + 'ꦠ꧀ꦭ': 3, + 'ꦠ꧀ꦭꦺ': 4, + 'ꦠ꧀ꦱ': 3, + 'ꦠ꧀ꦱꦶꦁ': 3, + 'ꦠ꧀ꦱꦶꦃ': 4, + 'ꦠ꧀ꦱꦾ': 4, + 'ꦠ꧀ꦱ꧀ꦮ': 5, + 'ꦠ꧀ꦲ': 3, + 'ꦠ꧀ꦲꦶꦁ': 3, + 'ꦠ꧀ꦲꦺꦴ': 5, + 'ꦢꦺꦴ': 3, + 'ꦢ꧀': 2, + 'ꦢ꧀ꦏ': 3, + 'ꦢ꧀ꦠ': 3, + 'ꦢ꧀ꦠꦶꦁ': 3, + 'ꦢ꧀ꦢ': 3, + 'ꦢ꧀ꦥ': 3, + 'ꦢ꧀ꦩꦺꦴ': 5, + 'ꦢ꧀ꦲ': 3, + 'ꦤꦺꦃ': 3, + 'ꦤꦺꦴ': 3, + 'ꦤ꧀': 2, + 'ꦤ꧀ꦏ': 3, + 'ꦤ꧀ꦏꦁ': 3, + 'ꦤ꧀ꦏꦸ': 3, + 'ꦤ꧀ꦏꦼ': 3, + 'ꦤ꧀ꦒ': 3, + 'ꦤ꧀ꦔ': 3, + 'ꦤ꧀ꦔꦁ': 3, + 'ꦤ꧀ꦔꦶ': 3, + 'ꦤ꧀ꦔꦸ': 3, + 'ꦤ꧀ꦔꦸꦂ': 3, + 'ꦤ꧀ꦔꦺ': 4, + 'ꦤ꧀ꦔꦼ': 3, + 'ꦤ꧀ꦔꦿꦸ': 4, + 'ꦤ꧀ꦗ': 3, + 'ꦤ꧀ꦗꦸ': 3, + 'ꦤ꧀ꦗꦼ': 3, + 'ꦤ꧀ꦚꦶ': 3, + 'ꦤ꧀ꦛꦃ': 4, + 'ꦤ꧀ꦛꦶ': 3, + 'ꦤ꧀ꦝ': 3, + 'ꦤ꧀ꦝꦁ': 3, + 'ꦤ꧀ꦝꦶ': 3, + 'ꦤ꧀ꦝꦸ': 3, + 'ꦤ꧀ꦝꦸꦁ': 3, + 'ꦤ꧀ꦝꦺꦁ': 4, + 'ꦤ꧀ꦝꦺꦴꦁ': 5, + 'ꦤ꧀ꦝꦼ': 3, + 'ꦤ꧀ꦠ': 3, + 'ꦤ꧀ꦠꦂ': 3, + 'ꦤ꧀ꦠꦃ': 4, + 'ꦤ꧀ꦠꦶ': 3, + 'ꦤ꧀ꦠꦸ': 3, + 'ꦤ꧀ꦠꦸꦁ': 3, + 'ꦤ꧀ꦠꦺ': 4, + 'ꦤ꧀ꦠꦼ': 3, + 'ꦤ꧀ꦠꦼꦂ': 3, + 'ꦤ꧀ꦠꦽ': 3, + 'ꦤ꧀ꦢ': 3, + 'ꦤ꧀ꦢꦁ': 3, + 'ꦤ꧀ꦢꦂ': 3, + 'ꦤ꧀ꦢꦶ': 3, + 'ꦤ꧀ꦢꦸ': 3, + 'ꦤ꧀ꦢꦺ': 4, + 'ꦤ꧀ꦢꦼ': 3, + 'ꦤ꧀ꦤ': 3, + 'ꦤ꧀ꦤꦶ': 3, + 'ꦤ꧀ꦤꦶꦁ': 3, + 'ꦤ꧀ꦤꦺ': 4, + 'ꦤ꧀ꦤꦼ': 3, + 'ꦤ꧀ꦥ': 3, + 'ꦤ꧀ꦥꦁ': 3, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 5, + 'ꦤ꧀ꦥꦶ': 3, + 'ꦤ꧀ꦥꦸ': 3, + 'ꦤ꧀ꦥꦼ': 3, + 'ꦤ꧀ꦥꦿ': 4, + 'ꦤ꧀ꦥꦿꦶ': 4, + 'ꦤ꧀ꦧ': 3, + 'ꦤ꧀ꦧꦁ': 3, + 'ꦤ꧀ꦧꦶ': 3, + 'ꦤ꧀ꦧꦸ': 3, + 'ꦤ꧀ꦧꦺ': 4, + 'ꦤ꧀ꦧꦺꦴ': 5, + 'ꦤ꧀ꦧꦼ': 3, + 'ꦤ꧀ꦩ': 3, + 'ꦤ꧀ꦩꦂ': 3, + 'ꦤ꧀ꦩꦶ': 3, + 'ꦤ꧀ꦩꦸꦂ': 3, + 'ꦤ꧀ꦩꦼ': 3, + 'ꦤ꧀ꦭ': 3, + 'ꦤ꧀ꦭꦶ': 3, + 'ꦤ꧀ꦭꦸ': 3, + 'ꦤ꧀ꦮ': 3, + 'ꦤ꧀ꦮꦂ': 3, + 'ꦤ꧀ꦮꦶ': 3, + 'ꦤ꧀ꦮꦸ': 3, + 'ꦤ꧀ꦮꦼ': 3, + 'ꦤ꧀ꦱ': 3, + 'ꦤ꧀ꦱꦂ': 3, + 'ꦤ꧀ꦱꦃ': 4, + 'ꦤ꧀ꦱꦶ': 3, + 'ꦤ꧀ꦱꦶꦁ': 3, + 'ꦤ꧀ꦱꦸ': 3, + 'ꦤ꧀ꦱꦺꦴ': 5, + 'ꦤ꧀ꦱꦼ': 3, + 'ꦤ꧀ꦲ': 3, + 'ꦤ꧀ꦲꦁ': 3, + 'ꦤ꧀ꦲꦶ': 3, + 'ꦤ꧀ꦲꦶꦁ': 3, + 'ꦤ꧀ꦲꦸ': 3, + 'ꦤ꧀ꦲꦺꦴ': 5, + 'ꦥ꦳꧀': 2, + 'ꦥꦺꦴ': 3, + 'ꦥꦿꦃ': 3, + 'ꦥꦿꦺꦴ': 4, + 'ꦥ꧀': 2, + 'ꦥ꧀ꦏ': 3, + 'ꦥ꧀ꦏꦁ': 3, + 'ꦥ꧀ꦠ': 3, + 'ꦥ꧀ꦠꦶ': 3, + 'ꦥ꧀ꦢꦸ': 3, + 'ꦥ꧀ꦤ': 3, + 'ꦥ꧀ꦤꦶ': 3, + 'ꦥ꧀ꦥ': 3, + 'ꦥ꧀ꦥꦶ': 3, + 'ꦥ꧀ꦥꦺ': 4, + 'ꦥ꧀ꦧꦺ': 4, + 'ꦥ꧀ꦩ': 3, + 'ꦥ꧀ꦩꦂ': 3, + 'ꦥ꧀ꦫꦺ': 4, + 'ꦥ꧀ꦭ': 3, + 'ꦥ꧀ꦭꦸ': 3, + 'ꦥ꧀ꦱ': 3, + 'ꦥ꧀ꦱꦶꦂ': 3, + 'ꦥ꧀ꦱꦼ': 3, + 'ꦥ꧀ꦲ': 3, + 'ꦧꦺꦃ': 3, + 'ꦧꦺꦴ': 3, + 'ꦧ꧀': 2, + 'ꦧ꧀ꦏ': 3, + 'ꦧ꧀ꦠꦸ': 3, + 'ꦧ꧀ꦥ': 3, + 'ꦧ꧀ꦧ': 3, + 'ꦧ꧀ꦧꦺ': 4, + 'ꦧ꧀ꦲ': 3, + 'ꦧ꧀ꦲꦶ': 3, + 'ꦩꦺꦃ': 3, + 'ꦩꦺꦴ': 3, + 'ꦩꦿꦃ': 3, + 'ꦩꦿꦶꦃ': 3, + 'ꦩ꧀': 2, + 'ꦩ꧀ꦏꦁ': 3, + 'ꦩ꧀ꦔꦼ': 3, + 'ꦩ꧀ꦠꦸ': 3, + 'ꦩ꧀ꦠꦺꦴ': 5, + 'ꦩ꧀ꦤꦶꦁ': 3, + 'ꦩ꧀ꦥ': 3, + 'ꦩ꧀ꦥꦶ': 3, + 'ꦩ꧀ꦥꦸ': 3, + 'ꦩ꧀ꦥꦼ': 3, + 'ꦩ꧀ꦧ': 3, + 'ꦩ꧀ꦧꦁ': 3, + 'ꦩ꧀ꦧꦂ': 3, + 'ꦩ꧀ꦧꦃ': 4, + 'ꦩ꧀ꦧꦶ': 3, + 'ꦩ꧀ꦧꦸ': 3, + 'ꦩ꧀ꦧꦸꦁ': 3, + 'ꦩ꧀ꦧꦺ': 4, + 'ꦩ꧀ꦧꦺꦂ': 4, + 'ꦩ꧀ꦧꦼꦂ': 3, + 'ꦩ꧀ꦧꦾꦸꦂ': 4, + 'ꦩ꧀ꦩ': 3, + 'ꦩ꧀ꦩꦶ': 3, + 'ꦩ꧀ꦫ': 3, + 'ꦩ꧀ꦫꦃ': 4, + 'ꦩ꧀ꦭ': 3, + 'ꦩ꧀ꦲꦶ': 3, + 'ꦪꦺꦴ': 3, + 'ꦫꦺꦴ': 3, + 'ꦭꦺꦃ': 3, + 'ꦭꦺꦴ': 3, + 'ꦭꦺꦴꦁ': 3, + 'ꦭ꧀': 2, + 'ꦭ꧀ꦏꦁ': 3, + 'ꦭ꧀ꦚꦼꦁ': 3, + 'ꦭ꧀ꦠꦸ': 3, + 'ꦭ꧀ꦧꦸ': 3, + 'ꦭ꧀ꦩꦸ': 3, + 'ꦭ꧀ꦭ': 3, + 'ꦭ꧀ꦭꦶ': 3, + 'ꦭ꧀ꦭꦶꦁ': 3, + 'ꦭ꧀ꦭꦺ': 4, + 'ꦭ꧀ꦮ': 3, + 'ꦭ꧀ꦱ': 3, + 'ꦭ꧀ꦱꦂ': 3, + 'ꦭ꧀ꦱꦶꦁ': 3, + 'ꦭ꧀ꦱꦸ': 3, + 'ꦭ꧀ꦲ': 3, + 'ꦭ꧀ꦲꦁ': 3, + 'ꦭ꧀ꦲꦶꦁ': 3, + 'ꦭ꧀ꦲꦸ': 3, + 'ꦮꦺꦴ': 3, + 'ꦮꦺꦴꦁ': 3, + 'ꦮꦺꦴꦃ': 4, + 'ꦮꦿꦸꦃ': 3, + 'ꦱꦺꦴ': 3, + 'ꦱꦿꦃ': 3, + 'ꦱ꧀': 2, + 'ꦱ꧀ꦏ': 3, + 'ꦱ꧀ꦏꦁ': 3, + 'ꦱ꧀ꦏꦿꦶ': 4, + 'ꦱ꧀ꦒ': 3, + 'ꦱ꧀ꦔꦸ': 3, + 'ꦱ꧀ꦔꦿ': 4, + 'ꦱ꧀ꦛꦶ': 3, + 'ꦱ꧀ꦠ': 3, + 'ꦱ꧀ꦠꦿ': 4, + 'ꦱ꧀ꦢꦂ': 3, + 'ꦱ꧀ꦢꦶ': 3, + 'ꦱ꧀ꦢꦸ': 3, + 'ꦱ꧀ꦥ': 3, + 'ꦱ꧀ꦧ': 3, + 'ꦱ꧀ꦧꦁ': 3, + 'ꦱ꧀ꦩ': 3, + 'ꦱ꧀ꦩꦶ': 3, + 'ꦱ꧀ꦩꦼ': 3, + 'ꦱ꧀ꦩꦿ': 4, + 'ꦱ꧀ꦭ': 3, + 'ꦱ꧀ꦮ': 3, + 'ꦱ꧀ꦱ': 3, + 'ꦱ꧀ꦱꦂ': 3, + 'ꦱ꧀ꦱꦶ': 3, + 'ꦱ꧀ꦱꦶꦁ': 3, + 'ꦱ꧀ꦱꦸ': 3, + 'ꦱ꧀ꦱꦺ': 4, + 'ꦱ꧀ꦲ': 3, + 'ꦱ꧀ꦲꦁ': 3, + 'ꦱ꧀ꦲꦶ': 3, + 'ꦱ꧀ꦲꦶꦁ': 3, + 'ꦱ꧀ꦲꦸ': 3, + 'ꦲꦺꦴ': 3, + '𑄇𑄳𑄠𑄬': 3, + '𑄈𑄳𑄠𑄬': 3, + '𑄌𑄳𑄠𑄬': 3, + '𑄎𑄳𑄠𑄬': 3, + '𑄑𑄳𑄢𑄬': 3, + '𑄖𑄳𑄠𑄬': 3, + '𑄖𑄳𑄢𑄬': 3, + '𑄘𑄳𑄠𑄬': 3, + '𑄚𑄳𑄠𑄬': 3, + '𑄝𑄳𑄢𑄬': 3, + '𑄟𑄳𑄠𑄬': 3, + '𑄡𑄳𑄠𑄬': 3, + '𑄣𑄳𑄦𑄬': 3, + '𑌕𑌾𑌂': 3, + '𑌕𑌾𑌃': 3, + '𑌕𑍍': 2, + '𑌗𑍍': 2, + '𑌚𑍍': 2, + '𑌜𑍍': 2, + '𑌞𑍍': 2, + '𑌟𑌾𑌂': 3, + '𑌟𑌾𑌃': 3, + '𑌟𑍍': 2, + '𑌠𑍈𑌃': 3, + '𑌣𑌾𑌂': 3, + '𑌣𑍍': 2, + '𑌤𑌾𑌂': 3, + '𑌤𑌾𑌃': 3, + '𑌤𑌿𑌂': 3, + '𑌤𑌿𑌃': 3, + '𑌤𑍁𑌂': 3, + '𑌤𑍇𑌃': 3, + '𑌤𑍍': 2, + '𑌥𑌾𑌂': 3, + '𑌦𑍍': 2, + '𑌧𑌾𑌃': 3, + '𑌧𑌿𑌂': 3, + '𑌧𑍇𑌃': 3, + '𑌧𑍈𑌃': 3, + '𑌧𑍍': 2, + '𑌨𑌾𑌂': 3, + '𑌨𑌾𑌃': 3, + '𑌨𑌿𑌃': 3, + '𑌨𑍈𑌃': 3, + '𑌨𑍍': 2, + '𑌪𑍍': 2, + '𑌬𑍍': 2, + '𑌭𑌿𑌃': 3, + '𑌭𑍍': 2, + '𑌮𑌿𑌂': 3, + '𑌮𑍍': 2, + '𑌯𑌾𑌂': 3, + '𑌯𑌾𑌃': 3, + '𑌯𑍁𑌃': 3, + '𑌯𑍈𑌃': 3, + '𑌯𑍋𑌃': 3, + '𑌯𑍍': 2, + '𑌰𑌾𑌃': 3, + '𑌰𑌿𑌂': 3, + '𑌰𑍍': 2, + '𑌲𑌾𑌃': 3, + '𑌲𑌿𑌂': 3, + '𑌲𑍍': 2, + '𑌵𑌾𑌂': 3, + '𑌵𑌾𑌃': 3, + '𑌵𑍍': 2, + '𑌶𑌾𑌃': 3, + '𑌶𑍍': 2, + '𑌷𑌾𑌂': 3, + '𑌷𑌾𑌃': 3, + '𑌷𑍍': 2, + '𑌸𑌾𑌂': 3, + '𑌸𑍍': 2, + '𑌹𑌾𑌃': 3, + '🍄‍🟫': 5, + '🍋‍🟩': 5, + '🏃‍♀️': 4, + '🏃‍♀️‍➡️': 6, + '🏃‍♂️': 4, + '🏃‍♂️‍➡️': 6, + '🏃‍➡️': 4, + '🏃🏻‍♀️': 6, + '🏃🏻‍♀️‍➡️': 8, + '🏃🏻‍♂️': 6, + '🏃🏻‍♂️‍➡️': 8, + '🏃🏻‍➡️': 6, + '🏃🏼‍♀️': 6, + '🏃🏼‍♀️‍➡️': 8, + '🏃🏼‍♂️': 6, + '🏃🏼‍♂️‍➡️': 8, + '🏃🏼‍➡️': 6, + '🏃🏽‍♀️': 6, + '🏃🏽‍♀️‍➡️': 8, + '🏃🏽‍♂️': 6, + '🏃🏽‍♂️‍➡️': 8, + '🏃🏽‍➡️': 6, + '🏃🏾‍♀️': 6, + '🏃🏾‍♀️‍➡️': 8, + '🏃🏾‍♂️': 6, + '🏃🏾‍♂️‍➡️': 8, + '🏃🏾‍➡️': 6, + '🏃🏿‍♀️': 6, + '🏃🏿‍♀️‍➡️': 8, + '🏃🏿‍♂️': 6, + '🏃🏿‍♂️‍➡️': 8, + '🏃🏿‍➡️': 6, + '🏄‍♀️': 4, + '🏄‍♂️': 4, + '🏄🏻‍♀️': 6, + '🏄🏻‍♂️': 6, + '🏄🏼‍♀️': 6, + '🏄🏼‍♂️': 6, + '🏄🏽‍♀️': 6, + '🏄🏽‍♂️': 6, + '🏄🏾‍♀️': 6, + '🏄🏾‍♂️': 6, + '🏄🏿‍♀️': 6, + '🏄🏿‍♂️': 6, + '🏊‍♀️': 4, + '🏊‍♂️': 4, + '🏊🏻‍♀️': 6, + '🏊🏻‍♂️': 6, + '🏊🏼‍♀️': 6, + '🏊🏼‍♂️': 6, + '🏊🏽‍♀️': 6, + '🏊🏽‍♂️': 6, + '🏊🏾‍♀️': 6, + '🏊🏾‍♂️': 6, + '🏊🏿‍♀️': 6, + '🏊🏿‍♂️': 6, + '🏋️‍♀️': 3, + '🏋️‍♂️': 3, + '🏋🏻‍♀️': 5, + '🏋🏻‍♂️': 5, + '🏋🏼‍♀️': 5, + '🏋🏼‍♂️': 5, + '🏋🏽‍♀️': 5, + '🏋🏽‍♂️': 5, + '🏋🏾‍♀️': 5, + '🏋🏾‍♂️': 5, + '🏋🏿‍♀️': 5, + '🏋🏿‍♂️': 5, + '🏌️‍♀️': 3, + '🏌️‍♂️': 3, + '🏌🏻‍♀️': 5, + '🏌🏻‍♂️': 5, + '🏌🏼‍♀️': 5, + '🏌🏼‍♂️': 5, + '🏌🏽‍♀️': 5, + '🏌🏽‍♂️': 5, + '🏌🏾‍♀️': 5, + '🏌🏾‍♂️': 5, + '🏌🏿‍♀️': 5, + '🏌🏿‍♂️': 5, + '🏳️‍⚧️': 3, + '🏳️‍🌈': 4, + '🏴‍☠️': 4, + '🏴󠁧󠁢󠁥󠁮󠁧󠁿': 8, + '🏴󠁧󠁢󠁳󠁣󠁴󠁿': 8, + '🏴󠁧󠁢󠁷󠁬󠁳󠁿': 8, + '🐈‍⬛': 5, + '🐕‍🦺': 5, + '🐦‍⬛': 5, + '🐦‍🔥': 5, + '🐻‍❄️': 4, + '👁️‍🗨️': 3, + '👨‍⚕️': 4, + '👨‍⚖️': 4, + '👨‍✈️': 4, + '👨‍❤️‍👨': 7, + '👨‍❤️‍💋‍👨': 10, + '👨‍🌾': 5, + '👨‍🍳': 5, + '👨‍🍼': 5, + '👨‍🎓': 5, + '👨‍🎤': 5, + '👨‍🎨': 5, + '👨‍🏫': 5, + '👨‍🏭': 5, + '👨‍👦': 5, + '👨‍👦‍👦': 8, + '👨‍👧': 5, + '👨‍👧‍👦': 8, + '👨‍👧‍👧': 8, + '👨‍👨‍👦': 8, + '👨‍👨‍👦‍👦': 11, + '👨‍👨‍👧': 8, + '👨‍👨‍👧‍👦': 11, + '👨‍👨‍👧‍👧': 11, + '👨‍👩‍👦': 8, + '👨‍👩‍👦‍👦': 11, + '👨‍👩‍👧': 8, + '👨‍👩‍👧‍👦': 11, + '👨‍👩‍👧‍👧': 11, + '👨‍💻': 5, + '👨‍💼': 5, + '👨‍🔧': 5, + '👨‍🔬': 5, + '👨‍🚀': 5, + '👨‍🚒': 5, + '👨‍🦯': 5, + '👨‍🦯‍➡️': 7, + '👨‍🦰': 5, + '👨‍🦱': 5, + '👨‍🦲': 5, + '👨‍🦳': 5, + '👨‍🦼': 5, + '👨‍🦼‍➡️': 7, + '👨‍🦽': 5, + '👨‍🦽‍➡️': 7, + '👨🏻‍⚕️': 6, + '👨🏻‍⚖️': 6, + '👨🏻‍✈️': 6, + '👨🏻‍❤️‍👨🏻': 11, + '👨🏻‍❤️‍👨🏽': 11, + '👨🏻‍❤️‍👨🏿': 11, + '👨🏻‍❤️‍💋‍👨🏻': 14, + '👨🏻‍❤️‍💋‍👨🏽': 14, + '👨🏻‍❤️‍💋‍👨🏾': 14, + '👨🏻‍❤️‍💋‍👨🏿': 14, + '👨🏻‍🌾': 7, + '👨🏻‍🍳': 7, + '👨🏻‍🍼': 7, + '👨🏻‍🎓': 7, + '👨🏻‍🎤': 7, + '👨🏻‍🎨': 7, + '👨🏻‍🏫': 7, + '👨🏻‍🏭': 7, + '👨🏻‍🐰‍👨🏼': 12, + '👨🏻‍🐰‍👨🏽': 12, + '👨🏻‍🐰‍👨🏾': 12, + '👨🏻‍🐰‍👨🏿': 12, + '👨🏻‍💻': 7, + '👨🏻‍💼': 7, + '👨🏻‍🔧': 7, + '👨🏻‍🔬': 7, + '👨🏻‍🚀': 7, + '👨🏻‍🚒': 7, + '👨🏻‍🤝‍👨🏼': 12, + '👨🏻‍🤝‍👨🏽': 12, + '👨🏻‍🤝‍👨🏾': 12, + '👨🏻‍🤝‍👨🏿': 12, + '👨🏻‍🦯': 7, + '👨🏻‍🦯‍➡️': 9, + '👨🏻‍🦰': 7, + '👨🏻‍🦱': 7, + '👨🏻‍🦲': 7, + '👨🏻‍🦳': 7, + '👨🏻‍🦼': 7, + '👨🏻‍🦼‍➡️': 9, + '👨🏻‍🦽': 7, + '👨🏻‍🦽‍➡️': 9, + '👨🏻‍🫯‍👨🏼': 12, + '👨🏻‍🫯‍👨🏽': 12, + '👨🏻‍🫯‍👨🏾': 12, + '👨🏻‍🫯‍👨🏿': 12, + '👨🏼‍⚕️': 6, + '👨🏼‍⚖️': 6, + '👨🏼‍✈️': 6, + '👨🏼‍❤️‍👨🏼': 11, + '👨🏼‍❤️‍💋‍👨🏼': 14, + '👨🏼‍❤️‍💋‍👨🏿': 14, + '👨🏼‍🌾': 7, + '👨🏼‍🍳': 7, + '👨🏼‍🍼': 7, + '👨🏼‍🎓': 7, + '👨🏼‍🎤': 7, + '👨🏼‍🎨': 7, + '👨🏼‍🏫': 7, + '👨🏼‍🏭': 7, + '👨🏼‍🐰‍👨🏻': 12, + '👨🏼‍🐰‍👨🏽': 12, + '👨🏼‍🐰‍👨🏿': 12, + '👨🏼‍💻': 7, + '👨🏼‍💼': 7, + '👨🏼‍🔧': 7, + '👨🏼‍🔬': 7, + '👨🏼‍🚀': 7, + '👨🏼‍🚒': 7, + '👨🏼‍🤝‍👨🏻': 12, + '👨🏼‍🤝‍👨🏽': 12, + '👨🏼‍🤝‍👨🏿': 12, + '👨🏼‍🦯': 7, + '👨🏼‍🦯‍➡️': 9, + '👨🏼‍🦰': 7, + '👨🏼‍🦱': 7, + '👨🏼‍🦲': 7, + '👨🏼‍🦳': 7, + '👨🏼‍🦼': 7, + '👨🏼‍🦽': 7, + '👨🏼‍🦽‍➡️': 9, + '👨🏼‍🫯‍👨🏻': 12, + '👨🏼‍🫯‍👨🏽': 12, + '👨🏼‍🫯‍👨🏾': 12, + '👨🏼‍🫯‍👨🏿': 12, + '👨🏽‍⚕️': 6, + '👨🏽‍⚖️': 6, + '👨🏽‍✈️': 6, + '👨🏽‍❤️‍👨🏻': 11, + '👨🏽‍❤️‍👨🏽': 11, + '👨🏽‍❤️‍👨🏿': 11, + '👨🏽‍❤️‍💋‍👨🏻': 14, + '👨🏽‍❤️‍💋‍👨🏽': 14, + '👨🏽‍❤️‍💋‍👨🏿': 14, + '👨🏽‍🌾': 7, + '👨🏽‍🍳': 7, + '👨🏽‍🍼': 7, + '👨🏽‍🎓': 7, + '👨🏽‍🎤': 7, + '👨🏽‍🎨': 7, + '👨🏽‍🏫': 7, + '👨🏽‍🏭': 7, + '👨🏽‍🐰‍👨🏻': 12, + '👨🏽‍🐰‍👨🏼': 12, + '👨🏽‍🐰‍👨🏾': 12, + '👨🏽‍🐰‍👨🏿': 12, + '👨🏽‍💻': 7, + '👨🏽‍💼': 7, + '👨🏽‍🔧': 7, + '👨🏽‍🔬': 7, + '👨🏽‍🚀': 7, + '👨🏽‍🚒': 7, + '👨🏽‍🤝‍👨🏻': 12, + '👨🏽‍🤝‍👨🏼': 12, + '👨🏽‍🤝‍👨🏾': 12, + '👨🏽‍🤝‍👨🏿': 12, + '👨🏽‍🦯': 7, + '👨🏽‍🦯‍➡️': 9, + '👨🏽‍🦰': 7, + '👨🏽‍🦱': 7, + '👨🏽‍🦲': 7, + '👨🏽‍🦳': 7, + '👨🏽‍🦼': 7, + '👨🏽‍🦼‍➡️': 9, + '👨🏽‍🦽': 7, + '👨🏽‍🦽‍➡️': 9, + '👨🏽‍🫯‍👨🏻': 12, + '👨🏽‍🫯‍👨🏼': 12, + '👨🏽‍🫯‍👨🏾': 12, + '👨🏽‍🫯‍👨🏿': 12, + '👨🏾‍⚕️': 6, + '👨🏾‍⚖️': 6, + '👨🏾‍✈️': 6, + '👨🏾‍❤️‍👨🏾': 11, + '👨🏾‍❤️‍💋‍👨🏻': 14, + '👨🏾‍❤️‍💋‍👨🏾': 14, + '👨🏾‍❤️‍💋‍👨🏿': 14, + '👨🏾‍🌾': 7, + '👨🏾‍🍳': 7, + '👨🏾‍🍼': 7, + '👨🏾‍🎓': 7, + '👨🏾‍🎤': 7, + '👨🏾‍🎨': 7, + '👨🏾‍🏫': 7, + '👨🏾‍🏭': 7, + '👨🏾‍🐰‍👨🏻': 12, + '👨🏾‍🐰‍👨🏽': 12, + '👨🏾‍🐰‍👨🏿': 12, + '👨🏾‍💻': 7, + '👨🏾‍💼': 7, + '👨🏾‍🔧': 7, + '👨🏾‍🔬': 7, + '👨🏾‍🚀': 7, + '👨🏾‍🚒': 7, + '👨🏾‍🤝‍👨🏻': 12, + '👨🏾‍🤝‍👨🏽': 12, + '👨🏾‍🤝‍👨🏿': 12, + '👨🏾‍🦯': 7, + '👨🏾‍🦯‍➡️': 9, + '👨🏾‍🦰': 7, + '👨🏾‍🦱': 7, + '👨🏾‍🦲': 7, + '👨🏾‍🦳': 7, + '👨🏾‍🦼': 7, + '👨🏾‍🦽': 7, + '👨🏾‍🦽‍➡️': 9, + '👨🏾‍🫯‍👨🏻': 12, + '👨🏾‍🫯‍👨🏼': 12, + '👨🏾‍🫯‍👨🏽': 12, + '👨🏾‍🫯‍👨🏿': 12, + '👨🏿‍⚕️': 6, + '👨🏿‍⚖️': 6, + '👨🏿‍✈️': 6, + '👨🏿‍❤️‍👨🏻': 11, + '👨🏿‍❤️‍👨🏽': 11, + '👨🏿‍❤️‍👨🏿': 11, + '👨🏿‍❤️‍💋‍👨🏻': 14, + '👨🏿‍❤️‍💋‍👨🏼': 14, + '👨🏿‍❤️‍💋‍👨🏽': 14, + '👨🏿‍❤️‍💋‍👨🏾': 14, + '👨🏿‍❤️‍💋‍👨🏿': 14, + '👨🏿‍🌾': 7, + '👨🏿‍🍳': 7, + '👨🏿‍🍼': 7, + '👨🏿‍🎓': 7, + '👨🏿‍🎤': 7, + '👨🏿‍🎨': 7, + '👨🏿‍🏫': 7, + '👨🏿‍🏭': 7, + '👨🏿‍🐰‍👨🏻': 12, + '👨🏿‍🐰‍👨🏼': 12, + '👨🏿‍🐰‍👨🏽': 12, + '👨🏿‍🐰‍👨🏾': 12, + '👨🏿‍💻': 7, + '👨🏿‍💼': 7, + '👨🏿‍🔧': 7, + '👨🏿‍🔬': 7, + '👨🏿‍🚀': 7, + '👨🏿‍🚒': 7, + '👨🏿‍🤝‍👨🏻': 12, + '👨🏿‍🤝‍👨🏼': 12, + '👨🏿‍🤝‍👨🏽': 12, + '👨🏿‍🤝‍👨🏾': 12, + '👨🏿‍🦯': 7, + '👨🏿‍🦯‍➡️': 9, + '👨🏿‍🦰': 7, + '👨🏿‍🦱': 7, + '👨🏿‍🦲': 7, + '👨🏿‍🦳': 7, + '👨🏿‍🦼': 7, + '👨🏿‍🦼‍➡️': 9, + '👨🏿‍🦽': 7, + '👨🏿‍🦽‍➡️': 9, + '👨🏿‍🫯‍👨🏻': 12, + '👨🏿‍🫯‍👨🏼': 12, + '👨🏿‍🫯‍👨🏽': 12, + '👨🏿‍🫯‍👨🏾': 12, + '👩‍⚕️': 4, + '👩‍⚖️': 4, + '👩‍✈️': 4, + '👩‍❤️‍👨': 7, + '👩‍❤️‍👩': 7, + '👩‍❤️‍💋‍👨': 10, + '👩‍❤️‍💋‍👩': 10, + '👩‍🌾': 5, + '👩‍🍳': 5, + '👩‍🍼': 5, + '👩‍🎓': 5, + '👩‍🎤': 5, + '👩‍🎨': 5, + '👩‍🏫': 5, + '👩‍🏭': 5, + '👩‍👦': 5, + '👩‍👦‍👦': 8, + '👩‍👧': 5, + '👩‍👧‍👦': 8, + '👩‍👧‍👧': 8, + '👩‍👩‍👦': 8, + '👩‍👩‍👦‍👦': 11, + '👩‍👩‍👧': 8, + '👩‍👩‍👧‍👦': 11, + '👩‍👩‍👧‍👧': 11, + '👩‍💻': 5, + '👩‍💼': 5, + '👩‍🔧': 5, + '👩‍🔬': 5, + '👩‍🚀': 5, + '👩‍🚒': 5, + '👩‍🦯': 5, + '👩‍🦯‍➡️': 7, + '👩‍🦰': 5, + '👩‍🦱': 5, + '👩‍🦲': 5, + '👩‍🦳': 5, + '👩‍🦼': 5, + '👩‍🦼‍➡️': 7, + '👩‍🦽': 5, + '👩‍🦽‍➡️': 7, + '👩🏻‍⚕️': 6, + '👩🏻‍⚖️': 6, + '👩🏻‍✈️': 6, + '👩🏻‍❤️‍👨🏻': 11, + '👩🏻‍❤️‍👨🏿': 11, + '👩🏻‍❤️‍👩🏻': 11, + '👩🏻‍❤️‍💋‍👨🏻': 14, + '👩🏻‍❤️‍💋‍👨🏽': 14, + '👩🏻‍❤️‍💋‍👨🏿': 14, + '👩🏻‍❤️‍💋‍👩🏻': 14, + '👩🏻‍❤️‍💋‍👩🏽': 14, + '👩🏻‍❤️‍💋‍👩🏿': 14, + '👩🏻‍🌾': 7, + '👩🏻‍🍳': 7, + '👩🏻‍🍼': 7, + '👩🏻‍🎓': 7, + '👩🏻‍🎤': 7, + '👩🏻‍🎨': 7, + '👩🏻‍🏫': 7, + '👩🏻‍🏭': 7, + '👩🏻‍🐰‍👩🏼': 12, + '👩🏻‍🐰‍👩🏽': 12, + '👩🏻‍🐰‍👩🏾': 12, + '👩🏻‍🐰‍👩🏿': 12, + '👩🏻‍💻': 7, + '👩🏻‍💼': 7, + '👩🏻‍🔧': 7, + '👩🏻‍🔬': 7, + '👩🏻‍🚀': 7, + '👩🏻‍🚒': 7, + '👩🏻‍🤝‍👨🏽': 12, + '👩🏻‍🤝‍👨🏿': 12, + '👩🏻‍🤝‍👩🏼': 12, + '👩🏻‍🤝‍👩🏽': 12, + '👩🏻‍🤝‍👩🏾': 12, + '👩🏻‍🤝‍👩🏿': 12, + '👩🏻‍🦯': 7, + '👩🏻‍🦯‍➡️': 9, + '👩🏻‍🦰': 7, + '👩🏻‍🦱': 7, + '👩🏻‍🦲': 7, + '👩🏻‍🦳': 7, + '👩🏻‍🦼': 7, + '👩🏻‍🦼‍➡️': 9, + '👩🏻‍🦽': 7, + '👩🏻‍🦽‍➡️': 9, + '👩🏻‍🫯‍👩🏼': 12, + '👩🏻‍🫯‍👩🏽': 12, + '👩🏻‍🫯‍👩🏾': 12, + '👩🏻‍🫯‍👩🏿': 12, + '👩🏼‍⚕️': 6, + '👩🏼‍⚖️': 6, + '👩🏼‍✈️': 6, + '👩🏼‍❤️‍👨🏼': 11, + '👩🏼‍❤️‍👩🏼': 11, + '👩🏼‍❤️‍💋‍👨🏼': 14, + '👩🏼‍❤️‍💋‍👩🏼': 14, + '👩🏼‍🌾': 7, + '👩🏼‍🍳': 7, + '👩🏼‍🍼': 7, + '👩🏼‍🎓': 7, + '👩🏼‍🎤': 7, + '👩🏼‍🎨': 7, + '👩🏼‍🏫': 7, + '👩🏼‍🏭': 7, + '👩🏼‍🐰‍👩🏻': 12, + '👩🏼‍🐰‍👩🏿': 12, + '👩🏼‍💻': 7, + '👩🏼‍💼': 7, + '👩🏼‍🔧': 7, + '👩🏼‍🔬': 7, + '👩🏼‍🚀': 7, + '👩🏼‍🚒': 7, + '👩🏼‍🤝‍👩🏻': 12, + '👩🏼‍🤝‍👩🏽': 12, + '👩🏼‍🤝‍👩🏿': 12, + '👩🏼‍🦯': 7, + '👩🏼‍🦯‍➡️': 9, + '👩🏼‍🦰': 7, + '👩🏼‍🦱': 7, + '👩🏼‍🦲': 7, + '👩🏼‍🦳': 7, + '👩🏼‍🦼': 7, + '👩🏼‍🦽': 7, + '👩🏼‍🫯‍👩🏻': 12, + '👩🏼‍🫯‍👩🏽': 12, + '👩🏼‍🫯‍👩🏾': 12, + '👩🏼‍🫯‍👩🏿': 12, + '👩🏽‍⚕️': 6, + '👩🏽‍⚖️': 6, + '👩🏽‍✈️': 6, + '👩🏽‍❤️‍👨🏽': 11, + '👩🏽‍❤️‍👩🏽': 11, + '👩🏽‍❤️‍💋‍👨🏻': 14, + '👩🏽‍❤️‍💋‍👨🏽': 14, + '👩🏽‍❤️‍💋‍👨🏿': 14, + '👩🏽‍❤️‍💋‍👩🏻': 14, + '👩🏽‍❤️‍💋‍👩🏽': 14, + '👩🏽‍❤️‍💋‍👩🏿': 14, + '👩🏽‍🌾': 7, + '👩🏽‍🍳': 7, + '👩🏽‍🍼': 7, + '👩🏽‍🎓': 7, + '👩🏽‍🎤': 7, + '👩🏽‍🎨': 7, + '👩🏽‍🏫': 7, + '👩🏽‍🏭': 7, + '👩🏽‍🐰‍👩🏻': 12, + '👩🏽‍🐰‍👩🏾': 12, + '👩🏽‍🐰‍👩🏿': 12, + '👩🏽‍💻': 7, + '👩🏽‍💼': 7, + '👩🏽‍🔧': 7, + '👩🏽‍🔬': 7, + '👩🏽‍🚀': 7, + '👩🏽‍🚒': 7, + '👩🏽‍🤝‍👨🏻': 12, + '👩🏽‍🤝‍👨🏿': 12, + '👩🏽‍🤝‍👩🏻': 12, + '👩🏽‍🤝‍👩🏼': 12, + '👩🏽‍🤝‍👩🏾': 12, + '👩🏽‍🤝‍👩🏿': 12, + '👩🏽‍🦯': 7, + '👩🏽‍🦯‍➡️': 9, + '👩🏽‍🦰': 7, + '👩🏽‍🦱': 7, + '👩🏽‍🦲': 7, + '👩🏽‍🦳': 7, + '👩🏽‍🦼': 7, + '👩🏽‍🦼‍➡️': 9, + '👩🏽‍🦽': 7, + '👩🏽‍🦽‍➡️': 9, + '👩🏽‍🫯‍👩🏻': 12, + '👩🏽‍🫯‍👩🏼': 12, + '👩🏽‍🫯‍👩🏾': 12, + '👩🏽‍🫯‍👩🏿': 12, + '👩🏾‍⚕️': 6, + '👩🏾‍⚖️': 6, + '👩🏾‍✈️': 6, + '👩🏾‍❤️‍👨🏾': 11, + '👩🏾‍❤️‍👩🏾': 11, + '👩🏾‍❤️‍💋‍👨🏾': 14, + '👩🏾‍❤️‍💋‍👩🏾': 14, + '👩🏾‍🌾': 7, + '👩🏾‍🍳': 7, + '👩🏾‍🍼': 7, + '👩🏾‍🎓': 7, + '👩🏾‍🎤': 7, + '👩🏾‍🎨': 7, + '👩🏾‍🏫': 7, + '👩🏾‍🏭': 7, + '👩🏾‍🐰‍👩🏻': 12, + '👩🏾‍🐰‍👩🏽': 12, + '👩🏾‍🐰‍👩🏿': 12, + '👩🏾‍💻': 7, + '👩🏾‍💼': 7, + '👩🏾‍🔧': 7, + '👩🏾‍🔬': 7, + '👩🏾‍🚀': 7, + '👩🏾‍🚒': 7, + '👩🏾‍🤝‍👩🏻': 12, + '👩🏾‍🤝‍👩🏽': 12, + '👩🏾‍🤝‍👩🏿': 12, + '👩🏾‍🦯': 7, + '👩🏾‍🦯‍➡️': 9, + '👩🏾‍🦰': 7, + '👩🏾‍🦱': 7, + '👩🏾‍🦲': 7, + '👩🏾‍🦳': 7, + '👩🏾‍🦼': 7, + '👩🏾‍🦽': 7, + '👩🏾‍🦽‍➡️': 9, + '👩🏾‍🫯‍👩🏻': 12, + '👩🏾‍🫯‍👩🏼': 12, + '👩🏾‍🫯‍👩🏽': 12, + '👩🏾‍🫯‍👩🏿': 12, + '👩🏿‍⚕️': 6, + '👩🏿‍⚖️': 6, + '👩🏿‍✈️': 6, + '👩🏿‍❤️‍👨🏻': 11, + '👩🏿‍❤️‍👨🏿': 11, + '👩🏿‍❤️‍👩🏿': 11, + '👩🏿‍❤️‍💋‍👨🏻': 14, + '👩🏿‍❤️‍💋‍👨🏽': 14, + '👩🏿‍❤️‍💋‍👨🏿': 14, + '👩🏿‍❤️‍💋‍👩🏻': 14, + '👩🏿‍❤️‍💋‍👩🏽': 14, + '👩🏿‍❤️‍💋‍👩🏿': 14, + '👩🏿‍🌾': 7, + '👩🏿‍🍳': 7, + '👩🏿‍🍼': 7, + '👩🏿‍🎓': 7, + '👩🏿‍🎤': 7, + '👩🏿‍🎨': 7, + '👩🏿‍🏫': 7, + '👩🏿‍🏭': 7, + '👩🏿‍🐰‍👩🏻': 12, + '👩🏿‍🐰‍👩🏼': 12, + '👩🏿‍🐰‍👩🏽': 12, + '👩🏿‍🐰‍👩🏾': 12, + '👩🏿‍💻': 7, + '👩🏿‍💼': 7, + '👩🏿‍🔧': 7, + '👩🏿‍🔬': 7, + '👩🏿‍🚀': 7, + '👩🏿‍🚒': 7, + '👩🏿‍🤝‍👨🏻': 12, + '👩🏿‍🤝‍👨🏽': 12, + '👩🏿‍🤝‍👩🏻': 12, + '👩🏿‍🤝‍👩🏼': 12, + '👩🏿‍🤝‍👩🏽': 12, + '👩🏿‍🤝‍👩🏾': 12, + '👩🏿‍🦯': 7, + '👩🏿‍🦯‍➡️': 9, + '👩🏿‍🦰': 7, + '👩🏿‍🦱': 7, + '👩🏿‍🦲': 7, + '👩🏿‍🦳': 7, + '👩🏿‍🦼': 7, + '👩🏿‍🦼‍➡️': 9, + '👩🏿‍🦽': 7, + '👩🏿‍🦽‍➡️': 9, + '👩🏿‍🫯‍👩🏻': 12, + '👩🏿‍🫯‍👩🏼': 12, + '👩🏿‍🫯‍👩🏽': 12, + '👩🏿‍🫯‍👩🏾': 12, + '👮‍♀️': 4, + '👮‍♂️': 4, + '👮🏻‍♀️': 6, + '👮🏻‍♂️': 6, + '👮🏼‍♀️': 6, + '👮🏼‍♂️': 6, + '👮🏽‍♀️': 6, + '👮🏽‍♂️': 6, + '👮🏾‍♀️': 6, + '👮🏾‍♂️': 6, + '👮🏿‍♀️': 6, + '👮🏿‍♂️': 6, + '👯‍♀️': 4, + '👯‍♂️': 4, + '👯🏻‍♀️': 6, + '👯🏻‍♂️': 6, + '👯🏼‍♀️': 6, + '👯🏼‍♂️': 6, + '👯🏽‍♀️': 6, + '👯🏽‍♂️': 6, + '👯🏾‍♀️': 6, + '👯🏾‍♂️': 6, + '👯🏿‍♀️': 6, + '👯🏿‍♂️': 6, + '👰‍♀️': 4, + '👰‍♂️': 4, + '👰🏻‍♀️': 6, + '👰🏻‍♂️': 6, + '👰🏼‍♀️': 6, + '👰🏼‍♂️': 6, + '👰🏽‍♀️': 6, + '👰🏽‍♂️': 6, + '👰🏾‍♀️': 6, + '👰🏾‍♂️': 6, + '👰🏿‍♀️': 6, + '👰🏿‍♂️': 6, + '👱‍♀️': 4, + '👱‍♂️': 4, + '👱🏻‍♀️': 6, + '👱🏻‍♂️': 6, + '👱🏼‍♀️': 6, + '👱🏼‍♂️': 6, + '👱🏽‍♀️': 6, + '👱🏽‍♂️': 6, + '👱🏾‍♀️': 6, + '👱🏾‍♂️': 6, + '👱🏿‍♀️': 6, + '👱🏿‍♂️': 6, + '👳‍♀️': 4, + '👳‍♂️': 4, + '👳🏻‍♀️': 6, + '👳🏻‍♂️': 6, + '👳🏼‍♀️': 6, + '👳🏼‍♂️': 6, + '👳🏽‍♀️': 6, + '👳🏽‍♂️': 6, + '👳🏾‍♀️': 6, + '👳🏾‍♂️': 6, + '👳🏿‍♀️': 6, + '👳🏿‍♂️': 6, + '👷‍♀️': 4, + '👷‍♂️': 4, + '👷🏻‍♀️': 6, + '👷🏻‍♂️': 6, + '👷🏼‍♀️': 6, + '👷🏼‍♂️': 6, + '👷🏽‍♀️': 6, + '👷🏽‍♂️': 6, + '👷🏾‍♀️': 6, + '👷🏾‍♂️': 6, + '👷🏿‍♀️': 6, + '👷🏿‍♂️': 6, + '💁‍♀️': 4, + '💁‍♂️': 4, + '💁🏻‍♀️': 6, + '💁🏻‍♂️': 6, + '💁🏼‍♀️': 6, + '💁🏼‍♂️': 6, + '💁🏽‍♀️': 6, + '💁🏽‍♂️': 6, + '💁🏾‍♀️': 6, + '💁🏾‍♂️': 6, + '💁🏿‍♀️': 6, + '💁🏿‍♂️': 6, + '💂‍♀️': 4, + '💂‍♂️': 4, + '💂🏻‍♀️': 6, + '💂🏻‍♂️': 6, + '💂🏼‍♀️': 6, + '💂🏼‍♂️': 6, + '💂🏽‍♀️': 6, + '💂🏽‍♂️': 6, + '💂🏾‍♀️': 6, + '💂🏾‍♂️': 6, + '💂🏿‍♀️': 6, + '💂🏿‍♂️': 6, + '💆‍♀️': 4, + '💆‍♂️': 4, + '💆🏻‍♀️': 6, + '💆🏻‍♂️': 6, + '💆🏼‍♀️': 6, + '💆🏼‍♂️': 6, + '💆🏽‍♀️': 6, + '💆🏽‍♂️': 6, + '💆🏾‍♀️': 6, + '💆🏾‍♂️': 6, + '💆🏿‍♀️': 6, + '💆🏿‍♂️': 6, + '💇‍♀️': 4, + '💇‍♂️': 4, + '💇🏻‍♀️': 6, + '💇🏻‍♂️': 6, + '💇🏼‍♀️': 6, + '💇🏼‍♂️': 6, + '💇🏽‍♀️': 6, + '💇🏽‍♂️': 6, + '💇🏾‍♀️': 6, + '💇🏾‍♂️': 6, + '💇🏿‍♀️': 6, + '💇🏿‍♂️': 6, + '🕵️‍♀️': 3, + '🕵️‍♂️': 3, + '🕵🏻‍♀️': 5, + '🕵🏻‍♂️': 5, + '🕵🏼‍♀️': 5, + '🕵🏼‍♂️': 5, + '🕵🏽‍♀️': 5, + '🕵🏽‍♂️': 5, + '🕵🏾‍♀️': 5, + '🕵🏾‍♂️': 5, + '🕵🏿‍♀️': 5, + '🕵🏿‍♂️': 5, + '😮‍💨': 5, + '😵‍💫': 5, + '😶‍🌫️': 4, + '🙂‍↔️': 4, + '🙂‍↕️': 4, + '🙅‍♀️': 4, + '🙅‍♂️': 4, + '🙅🏻‍♀️': 6, + '🙅🏻‍♂️': 6, + '🙅🏼‍♀️': 6, + '🙅🏼‍♂️': 6, + '🙅🏽‍♀️': 6, + '🙅🏽‍♂️': 6, + '🙅🏾‍♀️': 6, + '🙅🏾‍♂️': 6, + '🙅🏿‍♀️': 6, + '🙅🏿‍♂️': 6, + '🙆‍♀️': 4, + '🙆‍♂️': 4, + '🙆🏻‍♀️': 6, + '🙆🏻‍♂️': 6, + '🙆🏼‍♀️': 6, + '🙆🏼‍♂️': 6, + '🙆🏽‍♀️': 6, + '🙆🏽‍♂️': 6, + '🙆🏾‍♀️': 6, + '🙆🏾‍♂️': 6, + '🙆🏿‍♀️': 6, + '🙆🏿‍♂️': 6, + '🙇‍♀️': 4, + '🙇‍♂️': 4, + '🙇🏻‍♀️': 6, + '🙇🏻‍♂️': 6, + '🙇🏼‍♀️': 6, + '🙇🏼‍♂️': 6, + '🙇🏽‍♀️': 6, + '🙇🏽‍♂️': 6, + '🙇🏾‍♀️': 6, + '🙇🏾‍♂️': 6, + '🙇🏿‍♀️': 6, + '🙇🏿‍♂️': 6, + '🙋‍♀️': 4, + '🙋‍♂️': 4, + '🙋🏻‍♀️': 6, + '🙋🏻‍♂️': 6, + '🙋🏼‍♀️': 6, + '🙋🏼‍♂️': 6, + '🙋🏽‍♀️': 6, + '🙋🏽‍♂️': 6, + '🙋🏾‍♀️': 6, + '🙋🏾‍♂️': 6, + '🙋🏿‍♀️': 6, + '🙋🏿‍♂️': 6, + '🙍‍♀️': 4, + '🙍‍♂️': 4, + '🙍🏻‍♀️': 6, + '🙍🏻‍♂️': 6, + '🙍🏼‍♀️': 6, + '🙍🏼‍♂️': 6, + '🙍🏽‍♀️': 6, + '🙍🏽‍♂️': 6, + '🙍🏾‍♀️': 6, + '🙍🏾‍♂️': 6, + '🙍🏿‍♀️': 6, + '🙍🏿‍♂️': 6, + '🙎‍♀️': 4, + '🙎‍♂️': 4, + '🙎🏻‍♀️': 6, + '🙎🏻‍♂️': 6, + '🙎🏼‍♀️': 6, + '🙎🏼‍♂️': 6, + '🙎🏽‍♀️': 6, + '🙎🏽‍♂️': 6, + '🙎🏾‍♀️': 6, + '🙎🏾‍♂️': 6, + '🙎🏿‍♀️': 6, + '🙎🏿‍♂️': 6, + '🚣‍♀️': 4, + '🚣‍♂️': 4, + '🚣🏻‍♀️': 6, + '🚣🏻‍♂️': 6, + '🚣🏼‍♀️': 6, + '🚣🏼‍♂️': 6, + '🚣🏽‍♀️': 6, + '🚣🏽‍♂️': 6, + '🚣🏾‍♀️': 6, + '🚣🏾‍♂️': 6, + '🚣🏿‍♀️': 6, + '🚣🏿‍♂️': 6, + '🚴‍♀️': 4, + '🚴‍♂️': 4, + '🚴🏻‍♀️': 6, + '🚴🏻‍♂️': 6, + '🚴🏼‍♀️': 6, + '🚴🏼‍♂️': 6, + '🚴🏽‍♀️': 6, + '🚴🏽‍♂️': 6, + '🚴🏾‍♀️': 6, + '🚴🏾‍♂️': 6, + '🚴🏿‍♀️': 6, + '🚴🏿‍♂️': 6, + '🚵‍♀️': 4, + '🚵‍♂️': 4, + '🚵🏻‍♀️': 6, + '🚵🏻‍♂️': 6, + '🚵🏼‍♀️': 6, + '🚵🏼‍♂️': 6, + '🚵🏽‍♀️': 6, + '🚵🏽‍♂️': 6, + '🚵🏾‍♀️': 6, + '🚵🏾‍♂️': 6, + '🚵🏿‍♀️': 6, + '🚵🏿‍♂️': 6, + '🚶‍♀️': 4, + '🚶‍♀️‍➡️': 6, + '🚶‍♂️': 4, + '🚶‍♂️‍➡️': 6, + '🚶‍➡️': 4, + '🚶🏻‍♀️': 6, + '🚶🏻‍♀️‍➡️': 8, + '🚶🏻‍♂️': 6, + '🚶🏻‍♂️‍➡️': 8, + '🚶🏻‍➡️': 6, + '🚶🏼‍♀️': 6, + '🚶🏼‍♀️‍➡️': 8, + '🚶🏼‍♂️': 6, + '🚶🏼‍♂️‍➡️': 8, + '🚶🏼‍➡️': 6, + '🚶🏽‍♀️': 6, + '🚶🏽‍♀️‍➡️': 8, + '🚶🏽‍♂️': 6, + '🚶🏽‍♂️‍➡️': 8, + '🚶🏽‍➡️': 6, + '🚶🏾‍♀️': 6, + '🚶🏾‍♀️‍➡️': 8, + '🚶🏾‍♂️': 6, + '🚶🏾‍♂️‍➡️': 8, + '🚶🏾‍➡️': 6, + '🚶🏿‍♀️': 6, + '🚶🏿‍♀️‍➡️': 8, + '🚶🏿‍♂️': 6, + '🚶🏿‍♂️‍➡️': 8, + '🚶🏿‍➡️': 6, + '🤦‍♀️': 4, + '🤦‍♂️': 4, + '🤦🏻‍♀️': 6, + '🤦🏻‍♂️': 6, + '🤦🏼‍♀️': 6, + '🤦🏼‍♂️': 6, + '🤦🏽‍♀️': 6, + '🤦🏽‍♂️': 6, + '🤦🏾‍♀️': 6, + '🤦🏾‍♂️': 6, + '🤦🏿‍♀️': 6, + '🤦🏿‍♂️': 6, + '🤵‍♀️': 4, + '🤵‍♂️': 4, + '🤵🏻‍♀️': 6, + '🤵🏻‍♂️': 6, + '🤵🏼‍♀️': 6, + '🤵🏼‍♂️': 6, + '🤵🏽‍♀️': 6, + '🤵🏽‍♂️': 6, + '🤵🏾‍♀️': 6, + '🤵🏾‍♂️': 6, + '🤵🏿‍♀️': 6, + '🤵🏿‍♂️': 6, + '🤷‍♀️': 4, + '🤷‍♂️': 4, + '🤷🏻‍♀️': 6, + '🤷🏻‍♂️': 6, + '🤷🏼‍♀️': 6, + '🤷🏼‍♂️': 6, + '🤷🏽‍♀️': 6, + '🤷🏽‍♂️': 6, + '🤷🏾‍♀️': 6, + '🤷🏾‍♂️': 6, + '🤷🏿‍♀️': 6, + '🤷🏿‍♂️': 6, + '🤸‍♀️': 4, + '🤸‍♂️': 4, + '🤸🏻‍♀️': 6, + '🤸🏻‍♂️': 6, + '🤸🏼‍♀️': 6, + '🤸🏼‍♂️': 6, + '🤸🏽‍♀️': 6, + '🤸🏽‍♂️': 6, + '🤸🏾‍♀️': 6, + '🤸🏾‍♂️': 6, + '🤸🏿‍♀️': 6, + '🤸🏿‍♂️': 6, + '🤹‍♀️': 4, + '🤹‍♂️': 4, + '🤹🏻‍♀️': 6, + '🤹🏻‍♂️': 6, + '🤹🏼‍♀️': 6, + '🤹🏼‍♂️': 6, + '🤹🏽‍♀️': 6, + '🤹🏽‍♂️': 6, + '🤹🏾‍♀️': 6, + '🤹🏾‍♂️': 6, + '🤹🏿‍♀️': 6, + '🤹🏿‍♂️': 6, + '🤼‍♀️': 4, + '🤼‍♂️': 4, + '🤼🏻‍♀️': 6, + '🤼🏻‍♂️': 6, + '🤼🏼‍♀️': 6, + '🤼🏼‍♂️': 6, + '🤼🏽‍♀️': 6, + '🤼🏽‍♂️': 6, + '🤼🏾‍♀️': 6, + '🤼🏾‍♂️': 6, + '🤼🏿‍♀️': 6, + '🤼🏿‍♂️': 6, + '🤽‍♀️': 4, + '🤽‍♂️': 4, + '🤽🏻‍♀️': 6, + '🤽🏻‍♂️': 6, + '🤽🏼‍♀️': 6, + '🤽🏼‍♂️': 6, + '🤽🏽‍♀️': 6, + '🤽🏽‍♂️': 6, + '🤽🏾‍♀️': 6, + '🤽🏾‍♂️': 6, + '🤽🏿‍♀️': 6, + '🤽🏿‍♂️': 6, + '🤾‍♀️': 4, + '🤾‍♂️': 4, + '🤾🏻‍♀️': 6, + '🤾🏻‍♂️': 6, + '🤾🏼‍♀️': 6, + '🤾🏼‍♂️': 6, + '🤾🏽‍♀️': 6, + '🤾🏽‍♂️': 6, + '🤾🏾‍♀️': 6, + '🤾🏾‍♂️': 6, + '🤾🏿‍♀️': 6, + '🤾🏿‍♂️': 6, + '🦸‍♀️': 4, + '🦸‍♂️': 4, + '🦸🏻‍♀️': 6, + '🦸🏻‍♂️': 6, + '🦸🏼‍♀️': 6, + '🦸🏼‍♂️': 6, + '🦸🏽‍♀️': 6, + '🦸🏽‍♂️': 6, + '🦸🏾‍♀️': 6, + '🦸🏾‍♂️': 6, + '🦸🏿‍♀️': 6, + '🦸🏿‍♂️': 6, + '🦹‍♀️': 4, + '🦹‍♂️': 4, + '🦹🏻‍♀️': 6, + '🦹🏻‍♂️': 6, + '🦹🏼‍♀️': 6, + '🦹🏼‍♂️': 6, + '🦹🏽‍♀️': 6, + '🦹🏽‍♂️': 6, + '🦹🏾‍♀️': 6, + '🦹🏾‍♂️': 6, + '🦹🏿‍♀️': 6, + '🦹🏿‍♂️': 6, + '🧍‍♀️': 4, + '🧍‍♂️': 4, + '🧍🏻‍♀️': 6, + '🧍🏻‍♂️': 6, + '🧍🏼‍♀️': 6, + '🧍🏼‍♂️': 6, + '🧍🏽‍♀️': 6, + '🧍🏽‍♂️': 6, + '🧍🏾‍♀️': 6, + '🧍🏾‍♂️': 6, + '🧍🏿‍♀️': 6, + '🧍🏿‍♂️': 6, + '🧎‍♀️': 4, + '🧎‍♀️‍➡️': 6, + '🧎‍♂️': 4, + '🧎‍♂️‍➡️': 6, + '🧎‍➡️': 4, + '🧎🏻‍♀️': 6, + '🧎🏻‍♀️‍➡️': 8, + '🧎🏻‍♂️': 6, + '🧎🏻‍♂️‍➡️': 8, + '🧎🏻‍➡️': 6, + '🧎🏼‍♀️': 6, + '🧎🏼‍♀️‍➡️': 8, + '🧎🏼‍♂️': 6, + '🧎🏼‍♂️‍➡️': 8, + '🧎🏼‍➡️': 6, + '🧎🏽‍♀️': 6, + '🧎🏽‍♀️‍➡️': 8, + '🧎🏽‍♂️': 6, + '🧎🏽‍♂️‍➡️': 8, + '🧎🏽‍➡️': 6, + '🧎🏾‍♀️': 6, + '🧎🏾‍♀️‍➡️': 8, + '🧎🏾‍♂️': 6, + '🧎🏾‍♂️‍➡️': 8, + '🧎🏾‍➡️': 6, + '🧎🏿‍♀️': 6, + '🧎🏿‍♀️‍➡️': 8, + '🧎🏿‍♂️': 6, + '🧎🏿‍♂️‍➡️': 8, + '🧎🏿‍➡️': 6, + '🧏‍♀️': 4, + '🧏‍♂️': 4, + '🧏🏻‍♀️': 6, + '🧏🏻‍♂️': 6, + '🧏🏼‍♀️': 6, + '🧏🏼‍♂️': 6, + '🧏🏽‍♀️': 6, + '🧏🏽‍♂️': 6, + '🧏🏾‍♀️': 6, + '🧏🏾‍♂️': 6, + '🧏🏿‍♀️': 6, + '🧏🏿‍♂️': 6, + '🧑‍⚕️': 4, + '🧑‍⚖️': 4, + '🧑‍✈️': 4, + '🧑‍🌾': 5, + '🧑‍🍳': 5, + '🧑‍🍼': 5, + '🧑‍🎄': 5, + '🧑‍🎓': 5, + '🧑‍🎤': 5, + '🧑‍🎨': 5, + '🧑‍🏫': 5, + '🧑‍🏭': 5, + '🧑‍💻': 5, + '🧑‍💼': 5, + '🧑‍🔧': 5, + '🧑‍🔬': 5, + '🧑‍🚀': 5, + '🧑‍🚒': 5, + '🧑‍🤝‍🧑': 8, + '🧑‍🦯': 5, + '🧑‍🦯‍➡️': 7, + '🧑‍🦰': 5, + '🧑‍🦱': 5, + '🧑‍🦲': 5, + '🧑‍🦳': 5, + '🧑‍🦼': 5, + '🧑‍🦼‍➡️': 7, + '🧑‍🦽': 5, + '🧑‍🦽‍➡️': 7, + '🧑‍🧑‍🧒': 8, + '🧑‍🧑‍🧒‍🧒': 11, + '🧑‍🧒': 5, + '🧑‍🧒‍🧒': 8, + '🧑‍🩰': 5, + '🧑🏻‍⚕️': 6, + '🧑🏻‍⚖️': 6, + '🧑🏻‍✈️': 6, + '🧑🏻‍❤️‍💋‍🧑🏿': 14, + '🧑🏻‍🌾': 7, + '🧑🏻‍🍳': 7, + '🧑🏻‍🍼': 7, + '🧑🏻‍🎄': 7, + '🧑🏻‍🎓': 7, + '🧑🏻‍🎤': 7, + '🧑🏻‍🎨': 7, + '🧑🏻‍🏫': 7, + '🧑🏻‍🏭': 7, + '🧑🏻‍🐰‍🧑🏽': 12, + '🧑🏻‍🐰‍🧑🏾': 12, + '🧑🏻‍🐰‍🧑🏿': 12, + '🧑🏻‍💻': 7, + '🧑🏻‍💼': 7, + '🧑🏻‍🔧': 7, + '🧑🏻‍🔬': 7, + '🧑🏻‍🚀': 7, + '🧑🏻‍🚒': 7, + '🧑🏻‍🤝‍🧑🏻': 12, + '🧑🏻‍🤝‍🧑🏼': 12, + '🧑🏻‍🤝‍🧑🏽': 12, + '🧑🏻‍🤝‍🧑🏾': 12, + '🧑🏻‍🤝‍🧑🏿': 12, + '🧑🏻‍🦯': 7, + '🧑🏻‍🦯‍➡️': 9, + '🧑🏻‍🦰': 7, + '🧑🏻‍🦱': 7, + '🧑🏻‍🦲': 7, + '🧑🏻‍🦳': 7, + '🧑🏻‍🦼': 7, + '🧑🏻‍🦼‍➡️': 9, + '🧑🏻‍🦽': 7, + '🧑🏻‍🦽‍➡️': 9, + '🧑🏻‍🩰': 7, + '🧑🏻‍🫯‍🧑🏼': 12, + '🧑🏻‍🫯‍🧑🏽': 12, + '🧑🏻‍🫯‍🧑🏾': 12, + '🧑🏻‍🫯‍🧑🏿': 12, + '🧑🏼‍⚕️': 6, + '🧑🏼‍⚖️': 6, + '🧑🏼‍✈️': 6, + '🧑🏼‍🌾': 7, + '🧑🏼‍🍳': 7, + '🧑🏼‍🍼': 7, + '🧑🏼‍🎄': 7, + '🧑🏼‍🎓': 7, + '🧑🏼‍🎤': 7, + '🧑🏼‍🎨': 7, + '🧑🏼‍🏫': 7, + '🧑🏼‍🏭': 7, + '🧑🏼‍🐰‍🧑🏿': 12, + '🧑🏼‍💻': 7, + '🧑🏼‍💼': 7, + '🧑🏼‍🔧': 7, + '🧑🏼‍🔬': 7, + '🧑🏼‍🚀': 7, + '🧑🏼‍🚒': 7, + '🧑🏼‍🤝‍🧑🏻': 12, + '🧑🏼‍🤝‍🧑🏼': 12, + '🧑🏼‍🤝‍🧑🏽': 12, + '🧑🏼‍🤝‍🧑🏿': 12, + '🧑🏼‍🦯': 7, + '🧑🏼‍🦯‍➡️': 9, + '🧑🏼‍🦰': 7, + '🧑🏼‍🦱': 7, + '🧑🏼‍🦲': 7, + '🧑🏼‍🦳': 7, + '🧑🏼‍🦼': 7, + '🧑🏼‍🦽': 7, + '🧑🏼‍🩰': 7, + '🧑🏼‍🫯‍🧑🏻': 12, + '🧑🏼‍🫯‍🧑🏽': 12, + '🧑🏼‍🫯‍🧑🏿': 12, + '🧑🏽‍⚕️': 6, + '🧑🏽‍⚖️': 6, + '🧑🏽‍✈️': 6, + '🧑🏽‍❤️‍💋‍🧑🏿': 14, + '🧑🏽‍🌾': 7, + '🧑🏽‍🍳': 7, + '🧑🏽‍🍼': 7, + '🧑🏽‍🎄': 7, + '🧑🏽‍🎓': 7, + '🧑🏽‍🎤': 7, + '🧑🏽‍🎨': 7, + '🧑🏽‍🏫': 7, + '🧑🏽‍🏭': 7, + '🧑🏽‍🐰‍🧑🏻': 12, + '🧑🏽‍🐰‍🧑🏿': 12, + '🧑🏽‍💻': 7, + '🧑🏽‍💼': 7, + '🧑🏽‍🔧': 7, + '🧑🏽‍🔬': 7, + '🧑🏽‍🚀': 7, + '🧑🏽‍🚒': 7, + '🧑🏽‍🤝‍🧑🏻': 12, + '🧑🏽‍🤝‍🧑🏼': 12, + '🧑🏽‍🤝‍🧑🏽': 12, + '🧑🏽‍🤝‍🧑🏾': 12, + '🧑🏽‍🤝‍🧑🏿': 12, + '🧑🏽‍🦯': 7, + '🧑🏽‍🦯‍➡️': 9, + '🧑🏽‍🦰': 7, + '🧑🏽‍🦱': 7, + '🧑🏽‍🦲': 7, + '🧑🏽‍🦳': 7, + '🧑🏽‍🦼': 7, + '🧑🏽‍🦼‍➡️': 9, + '🧑🏽‍🦽': 7, + '🧑🏽‍🦽‍➡️': 9, + '🧑🏽‍🩰': 7, + '🧑🏽‍🫯‍🧑🏻': 12, + '🧑🏽‍🫯‍🧑🏼': 12, + '🧑🏽‍🫯‍🧑🏾': 12, + '🧑🏽‍🫯‍🧑🏿': 12, + '🧑🏾‍⚕️': 6, + '🧑🏾‍⚖️': 6, + '🧑🏾‍✈️': 6, + '🧑🏾‍🌾': 7, + '🧑🏾‍🍳': 7, + '🧑🏾‍🍼': 7, + '🧑🏾‍🎄': 7, + '🧑🏾‍🎓': 7, + '🧑🏾‍🎤': 7, + '🧑🏾‍🎨': 7, + '🧑🏾‍🏫': 7, + '🧑🏾‍🏭': 7, + '🧑🏾‍🐰‍🧑🏻': 12, + '🧑🏾‍🐰‍🧑🏿': 12, + '🧑🏾‍💻': 7, + '🧑🏾‍💼': 7, + '🧑🏾‍🔧': 7, + '🧑🏾‍🔬': 7, + '🧑🏾‍🚀': 7, + '🧑🏾‍🚒': 7, + '🧑🏾‍🤝‍🧑🏻': 12, + '🧑🏾‍🤝‍🧑🏽': 12, + '🧑🏾‍🤝‍🧑🏾': 12, + '🧑🏾‍🤝‍🧑🏿': 12, + '🧑🏾‍🦯': 7, + '🧑🏾‍🦯‍➡️': 9, + '🧑🏾‍🦰': 7, + '🧑🏾‍🦱': 7, + '🧑🏾‍🦲': 7, + '🧑🏾‍🦳': 7, + '🧑🏾‍🦼': 7, + '🧑🏾‍🦽': 7, + '🧑🏾‍🩰': 7, + '🧑🏾‍🫯‍🧑🏻': 12, + '🧑🏾‍🫯‍🧑🏽': 12, + '🧑🏾‍🫯‍🧑🏿': 12, + '🧑🏿‍⚕️': 6, + '🧑🏿‍⚖️': 6, + '🧑🏿‍✈️': 6, + '🧑🏿‍❤️‍💋‍🧑🏻': 14, + '🧑🏿‍❤️‍💋‍🧑🏽': 14, + '🧑🏿‍🌾': 7, + '🧑🏿‍🍳': 7, + '🧑🏿‍🍼': 7, + '🧑🏿‍🎄': 7, + '🧑🏿‍🎓': 7, + '🧑🏿‍🎤': 7, + '🧑🏿‍🎨': 7, + '🧑🏿‍🏫': 7, + '🧑🏿‍🏭': 7, + '🧑🏿‍🐰‍🧑🏻': 12, + '🧑🏿‍🐰‍🧑🏼': 12, + '🧑🏿‍🐰‍🧑🏽': 12, + '🧑🏿‍🐰‍🧑🏾': 12, + '🧑🏿‍💻': 7, + '🧑🏿‍💼': 7, + '🧑🏿‍🔧': 7, + '🧑🏿‍🔬': 7, + '🧑🏿‍🚀': 7, + '🧑🏿‍🚒': 7, + '🧑🏿‍🤝‍🧑🏻': 12, + '🧑🏿‍🤝‍🧑🏼': 12, + '🧑🏿‍🤝‍🧑🏽': 12, + '🧑🏿‍🤝‍🧑🏾': 12, + '🧑🏿‍🤝‍🧑🏿': 12, + '🧑🏿‍🦯': 7, + '🧑🏿‍🦯‍➡️': 9, + '🧑🏿‍🦰': 7, + '🧑🏿‍🦱': 7, + '🧑🏿‍🦲': 7, + '🧑🏿‍🦳': 7, + '🧑🏿‍🦼': 7, + '🧑🏿‍🦼‍➡️': 9, + '🧑🏿‍🦽': 7, + '🧑🏿‍🦽‍➡️': 9, + '🧑🏿‍🩰': 7, + '🧑🏿‍🫯‍🧑🏻': 12, + '🧑🏿‍🫯‍🧑🏼': 12, + '🧑🏿‍🫯‍🧑🏽': 12, + '🧑🏿‍🫯‍🧑🏾': 12, + '🧔‍♀️': 4, + '🧔‍♂️': 4, + '🧔🏻‍♀️': 6, + '🧔🏻‍♂️': 6, + '🧔🏼‍♀️': 6, + '🧔🏼‍♂️': 6, + '🧔🏽‍♀️': 6, + '🧔🏽‍♂️': 6, + '🧔🏾‍♀️': 6, + '🧔🏾‍♂️': 6, + '🧔🏿‍♀️': 6, + '🧔🏿‍♂️': 6, + '🧖‍♀️': 4, + '🧖‍♂️': 4, + '🧖🏻‍♀️': 6, + '🧖🏻‍♂️': 6, + '🧖🏼‍♀️': 6, + '🧖🏼‍♂️': 6, + '🧖🏽‍♀️': 6, + '🧖🏽‍♂️': 6, + '🧖🏾‍♀️': 6, + '🧖🏾‍♂️': 6, + '🧖🏿‍♀️': 6, + '🧖🏿‍♂️': 6, + '🧗‍♀️': 4, + '🧗‍♂️': 4, + '🧗🏻‍♀️': 6, + '🧗🏻‍♂️': 6, + '🧗🏼‍♀️': 6, + '🧗🏼‍♂️': 6, + '🧗🏽‍♀️': 6, + '🧗🏽‍♂️': 6, + '🧗🏾‍♀️': 6, + '🧗🏾‍♂️': 6, + '🧗🏿‍♀️': 6, + '🧗🏿‍♂️': 6, + '🧘‍♀️': 4, + '🧘‍♂️': 4, + '🧘🏻‍♀️': 6, + '🧘🏻‍♂️': 6, + '🧘🏼‍♀️': 6, + '🧘🏼‍♂️': 6, + '🧘🏽‍♀️': 6, + '🧘🏽‍♂️': 6, + '🧘🏾‍♀️': 6, + '🧘🏾‍♂️': 6, + '🧘🏿‍♀️': 6, + '🧘🏿‍♂️': 6, + '🧙‍♀️': 4, + '🧙‍♂️': 4, + '🧙🏻‍♀️': 6, + '🧙🏻‍♂️': 6, + '🧙🏼‍♀️': 6, + '🧙🏼‍♂️': 6, + '🧙🏽‍♀️': 6, + '🧙🏽‍♂️': 6, + '🧙🏾‍♀️': 6, + '🧙🏾‍♂️': 6, + '🧙🏿‍♀️': 6, + '🧙🏿‍♂️': 6, + '🧚‍♀️': 4, + '🧚‍♂️': 4, + '🧚🏻‍♀️': 6, + '🧚🏻‍♂️': 6, + '🧚🏼‍♀️': 6, + '🧚🏼‍♂️': 6, + '🧚🏽‍♀️': 6, + '🧚🏽‍♂️': 6, + '🧚🏾‍♀️': 6, + '🧚🏾‍♂️': 6, + '🧚🏿‍♀️': 6, + '🧚🏿‍♂️': 6, + '🧛‍♀️': 4, + '🧛‍♂️': 4, + '🧛🏻‍♀️': 6, + '🧛🏻‍♂️': 6, + '🧛🏼‍♀️': 6, + '🧛🏼‍♂️': 6, + '🧛🏽‍♀️': 6, + '🧛🏽‍♂️': 6, + '🧛🏾‍♀️': 6, + '🧛🏾‍♂️': 6, + '🧛🏿‍♀️': 6, + '🧛🏿‍♂️': 6, + '🧜‍♀️': 4, + '🧜‍♂️': 4, + '🧜🏻‍♀️': 6, + '🧜🏻‍♂️': 6, + '🧜🏼‍♀️': 6, + '🧜🏼‍♂️': 6, + '🧜🏽‍♀️': 6, + '🧜🏽‍♂️': 6, + '🧜🏾‍♀️': 6, + '🧜🏾‍♂️': 6, + '🧜🏿‍♀️': 6, + '🧜🏿‍♂️': 6, + '🧝‍♀️': 4, + '🧝‍♂️': 4, + '🧝🏻‍♀️': 6, + '🧝🏻‍♂️': 6, + '🧝🏼‍♀️': 6, + '🧝🏼‍♂️': 6, + '🧝🏽‍♀️': 6, + '🧝🏽‍♂️': 6, + '🧝🏾‍♀️': 6, + '🧝🏾‍♂️': 6, + '🧝🏿‍♀️': 6, + '🧝🏿‍♂️': 6, + '🧞‍♀️': 4, + '🧞‍♂️': 4, + '🧟‍♀️': 4, + '🧟‍♂️': 4, + '🫱🏻‍🫲🏼': 9, + '🫱🏻‍🫲🏽': 9, + '🫱🏻‍🫲🏾': 9, + '🫱🏻‍🫲🏿': 9, + '🫱🏼‍🫲🏻': 9, + '🫱🏼‍🫲🏽': 9, + '🫱🏼‍🫲🏾': 9, + '🫱🏼‍🫲🏿': 9, + '🫱🏽‍🫲🏻': 9, + '🫱🏽‍🫲🏼': 9, + '🫱🏽‍🫲🏾': 9, + '🫱🏽‍🫲🏿': 9, + '🫱🏾‍🫲🏻': 9, + '🫱🏾‍🫲🏼': 9, + '🫱🏾‍🫲🏽': 9, + '🫱🏾‍🫲🏿': 9, + '🫱🏿‍🫲🏻': 9, + '🫱🏿‍🫲🏼': 9, + '🫱🏿‍🫲🏽': 9, + '🫱🏿‍🫲🏾': 9, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_900356bf.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_900356bf.py new file mode 100644 index 0000000000000000000000000000000000000000..1d3f1d601fcd480eff78bbb0585479851c9253cf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_900356bf.py @@ -0,0 +1,115 @@ +""" +Grapheme overrides for _known_900356bf. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: rio +""" +# pylint: skip-file +GRAPHEMES = { + '؁۱': 1, + 'ൻ്റെ': 3, + 'ᨠᩮ᩠ᨯᩨ': 3, + 'ᨠᩯ᩠ᨯ': 3, + 'ᨠᩯ᩠ᨶ᩵': 3, + 'ᨡᩮ᩠ᨲ': 3, + 'ᨡᩯ᩠ᨠ': 3, + 'ᨡᩯ᩠ᨦ': 3, + 'ᨣᩕ᩠ᩋ': 3, + 'ᨣᩕᩮ᩠ᨦᩨ᩵': 3, + 'ᨣᩯ᩠ᨶᩢ': 3, + 'ᨣᩯ᩠ᩅ': 3, + 'ᨧᩮ᩠ᨷ': 3, + 'ᨧᩱ᩠ᨿ': 3, + 'ᨩᩮ᩠ᩋᩨ': 3, + 'ᨩᩮ᩠ᩋᩨ᩵': 3, + 'ᨩᩮ᩠ᩋᩨ᩶': 3, + 'ᨯᩯ᩠ᨦ': 3, + 'ᨯᩯ᩠ᨶ': 3, + 'ᨯᩰ᩠ᨿ': 3, + 'ᨲᩮ᩠ᨠ': 3, + 'ᨲᩮ᩠ᨦ': 3, + 'ᨲᩮ᩠ᨾ': 3, + 'ᨲᩮ᩠ᨾᩨ᩵': 3, + 'ᨲᩯ᩠ᨠ': 3, + 'ᨲᩯ᩠ᨦ᩵': 3, + 'ᨲᩯ᩠ᨾᩢ': 3, + 'ᨲᩱ᩠ᨿ': 3, + 'ᨳᩮ᩠ᨶᩨ᩵': 3, + 'ᨳᩯ᩠ᨦᩢ': 3, + 'ᨳᩯ᩠ᨾ': 3, + 'ᨴᩮ᩠ᩈ': 3, + 'ᨴᩮ᩠ᩈᩱ': 4, + 'ᨴᩯ᩠ᨶ': 3, + 'ᨴᩰ᩠ᩈ': 3, + 'ᨶᩯ᩠ᨶ': 3, + 'ᨷᩮ᩠ᨦᩨ᩶': 3, + 'ᨸᩮ᩠ᨦᩨ': 3, + 'ᨸᩮ᩠ᨶ': 3, + 'ᨹᩮᩨ᩠ᨿ': 3, + 'ᨻᩕ᩠ᩋᩢ': 3, + 'ᨻᩮ᩠ᩋᩨ᩵': 3, + 'ᨽᩱ᩠ᨿ': 3, + 'ᨾᩮ᩠ᨠᩨ': 3, + 'ᨾᩮ᩠ᨦᩨ': 3, + 'ᨾᩮ᩠ᩋᩨ᩵': 3, + 'ᨿᩮ᩠ᨶ': 3, + 'ᨿᩮ᩠ᨾᩨ': 3, + 'ᩁᩮ᩠ᨦᩨ᩵': 3, + 'ᩁᩮ᩠ᨧ': 3, + 'ᩁᩮ᩠ᨶᩨ': 3, + 'ᩁᩮᩨ᩠ᨬ': 3, + 'ᩁᩯ᩠ᨦ': 3, + 'ᩃᩮ᩠ᨠᩨ': 3, + 'ᩃᩮ᩠ᨦᩨ': 3, + 'ᩃᩰ᩠ᨠ': 3, + 'ᩅᩮ᩠ᨶ': 3, + 'ᩅᩮ᩠ᨶᩢ': 3, + 'ᩈᩮ᩠ᩈ': 3, + 'ᩈᩯ᩠ᩅ': 3, + 'ᩈᩱ᩠ᨿ': 3, + 'ᩉᩮ᩠ᨦᩢᩢ': 3, + 'ᩉᩮ᩠ᨯ': 3, + 'ᩉᩮ᩠ᨲᩩ': 3, + 'ᩉᩮ᩠ᨶᩨ': 3, + 'ᩉᩮ᩠ᨾᩨ': 3, + 'ᩉᩮ᩠ᨾᩨᩨ': 3, + 'ᩉᩯ᩠ᨦ᩵': 3, + 'ᩉᩯ᩠ᨶᩢ': 3, + 'ᩉᩯ᩠ᨾ': 3, + 'ᩉᩱ᩠ᨾ᩵': 3, + 'ᩉᩱ᩠ᨿ᩵': 3, + 'ᩣ᩠ᨲᩱ': 3, + 'ꦏ꧀': 2, + 'ꦠ꧀': 2, + 'ꦢ꧀': 2, + 'ꦤ꧀': 2, + 'ꦥ꦳꧀': 2, + 'ꦥ꧀': 2, + 'ꦧ꧀': 2, + 'ꦩ꧀': 2, + 'ꦭ꧀': 2, + 'ꦱ꧀': 2, + '𑌕𑍍': 2, + '𑌗𑍍': 2, + '𑌚𑍍': 2, + '𑌜𑍍': 2, + '𑌞𑍍': 2, + '𑌟𑍍': 2, + '𑌣𑍍': 2, + '𑌤𑍍': 2, + '𑌦𑍍': 2, + '𑌧𑍍': 2, + '𑌨𑍍': 2, + '𑌪𑍍': 2, + '𑌬𑍍': 2, + '𑌭𑍍': 2, + '𑌮𑍍': 2, + '𑌯𑍍': 2, + '𑌰𑍍': 2, + '𑌲𑍍': 2, + '𑌵𑍍': 2, + '𑌶𑍍': 2, + '𑌷𑍍': 2, + '𑌸𑍍': 2, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_97904ece.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_97904ece.py new file mode 100644 index 0000000000000000000000000000000000000000..e9ddaf7a44d5468e975fb8eb44dda28973e2e931 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_97904ece.py @@ -0,0 +1,2571 @@ +""" +Grapheme overrides for _known_97904ece. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: pterm +""" +# pylint: skip-file +GRAPHEMES = { + '؁۱': 1, + 'क्का': 3, + 'क्कां': 3, + 'क्को': 3, + 'क्घ्घि्': 4, + 'क्ता': 3, + 'क्ति': 3, + 'क्ती': 3, + 'क्तीं': 3, + 'क्तेः': 3, + 'क्त्योः': 5, + 'क्ना': 3, + 'क्नि': 3, + 'क्या': 3, + 'क्रा': 3, + 'क्रि': 3, + 'क्षा': 3, + 'क्षां': 3, + 'क्षाः': 4, + 'क्षि': 3, + 'क्षो': 3, + 'क्ष्ण': 3, + 'क्ष्य': 3, + 'क्ष्या': 4, + 'क्सा': 3, + 'ख्यः': 3, + 'ख्या': 3, + 'ग्या': 3, + 'ग्यैः': 3, + 'ग्र्य': 3, + 'घ्का': 3, + 'घ्र्व्य': 4, + 'घ्लि': 3, + 'घ्श्य': 3, + 'घ्स्ट': 3, + 'च्चा': 3, + 'च्चों': 3, + 'च्छा': 3, + 'च्छि': 3, + 'च्या': 3, + 'च्यां': 3, + 'च्यो': 3, + 'ज्ञा': 3, + 'ज्या': 3, + 'ज्या‌': 3, + 'ज्रा': 3, + 'ञ्चा': 3, + 'ञ्चि': 3, + 'ट्टि': 3, + 'ट्टी': 3, + 'ट्या': 3, + 'ट्रा': 3, + 'ण्डः': 3, + 'ण्डि': 3, + 'ण्या': 3, + 'ण्यां': 3, + 'ताः': 3, + 'त्का': 3, + 'त्ता': 3, + 'त्ति': 3, + 'त्त्थि': 4, + 'त्त्व': 3, + 'त्त्वा': 4, + 'त्त्वे': 3, + 'त्नी': 3, + 'त्नों': 3, + 'त्पा': 3, + 'त्पी': 3, + 'त्मा': 3, + 'त्या': 3, + 'त्यां': 3, + 'त्यि': 3, + 'त्रा': 3, + 'त्राा': 4, + 'त्राि': 4, + 'त्रि': 3, + 'त्री': 3, + 'त्र्त': 3, + 'त्र्य': 3, + 'त्र्या': 4, + 'त्र्ये': 3, + 'त्वा': 3, + 'त्वां': 3, + 'त्सा': 3, + 'त्सो': 3, + 'त्स्वा': 4, + 'द्घि': 3, + 'द्घो': 3, + 'द्दा': 3, + 'द्दि': 3, + 'द्दी': 3, + 'द्धः': 3, + 'द्धा': 3, + 'द्धां': 3, + 'द्धि': 3, + 'द्धिं': 3, + 'द्धी': 3, + 'द्धीं': 3, + 'द्धैः': 3, + 'द्भा': 3, + 'द्या': 3, + 'द्रो': 3, + 'द्वा': 3, + 'द्वि': 3, + 'धाः': 3, + 'ध्या': 3, + 'नाः': 3, + 'निः': 3, + 'न्का': 3, + 'न्चि': 3, + 'न्ञ्या': 4, + 'न्तः': 3, + 'न्ता': 3, + 'न्ति': 3, + 'न्तो': 3, + 'न्तों': 3, + 'न्त्र': 3, + 'न्त्रा': 4, + 'न्त्राः': 5, + 'न्त्रि': 4, + 'न्त्री': 4, + 'न्त्र्य': 4, + 'न्त्र्यं': 4, + 'न्त्र्या': 5, + 'न्त्र्ये': 4, + 'न्दा': 3, + 'न्दी': 3, + 'न्दो': 3, + 'न्धा': 3, + 'न्धि': 3, + 'न्धी': 3, + 'न्धों': 3, + 'न्ना': 3, + 'न्नाः': 4, + 'न्नि': 3, + 'न्मा': 3, + 'न्या': 3, + 'न्यो': 3, + 'न्हा': 3, + 'न्ह्यां': 4, + 'प्ति': 3, + 'प्तौ': 3, + 'प्या': 3, + 'प्रा': 3, + 'फ्ता': 3, + 'फ्ना': 3, + 'फ्नो': 3, + 'फ्रां': 3, + 'ब्धि': 3, + 'भिः': 3, + 'भ्यः': 3, + 'भ्या': 3, + 'भ्यां': 3, + 'भ्यो': 3, + 'म्ति': 3, + 'म्नि': 3, + 'म्पा': 3, + 'म्प्र': 3, + 'म्भि': 3, + 'म्मा': 3, + 'म्मि': 3, + 'म्या': 3, + 'म्ही': 3, + 'म्हो': 3, + 'याः': 3, + 'य्यो': 3, + 'राः': 3, + 'र्कि': 3, + 'र्गी': 3, + 'र्चि': 3, + 'र्जा': 3, + 'र्जि': 3, + 'र्जी': 3, + 'र्णां': 3, + 'र्णी': 3, + 'र्ता': 3, + 'र्ति': 3, + 'र्तिः': 4, + 'र्ती': 3, + 'र्त्त': 3, + 'र्त्ति': 4, + 'र्थि': 3, + 'र्थी': 3, + 'र्दा': 3, + 'र्दि': 3, + 'र्दो': 3, + 'र्द्ध': 3, + 'र्धा': 3, + 'र्धि': 3, + 'र्नि': 3, + 'र्बा': 3, + 'र्भा': 3, + 'र्मा': 3, + 'र्मि': 3, + 'र्या': 3, + 'र्यां': 3, + 'र्यों': 3, + 'र्रा': 3, + 'र्वा': 3, + 'र्वां': 3, + 'र्वो': 3, + 'र्सा': 3, + 'र्हाः': 4, + 'र्हि': 3, + 'र्हो': 3, + 'र्‍या': 3, + 'लाः': 3, + 'ल्का': 3, + 'ल्पि': 3, + 'ल्या': 3, + 'ल्यां': 3, + 'ल्याः': 4, + 'ल्ला': 3, + 'ल्लि': 3, + 'वाः': 3, + 'व्या': 3, + 'व्यों': 3, + 'शाः': 3, + 'श्चि': 3, + 'श्या': 3, + 'श्यि': 3, + 'श्यों': 3, + 'श्रा': 3, + 'श्रां': 3, + 'श्वा': 3, + 'श्वि': 3, + 'षाः': 3, + 'ष्का': 3, + 'ष्टः': 3, + 'ष्टा': 3, + 'ष्टां': 3, + 'ष्टाः': 4, + 'ष्टि': 3, + 'ष्टी': 3, + 'ष्टीं': 3, + 'ष्ट्र': 3, + 'ष्ट्रा': 4, + 'ष्ट्रां': 4, + 'ष्ट्रि': 4, + 'ष्ट्री': 4, + 'ष्ट्रे': 3, + 'ष्ट्रो': 4, + 'ष्ट्रों': 4, + 'ष्ठा': 3, + 'ष्ठों': 3, + 'ष्प्र': 3, + 'ष्यः': 3, + 'ष्यों': 3, + 'स्का': 3, + 'स्काः': 4, + 'स्ट्या': 4, + 'स्ता': 3, + 'स्ति': 3, + 'स्ती': 3, + 'स्तो': 3, + 'स्त्र': 3, + 'स्त्रा': 4, + 'स्त्रि': 4, + 'स्त्री': 4, + 'स्था': 3, + 'स्थां': 3, + 'स्थि': 3, + 'स्थी': 3, + 'स्थ्य': 3, + 'स्धी': 3, + 'स्मि': 3, + 'स्मिं': 3, + 'स्या': 3, + 'स्यां': 3, + 'स्याः': 4, + 'स्युः': 3, + 'स्यों': 3, + 'स्रो': 3, + 'स्वा': 3, + 'स्वी': 3, + 'स्सा': 3, + 'ह्या': 3, + 'ह्रा': 3, + 'फ़्ता': 3, + 'কিং': 3, + 'ক্তি': 3, + 'ক্রী': 3, + 'ক্ষা': 3, + 'ক্ষি': 3, + 'ক্ষে': 3, + 'ক্ষ্য': 3, + 'ক্ষ্যে': 4, + 'খ্যা': 3, + 'গ্রা': 3, + 'গ্রে': 3, + 'ঘো': 3, + 'ঙ্খা': 3, + 'ঙ্গী': 3, + 'ঙ্গে': 3, + 'চ্ছা': 3, + 'চ্ছা‌': 3, + 'চ্ছে': 3, + 'জ্ঞা': 3, + 'ঞ্চি': 3, + 'ঞ্ছি': 3, + 'ট্রে': 3, + 'ণ্ডে': 3, + 'ত্তা': 3, + 'ত্তি': 3, + 'ত্বে': 3, + 'ত্যা': 3, + 'ত্যি': 3, + 'ত্যে': 3, + 'ত্রা': 3, + 'ত্রে': 3, + 'ত্‍পী': 3, + 'ত্‍সা': 3, + 'দ্দি': 3, + 'দ্দে': 3, + 'দ্ধা': 3, + 'দ্ধি': 3, + 'দ্ধে': 3, + 'দ্বা': 3, + 'দ্রো': 3, + 'ধ্যে': 3, + 'ন্তা': 3, + 'ন্তি': 3, + 'ন্তে': 3, + 'ন্ত্রি': 4, + 'ন্ত্রে': 4, + 'ন্থী': 3, + 'ন্ধা': 3, + 'ন্মা': 3, + 'ন্যা': 3, + 'ন্যে': 3, + 'প্তা': 3, + 'প্রা': 3, + 'ব্ধি': 3, + 'ব্যা': 3, + 'ভ্রা': 3, + 'ম্পা': 3, + 'ম্মা': 3, + 'রাং': 3, + 'র্জা': 3, + 'র্থে': 3, + 'র্দো': 3, + 'র্ধা': 3, + 'র্নী': 3, + 'র্বা': 3, + 'র্বি': 3, + 'র্বো': 3, + 'র্ব্য': 3, + 'র্মে': 3, + 'র্যা': 3, + 'ল্যা': 3, + 'ল্যে': 3, + 'ল্লে': 3, + 'শ্চি': 3, + 'শ্বা': 3, + 'শ্বে': 3, + 'শ্যে': 3, + 'শ্রা': 3, + 'ষ্টা': 3, + 'ষ্টি': 3, + 'ষ্ট্র': 3, + 'ষ্ট্রী': 4, + 'ষ্ট্রে': 4, + 'ষ্ঠা': 3, + 'ষ্ঠি': 3, + 'ষ্ঠী': 3, + 'সাং': 3, + 'স্তি': 3, + 'স্তি‌': 3, + 'স্ত্র': 3, + 'স্থা': 3, + 'স্থ্য': 3, + 'স্বা': 3, + 'স্বী': 3, + 'স্যা': 3, + 'স্যে': 3, + 'ક્કા': 3, + 'ક્કો': 3, + 'ક્તિ': 3, + 'ક્ષા': 3, + 'ચ્ચા': 3, + 'ચ્છા': 3, + 'જ્ઞા': 3, + 'જ્યો': 3, + 'ત્તા': 3, + 'ત્તિ': 3, + 'ત્ત્વ': 3, + 'ત્ત્વા': 4, + 'ત્યા': 3, + 'ત્યાં': 3, + 'ત્યિ': 3, + 'ત્યો': 3, + 'ત્રી': 3, + 'ત્ર્ય': 3, + 'દ્ધા': 3, + 'દ્ધાં': 3, + 'દ્ધિ': 3, + 'દ્વા': 3, + 'ધ્યા': 3, + 'ન્તો': 3, + 'ન્મા': 3, + 'ન્યા': 3, + 'પ્રા': 3, + 'મ્યાં': 3, + 'ર્તા': 3, + 'ર્થિ': 3, + 'ર્દો': 3, + 'ર્મિ': 3, + 'ર્યા': 3, + 'ર્યો': 3, + 'વ્યા': 3, + 'વ્યો': 3, + 'ષ્ટિ': 3, + 'ષ્ટ્ર': 3, + 'ષ્ટ્રી': 4, + 'ષ્ટ્રો': 4, + 'ષ્ઠા': 3, + 'સ્તિ': 3, + 'સ્તી': 3, + 'સ્ત્રી': 4, + 'સ્થા': 3, + 'સ્થિ': 3, + 'સ્રી': 3, + 'સ્વા': 3, + 'સ્વી': 3, + 'સ્સા': 3, + 'కుం': 3, + 'క్కు': 3, + 'క్తు': 3, + 'క్రాం': 3, + 'క్రూ': 3, + 'క్షిం': 3, + 'క్స్వా': 3, + 'చ్చు': 3, + 'టుం': 3, + 'ట్లు': 3, + 'డ్రు': 3, + 'త్తు': 3, + 'త్నిం': 3, + 'త్యం': 3, + 'త్రు': 3, + 'త్ర్య': 3, + 'దుం': 3, + 'ద్దు': 3, + 'ద్ధిం': 3, + 'ద్ర్య': 3, + 'నుం': 3, + 'న్ను': 3, + 'భ్యు': 3, + 'యుం': 3, + 'ర్చు': 3, + 'ర్ణాం': 3, + 'ర్ణు': 3, + 'ర్తిం': 3, + 'ర్తృ': 3, + 'ర్థిం': 3, + 'ర్బం': 3, + 'ర్హాం': 3, + 'ర్హు': 3, + 'శ్రాం': 3, + 'ష్టు': 3, + 'ష్ట్ర': 3, + 'ష్ట్రీ': 3, + 'ష్ఠు': 3, + 'స్కృ': 3, + 'స్త్ర': 3, + 'స్త్రీ': 3, + 'స్థ్య': 3, + 'ಕಾಂ': 3, + 'ಕುಂ': 3, + 'ಕೊಂ': 3, + 'ಖಾಂ': 3, + 'ಗಾಂ': 3, + 'ಗೊಂ': 3, + 'ಟುಂ': 3, + 'ನಾಂ': 3, + 'ಯುಂ': 3, + 'ರಾಂ': 3, + 'ವುಂ': 3, + 'ಶಾಂ': 3, + 'ಸಾಂ': 3, + 'ಹೊಂ': 3, + 'ക്കാ': 3, + 'ക്കി': 3, + 'ക്കും': 3, + 'ക്കെ': 3, + 'ക്കേ': 3, + 'ക്കൊ': 3, + 'ക്കോ': 3, + 'ക്തി': 3, + 'ക്യം': 3, + 'ക്ഷാ': 3, + 'ക്ഷി': 3, + 'ക്ഷേ': 3, + 'ഖ്യാ': 3, + 'ഗ്ഗം': 3, + 'ഗ്ദാ': 3, + 'ഗ്യം': 3, + 'ങ്കി': 3, + 'ങ്കെ': 3, + 'ങ്കേ': 3, + 'ങ്ങി': 3, + 'ച്ചി': 3, + 'ച്ചും': 3, + 'ച്ചെ': 3, + 'ച്ചേ': 3, + 'ജ്യാ': 3, + 'ഞ്ഞി': 3, + 'ഞ്ഞെ': 3, + 'ട്ടാ': 3, + 'ട്ടി': 3, + 'ട്ടോ': 3, + 'ണ്ടാ': 3, + 'ണ്ടി': 3, + 'ണ്ടും': 3, + 'ണ്ടെ': 3, + 'ത്താ': 3, + 'ത്തി': 3, + 'ത്തും': 3, + 'ത്തെ': 3, + 'ത്തേ': 3, + 'ത്തോ': 3, + 'ത്നം': 3, + 'ത്നി': 3, + 'ത്യാ': 3, + 'ത്യേ': 3, + 'ത്വം': 3, + 'ദ്ധി': 3, + 'ദ്യാ': 3, + 'ന്തം': 3, + 'ന്തെ': 3, + 'ന്ത്ര': 3, + 'ന്ത്ര്യ': 4, + 'ന്ത്ര്യം': 5, + 'ന്ധി': 3, + 'ന്നാ': 3, + 'ന്നി': 3, + 'ന്നീ': 3, + 'ന്നും': 3, + 'ന്നെ': 3, + 'ന്നേ': 3, + 'ന്നോ': 3, + 'ന്മാ': 3, + 'ന്യം': 3, + 'ന്യാ': 3, + 'ന്യേ': 3, + 'ന്യോ': 3, + 'ന്റെ': 3, + 'ന്‍പി': 3, + 'പ്പി': 3, + 'പ്പെ': 3, + 'പ്പോ': 3, + 'പ്രാ': 3, + 'ബ്ലി': 3, + 'ഭ്യാ': 3, + 'ഭ്രാ': 3, + 'മ്പാ': 3, + 'മ്പ്ര': 3, + 'മ്മി': 3, + 'യ്ക്കു': 3, + 'യ്തി': 3, + 'യ്യാ': 3, + 'യ്യി': 3, + 'ര്യം': 3, + 'ര്‍ക്കു': 3, + 'ര്‍ക്കും': 4, + 'ര്‍ക്ക്‌': 3, + 'ര്‍ഗ്ഗം': 4, + 'ര്‍ച്ച': 3, + 'ര്‍ണ്ണ': 3, + 'ര്‍ത്ത': 3, + 'ര്‍ത്തി': 4, + 'ര്‍ത്തു': 3, + 'ര്‍ത്തേ': 4, + 'ര്‍ദേ': 3, + 'ര്‍ദ്ദ': 3, + 'ര്‍പ്പെ': 4, + 'ര്‍മ്മി': 4, + 'ര്‍രാ': 3, + 'ര്‍വ്വ': 3, + 'ര്‍ഹി': 3, + 'റ്റം': 3, + 'റ്റേ': 3, + 'ല്യാ': 3, + 'ല്ലാ': 3, + 'ല്ലാം': 4, + 'ല്ലെ': 3, + 'ല്‍കി': 3, + 'ല്‍കേ': 3, + 'ല്‍നി': 3, + 'ല്‍പ്പ': 3, + 'ള്ളാ': 3, + 'ള്ളി': 3, + 'ള്‍കൊ': 3, + 'ള്‍ക്ക': 3, + 'ള്‍ക്കി': 4, + 'ള്‍ക്കു': 3, + 'ള്‍ക്കും': 4, + 'ള്‍ക്കെ': 4, + 'ള്‍ക്ക്‌': 3, + 'വ്യം': 3, + 'വ്യാ': 3, + 'ശ്വാ': 3, + 'ഷ്ട്യാ': 4, + 'ഷ്ട്ര': 3, + 'ഷ്ട്രീ': 4, + 'ഷ്യാ': 3, + 'സാം': 3, + 'സ്കാ': 3, + 'സ്ത്രം': 4, + 'സ്ത്രീ': 4, + 'സ്ഥാ': 3, + 'സ്ഥി': 3, + 'സ്റ്റ്‌': 3, + 'സ്വാ': 3, + 'സ്വീ': 3, + 'സ്സാ': 3, + 'സ്സി': 3, + 'സ്സും': 3, + 'സ്സോ': 3, + 'ഹിം': 3, + 'ကျေ': 3, + 'ကြေ': 3, + 'ကြွေ': 3, + 'ချေ': 3, + 'ခြေ': 3, + 'ဇြေ': 3, + 'ဒ္ဂေ': 3, + 'ပျေ': 3, + 'ပြေ': 3, + 'ဖျေံ': 3, + 'ဗ္တေ': 3, + 'ဗ္ၜေ': 3, + 'ဗြေ': 3, + 'မြေ': 3, + 'လျေ': 3, + 'လျှေ': 3, + 'သ္ဂေ': 3, + 'ក្ដៅ': 3, + 'ក្រោ': 3, + 'ក្សា': 3, + 'ខ្ជា': 3, + 'ខ្លា': 3, + 'គ្នា': 3, + 'គ្មា': 3, + 'គ្រា': 3, + 'គ្រឹះ': 3, + 'ង្កើ': 3, + 'ង្រៀ': 3, + 'ង្ហា': 3, + 'ច្ចេ': 3, + 'ច្បា': 3, + 'ឆ្នាំ': 3, + 'ឆ្នោ': 3, + 'ឆ្លើ': 3, + 'ជ្ជា': 3, + 'ជ្ញា': 3, + 'ជ្រើ': 3, + 'ជ្រៀ': 3, + 'ជ្រែ': 3, + 'ឈ្មោះ': 4, + 'ញ្ជា': 3, + 'ញ្ញា': 3, + 'ញ្ញៈ': 3, + 'ដ្ឋា': 3, + 'ណោះ': 3, + 'ណ្ដា': 3, + 'ណ្ដុះ': 3, + 'ណ្ណោះ': 4, + 'ត្រា': 3, + 'ថ្ងៃ': 3, + 'ថ្នា': 3, + 'ថ្លៃ': 3, + 'ទោះ': 3, + 'ទ្យា': 3, + 'ធ្នា': 3, + 'ធ្យា': 3, + 'ធ្យោ': 3, + 'ធ្វើ': 3, + 'នេះ': 3, + 'នោះ': 3, + 'ន្ថែ': 3, + 'ន្ថោ': 3, + 'ន្ទា': 3, + 'ន្ទៈ': 3, + 'ន្យា': 3, + 'ន្លែ': 3, + 'បោះ': 3, + 'ប្ដេ': 3, + 'ប្រា': 3, + 'ប្រើ': 3, + 'ប្រែ': 3, + 'ផ្ដា': 3, + 'ផ្ទា': 3, + 'ផ្ទេ': 3, + 'ផ្នែ': 3, + 'ផ្លា': 3, + 'ផ្សា': 3, + 'ផ្សេ': 3, + 'ផ្សៃ': 3, + 'ពោះ': 3, + 'ព្យា': 3, + 'ព្រៀ': 3, + 'ព្រៃ': 3, + 'ម្ងា': 3, + 'ម្ចា': 3, + 'ម្ដា': 3, + 'ម្ដែ': 3, + 'ម្នា': 3, + 'ម្នេ': 3, + 'ម្ភា': 3, + 'ម្រា': 3, + 'ម្រើ': 3, + 'ម្រេ': 3, + 'ម្លៀ': 3, + 'ម្លៃ': 3, + 'ល្បៈ': 3, + 'ល្មើ': 3, + 'ស្គា': 3, + 'ស្ដ្រី': 3, + 'ស្ត្រ': 3, + 'ស្ថា': 3, + 'ស្នា': 3, + 'ស្មា': 3, + 'ស្មើ': 3, + 'ស្រា': 3, + 'ស្លា': 3, + 'ស្វែ': 3, + 'ᨣᩕᩮ᩠': 3, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 3, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 3, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 3, + '⛓️‍💥': 3, + '⛹🏻‍♀️': 4, + '⛹🏻‍♂️': 4, + '⛹🏼‍♀️': 4, + '⛹🏼‍♂️': 4, + '⛹🏽‍♀️': 4, + '⛹🏽‍♂️': 4, + '⛹🏾‍♀️': 4, + '⛹🏾‍♂️': 4, + '⛹🏿‍♀️': 4, + '⛹🏿‍♂️': 4, + '❤️‍🔥': 3, + '❤️‍🩹': 3, + 'ꦏꦺꦴ': 3, + 'ꦏ꧀': 2, + 'ꦏ꧀ꦏ': 3, + 'ꦏ꧀ꦏꦁ': 3, + 'ꦏ꧀ꦏꦺ': 4, + 'ꦏ꧀ꦏꦼ': 3, + 'ꦏ꧀ꦔ': 3, + 'ꦏ꧀ꦔꦸ': 3, + 'ꦏ꧀ꦔꦿ': 4, + 'ꦏ꧀ꦕ': 3, + 'ꦏ꧀ꦠ': 3, + 'ꦏ꧀ꦠꦶ': 3, + 'ꦏ꧀ꦠꦸ': 3, + 'ꦏ꧀ꦠꦺ': 4, + 'ꦏ꧀ꦢ': 3, + 'ꦏ꧀ꦢꦂ': 3, + 'ꦏ꧀ꦢꦶ': 3, + 'ꦏ꧀ꦤ': 3, + 'ꦏ꧀ꦤꦶꦁ': 3, + 'ꦏ꧀ꦥ': 3, + 'ꦏ꧀ꦥꦶ': 3, + 'ꦏ꧀ꦥꦿꦶ': 4, + 'ꦏ꧀ꦧ': 3, + 'ꦏ꧀ꦧꦶ': 3, + 'ꦏ꧀ꦧꦺ': 4, + 'ꦏ꧀ꦩ': 3, + 'ꦏ꧀ꦩꦸ': 3, + 'ꦏ꧀ꦪ': 3, + 'ꦏ꧀ꦭ': 3, + 'ꦏ꧀ꦮ': 3, + 'ꦏ꧀ꦱ': 3, + 'ꦏ꧀ꦱꦂ': 3, + 'ꦏ꧀ꦱꦶ': 3, + 'ꦏ꧀ꦱꦸ': 3, + 'ꦏ꧀ꦱꦺ': 4, + 'ꦏ꧀ꦲ': 3, + 'ꦏ꧀ꦲꦁ': 3, + 'ꦏ꧀ꦲꦶꦁ': 3, + 'ꦏ꧀ꦲꦸ': 3, + 'ꦏ꧀ꦲꦺ': 4, + 'ꦏ꧀ꦲꦺꦴ': 5, + 'ꦒꦺꦴ': 3, + 'ꦒꦿꦺ': 3, + 'ꦒ꧀ꦒ': 3, + 'ꦔꦺꦴ': 3, + 'ꦔ꧀ꦒꦼ': 3, + 'ꦔ꧀ꦒꦿꦼꦁ': 4, + 'ꦔ꧀ꦭ': 3, + 'ꦔ꧀ꦭꦁ': 3, + 'ꦔ꧀ꦭꦸ': 3, + 'ꦔ꧀ꦭꦼ': 3, + 'ꦕꦺꦴ': 3, + 'ꦗꦿꦺꦴ': 4, + 'ꦚ꧀ꦕ': 3, + 'ꦚ꧀ꦕꦶ': 3, + 'ꦚ꧀ꦗ': 3, + 'ꦚ꧀ꦗꦶ': 3, + 'ꦚ꧀ꦗꦸꦁ': 3, + 'ꦚ꧀ꦗꦸꦂ': 3, + 'ꦝꦺꦴ': 3, + 'ꦝꦺꦴꦂ': 3, + 'ꦠꦺꦃ': 3, + 'ꦠꦺꦴ': 3, + 'ꦠ꧀': 2, + 'ꦠ꧀ꦏꦁ': 3, + 'ꦠ꧀ꦏꦸ': 3, + 'ꦠ꧀ꦒ': 3, + 'ꦠ꧀ꦔꦸ': 3, + 'ꦠ꧀ꦚ': 3, + 'ꦠ꧀ꦠ': 3, + 'ꦠ꧀ꦠꦶ': 3, + 'ꦠ꧀ꦠꦶꦁ': 3, + 'ꦠ꧀ꦠꦸ': 3, + 'ꦠ꧀ꦠꦺ': 4, + 'ꦠ꧀ꦤ': 3, + 'ꦠ꧀ꦤꦶ': 3, + 'ꦠ꧀ꦩ': 3, + 'ꦠ꧀ꦩꦼ': 3, + 'ꦠ꧀ꦭ': 3, + 'ꦠ꧀ꦭꦺ': 4, + 'ꦠ꧀ꦱ': 3, + 'ꦠ꧀ꦱꦶꦁ': 3, + 'ꦠ꧀ꦱꦶꦃ': 4, + 'ꦠ꧀ꦱꦾ': 4, + 'ꦠ꧀ꦱ꧀ꦮ': 5, + 'ꦠ꧀ꦲ': 3, + 'ꦠ꧀ꦲꦶꦁ': 3, + 'ꦠ꧀ꦲꦺꦴ': 5, + 'ꦢꦺꦴ': 3, + 'ꦢ꧀': 2, + 'ꦢ꧀ꦏ': 3, + 'ꦢ꧀ꦠ': 3, + 'ꦢ꧀ꦠꦶꦁ': 3, + 'ꦢ꧀ꦢ': 3, + 'ꦢ꧀ꦥ': 3, + 'ꦢ꧀ꦩꦺꦴ': 5, + 'ꦢ꧀ꦲ': 3, + 'ꦤꦺꦃ': 3, + 'ꦤꦺꦴ': 3, + 'ꦤ꧀': 2, + 'ꦤ꧀ꦏ': 3, + 'ꦤ꧀ꦏꦁ': 3, + 'ꦤ꧀ꦏꦸ': 3, + 'ꦤ꧀ꦏꦼ': 3, + 'ꦤ꧀ꦒ': 3, + 'ꦤ꧀ꦔ': 3, + 'ꦤ꧀ꦔꦁ': 3, + 'ꦤ꧀ꦔꦶ': 3, + 'ꦤ꧀ꦔꦸ': 3, + 'ꦤ꧀ꦔꦸꦂ': 3, + 'ꦤ꧀ꦔꦺ': 4, + 'ꦤ꧀ꦔꦼ': 3, + 'ꦤ꧀ꦔꦿꦸ': 4, + 'ꦤ꧀ꦗ': 3, + 'ꦤ꧀ꦗꦸ': 3, + 'ꦤ꧀ꦗꦼ': 3, + 'ꦤ꧀ꦚꦶ': 3, + 'ꦤ꧀ꦛꦃ': 4, + 'ꦤ꧀ꦛꦶ': 3, + 'ꦤ꧀ꦝ': 3, + 'ꦤ꧀ꦝꦁ': 3, + 'ꦤ꧀ꦝꦶ': 3, + 'ꦤ꧀ꦝꦸ': 3, + 'ꦤ꧀ꦝꦸꦁ': 3, + 'ꦤ꧀ꦝꦺꦁ': 4, + 'ꦤ꧀ꦝꦺꦴꦁ': 5, + 'ꦤ꧀ꦝꦼ': 3, + 'ꦤ꧀ꦠ': 3, + 'ꦤ꧀ꦠꦂ': 3, + 'ꦤ꧀ꦠꦃ': 4, + 'ꦤ꧀ꦠꦶ': 3, + 'ꦤ꧀ꦠꦸ': 3, + 'ꦤ꧀ꦠꦸꦁ': 3, + 'ꦤ꧀ꦠꦺ': 4, + 'ꦤ꧀ꦠꦼ': 3, + 'ꦤ꧀ꦠꦼꦂ': 3, + 'ꦤ꧀ꦠꦽ': 3, + 'ꦤ꧀ꦢ': 3, + 'ꦤ꧀ꦢꦁ': 3, + 'ꦤ꧀ꦢꦂ': 3, + 'ꦤ꧀ꦢꦶ': 3, + 'ꦤ꧀ꦢꦸ': 3, + 'ꦤ꧀ꦢꦺ': 4, + 'ꦤ꧀ꦢꦼ': 3, + 'ꦤ꧀ꦤ': 3, + 'ꦤ꧀ꦤꦶ': 3, + 'ꦤ꧀ꦤꦶꦁ': 3, + 'ꦤ꧀ꦤꦺ': 4, + 'ꦤ꧀ꦤꦼ': 3, + 'ꦤ꧀ꦥ': 3, + 'ꦤ꧀ꦥꦁ': 3, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 5, + 'ꦤ꧀ꦥꦶ': 3, + 'ꦤ꧀ꦥꦸ': 3, + 'ꦤ꧀ꦥꦼ': 3, + 'ꦤ꧀ꦥꦿ': 4, + 'ꦤ꧀ꦥꦿꦶ': 4, + 'ꦤ꧀ꦧ': 3, + 'ꦤ꧀ꦧꦁ': 3, + 'ꦤ꧀ꦧꦶ': 3, + 'ꦤ꧀ꦧꦸ': 3, + 'ꦤ꧀ꦧꦺ': 4, + 'ꦤ꧀ꦧꦺꦴ': 5, + 'ꦤ꧀ꦧꦼ': 3, + 'ꦤ꧀ꦩ': 3, + 'ꦤ꧀ꦩꦂ': 3, + 'ꦤ꧀ꦩꦶ': 3, + 'ꦤ꧀ꦩꦸꦂ': 3, + 'ꦤ꧀ꦩꦼ': 3, + 'ꦤ꧀ꦭ': 3, + 'ꦤ꧀ꦭꦶ': 3, + 'ꦤ꧀ꦭꦸ': 3, + 'ꦤ꧀ꦮ': 3, + 'ꦤ꧀ꦮꦂ': 3, + 'ꦤ꧀ꦮꦶ': 3, + 'ꦤ꧀ꦮꦸ': 3, + 'ꦤ꧀ꦮꦼ': 3, + 'ꦤ꧀ꦱ': 3, + 'ꦤ꧀ꦱꦂ': 3, + 'ꦤ꧀ꦱꦃ': 4, + 'ꦤ꧀ꦱꦶ': 3, + 'ꦤ꧀ꦱꦶꦁ': 3, + 'ꦤ꧀ꦱꦸ': 3, + 'ꦤ꧀ꦱꦺꦴ': 5, + 'ꦤ꧀ꦱꦼ': 3, + 'ꦤ꧀ꦲ': 3, + 'ꦤ꧀ꦲꦁ': 3, + 'ꦤ꧀ꦲꦶ': 3, + 'ꦤ꧀ꦲꦶꦁ': 3, + 'ꦤ꧀ꦲꦸ': 3, + 'ꦤ꧀ꦲꦺꦴ': 5, + 'ꦥ꦳꧀': 2, + 'ꦥꦺꦴ': 3, + 'ꦥꦿꦃ': 3, + 'ꦥꦿꦺꦴ': 4, + 'ꦥ꧀': 2, + 'ꦥ꧀ꦏ': 3, + 'ꦥ꧀ꦏꦁ': 3, + 'ꦥ꧀ꦠ': 3, + 'ꦥ꧀ꦠꦶ': 3, + 'ꦥ꧀ꦢꦸ': 3, + 'ꦥ꧀ꦤ': 3, + 'ꦥ꧀ꦤꦶ': 3, + 'ꦥ꧀ꦥ': 3, + 'ꦥ꧀ꦥꦶ': 3, + 'ꦥ꧀ꦥꦺ': 4, + 'ꦥ꧀ꦧꦺ': 4, + 'ꦥ꧀ꦩ': 3, + 'ꦥ꧀ꦩꦂ': 3, + 'ꦥ꧀ꦫꦺ': 4, + 'ꦥ꧀ꦭ': 3, + 'ꦥ꧀ꦭꦸ': 3, + 'ꦥ꧀ꦱ': 3, + 'ꦥ꧀ꦱꦶꦂ': 3, + 'ꦥ꧀ꦱꦼ': 3, + 'ꦥ꧀ꦲ': 3, + 'ꦧꦺꦃ': 3, + 'ꦧꦺꦴ': 3, + 'ꦧ꧀': 2, + 'ꦧ꧀ꦏ': 3, + 'ꦧ꧀ꦠꦸ': 3, + 'ꦧ꧀ꦥ': 3, + 'ꦧ꧀ꦧ': 3, + 'ꦧ꧀ꦧꦺ': 4, + 'ꦧ꧀ꦲ': 3, + 'ꦧ꧀ꦲꦶ': 3, + 'ꦩꦺꦃ': 3, + 'ꦩꦺꦴ': 3, + 'ꦩꦿꦃ': 3, + 'ꦩꦿꦶꦃ': 3, + 'ꦩ꧀': 2, + 'ꦩ꧀ꦏꦁ': 3, + 'ꦩ꧀ꦔꦼ': 3, + 'ꦩ꧀ꦠꦸ': 3, + 'ꦩ꧀ꦠꦺꦴ': 5, + 'ꦩ꧀ꦤꦶꦁ': 3, + 'ꦩ꧀ꦥ': 3, + 'ꦩ꧀ꦥꦶ': 3, + 'ꦩ꧀ꦥꦸ': 3, + 'ꦩ꧀ꦥꦼ': 3, + 'ꦩ꧀ꦧ': 3, + 'ꦩ꧀ꦧꦁ': 3, + 'ꦩ꧀ꦧꦂ': 3, + 'ꦩ꧀ꦧꦃ': 4, + 'ꦩ꧀ꦧꦶ': 3, + 'ꦩ꧀ꦧꦸ': 3, + 'ꦩ꧀ꦧꦸꦁ': 3, + 'ꦩ꧀ꦧꦺ': 4, + 'ꦩ꧀ꦧꦺꦂ': 4, + 'ꦩ꧀ꦧꦼꦂ': 3, + 'ꦩ꧀ꦧꦾꦸꦂ': 4, + 'ꦩ꧀ꦩ': 3, + 'ꦩ꧀ꦩꦶ': 3, + 'ꦩ꧀ꦫ': 3, + 'ꦩ꧀ꦫꦃ': 4, + 'ꦩ꧀ꦭ': 3, + 'ꦩ꧀ꦲꦶ': 3, + 'ꦪꦺꦴ': 3, + 'ꦫꦺꦴ': 3, + 'ꦭꦺꦃ': 3, + 'ꦭꦺꦴ': 3, + 'ꦭꦺꦴꦁ': 3, + 'ꦭ꧀': 2, + 'ꦭ꧀ꦏꦁ': 3, + 'ꦭ꧀ꦚꦼꦁ': 3, + 'ꦭ꧀ꦠꦸ': 3, + 'ꦭ꧀ꦧꦸ': 3, + 'ꦭ꧀ꦩꦸ': 3, + 'ꦭ꧀ꦭ': 3, + 'ꦭ꧀ꦭꦶ': 3, + 'ꦭ꧀ꦭꦶꦁ': 3, + 'ꦭ꧀ꦭꦺ': 4, + 'ꦭ꧀ꦮ': 3, + 'ꦭ꧀ꦱ': 3, + 'ꦭ꧀ꦱꦂ': 3, + 'ꦭ꧀ꦱꦶꦁ': 3, + 'ꦭ꧀ꦱꦸ': 3, + 'ꦭ꧀ꦲ': 3, + 'ꦭ꧀ꦲꦁ': 3, + 'ꦭ꧀ꦲꦶꦁ': 3, + 'ꦭ꧀ꦲꦸ': 3, + 'ꦮꦺꦴ': 3, + 'ꦮꦺꦴꦁ': 3, + 'ꦮꦺꦴꦃ': 4, + 'ꦮꦿꦸꦃ': 3, + 'ꦱꦺꦴ': 3, + 'ꦱꦿꦃ': 3, + 'ꦱ꧀': 2, + 'ꦱ꧀ꦏ': 3, + 'ꦱ꧀ꦏꦁ': 3, + 'ꦱ꧀ꦏꦿꦶ': 4, + 'ꦱ꧀ꦒ': 3, + 'ꦱ꧀ꦔꦸ': 3, + 'ꦱ꧀ꦔꦿ': 4, + 'ꦱ꧀ꦛꦶ': 3, + 'ꦱ꧀ꦠ': 3, + 'ꦱ꧀ꦠꦿ': 4, + 'ꦱ꧀ꦢꦂ': 3, + 'ꦱ꧀ꦢꦶ': 3, + 'ꦱ꧀ꦢꦸ': 3, + 'ꦱ꧀ꦥ': 3, + 'ꦱ꧀ꦧ': 3, + 'ꦱ꧀ꦧꦁ': 3, + 'ꦱ꧀ꦩ': 3, + 'ꦱ꧀ꦩꦶ': 3, + 'ꦱ꧀ꦩꦼ': 3, + 'ꦱ꧀ꦩꦿ': 4, + 'ꦱ꧀ꦭ': 3, + 'ꦱ꧀ꦮ': 3, + 'ꦱ꧀ꦱ': 3, + 'ꦱ꧀ꦱꦂ': 3, + 'ꦱ꧀ꦱꦶ': 3, + 'ꦱ꧀ꦱꦶꦁ': 3, + 'ꦱ꧀ꦱꦸ': 3, + 'ꦱ꧀ꦱꦺ': 4, + 'ꦱ꧀ꦲ': 3, + 'ꦱ꧀ꦲꦁ': 3, + 'ꦱ꧀ꦲꦶ': 3, + 'ꦱ꧀ꦲꦶꦁ': 3, + 'ꦱ꧀ꦲꦸ': 3, + 'ꦲꦺꦴ': 3, + '𑄇𑄳𑄠𑄬': 3, + '𑄈𑄳𑄠𑄬': 3, + '𑄌𑄳𑄠𑄬': 3, + '𑄎𑄳𑄠𑄬': 3, + '𑄑𑄳𑄢𑄬': 3, + '𑄖𑄳𑄠𑄬': 3, + '𑄖𑄳𑄢𑄬': 3, + '𑄘𑄳𑄠𑄬': 3, + '𑄚𑄳𑄠𑄬': 3, + '𑄝𑄳𑄢𑄬': 3, + '𑄟𑄳𑄠𑄬': 3, + '𑄡𑄳𑄠𑄬': 3, + '𑄣𑄳𑄦𑄬': 3, + '𑌕𑌾𑌂': 3, + '𑌕𑌾𑌃': 3, + '𑌕𑍍': 2, + '𑌗𑍍': 2, + '𑌚𑍍': 2, + '𑌜𑍍': 2, + '𑌞𑍍': 2, + '𑌟𑌾𑌂': 3, + '𑌟𑌾𑌃': 3, + '𑌟𑍍': 2, + '𑌠𑍈𑌃': 3, + '𑌣𑌾𑌂': 3, + '𑌣𑍍': 2, + '𑌤𑌾𑌂': 3, + '𑌤𑌾𑌃': 3, + '𑌤𑌿𑌂': 3, + '𑌤𑌿𑌃': 3, + '𑌤𑍁𑌂': 3, + '𑌤𑍇𑌃': 3, + '𑌤𑍍': 2, + '𑌥𑌾𑌂': 3, + '𑌦𑍍': 2, + '𑌧𑌾𑌃': 3, + '𑌧𑌿𑌂': 3, + '𑌧𑍇𑌃': 3, + '𑌧𑍈𑌃': 3, + '𑌧𑍍': 2, + '𑌨𑌾𑌂': 3, + '𑌨𑌾𑌃': 3, + '𑌨𑌿𑌃': 3, + '𑌨𑍈𑌃': 3, + '𑌨𑍍': 2, + '𑌪𑍍': 2, + '𑌬𑍍': 2, + '𑌭𑌿𑌃': 3, + '𑌭𑍍': 2, + '𑌮𑌿𑌂': 3, + '𑌮𑍍': 2, + '𑌯𑌾𑌂': 3, + '𑌯𑌾𑌃': 3, + '𑌯𑍁𑌃': 3, + '𑌯𑍈𑌃': 3, + '𑌯𑍋𑌃': 3, + '𑌯𑍍': 2, + '𑌰𑌾𑌃': 3, + '𑌰𑌿𑌂': 3, + '𑌰𑍍': 2, + '𑌲𑌾𑌃': 3, + '𑌲𑌿𑌂': 3, + '𑌲𑍍': 2, + '𑌵𑌾𑌂': 3, + '𑌵𑌾𑌃': 3, + '𑌵𑍍': 2, + '𑌶𑌾𑌃': 3, + '𑌶𑍍': 2, + '𑌷𑌾𑌂': 3, + '𑌷𑌾𑌃': 3, + '𑌷𑍍': 2, + '𑌸𑌾𑌂': 3, + '𑌸𑍍': 2, + '𑌹𑌾𑌃': 3, + '🍄‍🟫': 4, + '🍋‍🟩': 4, + '🏃‍♀️': 3, + '🏃‍♀️‍➡️': 4, + '🏃‍♂️': 3, + '🏃‍♂️‍➡️': 4, + '🏃‍➡️': 3, + '🏃🏻‍♀️': 5, + '🏃🏻‍♀️‍➡️': 6, + '🏃🏻‍♂️': 5, + '🏃🏻‍♂️‍➡️': 6, + '🏃🏻‍➡️': 5, + '🏃🏼‍♀️': 5, + '🏃🏼‍♀️‍➡️': 6, + '🏃🏼‍♂️': 5, + '🏃🏼‍♂️‍➡️': 6, + '🏃🏼‍➡️': 5, + '🏃🏽‍♀️': 5, + '🏃🏽‍♀️‍➡️': 6, + '🏃🏽‍♂️': 5, + '🏃🏽‍♂️‍➡️': 6, + '🏃🏽‍➡️': 5, + '🏃🏾‍♀️': 5, + '🏃🏾‍♀️‍➡️': 6, + '🏃🏾‍♂️': 5, + '🏃🏾‍♂️‍➡️': 6, + '🏃🏾‍➡️': 5, + '🏃🏿‍♀️': 5, + '🏃🏿‍♀️‍➡️': 6, + '🏃🏿‍♂️': 5, + '🏃🏿‍♂️‍➡️': 6, + '🏃🏿‍➡️': 5, + '🏄‍♀️': 3, + '🏄‍♂️': 3, + '🏄🏻‍♀️': 5, + '🏄🏻‍♂️': 5, + '🏄🏼‍♀️': 5, + '🏄🏼‍♂️': 5, + '🏄🏽‍♀️': 5, + '🏄🏽‍♂️': 5, + '🏄🏾‍♀️': 5, + '🏄🏾‍♂️': 5, + '🏄🏿‍♀️': 5, + '🏄🏿‍♂️': 5, + '🏊‍♀️': 3, + '🏊‍♂️': 3, + '🏊🏻‍♀️': 5, + '🏊🏻‍♂️': 5, + '🏊🏼‍♀️': 5, + '🏊🏼‍♂️': 5, + '🏊🏽‍♀️': 5, + '🏊🏽‍♂️': 5, + '🏊🏾‍♀️': 5, + '🏊🏾‍♂️': 5, + '🏊🏿‍♀️': 5, + '🏊🏿‍♂️': 5, + '🏋🏻‍♀️': 4, + '🏋🏻‍♂️': 4, + '🏋🏼‍♀️': 4, + '🏋🏼‍♂️': 4, + '🏋🏽‍♀️': 4, + '🏋🏽‍♂️': 4, + '🏋🏾‍♀️': 4, + '🏋🏾‍♂️': 4, + '🏋🏿‍♀️': 4, + '🏋🏿‍♂️': 4, + '🏌🏻‍♀️': 4, + '🏌🏻‍♂️': 4, + '🏌🏼‍♀️': 4, + '🏌🏼‍♂️': 4, + '🏌🏽‍♀️': 4, + '🏌🏽‍♂️': 4, + '🏌🏾‍♀️': 4, + '🏌🏾‍♂️': 4, + '🏌🏿‍♀️': 4, + '🏌🏿‍♂️': 4, + '🏳️‍🌈': 3, + '🏴‍☠️': 3, + '🐈‍⬛': 4, + '🐕‍🦺': 4, + '🐦‍⬛': 4, + '🐦‍🔥': 4, + '🐻‍❄️': 3, + '👨‍⚕️': 3, + '👨‍⚖️': 3, + '👨‍✈️': 3, + '👨‍❤️‍👨': 5, + '👨‍❤️‍💋‍👨': 7, + '👨‍🌾': 4, + '👨‍🍳': 4, + '👨‍🍼': 4, + '👨‍🎓': 4, + '👨‍🎤': 4, + '👨‍🎨': 4, + '👨‍🏫': 4, + '👨‍🏭': 4, + '👨‍👦': 4, + '👨‍👦‍👦': 6, + '👨‍👧': 4, + '👨‍👧‍👦': 6, + '👨‍👧‍👧': 6, + '👨‍👨‍👦': 6, + '👨‍👨‍👦‍👦': 8, + '👨‍👨‍👧': 6, + '👨‍👨‍👧‍👦': 8, + '👨‍👨‍👧‍👧': 8, + '👨‍👩‍👦': 6, + '👨‍👩‍👦‍👦': 8, + '👨‍👩‍👧': 6, + '👨‍👩‍👧‍👦': 8, + '👨‍👩‍👧‍👧': 8, + '👨‍💻': 4, + '👨‍💼': 4, + '👨‍🔧': 4, + '👨‍🔬': 4, + '👨‍🚀': 4, + '👨‍🚒': 4, + '👨‍🦯': 4, + '👨‍🦯‍➡️': 5, + '👨‍🦰': 4, + '👨‍🦱': 4, + '👨‍🦲': 4, + '👨‍🦳': 4, + '👨‍🦼': 4, + '👨‍🦼‍➡️': 5, + '👨‍🦽': 4, + '👨‍🦽‍➡️': 5, + '👨🏻‍⚕️': 5, + '👨🏻‍⚖️': 5, + '👨🏻‍✈️': 5, + '👨🏻‍❤️‍👨🏻': 9, + '👨🏻‍❤️‍👨🏽': 9, + '👨🏻‍❤️‍👨🏿': 9, + '👨🏻‍❤️‍💋‍👨🏻': 11, + '👨🏻‍❤️‍💋‍👨🏽': 11, + '👨🏻‍❤️‍💋‍👨🏾': 11, + '👨🏻‍❤️‍💋‍👨🏿': 11, + '👨🏻‍🌾': 6, + '👨🏻‍🍳': 6, + '👨🏻‍🍼': 6, + '👨🏻‍🎓': 6, + '👨🏻‍🎤': 6, + '👨🏻‍🎨': 6, + '👨🏻‍🏫': 6, + '👨🏻‍🏭': 6, + '👨🏻‍🐰‍👨🏼': 10, + '👨🏻‍🐰‍👨🏽': 10, + '👨🏻‍🐰‍👨🏾': 10, + '👨🏻‍🐰‍👨🏿': 10, + '👨🏻‍💻': 6, + '👨🏻‍💼': 6, + '👨🏻‍🔧': 6, + '👨🏻‍🔬': 6, + '👨🏻‍🚀': 6, + '👨🏻‍🚒': 6, + '👨🏻‍🤝‍👨🏼': 10, + '👨🏻‍🤝‍👨🏽': 10, + '👨🏻‍🤝‍👨🏾': 10, + '👨🏻‍🤝‍👨🏿': 10, + '👨🏻‍🦯': 6, + '👨🏻‍🦯‍➡️': 7, + '👨🏻‍🦰': 6, + '👨🏻‍🦱': 6, + '👨🏻‍🦲': 6, + '👨🏻‍🦳': 6, + '👨🏻‍🦼': 6, + '👨🏻‍🦼‍➡️': 7, + '👨🏻‍🦽': 6, + '👨🏻‍🦽‍➡️': 7, + '👨🏻‍🫯‍👨🏼': 9, + '👨🏻‍🫯‍👨🏽': 9, + '👨🏻‍🫯‍👨🏾': 9, + '👨🏻‍🫯‍👨🏿': 9, + '👨🏼‍⚕️': 5, + '👨🏼‍⚖️': 5, + '👨🏼‍✈️': 5, + '👨🏼‍❤️‍👨🏼': 9, + '👨🏼‍❤️‍💋‍👨🏼': 11, + '👨🏼‍❤️‍💋‍👨🏿': 11, + '👨🏼‍🌾': 6, + '👨🏼‍🍳': 6, + '👨🏼‍🍼': 6, + '👨🏼‍🎓': 6, + '👨🏼‍🎤': 6, + '👨🏼‍🎨': 6, + '👨🏼‍🏫': 6, + '👨🏼‍🏭': 6, + '👨🏼‍🐰‍👨🏻': 10, + '👨🏼‍🐰‍👨🏽': 10, + '👨🏼‍🐰‍👨🏿': 10, + '👨🏼‍💻': 6, + '👨🏼‍💼': 6, + '👨🏼‍🔧': 6, + '👨🏼‍🔬': 6, + '👨🏼‍🚀': 6, + '👨🏼‍🚒': 6, + '👨🏼‍🤝‍👨🏻': 10, + '👨🏼‍🤝‍👨🏽': 10, + '👨🏼‍🤝‍👨🏿': 10, + '👨🏼‍🦯': 6, + '👨🏼‍🦯‍➡️': 7, + '👨🏼‍🦰': 6, + '👨🏼‍🦱': 6, + '👨🏼‍🦲': 6, + '👨🏼‍🦳': 6, + '👨🏼‍🦼': 6, + '👨🏼‍🦽': 6, + '👨🏼‍🦽‍➡️': 7, + '👨🏼‍🫯‍👨🏻': 9, + '👨🏼‍🫯‍👨🏽': 9, + '👨🏼‍🫯‍👨🏾': 9, + '👨🏼‍🫯‍👨🏿': 9, + '👨🏽‍⚕️': 5, + '👨🏽‍⚖️': 5, + '👨🏽‍✈️': 5, + '👨🏽‍❤️‍👨🏻': 9, + '👨🏽‍❤️‍👨🏽': 9, + '👨🏽‍❤️‍👨🏿': 9, + '👨🏽‍❤️‍💋‍👨🏻': 11, + '👨🏽‍❤️‍💋‍👨🏽': 11, + '👨🏽‍❤️‍💋‍👨🏿': 11, + '👨🏽‍🌾': 6, + '👨🏽‍🍳': 6, + '👨🏽‍🍼': 6, + '👨🏽‍🎓': 6, + '👨🏽‍🎤': 6, + '👨🏽‍🎨': 6, + '👨🏽‍🏫': 6, + '👨🏽‍🏭': 6, + '👨🏽‍🐰‍👨🏻': 10, + '👨🏽‍🐰‍👨🏼': 10, + '👨🏽‍🐰‍👨🏾': 10, + '👨🏽‍🐰‍👨🏿': 10, + '👨🏽‍💻': 6, + '👨🏽‍💼': 6, + '👨🏽‍🔧': 6, + '👨🏽‍🔬': 6, + '👨🏽‍🚀': 6, + '👨🏽‍🚒': 6, + '👨🏽‍🤝‍👨🏻': 10, + '👨🏽‍🤝‍👨🏼': 10, + '👨🏽‍🤝‍👨🏾': 10, + '👨🏽‍🤝‍👨🏿': 10, + '👨🏽‍🦯': 6, + '👨🏽‍🦯‍➡️': 7, + '👨🏽‍🦰': 6, + '👨🏽‍🦱': 6, + '👨🏽‍🦲': 6, + '👨🏽‍🦳': 6, + '👨🏽‍🦼': 6, + '👨🏽‍🦼‍➡️': 7, + '👨🏽‍🦽': 6, + '👨🏽‍🦽‍➡️': 7, + '👨🏽‍🫯‍👨🏻': 9, + '👨🏽‍🫯‍👨🏼': 9, + '👨🏽‍🫯‍👨🏾': 9, + '👨🏽‍🫯‍👨🏿': 9, + '👨🏾‍⚕️': 5, + '👨🏾‍⚖️': 5, + '👨🏾‍✈️': 5, + '👨🏾‍❤️‍👨🏾': 9, + '👨🏾‍❤️‍💋‍👨🏻': 11, + '👨🏾‍❤️‍💋‍👨🏾': 11, + '👨🏾‍❤️‍💋‍👨🏿': 11, + '👨🏾‍🌾': 6, + '👨🏾‍🍳': 6, + '👨🏾‍🍼': 6, + '👨🏾‍🎓': 6, + '👨🏾‍🎤': 6, + '👨🏾‍🎨': 6, + '👨🏾‍🏫': 6, + '👨🏾‍🏭': 6, + '👨🏾‍🐰‍👨🏻': 10, + '👨🏾‍🐰‍👨🏽': 10, + '👨🏾‍🐰‍👨🏿': 10, + '👨🏾‍💻': 6, + '👨🏾‍💼': 6, + '👨🏾‍🔧': 6, + '👨🏾‍🔬': 6, + '👨🏾‍🚀': 6, + '👨🏾‍🚒': 6, + '👨🏾‍🤝‍👨🏻': 10, + '👨🏾‍🤝‍👨🏽': 10, + '👨🏾‍🤝‍👨🏿': 10, + '👨🏾‍🦯': 6, + '👨🏾‍🦯‍➡️': 7, + '👨🏾‍🦰': 6, + '👨🏾‍🦱': 6, + '👨🏾‍🦲': 6, + '👨🏾‍🦳': 6, + '👨🏾‍🦼': 6, + '👨🏾‍🦽': 6, + '👨🏾‍🦽‍➡️': 7, + '👨🏾‍🫯‍👨🏻': 9, + '👨🏾‍🫯‍👨🏼': 9, + '👨🏾‍🫯‍👨🏽': 9, + '👨🏾‍🫯‍👨🏿': 9, + '👨🏿‍⚕️': 5, + '👨🏿‍⚖️': 5, + '👨🏿‍✈️': 5, + '👨🏿‍❤️‍👨🏻': 9, + '👨🏿‍❤️‍👨🏽': 9, + '👨🏿‍❤️‍👨🏿': 9, + '👨🏿‍❤️‍💋‍👨🏻': 11, + '👨🏿‍❤️‍💋‍👨🏼': 11, + '👨🏿‍❤️‍💋‍👨🏽': 11, + '👨🏿‍❤️‍💋‍👨🏾': 11, + '👨🏿‍❤️‍💋‍👨🏿': 11, + '👨🏿‍🌾': 6, + '👨🏿‍🍳': 6, + '👨🏿‍🍼': 6, + '👨🏿‍🎓': 6, + '👨🏿‍🎤': 6, + '👨🏿‍🎨': 6, + '👨🏿‍🏫': 6, + '👨🏿‍🏭': 6, + '👨🏿‍🐰‍👨🏻': 10, + '👨🏿‍🐰‍👨🏼': 10, + '👨🏿‍🐰‍👨🏽': 10, + '👨🏿‍🐰‍👨🏾': 10, + '👨🏿‍💻': 6, + '👨🏿‍💼': 6, + '👨🏿‍🔧': 6, + '👨🏿‍🔬': 6, + '👨🏿‍🚀': 6, + '👨🏿‍🚒': 6, + '👨🏿‍🤝‍👨🏻': 10, + '👨🏿‍🤝‍👨🏼': 10, + '👨🏿‍🤝‍👨🏽': 10, + '👨🏿‍🤝‍👨🏾': 10, + '👨🏿‍🦯': 6, + '👨🏿‍🦯‍➡️': 7, + '👨🏿‍🦰': 6, + '👨🏿‍🦱': 6, + '👨🏿‍🦲': 6, + '👨🏿‍🦳': 6, + '👨🏿‍🦼': 6, + '👨🏿‍🦼‍➡️': 7, + '👨🏿‍🦽': 6, + '👨🏿‍🦽‍➡️': 7, + '👨🏿‍🫯‍👨🏻': 9, + '👨🏿‍🫯‍👨🏼': 9, + '👨🏿‍🫯‍👨🏽': 9, + '👨🏿‍🫯‍👨🏾': 9, + '👩‍⚕️': 3, + '👩‍⚖️': 3, + '👩‍✈️': 3, + '👩‍❤️‍👨': 5, + '👩‍❤️‍👩': 5, + '👩‍❤️‍💋‍👨': 7, + '👩‍❤️‍💋‍👩': 7, + '👩‍🌾': 4, + '👩‍🍳': 4, + '👩‍🍼': 4, + '👩‍🎓': 4, + '👩‍🎤': 4, + '👩‍🎨': 4, + '👩‍🏫': 4, + '👩‍🏭': 4, + '👩‍👦': 4, + '👩‍👦‍👦': 6, + '👩‍👧': 4, + '👩‍👧‍👦': 6, + '👩‍👧‍👧': 6, + '👩‍👩‍👦': 6, + '👩‍👩‍👦‍👦': 8, + '👩‍👩‍👧': 6, + '👩‍👩‍👧‍👦': 8, + '👩‍👩‍👧‍👧': 8, + '👩‍💻': 4, + '👩‍💼': 4, + '👩‍🔧': 4, + '👩‍🔬': 4, + '👩‍🚀': 4, + '👩‍🚒': 4, + '👩‍🦯': 4, + '👩‍🦯‍➡️': 5, + '👩‍🦰': 4, + '👩‍🦱': 4, + '👩‍🦲': 4, + '👩‍🦳': 4, + '👩‍🦼': 4, + '👩‍🦼‍➡️': 5, + '👩‍🦽': 4, + '👩‍🦽‍➡️': 5, + '👩🏻‍⚕️': 5, + '👩🏻‍⚖️': 5, + '👩🏻‍✈️': 5, + '👩🏻‍❤️‍👨🏻': 9, + '👩🏻‍❤️‍👨🏿': 9, + '👩🏻‍❤️‍👩🏻': 9, + '👩🏻‍❤️‍💋‍👨🏻': 11, + '👩🏻‍❤️‍💋‍👨🏽': 11, + '👩🏻‍❤️‍💋‍👨🏿': 11, + '👩🏻‍❤️‍💋‍👩🏻': 11, + '👩🏻‍❤️‍💋‍👩🏽': 11, + '👩🏻‍❤️‍💋‍👩🏿': 11, + '👩🏻‍🌾': 6, + '👩🏻‍🍳': 6, + '👩🏻‍🍼': 6, + '👩🏻‍🎓': 6, + '👩🏻‍🎤': 6, + '👩🏻‍🎨': 6, + '👩🏻‍🏫': 6, + '👩🏻‍🏭': 6, + '👩🏻‍🐰‍👩🏼': 10, + '👩🏻‍🐰‍👩🏽': 10, + '👩🏻‍🐰‍👩🏾': 10, + '👩🏻‍🐰‍👩🏿': 10, + '👩🏻‍💻': 6, + '👩🏻‍💼': 6, + '👩🏻‍🔧': 6, + '👩🏻‍🔬': 6, + '👩🏻‍🚀': 6, + '👩🏻‍🚒': 6, + '👩🏻‍🤝‍👨🏽': 10, + '👩🏻‍🤝‍👨🏿': 10, + '👩🏻‍🤝‍👩🏼': 10, + '👩🏻‍🤝‍👩🏽': 10, + '👩🏻‍🤝‍👩🏾': 10, + '👩🏻‍🤝‍👩🏿': 10, + '👩🏻‍🦯': 6, + '👩🏻‍🦯‍➡️': 7, + '👩🏻‍🦰': 6, + '👩🏻‍🦱': 6, + '👩🏻‍🦲': 6, + '👩🏻‍🦳': 6, + '👩🏻‍🦼': 6, + '👩🏻‍🦼‍➡️': 7, + '👩🏻‍🦽': 6, + '👩🏻‍🦽‍➡️': 7, + '👩🏻‍🫯‍👩🏼': 9, + '👩🏻‍🫯‍👩🏽': 9, + '👩🏻‍🫯‍👩🏾': 9, + '👩🏻‍🫯‍👩🏿': 9, + '👩🏼‍⚕️': 5, + '👩🏼‍⚖️': 5, + '👩🏼‍✈️': 5, + '👩🏼‍❤️‍👨🏼': 9, + '👩🏼‍❤️‍👩🏼': 9, + '👩🏼‍❤️‍💋‍👨🏼': 11, + '👩🏼‍❤️‍💋‍👩🏼': 11, + '👩🏼‍🌾': 6, + '👩🏼‍🍳': 6, + '👩🏼‍🍼': 6, + '👩🏼‍🎓': 6, + '👩🏼‍🎤': 6, + '👩🏼‍🎨': 6, + '👩🏼‍🏫': 6, + '👩🏼‍🏭': 6, + '👩🏼‍🐰‍👩🏻': 10, + '👩🏼‍🐰‍👩🏿': 10, + '👩🏼‍💻': 6, + '👩🏼‍💼': 6, + '👩🏼‍🔧': 6, + '👩🏼‍🔬': 6, + '👩🏼‍🚀': 6, + '👩🏼‍🚒': 6, + '👩🏼‍🤝‍👩🏻': 10, + '👩🏼‍🤝‍👩🏽': 10, + '👩🏼‍🤝‍👩🏿': 10, + '👩🏼‍🦯': 6, + '👩🏼‍🦯‍➡️': 7, + '👩🏼‍🦰': 6, + '👩🏼‍🦱': 6, + '👩🏼‍🦲': 6, + '👩🏼‍🦳': 6, + '👩🏼‍🦼': 6, + '👩🏼‍🦽': 6, + '👩🏼‍🫯‍👩🏻': 9, + '👩🏼‍🫯‍👩🏽': 9, + '👩🏼‍🫯‍👩🏾': 9, + '👩🏼‍🫯‍👩🏿': 9, + '👩🏽‍⚕️': 5, + '👩🏽‍⚖️': 5, + '👩🏽‍✈️': 5, + '👩🏽‍❤️‍👨🏽': 9, + '👩🏽‍❤️‍👩🏽': 9, + '👩🏽‍❤️‍💋‍👨🏻': 11, + '👩🏽‍❤️‍💋‍👨🏽': 11, + '👩🏽‍❤️‍💋‍👨🏿': 11, + '👩🏽‍❤️‍💋‍👩🏻': 11, + '👩🏽‍❤️‍💋‍👩🏽': 11, + '👩🏽‍❤️‍💋‍👩🏿': 11, + '👩🏽‍🌾': 6, + '👩🏽‍🍳': 6, + '👩🏽‍🍼': 6, + '👩🏽‍🎓': 6, + '👩🏽‍🎤': 6, + '👩🏽‍🎨': 6, + '👩🏽‍🏫': 6, + '👩🏽‍🏭': 6, + '👩🏽‍🐰‍👩🏻': 10, + '👩🏽‍🐰‍👩🏾': 10, + '👩🏽‍🐰‍👩🏿': 10, + '👩🏽‍💻': 6, + '👩🏽‍💼': 6, + '👩🏽‍🔧': 6, + '👩🏽‍🔬': 6, + '👩🏽‍🚀': 6, + '👩🏽‍🚒': 6, + '👩🏽‍🤝‍👨🏻': 10, + '👩🏽‍🤝‍👨🏿': 10, + '👩🏽‍🤝‍👩🏻': 10, + '👩🏽‍🤝‍👩🏼': 10, + '👩🏽‍🤝‍👩🏾': 10, + '👩🏽‍🤝‍👩🏿': 10, + '👩🏽‍🦯': 6, + '👩🏽‍🦯‍➡️': 7, + '👩🏽‍🦰': 6, + '👩🏽‍🦱': 6, + '👩🏽‍🦲': 6, + '👩🏽‍🦳': 6, + '👩🏽‍🦼': 6, + '👩🏽‍🦼‍➡️': 7, + '👩🏽‍🦽': 6, + '👩🏽‍🦽‍➡️': 7, + '👩🏽‍🫯‍👩🏻': 9, + '👩🏽‍🫯‍👩🏼': 9, + '👩🏽‍🫯‍👩🏾': 9, + '👩🏽‍🫯‍👩🏿': 9, + '👩🏾‍⚕️': 5, + '👩🏾‍⚖️': 5, + '👩🏾‍✈️': 5, + '👩🏾‍❤️‍👨🏾': 9, + '👩🏾‍❤️‍👩🏾': 9, + '👩🏾‍❤️‍💋‍👨🏾': 11, + '👩🏾‍❤️‍💋‍👩🏾': 11, + '👩🏾‍🌾': 6, + '👩🏾‍🍳': 6, + '👩🏾‍🍼': 6, + '👩🏾‍🎓': 6, + '👩🏾‍🎤': 6, + '👩🏾‍🎨': 6, + '👩🏾‍🏫': 6, + '👩🏾‍🏭': 6, + '👩🏾‍🐰‍👩🏻': 10, + '👩🏾‍🐰‍👩🏽': 10, + '👩🏾‍🐰‍👩🏿': 10, + '👩🏾‍💻': 6, + '👩🏾‍💼': 6, + '👩🏾‍🔧': 6, + '👩🏾‍🔬': 6, + '👩🏾‍🚀': 6, + '👩🏾‍🚒': 6, + '👩🏾‍🤝‍👩🏻': 10, + '👩🏾‍🤝‍👩🏽': 10, + '👩🏾‍🤝‍👩🏿': 10, + '👩🏾‍🦯': 6, + '👩🏾‍🦯‍➡️': 7, + '👩🏾‍🦰': 6, + '👩🏾‍🦱': 6, + '👩🏾‍🦲': 6, + '👩🏾‍🦳': 6, + '👩🏾‍🦼': 6, + '👩🏾‍🦽': 6, + '👩🏾‍🦽‍➡️': 7, + '👩🏾‍🫯‍👩🏻': 9, + '👩🏾‍🫯‍👩🏼': 9, + '👩🏾‍🫯‍👩🏽': 9, + '👩🏾‍🫯‍👩🏿': 9, + '👩🏿‍⚕️': 5, + '👩🏿‍⚖️': 5, + '👩🏿‍✈️': 5, + '👩🏿‍❤️‍👨🏻': 9, + '👩🏿‍❤️‍👨🏿': 9, + '👩🏿‍❤️‍👩🏿': 9, + '👩🏿‍❤️‍💋‍👨🏻': 11, + '👩🏿‍❤️‍💋‍👨🏽': 11, + '👩🏿‍❤️‍💋‍👨🏿': 11, + '👩🏿‍❤️‍💋‍👩🏻': 11, + '👩🏿‍❤️‍💋‍👩🏽': 11, + '👩🏿‍❤️‍💋‍👩🏿': 11, + '👩🏿‍🌾': 6, + '👩🏿‍🍳': 6, + '👩🏿‍🍼': 6, + '👩🏿‍🎓': 6, + '👩🏿‍🎤': 6, + '👩🏿‍🎨': 6, + '👩🏿‍🏫': 6, + '👩🏿‍🏭': 6, + '👩🏿‍🐰‍👩🏻': 10, + '👩🏿‍🐰‍👩🏼': 10, + '👩🏿‍🐰‍👩🏽': 10, + '👩🏿‍🐰‍👩🏾': 10, + '👩🏿‍💻': 6, + '👩🏿‍💼': 6, + '👩🏿‍🔧': 6, + '👩🏿‍🔬': 6, + '👩🏿‍🚀': 6, + '👩🏿‍🚒': 6, + '👩🏿‍🤝‍👨🏻': 10, + '👩🏿‍🤝‍👨🏽': 10, + '👩🏿‍🤝‍👩🏻': 10, + '👩🏿‍🤝‍👩🏼': 10, + '👩🏿‍🤝‍👩🏽': 10, + '👩🏿‍🤝‍👩🏾': 10, + '👩🏿‍🦯': 6, + '👩🏿‍🦯‍➡️': 7, + '👩🏿‍🦰': 6, + '👩🏿‍🦱': 6, + '👩🏿‍🦲': 6, + '👩🏿‍🦳': 6, + '👩🏿‍🦼': 6, + '👩🏿‍🦼‍➡️': 7, + '👩🏿‍🦽': 6, + '👩🏿‍🦽‍➡️': 7, + '👩🏿‍🫯‍👩🏻': 9, + '👩🏿‍🫯‍👩🏼': 9, + '👩🏿‍🫯‍👩🏽': 9, + '👩🏿‍🫯‍👩🏾': 9, + '👮‍♀️': 3, + '👮‍♂️': 3, + '👮🏻‍♀️': 5, + '👮🏻‍♂️': 5, + '👮🏼‍♀️': 5, + '👮🏼‍♂️': 5, + '👮🏽‍♀️': 5, + '👮🏽‍♂️': 5, + '👮🏾‍♀️': 5, + '👮🏾‍♂️': 5, + '👮🏿‍♀️': 5, + '👮🏿‍♂️': 5, + '👯‍♀️': 3, + '👯‍♂️': 3, + '👯🏻‍♀️': 5, + '👯🏻‍♂️': 5, + '👯🏼‍♀️': 5, + '👯🏼‍♂️': 5, + '👯🏽‍♀️': 5, + '👯🏽‍♂️': 5, + '👯🏾‍♀️': 5, + '👯🏾‍♂️': 5, + '👯🏿‍♀️': 5, + '👯🏿‍♂️': 5, + '👰‍♀️': 3, + '👰‍♂️': 3, + '👰🏻‍♀️': 5, + '👰🏻‍♂️': 5, + '👰🏼‍♀️': 5, + '👰🏼‍♂️': 5, + '👰🏽‍♀️': 5, + '👰🏽‍♂️': 5, + '👰🏾‍♀️': 5, + '👰🏾‍♂️': 5, + '👰🏿‍♀️': 5, + '👰🏿‍♂️': 5, + '👱‍♀️': 3, + '👱‍♂️': 3, + '👱🏻‍♀️': 5, + '👱🏻‍♂️': 5, + '👱🏼‍♀️': 5, + '👱🏼‍♂️': 5, + '👱🏽‍♀️': 5, + '👱🏽‍♂️': 5, + '👱🏾‍♀️': 5, + '👱🏾‍♂️': 5, + '👱🏿‍♀️': 5, + '👱🏿‍♂️': 5, + '👳‍♀️': 3, + '👳‍♂️': 3, + '👳🏻‍♀️': 5, + '👳🏻‍♂️': 5, + '👳🏼‍♀️': 5, + '👳🏼‍♂️': 5, + '👳🏽‍♀️': 5, + '👳🏽‍♂️': 5, + '👳🏾‍♀️': 5, + '👳🏾‍♂️': 5, + '👳🏿‍♀️': 5, + '👳🏿‍♂️': 5, + '👷‍♀️': 3, + '👷‍♂️': 3, + '👷🏻‍♀️': 5, + '👷🏻‍♂️': 5, + '👷🏼‍♀️': 5, + '👷🏼‍♂️': 5, + '👷🏽‍♀️': 5, + '👷🏽‍♂️': 5, + '👷🏾‍♀️': 5, + '👷🏾‍♂️': 5, + '👷🏿‍♀️': 5, + '👷🏿‍♂️': 5, + '💁‍♀️': 3, + '💁‍♂️': 3, + '💁🏻‍♀️': 5, + '💁🏻‍♂️': 5, + '💁🏼‍♀️': 5, + '💁🏼‍♂️': 5, + '💁🏽‍♀️': 5, + '💁🏽‍♂️': 5, + '💁🏾‍♀️': 5, + '💁🏾‍♂️': 5, + '💁🏿‍♀️': 5, + '💁🏿‍♂️': 5, + '💂‍♀️': 3, + '💂‍♂️': 3, + '💂🏻‍♀️': 5, + '💂🏻‍♂️': 5, + '💂🏼‍♀️': 5, + '💂🏼‍♂️': 5, + '💂🏽‍♀️': 5, + '💂🏽‍♂️': 5, + '💂🏾‍♀️': 5, + '💂🏾‍♂️': 5, + '💂🏿‍♀️': 5, + '💂🏿‍♂️': 5, + '💆‍♀️': 3, + '💆‍♂️': 3, + '💆🏻‍♀️': 5, + '💆🏻‍♂️': 5, + '💆🏼‍♀️': 5, + '💆🏼‍♂️': 5, + '💆🏽‍♀️': 5, + '💆🏽‍♂️': 5, + '💆🏾‍♀️': 5, + '💆🏾‍♂️': 5, + '💆🏿‍♀️': 5, + '💆🏿‍♂️': 5, + '💇‍♀️': 3, + '💇‍♂️': 3, + '💇🏻‍♀️': 5, + '💇🏻‍♂️': 5, + '💇🏼‍♀️': 5, + '💇🏼‍♂️': 5, + '💇🏽‍♀️': 5, + '💇🏽‍♂️': 5, + '💇🏾‍♀️': 5, + '💇🏾‍♂️': 5, + '💇🏿‍♀️': 5, + '💇🏿‍♂️': 5, + '🕵🏻‍♀️': 4, + '🕵🏻‍♂️': 4, + '🕵🏼‍♀️': 4, + '🕵🏼‍♂️': 4, + '🕵🏽‍♀️': 4, + '🕵🏽‍♂️': 4, + '🕵🏾‍♀️': 4, + '🕵🏾‍♂️': 4, + '🕵🏿‍♀️': 4, + '🕵🏿‍♂️': 4, + '😮‍💨': 4, + '😵‍💫': 4, + '😶‍🌫️': 3, + '🙂‍↔️': 3, + '🙂‍↕️': 3, + '🙅‍♀️': 3, + '🙅‍♂️': 3, + '🙅🏻‍♀️': 5, + '🙅🏻‍♂️': 5, + '🙅🏼‍♀️': 5, + '🙅🏼‍♂️': 5, + '🙅🏽‍♀️': 5, + '🙅🏽‍♂️': 5, + '🙅🏾‍♀️': 5, + '🙅🏾‍♂️': 5, + '🙅🏿‍♀️': 5, + '🙅🏿‍♂️': 5, + '🙆‍♀️': 3, + '🙆‍♂️': 3, + '🙆🏻‍♀️': 5, + '🙆🏻‍♂️': 5, + '🙆🏼‍♀️': 5, + '🙆🏼‍♂️': 5, + '🙆🏽‍♀️': 5, + '🙆🏽‍♂️': 5, + '🙆🏾‍♀️': 5, + '🙆🏾‍♂️': 5, + '🙆🏿‍♀️': 5, + '🙆🏿‍♂️': 5, + '🙇‍♀️': 3, + '🙇‍♂️': 3, + '🙇🏻‍♀️': 5, + '🙇🏻‍♂️': 5, + '🙇🏼‍♀️': 5, + '🙇🏼‍♂️': 5, + '🙇🏽‍♀️': 5, + '🙇🏽‍♂️': 5, + '🙇🏾‍♀️': 5, + '🙇🏾‍♂️': 5, + '🙇🏿‍♀️': 5, + '🙇🏿‍♂️': 5, + '🙋‍♀️': 3, + '🙋‍♂️': 3, + '🙋🏻‍♀️': 5, + '🙋🏻‍♂️': 5, + '🙋🏼‍♀️': 5, + '🙋🏼‍♂️': 5, + '🙋🏽‍♀️': 5, + '🙋🏽‍♂️': 5, + '🙋🏾‍♀️': 5, + '🙋🏾‍♂️': 5, + '🙋🏿‍♀️': 5, + '🙋🏿‍♂️': 5, + '🙍‍♀️': 3, + '🙍‍♂️': 3, + '🙍🏻‍♀️': 5, + '🙍🏻‍♂️': 5, + '🙍🏼‍♀️': 5, + '🙍🏼‍♂️': 5, + '🙍🏽‍♀️': 5, + '🙍🏽‍♂️': 5, + '🙍🏾‍♀️': 5, + '🙍🏾‍♂️': 5, + '🙍🏿‍♀️': 5, + '🙍🏿‍♂️': 5, + '🙎‍♀️': 3, + '🙎‍♂️': 3, + '🙎🏻‍♀️': 5, + '🙎🏻‍♂️': 5, + '🙎🏼‍♀️': 5, + '🙎🏼‍♂️': 5, + '🙎🏽‍♀️': 5, + '🙎🏽‍♂️': 5, + '🙎🏾‍♀️': 5, + '🙎🏾‍♂️': 5, + '🙎🏿‍♀️': 5, + '🙎🏿‍♂️': 5, + '🚣‍♀️': 3, + '🚣‍♂️': 3, + '🚣🏻‍♀️': 5, + '🚣🏻‍♂️': 5, + '🚣🏼‍♀️': 5, + '🚣🏼‍♂️': 5, + '🚣🏽‍♀️': 5, + '🚣🏽‍♂️': 5, + '🚣🏾‍♀️': 5, + '🚣🏾‍♂️': 5, + '🚣🏿‍♀️': 5, + '🚣🏿‍♂️': 5, + '🚴‍♀️': 3, + '🚴‍♂️': 3, + '🚴🏻‍♀️': 5, + '🚴🏻‍♂️': 5, + '🚴🏼‍♀️': 5, + '🚴🏼‍♂️': 5, + '🚴🏽‍♀️': 5, + '🚴🏽‍♂️': 5, + '🚴🏾‍♀️': 5, + '🚴🏾‍♂️': 5, + '🚴🏿‍♀️': 5, + '🚴🏿‍♂️': 5, + '🚵‍♀️': 3, + '🚵‍♂️': 3, + '🚵🏻‍♀️': 5, + '🚵🏻‍♂️': 5, + '🚵🏼‍♀️': 5, + '🚵🏼‍♂️': 5, + '🚵🏽‍♀️': 5, + '🚵🏽‍♂️': 5, + '🚵🏾‍♀️': 5, + '🚵🏾‍♂️': 5, + '🚵🏿‍♀️': 5, + '🚵🏿‍♂️': 5, + '🚶‍♀️': 3, + '🚶‍♀️‍➡️': 4, + '🚶‍♂️': 3, + '🚶‍♂️‍➡️': 4, + '🚶‍➡️': 3, + '🚶🏻‍♀️': 5, + '🚶🏻‍♀️‍➡️': 6, + '🚶🏻‍♂️': 5, + '🚶🏻‍♂️‍➡️': 6, + '🚶🏻‍➡️': 5, + '🚶🏼‍♀️': 5, + '🚶🏼‍♀️‍➡️': 6, + '🚶🏼‍♂️': 5, + '🚶🏼‍♂️‍➡️': 6, + '🚶🏼‍➡️': 5, + '🚶🏽‍♀️': 5, + '🚶🏽‍♀️‍➡️': 6, + '🚶🏽‍♂️': 5, + '🚶🏽‍♂️‍➡️': 6, + '🚶🏽‍➡️': 5, + '🚶🏾‍♀️': 5, + '🚶🏾‍♀️‍➡️': 6, + '🚶🏾‍♂️': 5, + '🚶🏾‍♂️‍➡️': 6, + '🚶🏾‍➡️': 5, + '🚶🏿‍♀️': 5, + '🚶🏿‍♀️‍➡️': 6, + '🚶🏿‍♂️': 5, + '🚶🏿‍♂️‍➡️': 6, + '🚶🏿‍➡️': 5, + '🤦‍♀️': 3, + '🤦‍♂️': 3, + '🤦🏻‍♀️': 5, + '🤦🏻‍♂️': 5, + '🤦🏼‍♀️': 5, + '🤦🏼‍♂️': 5, + '🤦🏽‍♀️': 5, + '🤦🏽‍♂️': 5, + '🤦🏾‍♀️': 5, + '🤦🏾‍♂️': 5, + '🤦🏿‍♀️': 5, + '🤦🏿‍♂️': 5, + '🤵‍♀️': 3, + '🤵‍♂️': 3, + '🤵🏻‍♀️': 5, + '🤵🏻‍♂️': 5, + '🤵🏼‍♀️': 5, + '🤵🏼‍♂️': 5, + '🤵🏽‍♀️': 5, + '🤵🏽‍♂️': 5, + '🤵🏾‍♀️': 5, + '🤵🏾‍♂️': 5, + '🤵🏿‍♀️': 5, + '🤵🏿‍♂️': 5, + '🤷‍♀️': 3, + '🤷‍♂️': 3, + '🤷🏻‍♀️': 5, + '🤷🏻‍♂️': 5, + '🤷🏼‍♀️': 5, + '🤷🏼‍♂️': 5, + '🤷🏽‍♀️': 5, + '🤷🏽‍♂️': 5, + '🤷🏾‍♀️': 5, + '🤷🏾‍♂️': 5, + '🤷🏿‍♀️': 5, + '🤷🏿‍♂️': 5, + '🤸‍♀️': 3, + '🤸‍♂️': 3, + '🤸🏻‍♀️': 5, + '🤸🏻‍♂️': 5, + '🤸🏼‍♀️': 5, + '🤸🏼‍♂️': 5, + '🤸🏽‍♀️': 5, + '🤸🏽‍♂️': 5, + '🤸🏾‍♀️': 5, + '🤸🏾‍♂️': 5, + '🤸🏿‍♀️': 5, + '🤸🏿‍♂️': 5, + '🤹‍♀️': 3, + '🤹‍♂️': 3, + '🤹🏻‍♀️': 5, + '🤹🏻‍♂️': 5, + '🤹🏼‍♀️': 5, + '🤹🏼‍♂️': 5, + '🤹🏽‍♀️': 5, + '🤹🏽‍♂️': 5, + '🤹🏾‍♀️': 5, + '🤹🏾‍♂️': 5, + '🤹🏿‍♀️': 5, + '🤹🏿‍♂️': 5, + '🤼‍♀️': 3, + '🤼‍♂️': 3, + '🤼🏻‍♀️': 5, + '🤼🏻‍♂️': 5, + '🤼🏼‍♀️': 5, + '🤼🏼‍♂️': 5, + '🤼🏽‍♀️': 5, + '🤼🏽‍♂️': 5, + '🤼🏾‍♀️': 5, + '🤼🏾‍♂️': 5, + '🤼🏿‍♀️': 5, + '🤼🏿‍♂️': 5, + '🤽‍♀️': 3, + '🤽‍♂️': 3, + '🤽🏻‍♀️': 5, + '🤽🏻‍♂️': 5, + '🤽🏼‍♀️': 5, + '🤽🏼‍♂️': 5, + '🤽🏽‍♀️': 5, + '🤽🏽‍♂️': 5, + '🤽🏾‍♀️': 5, + '🤽🏾‍♂️': 5, + '🤽🏿‍♀️': 5, + '🤽🏿‍♂️': 5, + '🤾‍♀️': 3, + '🤾‍♂️': 3, + '🤾🏻‍♀️': 5, + '🤾🏻‍♂️': 5, + '🤾🏼‍♀️': 5, + '🤾🏼‍♂️': 5, + '🤾🏽‍♀️': 5, + '🤾🏽‍♂️': 5, + '🤾🏾‍♀️': 5, + '🤾🏾‍♂️': 5, + '🤾🏿‍♀️': 5, + '🤾🏿‍♂️': 5, + '🦸‍♀️': 3, + '🦸‍♂️': 3, + '🦸🏻‍♀️': 5, + '🦸🏻‍♂️': 5, + '🦸🏼‍♀️': 5, + '🦸🏼‍♂️': 5, + '🦸🏽‍♀️': 5, + '🦸🏽‍♂️': 5, + '🦸🏾‍♀️': 5, + '🦸🏾‍♂️': 5, + '🦸🏿‍♀️': 5, + '🦸🏿‍♂️': 5, + '🦹‍♀️': 3, + '🦹‍♂️': 3, + '🦹🏻‍♀️': 5, + '🦹🏻‍♂️': 5, + '🦹🏼‍♀️': 5, + '🦹🏼‍♂️': 5, + '🦹🏽‍♀️': 5, + '🦹🏽‍♂️': 5, + '🦹🏾‍♀️': 5, + '🦹🏾‍♂️': 5, + '🦹🏿‍♀️': 5, + '🦹🏿‍♂️': 5, + '🧍‍♀️': 3, + '🧍‍♂️': 3, + '🧍🏻‍♀️': 5, + '🧍🏻‍♂️': 5, + '🧍🏼‍♀️': 5, + '🧍🏼‍♂️': 5, + '🧍🏽‍♀️': 5, + '🧍🏽‍♂️': 5, + '🧍🏾‍♀️': 5, + '🧍🏾‍♂️': 5, + '🧍🏿‍♀️': 5, + '🧍🏿‍♂️': 5, + '🧎‍♀️': 3, + '🧎‍♀️‍➡️': 4, + '🧎‍♂️': 3, + '🧎‍♂️‍➡️': 4, + '🧎‍➡️': 3, + '🧎🏻‍♀️': 5, + '🧎🏻‍♀️‍➡️': 6, + '🧎🏻‍♂️': 5, + '🧎🏻‍♂️‍➡️': 6, + '🧎🏻‍➡️': 5, + '🧎🏼‍♀️': 5, + '🧎🏼‍♀️‍➡️': 6, + '🧎🏼‍♂️': 5, + '🧎🏼‍♂️‍➡️': 6, + '🧎🏼‍➡️': 5, + '🧎🏽‍♀️': 5, + '🧎🏽‍♀️‍➡️': 6, + '🧎🏽‍♂️': 5, + '🧎🏽‍♂️‍➡️': 6, + '🧎🏽‍➡️': 5, + '🧎🏾‍♀️': 5, + '🧎🏾‍♀️‍➡️': 6, + '🧎🏾‍♂️': 5, + '🧎🏾‍♂️‍➡️': 6, + '🧎🏾‍➡️': 5, + '🧎🏿‍♀️': 5, + '🧎🏿‍♀️‍➡️': 6, + '🧎🏿‍♂️': 5, + '🧎🏿‍♂️‍➡️': 6, + '🧎🏿‍➡️': 5, + '🧏‍♀️': 3, + '🧏‍♂️': 3, + '🧏🏻‍♀️': 5, + '🧏🏻‍♂️': 5, + '🧏🏼‍♀️': 5, + '🧏🏼‍♂️': 5, + '🧏🏽‍♀️': 5, + '🧏🏽‍♂️': 5, + '🧏🏾‍♀️': 5, + '🧏🏾‍♂️': 5, + '🧏🏿‍♀️': 5, + '🧏🏿‍♂️': 5, + '🧑‍⚕️': 3, + '🧑‍⚖️': 3, + '🧑‍✈️': 3, + '🧑‍🌾': 4, + '🧑‍🍳': 4, + '🧑‍🍼': 4, + '🧑‍🎄': 4, + '🧑‍🎓': 4, + '🧑‍🎤': 4, + '🧑‍🎨': 4, + '🧑‍🏫': 4, + '🧑‍🏭': 4, + '🧑‍💻': 4, + '🧑‍💼': 4, + '🧑‍🔧': 4, + '🧑‍🔬': 4, + '🧑‍🚀': 4, + '🧑‍🚒': 4, + '🧑‍🤝‍🧑': 6, + '🧑‍🦯': 4, + '🧑‍🦯‍➡️': 5, + '🧑‍🦰': 4, + '🧑‍🦱': 4, + '🧑‍🦲': 4, + '🧑‍🦳': 4, + '🧑‍🦼': 4, + '🧑‍🦼‍➡️': 5, + '🧑‍🦽': 4, + '🧑‍🦽‍➡️': 5, + '🧑‍🧑‍🧒': 6, + '🧑‍🧑‍🧒‍🧒': 8, + '🧑‍🧒': 4, + '🧑‍🧒‍🧒': 6, + '🧑‍🩰': 4, + '🧑🏻‍⚕️': 5, + '🧑🏻‍⚖️': 5, + '🧑🏻‍✈️': 5, + '🧑🏻‍❤️‍💋‍🧑🏿': 11, + '🧑🏻‍🌾': 6, + '🧑🏻‍🍳': 6, + '🧑🏻‍🍼': 6, + '🧑🏻‍🎄': 6, + '🧑🏻‍🎓': 6, + '🧑🏻‍🎤': 6, + '🧑🏻‍🎨': 6, + '🧑🏻‍🏫': 6, + '🧑🏻‍🏭': 6, + '🧑🏻‍🐰‍🧑🏽': 10, + '🧑🏻‍🐰‍🧑🏾': 10, + '🧑🏻‍🐰‍🧑🏿': 10, + '🧑🏻‍💻': 6, + '🧑🏻‍💼': 6, + '🧑🏻‍🔧': 6, + '🧑🏻‍🔬': 6, + '🧑🏻‍🚀': 6, + '🧑🏻‍🚒': 6, + '🧑🏻‍🤝‍🧑🏻': 10, + '🧑🏻‍🤝‍🧑🏼': 10, + '🧑🏻‍🤝‍🧑🏽': 10, + '🧑🏻‍🤝‍🧑🏾': 10, + '🧑🏻‍🤝‍🧑🏿': 10, + '🧑🏻‍🦯': 6, + '🧑🏻‍🦯‍➡️': 7, + '🧑🏻‍🦰': 6, + '🧑🏻‍🦱': 6, + '🧑🏻‍🦲': 6, + '🧑🏻‍🦳': 6, + '🧑🏻‍🦼': 6, + '🧑🏻‍🦼‍➡️': 7, + '🧑🏻‍🦽': 6, + '🧑🏻‍🦽‍➡️': 7, + '🧑🏻‍🩰': 6, + '🧑🏻‍🫯‍🧑🏼': 9, + '🧑🏻‍🫯‍🧑🏽': 9, + '🧑🏻‍🫯‍🧑🏾': 9, + '🧑🏻‍🫯‍🧑🏿': 9, + '🧑🏼‍⚕️': 5, + '🧑🏼‍⚖️': 5, + '🧑🏼‍✈️': 5, + '🧑🏼‍🌾': 6, + '🧑🏼‍🍳': 6, + '🧑🏼‍🍼': 6, + '🧑🏼‍🎄': 6, + '🧑🏼‍🎓': 6, + '🧑🏼‍🎤': 6, + '🧑🏼‍🎨': 6, + '🧑🏼‍🏫': 6, + '🧑🏼‍🏭': 6, + '🧑🏼‍🐰‍🧑🏿': 10, + '🧑🏼‍💻': 6, + '🧑🏼‍💼': 6, + '🧑🏼‍🔧': 6, + '🧑🏼‍🔬': 6, + '🧑🏼‍🚀': 6, + '🧑🏼‍🚒': 6, + '🧑🏼‍🤝‍🧑🏻': 10, + '🧑🏼‍🤝‍🧑🏼': 10, + '🧑🏼‍🤝‍🧑🏽': 10, + '🧑🏼‍🤝‍🧑🏿': 10, + '🧑🏼‍🦯': 6, + '🧑🏼‍🦯‍➡️': 7, + '🧑🏼‍🦰': 6, + '🧑🏼‍🦱': 6, + '🧑🏼‍🦲': 6, + '🧑🏼‍🦳': 6, + '🧑🏼‍🦼': 6, + '🧑🏼‍🦽': 6, + '🧑🏼‍🩰': 6, + '🧑🏼‍🫯‍🧑🏻': 9, + '🧑🏼‍🫯‍🧑🏽': 9, + '🧑🏼‍🫯‍🧑🏿': 9, + '🧑🏽‍⚕️': 5, + '🧑🏽‍⚖️': 5, + '🧑🏽‍✈️': 5, + '🧑🏽‍❤️‍💋‍🧑🏿': 11, + '🧑🏽‍🌾': 6, + '🧑🏽‍🍳': 6, + '🧑🏽‍🍼': 6, + '🧑🏽‍🎄': 6, + '🧑🏽‍🎓': 6, + '🧑🏽‍🎤': 6, + '🧑🏽‍🎨': 6, + '🧑🏽‍🏫': 6, + '🧑🏽‍🏭': 6, + '🧑🏽‍🐰‍🧑🏻': 10, + '🧑🏽‍🐰‍🧑🏿': 10, + '🧑🏽‍💻': 6, + '🧑🏽‍💼': 6, + '🧑🏽‍🔧': 6, + '🧑🏽‍🔬': 6, + '🧑🏽‍🚀': 6, + '🧑🏽‍🚒': 6, + '🧑🏽‍🤝‍🧑🏻': 10, + '🧑🏽‍🤝‍🧑🏼': 10, + '🧑🏽‍🤝‍🧑🏽': 10, + '🧑🏽‍🤝‍🧑🏾': 10, + '🧑🏽‍🤝‍🧑🏿': 10, + '🧑🏽‍🦯': 6, + '🧑🏽‍🦯‍➡️': 7, + '🧑🏽‍🦰': 6, + '🧑🏽‍🦱': 6, + '🧑🏽‍🦲': 6, + '🧑🏽‍🦳': 6, + '🧑🏽‍🦼': 6, + '🧑🏽‍🦼‍➡️': 7, + '🧑🏽‍🦽': 6, + '🧑🏽‍🦽‍➡️': 7, + '🧑🏽‍🩰': 6, + '🧑🏽‍🫯‍🧑🏻': 9, + '🧑🏽‍🫯‍🧑🏼': 9, + '🧑🏽‍🫯‍🧑🏾': 9, + '🧑🏽‍🫯‍🧑🏿': 9, + '🧑🏾‍⚕️': 5, + '🧑🏾‍⚖️': 5, + '🧑🏾‍✈️': 5, + '🧑🏾‍🌾': 6, + '🧑🏾‍🍳': 6, + '🧑🏾‍🍼': 6, + '🧑🏾‍🎄': 6, + '🧑🏾‍🎓': 6, + '🧑🏾‍🎤': 6, + '🧑🏾‍🎨': 6, + '🧑🏾‍🏫': 6, + '🧑🏾‍🏭': 6, + '🧑🏾‍🐰‍🧑🏻': 10, + '🧑🏾‍🐰‍🧑🏿': 10, + '🧑🏾‍💻': 6, + '🧑🏾‍💼': 6, + '🧑🏾‍🔧': 6, + '🧑🏾‍🔬': 6, + '🧑🏾‍🚀': 6, + '🧑🏾‍🚒': 6, + '🧑🏾‍🤝‍🧑🏻': 10, + '🧑🏾‍🤝‍🧑🏽': 10, + '🧑🏾‍🤝‍🧑🏾': 10, + '🧑🏾‍🤝‍🧑🏿': 10, + '🧑🏾‍🦯': 6, + '🧑🏾‍🦯‍➡️': 7, + '🧑🏾‍🦰': 6, + '🧑🏾‍🦱': 6, + '🧑🏾‍🦲': 6, + '🧑🏾‍🦳': 6, + '🧑🏾‍🦼': 6, + '🧑🏾‍🦽': 6, + '🧑🏾‍🩰': 6, + '🧑🏾‍🫯‍🧑🏻': 9, + '🧑🏾‍🫯‍🧑🏽': 9, + '🧑🏾‍🫯‍🧑🏿': 9, + '🧑🏿‍⚕️': 5, + '🧑🏿‍⚖️': 5, + '🧑🏿‍✈️': 5, + '🧑🏿‍❤️‍💋‍🧑🏻': 11, + '🧑🏿‍❤️‍💋‍🧑🏽': 11, + '🧑🏿‍🌾': 6, + '🧑🏿‍🍳': 6, + '🧑🏿‍🍼': 6, + '🧑🏿‍🎄': 6, + '🧑🏿‍🎓': 6, + '🧑🏿‍🎤': 6, + '🧑🏿‍🎨': 6, + '🧑🏿‍🏫': 6, + '🧑🏿‍🏭': 6, + '🧑🏿‍🐰‍🧑🏻': 10, + '🧑🏿‍🐰‍🧑🏼': 10, + '🧑🏿‍🐰‍🧑🏽': 10, + '🧑🏿‍🐰‍🧑🏾': 10, + '🧑🏿‍💻': 6, + '🧑🏿‍💼': 6, + '🧑🏿‍🔧': 6, + '🧑🏿‍🔬': 6, + '🧑🏿‍🚀': 6, + '🧑🏿‍🚒': 6, + '🧑🏿‍🤝‍🧑🏻': 10, + '🧑🏿‍🤝‍🧑🏼': 10, + '🧑🏿‍🤝‍🧑🏽': 10, + '🧑🏿‍🤝‍🧑🏾': 10, + '🧑🏿‍🤝‍🧑🏿': 10, + '🧑🏿‍🦯': 6, + '🧑🏿‍🦯‍➡️': 7, + '🧑🏿‍🦰': 6, + '🧑🏿‍🦱': 6, + '🧑🏿‍🦲': 6, + '🧑🏿‍🦳': 6, + '🧑🏿‍🦼': 6, + '🧑🏿‍🦼‍➡️': 7, + '🧑🏿‍🦽': 6, + '🧑🏿‍🦽‍➡️': 7, + '🧑🏿‍🩰': 6, + '🧑🏿‍🫯‍🧑🏻': 9, + '🧑🏿‍🫯‍🧑🏼': 9, + '🧑🏿‍🫯‍🧑🏽': 9, + '🧑🏿‍🫯‍🧑🏾': 9, + '🧔‍♀️': 3, + '🧔‍♂️': 3, + '🧔🏻‍♀️': 5, + '🧔🏻‍♂️': 5, + '🧔🏼‍♀️': 5, + '🧔🏼‍♂️': 5, + '🧔🏽‍♀️': 5, + '🧔🏽‍♂️': 5, + '🧔🏾‍♀️': 5, + '🧔🏾‍♂️': 5, + '🧔🏿‍♀️': 5, + '🧔🏿‍♂️': 5, + '🧖‍♀️': 3, + '🧖‍♂️': 3, + '🧖🏻‍♀️': 5, + '🧖🏻‍♂️': 5, + '🧖🏼‍♀️': 5, + '🧖🏼‍♂️': 5, + '🧖🏽‍♀️': 5, + '🧖🏽‍♂️': 5, + '🧖🏾‍♀️': 5, + '🧖🏾‍♂️': 5, + '🧖🏿‍♀️': 5, + '🧖🏿‍♂️': 5, + '🧗‍♀️': 3, + '🧗‍♂️': 3, + '🧗🏻‍♀️': 5, + '🧗🏻‍♂️': 5, + '🧗🏼‍♀️': 5, + '🧗🏼‍♂️': 5, + '🧗🏽‍♀️': 5, + '🧗🏽‍♂️': 5, + '🧗🏾‍♀️': 5, + '🧗🏾‍♂️': 5, + '🧗🏿‍♀️': 5, + '🧗🏿‍♂️': 5, + '🧘‍♀️': 3, + '🧘‍♂️': 3, + '🧘🏻‍♀️': 5, + '🧘🏻‍♂️': 5, + '🧘🏼‍♀️': 5, + '🧘🏼‍♂️': 5, + '🧘🏽‍♀️': 5, + '🧘🏽‍♂️': 5, + '🧘🏾‍♀️': 5, + '🧘🏾‍♂️': 5, + '🧘🏿‍♀️': 5, + '🧘🏿‍♂️': 5, + '🧙‍♀️': 3, + '🧙‍♂️': 3, + '🧙🏻‍♀️': 5, + '🧙🏻‍♂️': 5, + '🧙🏼‍♀️': 5, + '🧙🏼‍♂️': 5, + '🧙🏽‍♀️': 5, + '🧙🏽‍♂️': 5, + '🧙🏾‍♀️': 5, + '🧙🏾‍♂️': 5, + '🧙🏿‍♀️': 5, + '🧙🏿‍♂️': 5, + '🧚‍♀️': 3, + '🧚‍♂️': 3, + '🧚🏻‍♀️': 5, + '🧚🏻‍♂️': 5, + '🧚🏼‍♀️': 5, + '🧚🏼‍♂️': 5, + '🧚🏽‍♀️': 5, + '🧚🏽‍♂️': 5, + '🧚🏾‍♀️': 5, + '🧚🏾‍♂️': 5, + '🧚🏿‍♀️': 5, + '🧚🏿‍♂️': 5, + '🧛‍♀️': 3, + '🧛‍♂️': 3, + '🧛🏻‍♀️': 5, + '🧛🏻‍♂️': 5, + '🧛🏼‍♀️': 5, + '🧛🏼‍♂️': 5, + '🧛🏽‍♀️': 5, + '🧛🏽‍♂️': 5, + '🧛🏾‍♀️': 5, + '🧛🏾‍♂️': 5, + '🧛🏿‍♀️': 5, + '🧛🏿‍♂️': 5, + '🧜‍♀️': 3, + '🧜‍♂️': 3, + '🧜🏻‍♀️': 5, + '🧜🏻‍♂️': 5, + '🧜🏼‍♀️': 5, + '🧜🏼‍♂️': 5, + '🧜🏽‍♀️': 5, + '🧜🏽‍♂️': 5, + '🧜🏾‍♀️': 5, + '🧜🏾‍♂️': 5, + '🧜🏿‍♀️': 5, + '🧜🏿‍♂️': 5, + '🧝‍♀️': 3, + '🧝‍♂️': 3, + '🧝🏻‍♀️': 5, + '🧝🏻‍♂️': 5, + '🧝🏼‍♀️': 5, + '🧝🏼‍♂️': 5, + '🧝🏽‍♀️': 5, + '🧝🏽‍♂️': 5, + '🧝🏾‍♀️': 5, + '🧝🏾‍♂️': 5, + '🧝🏿‍♀️': 5, + '🧝🏿‍♂️': 5, + '🧞‍♀️': 3, + '🧞‍♂️': 3, + '🧟‍♀️': 3, + '🧟‍♂️': 3, + '🫱🏻‍🫲🏼': 8, + '🫱🏻‍🫲🏽': 8, + '🫱🏻‍🫲🏾': 8, + '🫱🏻‍🫲🏿': 8, + '🫱🏼‍🫲🏻': 8, + '🫱🏼‍🫲🏽': 8, + '🫱🏼‍🫲🏾': 8, + '🫱🏼‍🫲🏿': 8, + '🫱🏽‍🫲🏻': 8, + '🫱🏽‍🫲🏼': 8, + '🫱🏽‍🫲🏾': 8, + '🫱🏽‍🫲🏿': 8, + '🫱🏾‍🫲🏻': 8, + '🫱🏾‍🫲🏼': 8, + '🫱🏾‍🫲🏽': 8, + '🫱🏾‍🫲🏿': 8, + '🫱🏿‍🫲🏻': 8, + '🫱🏿‍🫲🏼': 8, + '🫱🏿‍🫲🏽': 8, + '🫱🏿‍🫲🏾': 8, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_a5880eeb.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_a5880eeb.py new file mode 100644 index 0000000000000000000000000000000000000000..de036053e0cde76005296abab39cb0e8a921bbd7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_a5880eeb.py @@ -0,0 +1,2570 @@ +""" +Grapheme overrides for _known_a5880eeb. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: st, urxvt, xterm +""" +# pylint: skip-file +GRAPHEMES = { + 'क्का': 3, + 'क्कां': 3, + 'क्को': 3, + 'क्घ्घि्': 4, + 'क्ता': 3, + 'क्ति': 3, + 'क्ती': 3, + 'क्तीं': 3, + 'क्तेः': 3, + 'क्त्योः': 5, + 'क्ना': 3, + 'क्नि': 3, + 'क्या': 3, + 'क्रा': 3, + 'क्रि': 3, + 'क्षा': 3, + 'क्षां': 3, + 'क्षाः': 4, + 'क्षि': 3, + 'क्षो': 3, + 'क्ष्ण': 3, + 'क्ष्य': 3, + 'क्ष्या': 4, + 'क्सा': 3, + 'ख्यः': 3, + 'ख्या': 3, + 'ग्या': 3, + 'ग्यैः': 3, + 'ग्र्य': 3, + 'घ्का': 3, + 'घ्र्व्य': 4, + 'घ्लि': 3, + 'घ्श्य': 3, + 'घ्स्ट': 3, + 'च्चा': 3, + 'च्चों': 3, + 'च्छा': 3, + 'च्छि': 3, + 'च्या': 3, + 'च्यां': 3, + 'च्यो': 3, + 'ज्ञा': 3, + 'ज्या': 3, + 'ज्या‌': 3, + 'ज्रा': 3, + 'ञ्चा': 3, + 'ञ्चि': 3, + 'ट्टि': 3, + 'ट्टी': 3, + 'ट्या': 3, + 'ट्रा': 3, + 'ण्डः': 3, + 'ण्डि': 3, + 'ण्या': 3, + 'ण्यां': 3, + 'ताः': 3, + 'त्का': 3, + 'त्ता': 3, + 'त्ति': 3, + 'त्त्थि': 4, + 'त्त्व': 3, + 'त्त्वा': 4, + 'त्त्वे': 3, + 'त्नी': 3, + 'त्नों': 3, + 'त्पा': 3, + 'त्पी': 3, + 'त्मा': 3, + 'त्या': 3, + 'त्यां': 3, + 'त्यि': 3, + 'त्रा': 3, + 'त्राा': 4, + 'त्राि': 4, + 'त्रि': 3, + 'त्री': 3, + 'त्र्त': 3, + 'त्र्य': 3, + 'त्र्या': 4, + 'त्र्ये': 3, + 'त्वा': 3, + 'त्वां': 3, + 'त्सा': 3, + 'त्सो': 3, + 'त्स्वा': 4, + 'द्घि': 3, + 'द्घो': 3, + 'द्दा': 3, + 'द्दि': 3, + 'द्दी': 3, + 'द्धः': 3, + 'द्धा': 3, + 'द्धां': 3, + 'द्धि': 3, + 'द्धिं': 3, + 'द्धी': 3, + 'द्धीं': 3, + 'द्धैः': 3, + 'द्भा': 3, + 'द्या': 3, + 'द्रो': 3, + 'द्वा': 3, + 'द्वि': 3, + 'धाः': 3, + 'ध्या': 3, + 'नाः': 3, + 'निः': 3, + 'न्का': 3, + 'न्चि': 3, + 'न्ञ्या': 4, + 'न्तः': 3, + 'न्ता': 3, + 'न्ति': 3, + 'न्तो': 3, + 'न्तों': 3, + 'न्त्र': 3, + 'न्त्रा': 4, + 'न्त्राः': 5, + 'न्त्रि': 4, + 'न्त्री': 4, + 'न्त्र्य': 4, + 'न्त्र्यं': 4, + 'न्त्र्या': 5, + 'न्त्र्ये': 4, + 'न्दा': 3, + 'न्दी': 3, + 'न्दो': 3, + 'न्धा': 3, + 'न्धि': 3, + 'न्धी': 3, + 'न्धों': 3, + 'न्ना': 3, + 'न्नाः': 4, + 'न्नि': 3, + 'न्मा': 3, + 'न्या': 3, + 'न्यो': 3, + 'न्हा': 3, + 'न्ह्यां': 4, + 'प्ति': 3, + 'प्तौ': 3, + 'प्या': 3, + 'प्रा': 3, + 'फ्ता': 3, + 'फ्ना': 3, + 'फ्नो': 3, + 'फ्रां': 3, + 'ब्धि': 3, + 'भिः': 3, + 'भ्यः': 3, + 'भ्या': 3, + 'भ्यां': 3, + 'भ्यो': 3, + 'म्ति': 3, + 'म्नि': 3, + 'म्पा': 3, + 'म्प्र': 3, + 'म्भि': 3, + 'म्मा': 3, + 'म्मि': 3, + 'म्या': 3, + 'म्ही': 3, + 'म्हो': 3, + 'याः': 3, + 'य्यो': 3, + 'राः': 3, + 'र्कि': 3, + 'र्गी': 3, + 'र्चि': 3, + 'र्जा': 3, + 'र्जि': 3, + 'र्जी': 3, + 'र्णां': 3, + 'र्णी': 3, + 'र्ता': 3, + 'र्ति': 3, + 'र्तिः': 4, + 'र्ती': 3, + 'र्त्त': 3, + 'र्त्ति': 4, + 'र्थि': 3, + 'र्थी': 3, + 'र्दा': 3, + 'र्दि': 3, + 'र्दो': 3, + 'र्द्ध': 3, + 'र्धा': 3, + 'र्धि': 3, + 'र्नि': 3, + 'र्बा': 3, + 'र्भा': 3, + 'र्मा': 3, + 'र्मि': 3, + 'र्या': 3, + 'र्यां': 3, + 'र्यों': 3, + 'र्रा': 3, + 'र्वा': 3, + 'र्वां': 3, + 'र्वो': 3, + 'र्सा': 3, + 'र्हाः': 4, + 'र्हि': 3, + 'र्हो': 3, + 'र्‍या': 3, + 'लाः': 3, + 'ल्का': 3, + 'ल्पि': 3, + 'ल्या': 3, + 'ल्यां': 3, + 'ल्याः': 4, + 'ल्ला': 3, + 'ल्लि': 3, + 'वाः': 3, + 'व्या': 3, + 'व्यों': 3, + 'शाः': 3, + 'श्चि': 3, + 'श्या': 3, + 'श्यि': 3, + 'श्यों': 3, + 'श्रा': 3, + 'श्रां': 3, + 'श्वा': 3, + 'श्वि': 3, + 'षाः': 3, + 'ष्का': 3, + 'ष्टः': 3, + 'ष्टा': 3, + 'ष्टां': 3, + 'ष्टाः': 4, + 'ष्टि': 3, + 'ष्टी': 3, + 'ष्टीं': 3, + 'ष्ट्र': 3, + 'ष्ट्रा': 4, + 'ष्ट्रां': 4, + 'ष्ट्रि': 4, + 'ष्ट्री': 4, + 'ष्ट्रे': 3, + 'ष्ट्रो': 4, + 'ष्ट्रों': 4, + 'ष्ठा': 3, + 'ष्ठों': 3, + 'ष्प्र': 3, + 'ष्यः': 3, + 'ष्यों': 3, + 'स्का': 3, + 'स्काः': 4, + 'स्ट्या': 4, + 'स्ता': 3, + 'स्ति': 3, + 'स्ती': 3, + 'स्तो': 3, + 'स्त्र': 3, + 'स्त्रा': 4, + 'स्त्रि': 4, + 'स्त्री': 4, + 'स्था': 3, + 'स्थां': 3, + 'स्थि': 3, + 'स्थी': 3, + 'स्थ्य': 3, + 'स्धी': 3, + 'स्मि': 3, + 'स्मिं': 3, + 'स्या': 3, + 'स्यां': 3, + 'स्याः': 4, + 'स्युः': 3, + 'स्यों': 3, + 'स्रो': 3, + 'स्वा': 3, + 'स्वी': 3, + 'स्सा': 3, + 'ह्या': 3, + 'ह्रा': 3, + 'फ़्ता': 3, + 'কিং': 3, + 'ক্তি': 3, + 'ক্রী': 3, + 'ক্ষা': 3, + 'ক্ষি': 3, + 'ক্ষে': 3, + 'ক্ষ্য': 3, + 'ক্ষ্যে': 4, + 'খ্যা': 3, + 'গ্রা': 3, + 'গ্রে': 3, + 'ঘো': 3, + 'ঙ্খা': 3, + 'ঙ্গী': 3, + 'ঙ্গে': 3, + 'চ্ছা': 3, + 'চ্ছা‌': 3, + 'চ্ছে': 3, + 'জ্ঞা': 3, + 'ঞ্চি': 3, + 'ঞ্ছি': 3, + 'ট্রে': 3, + 'ণ্ডে': 3, + 'ত্তা': 3, + 'ত্তি': 3, + 'ত্বে': 3, + 'ত্যা': 3, + 'ত্যি': 3, + 'ত্যে': 3, + 'ত্রা': 3, + 'ত্রে': 3, + 'ত্‍পী': 3, + 'ত্‍সা': 3, + 'দ্দি': 3, + 'দ্দে': 3, + 'দ্ধা': 3, + 'দ্ধি': 3, + 'দ্ধে': 3, + 'দ্বা': 3, + 'দ্রো': 3, + 'ধ্যে': 3, + 'ন্তা': 3, + 'ন্তি': 3, + 'ন্তে': 3, + 'ন্ত্রি': 4, + 'ন্ত্রে': 4, + 'ন্থী': 3, + 'ন্ধা': 3, + 'ন্মা': 3, + 'ন্যা': 3, + 'ন্যে': 3, + 'প্তা': 3, + 'প্রা': 3, + 'ব্ধি': 3, + 'ব্যা': 3, + 'ভ্রা': 3, + 'ম্পা': 3, + 'ম্মা': 3, + 'রাং': 3, + 'র্জা': 3, + 'র্থে': 3, + 'র্দো': 3, + 'র্ধা': 3, + 'র্নী': 3, + 'র্বা': 3, + 'র্বি': 3, + 'র্বো': 3, + 'র্ব্য': 3, + 'র্মে': 3, + 'র্যা': 3, + 'ল্যা': 3, + 'ল্যে': 3, + 'ল্লে': 3, + 'শ্চি': 3, + 'শ্বা': 3, + 'শ্বে': 3, + 'শ্যে': 3, + 'শ্রা': 3, + 'ষ্টা': 3, + 'ষ্টি': 3, + 'ষ্ট্র': 3, + 'ষ্ট্রী': 4, + 'ষ্ট্রে': 4, + 'ষ্ঠা': 3, + 'ষ্ঠি': 3, + 'ষ্ঠী': 3, + 'সাং': 3, + 'স্তি': 3, + 'স্তি‌': 3, + 'স্ত্র': 3, + 'স্থা': 3, + 'স্থ্য': 3, + 'স্বা': 3, + 'স্বী': 3, + 'স্যা': 3, + 'স্যে': 3, + 'ક્કા': 3, + 'ક્કો': 3, + 'ક્તિ': 3, + 'ક્ષા': 3, + 'ચ્ચા': 3, + 'ચ્છા': 3, + 'જ્ઞા': 3, + 'જ્યો': 3, + 'ત્તા': 3, + 'ત્તિ': 3, + 'ત્ત્વ': 3, + 'ત્ત્વા': 4, + 'ત્યા': 3, + 'ત્યાં': 3, + 'ત્યિ': 3, + 'ત્યો': 3, + 'ત્રી': 3, + 'ત્ર્ય': 3, + 'દ્ધા': 3, + 'દ્ધાં': 3, + 'દ્ધિ': 3, + 'દ્વા': 3, + 'ધ્યા': 3, + 'ન્તો': 3, + 'ન્મા': 3, + 'ન્યા': 3, + 'પ્રા': 3, + 'મ્યાં': 3, + 'ર્તા': 3, + 'ર્થિ': 3, + 'ર્દો': 3, + 'ર્મિ': 3, + 'ર્યા': 3, + 'ર્યો': 3, + 'વ્યા': 3, + 'વ્યો': 3, + 'ષ્ટિ': 3, + 'ષ્ટ્ર': 3, + 'ષ્ટ્રી': 4, + 'ષ્ટ્રો': 4, + 'ષ્ઠા': 3, + 'સ્તિ': 3, + 'સ્તી': 3, + 'સ્ત્રી': 4, + 'સ્થા': 3, + 'સ્થિ': 3, + 'સ્રી': 3, + 'સ્વા': 3, + 'સ્વી': 3, + 'સ્સા': 3, + 'కుం': 3, + 'క్కు': 3, + 'క్తు': 3, + 'క్రాం': 3, + 'క్రూ': 3, + 'క్షిం': 3, + 'క్స్వా': 3, + 'చ్చు': 3, + 'టుం': 3, + 'ట్లు': 3, + 'డ్రు': 3, + 'త్తు': 3, + 'త్నిం': 3, + 'త్యం': 3, + 'త్రు': 3, + 'త్ర్య': 3, + 'దుం': 3, + 'ద్దు': 3, + 'ద్ధిం': 3, + 'ద్ర్య': 3, + 'నుం': 3, + 'న్ను': 3, + 'భ్యు': 3, + 'యుం': 3, + 'ర్చు': 3, + 'ర్ణాం': 3, + 'ర్ణు': 3, + 'ర్తిం': 3, + 'ర్తృ': 3, + 'ర్థిం': 3, + 'ర్బం': 3, + 'ర్హాం': 3, + 'ర్హు': 3, + 'శ్రాం': 3, + 'ష్టు': 3, + 'ష్ట్ర': 3, + 'ష్ట్రీ': 3, + 'ష్ఠు': 3, + 'స్కృ': 3, + 'స్త్ర': 3, + 'స్త్రీ': 3, + 'స్థ్య': 3, + 'ಕಾಂ': 3, + 'ಕುಂ': 3, + 'ಕೊಂ': 3, + 'ಖಾಂ': 3, + 'ಗಾಂ': 3, + 'ಗೊಂ': 3, + 'ಟುಂ': 3, + 'ನಾಂ': 3, + 'ಯುಂ': 3, + 'ರಾಂ': 3, + 'ವುಂ': 3, + 'ಶಾಂ': 3, + 'ಸಾಂ': 3, + 'ಹೊಂ': 3, + 'ക്കാ': 3, + 'ക്കി': 3, + 'ക്കും': 3, + 'ക്കെ': 3, + 'ക്കേ': 3, + 'ക്കൊ': 3, + 'ക്കോ': 3, + 'ക്തി': 3, + 'ക്യം': 3, + 'ക്ഷാ': 3, + 'ക്ഷി': 3, + 'ക്ഷേ': 3, + 'ഖ്യാ': 3, + 'ഗ്ഗം': 3, + 'ഗ്ദാ': 3, + 'ഗ്യം': 3, + 'ങ്കി': 3, + 'ങ്കെ': 3, + 'ങ്കേ': 3, + 'ങ്ങി': 3, + 'ച്ചി': 3, + 'ച്ചും': 3, + 'ച്ചെ': 3, + 'ച്ചേ': 3, + 'ജ്യാ': 3, + 'ഞ്ഞി': 3, + 'ഞ്ഞെ': 3, + 'ട്ടാ': 3, + 'ട്ടി': 3, + 'ട്ടോ': 3, + 'ണ്ടാ': 3, + 'ണ്ടി': 3, + 'ണ്ടും': 3, + 'ണ്ടെ': 3, + 'ത്താ': 3, + 'ത്തി': 3, + 'ത്തും': 3, + 'ത്തെ': 3, + 'ത്തേ': 3, + 'ത്തോ': 3, + 'ത്നം': 3, + 'ത്നി': 3, + 'ത്യാ': 3, + 'ത്യേ': 3, + 'ത്വം': 3, + 'ദ്ധി': 3, + 'ദ്യാ': 3, + 'ന്തം': 3, + 'ന്തെ': 3, + 'ന്ത്ര': 3, + 'ന്ത്ര്യ': 4, + 'ന്ത്ര്യം': 5, + 'ന്ധി': 3, + 'ന്നാ': 3, + 'ന്നി': 3, + 'ന്നീ': 3, + 'ന്നും': 3, + 'ന്നെ': 3, + 'ന്നേ': 3, + 'ന്നോ': 3, + 'ന്മാ': 3, + 'ന്യം': 3, + 'ന്യാ': 3, + 'ന്യേ': 3, + 'ന്യോ': 3, + 'ന്റെ': 3, + 'ന്‍പി': 3, + 'പ്പി': 3, + 'പ്പെ': 3, + 'പ്പോ': 3, + 'പ്രാ': 3, + 'ബ്ലി': 3, + 'ഭ്യാ': 3, + 'ഭ്രാ': 3, + 'മ്പാ': 3, + 'മ്പ്ര': 3, + 'മ്മി': 3, + 'യ്ക്കു': 3, + 'യ്തി': 3, + 'യ്യാ': 3, + 'യ്യി': 3, + 'ര്യം': 3, + 'ര്‍ക്കു': 3, + 'ര്‍ക്കും': 4, + 'ര്‍ക്ക്‌': 3, + 'ര്‍ഗ്ഗം': 4, + 'ര്‍ച്ച': 3, + 'ര്‍ണ്ണ': 3, + 'ര്‍ത്ത': 3, + 'ര്‍ത്തി': 4, + 'ര്‍ത്തു': 3, + 'ര്‍ത്തേ': 4, + 'ര്‍ദേ': 3, + 'ര്‍ദ്ദ': 3, + 'ര്‍പ്പെ': 4, + 'ര്‍മ്മി': 4, + 'ര്‍രാ': 3, + 'ര്‍വ്വ': 3, + 'ര്‍ഹി': 3, + 'റ്റം': 3, + 'റ്റേ': 3, + 'ല്യാ': 3, + 'ല്ലാ': 3, + 'ല്ലാം': 4, + 'ല്ലെ': 3, + 'ല്‍കി': 3, + 'ല്‍കേ': 3, + 'ല്‍നി': 3, + 'ല്‍പ്പ': 3, + 'ള്ളാ': 3, + 'ള്ളി': 3, + 'ള്‍കൊ': 3, + 'ള്‍ക്ക': 3, + 'ള്‍ക്കി': 4, + 'ള്‍ക്കു': 3, + 'ള്‍ക്കും': 4, + 'ള്‍ക്കെ': 4, + 'ള്‍ക്ക്‌': 3, + 'വ്യം': 3, + 'വ്യാ': 3, + 'ശ്വാ': 3, + 'ഷ്ട്യാ': 4, + 'ഷ്ട്ര': 3, + 'ഷ്ട്രീ': 4, + 'ഷ്യാ': 3, + 'സാം': 3, + 'സ്കാ': 3, + 'സ്ത്രം': 4, + 'സ്ത്രീ': 4, + 'സ്ഥാ': 3, + 'സ്ഥി': 3, + 'സ്റ്റ്‌': 3, + 'സ്വാ': 3, + 'സ്വീ': 3, + 'സ്സാ': 3, + 'സ്സി': 3, + 'സ്സും': 3, + 'സ്സോ': 3, + 'ഹിം': 3, + 'ကျေ': 3, + 'ကြေ': 3, + 'ကြွေ': 3, + 'ချေ': 3, + 'ခြေ': 3, + 'ဇြေ': 3, + 'ဒ္ဂေ': 3, + 'ပျေ': 3, + 'ပြေ': 3, + 'ဖျေံ': 3, + 'ဗ္တေ': 3, + 'ဗ္ၜေ': 3, + 'ဗြေ': 3, + 'မြေ': 3, + 'လျေ': 3, + 'လျှေ': 3, + 'သ္ဂေ': 3, + 'ក្ដៅ': 3, + 'ក្រោ': 3, + 'ក្សា': 3, + 'ខ្ជា': 3, + 'ខ្លា': 3, + 'គ្នា': 3, + 'គ្មា': 3, + 'គ្រា': 3, + 'គ្រឹះ': 3, + 'ង្កើ': 3, + 'ង្រៀ': 3, + 'ង្ហា': 3, + 'ច្ចេ': 3, + 'ច្បា': 3, + 'ឆ្នាំ': 3, + 'ឆ្នោ': 3, + 'ឆ្លើ': 3, + 'ជ្ជា': 3, + 'ជ្ញា': 3, + 'ជ្រើ': 3, + 'ជ្រៀ': 3, + 'ជ្រែ': 3, + 'ឈ្មោះ': 4, + 'ញ្ជា': 3, + 'ញ្ញា': 3, + 'ញ្ញៈ': 3, + 'ដ្ឋា': 3, + 'ណោះ': 3, + 'ណ្ដា': 3, + 'ណ្ដុះ': 3, + 'ណ្ណោះ': 4, + 'ត្រា': 3, + 'ថ្ងៃ': 3, + 'ថ្នា': 3, + 'ថ្លៃ': 3, + 'ទោះ': 3, + 'ទ្យា': 3, + 'ធ្នា': 3, + 'ធ្យា': 3, + 'ធ្យោ': 3, + 'ធ្វើ': 3, + 'នេះ': 3, + 'នោះ': 3, + 'ន្ថែ': 3, + 'ន្ថោ': 3, + 'ន្ទា': 3, + 'ន្ទៈ': 3, + 'ន្យា': 3, + 'ន្លែ': 3, + 'បោះ': 3, + 'ប្ដេ': 3, + 'ប្រា': 3, + 'ប្រើ': 3, + 'ប្រែ': 3, + 'ផ្ដា': 3, + 'ផ្ទា': 3, + 'ផ្ទេ': 3, + 'ផ្នែ': 3, + 'ផ្លា': 3, + 'ផ្សា': 3, + 'ផ្សេ': 3, + 'ផ្សៃ': 3, + 'ពោះ': 3, + 'ព្យា': 3, + 'ព្រៀ': 3, + 'ព្រៃ': 3, + 'ម្ងា': 3, + 'ម្ចា': 3, + 'ម្ដា': 3, + 'ម្ដែ': 3, + 'ម្នា': 3, + 'ម្នេ': 3, + 'ម្ភា': 3, + 'ម្រា': 3, + 'ម្រើ': 3, + 'ម្រេ': 3, + 'ម្លៀ': 3, + 'ម្លៃ': 3, + 'ល្បៈ': 3, + 'ល្មើ': 3, + 'ស្គា': 3, + 'ស្ដ្រី': 3, + 'ស្ត្រ': 3, + 'ស្ថា': 3, + 'ស្នា': 3, + 'ស្មា': 3, + 'ស្មើ': 3, + 'ស្រា': 3, + 'ស្លា': 3, + 'ស្វែ': 3, + 'ᨣᩕᩮ᩠': 3, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 3, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 3, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 3, + '⛓️‍💥': 3, + '⛹🏻‍♀️': 4, + '⛹🏻‍♂️': 4, + '⛹🏼‍♀️': 4, + '⛹🏼‍♂️': 4, + '⛹🏽‍♀️': 4, + '⛹🏽‍♂️': 4, + '⛹🏾‍♀️': 4, + '⛹🏾‍♂️': 4, + '⛹🏿‍♀️': 4, + '⛹🏿‍♂️': 4, + '❤️‍🔥': 3, + '❤️‍🩹': 3, + 'ꦏꦺꦴ': 3, + 'ꦏ꧀': 2, + 'ꦏ꧀ꦏ': 3, + 'ꦏ꧀ꦏꦁ': 3, + 'ꦏ꧀ꦏꦺ': 4, + 'ꦏ꧀ꦏꦼ': 3, + 'ꦏ꧀ꦔ': 3, + 'ꦏ꧀ꦔꦸ': 3, + 'ꦏ꧀ꦔꦿ': 4, + 'ꦏ꧀ꦕ': 3, + 'ꦏ꧀ꦠ': 3, + 'ꦏ꧀ꦠꦶ': 3, + 'ꦏ꧀ꦠꦸ': 3, + 'ꦏ꧀ꦠꦺ': 4, + 'ꦏ꧀ꦢ': 3, + 'ꦏ꧀ꦢꦂ': 3, + 'ꦏ꧀ꦢꦶ': 3, + 'ꦏ꧀ꦤ': 3, + 'ꦏ꧀ꦤꦶꦁ': 3, + 'ꦏ꧀ꦥ': 3, + 'ꦏ꧀ꦥꦶ': 3, + 'ꦏ꧀ꦥꦿꦶ': 4, + 'ꦏ꧀ꦧ': 3, + 'ꦏ꧀ꦧꦶ': 3, + 'ꦏ꧀ꦧꦺ': 4, + 'ꦏ꧀ꦩ': 3, + 'ꦏ꧀ꦩꦸ': 3, + 'ꦏ꧀ꦪ': 3, + 'ꦏ꧀ꦭ': 3, + 'ꦏ꧀ꦮ': 3, + 'ꦏ꧀ꦱ': 3, + 'ꦏ꧀ꦱꦂ': 3, + 'ꦏ꧀ꦱꦶ': 3, + 'ꦏ꧀ꦱꦸ': 3, + 'ꦏ꧀ꦱꦺ': 4, + 'ꦏ꧀ꦲ': 3, + 'ꦏ꧀ꦲꦁ': 3, + 'ꦏ꧀ꦲꦶꦁ': 3, + 'ꦏ꧀ꦲꦸ': 3, + 'ꦏ꧀ꦲꦺ': 4, + 'ꦏ꧀ꦲꦺꦴ': 5, + 'ꦒꦺꦴ': 3, + 'ꦒꦿꦺ': 3, + 'ꦒ꧀ꦒ': 3, + 'ꦔꦺꦴ': 3, + 'ꦔ꧀ꦒꦼ': 3, + 'ꦔ꧀ꦒꦿꦼꦁ': 4, + 'ꦔ꧀ꦭ': 3, + 'ꦔ꧀ꦭꦁ': 3, + 'ꦔ꧀ꦭꦸ': 3, + 'ꦔ꧀ꦭꦼ': 3, + 'ꦕꦺꦴ': 3, + 'ꦗꦿꦺꦴ': 4, + 'ꦚ꧀ꦕ': 3, + 'ꦚ꧀ꦕꦶ': 3, + 'ꦚ꧀ꦗ': 3, + 'ꦚ꧀ꦗꦶ': 3, + 'ꦚ꧀ꦗꦸꦁ': 3, + 'ꦚ꧀ꦗꦸꦂ': 3, + 'ꦝꦺꦴ': 3, + 'ꦝꦺꦴꦂ': 3, + 'ꦠꦺꦃ': 3, + 'ꦠꦺꦴ': 3, + 'ꦠ꧀': 2, + 'ꦠ꧀ꦏꦁ': 3, + 'ꦠ꧀ꦏꦸ': 3, + 'ꦠ꧀ꦒ': 3, + 'ꦠ꧀ꦔꦸ': 3, + 'ꦠ꧀ꦚ': 3, + 'ꦠ꧀ꦠ': 3, + 'ꦠ꧀ꦠꦶ': 3, + 'ꦠ꧀ꦠꦶꦁ': 3, + 'ꦠ꧀ꦠꦸ': 3, + 'ꦠ꧀ꦠꦺ': 4, + 'ꦠ꧀ꦤ': 3, + 'ꦠ꧀ꦤꦶ': 3, + 'ꦠ꧀ꦩ': 3, + 'ꦠ꧀ꦩꦼ': 3, + 'ꦠ꧀ꦭ': 3, + 'ꦠ꧀ꦭꦺ': 4, + 'ꦠ꧀ꦱ': 3, + 'ꦠ꧀ꦱꦶꦁ': 3, + 'ꦠ꧀ꦱꦶꦃ': 4, + 'ꦠ꧀ꦱꦾ': 4, + 'ꦠ꧀ꦱ꧀ꦮ': 5, + 'ꦠ꧀ꦲ': 3, + 'ꦠ꧀ꦲꦶꦁ': 3, + 'ꦠ꧀ꦲꦺꦴ': 5, + 'ꦢꦺꦴ': 3, + 'ꦢ꧀': 2, + 'ꦢ꧀ꦏ': 3, + 'ꦢ꧀ꦠ': 3, + 'ꦢ꧀ꦠꦶꦁ': 3, + 'ꦢ꧀ꦢ': 3, + 'ꦢ꧀ꦥ': 3, + 'ꦢ꧀ꦩꦺꦴ': 5, + 'ꦢ꧀ꦲ': 3, + 'ꦤꦺꦃ': 3, + 'ꦤꦺꦴ': 3, + 'ꦤ꧀': 2, + 'ꦤ꧀ꦏ': 3, + 'ꦤ꧀ꦏꦁ': 3, + 'ꦤ꧀ꦏꦸ': 3, + 'ꦤ꧀ꦏꦼ': 3, + 'ꦤ꧀ꦒ': 3, + 'ꦤ꧀ꦔ': 3, + 'ꦤ꧀ꦔꦁ': 3, + 'ꦤ꧀ꦔꦶ': 3, + 'ꦤ꧀ꦔꦸ': 3, + 'ꦤ꧀ꦔꦸꦂ': 3, + 'ꦤ꧀ꦔꦺ': 4, + 'ꦤ꧀ꦔꦼ': 3, + 'ꦤ꧀ꦔꦿꦸ': 4, + 'ꦤ꧀ꦗ': 3, + 'ꦤ꧀ꦗꦸ': 3, + 'ꦤ꧀ꦗꦼ': 3, + 'ꦤ꧀ꦚꦶ': 3, + 'ꦤ꧀ꦛꦃ': 4, + 'ꦤ꧀ꦛꦶ': 3, + 'ꦤ꧀ꦝ': 3, + 'ꦤ꧀ꦝꦁ': 3, + 'ꦤ꧀ꦝꦶ': 3, + 'ꦤ꧀ꦝꦸ': 3, + 'ꦤ꧀ꦝꦸꦁ': 3, + 'ꦤ꧀ꦝꦺꦁ': 4, + 'ꦤ꧀ꦝꦺꦴꦁ': 5, + 'ꦤ꧀ꦝꦼ': 3, + 'ꦤ꧀ꦠ': 3, + 'ꦤ꧀ꦠꦂ': 3, + 'ꦤ꧀ꦠꦃ': 4, + 'ꦤ꧀ꦠꦶ': 3, + 'ꦤ꧀ꦠꦸ': 3, + 'ꦤ꧀ꦠꦸꦁ': 3, + 'ꦤ꧀ꦠꦺ': 4, + 'ꦤ꧀ꦠꦼ': 3, + 'ꦤ꧀ꦠꦼꦂ': 3, + 'ꦤ꧀ꦠꦽ': 3, + 'ꦤ꧀ꦢ': 3, + 'ꦤ꧀ꦢꦁ': 3, + 'ꦤ꧀ꦢꦂ': 3, + 'ꦤ꧀ꦢꦶ': 3, + 'ꦤ꧀ꦢꦸ': 3, + 'ꦤ꧀ꦢꦺ': 4, + 'ꦤ꧀ꦢꦼ': 3, + 'ꦤ꧀ꦤ': 3, + 'ꦤ꧀ꦤꦶ': 3, + 'ꦤ꧀ꦤꦶꦁ': 3, + 'ꦤ꧀ꦤꦺ': 4, + 'ꦤ꧀ꦤꦼ': 3, + 'ꦤ꧀ꦥ': 3, + 'ꦤ꧀ꦥꦁ': 3, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 5, + 'ꦤ꧀ꦥꦶ': 3, + 'ꦤ꧀ꦥꦸ': 3, + 'ꦤ꧀ꦥꦼ': 3, + 'ꦤ꧀ꦥꦿ': 4, + 'ꦤ꧀ꦥꦿꦶ': 4, + 'ꦤ꧀ꦧ': 3, + 'ꦤ꧀ꦧꦁ': 3, + 'ꦤ꧀ꦧꦶ': 3, + 'ꦤ꧀ꦧꦸ': 3, + 'ꦤ꧀ꦧꦺ': 4, + 'ꦤ꧀ꦧꦺꦴ': 5, + 'ꦤ꧀ꦧꦼ': 3, + 'ꦤ꧀ꦩ': 3, + 'ꦤ꧀ꦩꦂ': 3, + 'ꦤ꧀ꦩꦶ': 3, + 'ꦤ꧀ꦩꦸꦂ': 3, + 'ꦤ꧀ꦩꦼ': 3, + 'ꦤ꧀ꦭ': 3, + 'ꦤ꧀ꦭꦶ': 3, + 'ꦤ꧀ꦭꦸ': 3, + 'ꦤ꧀ꦮ': 3, + 'ꦤ꧀ꦮꦂ': 3, + 'ꦤ꧀ꦮꦶ': 3, + 'ꦤ꧀ꦮꦸ': 3, + 'ꦤ꧀ꦮꦼ': 3, + 'ꦤ꧀ꦱ': 3, + 'ꦤ꧀ꦱꦂ': 3, + 'ꦤ꧀ꦱꦃ': 4, + 'ꦤ꧀ꦱꦶ': 3, + 'ꦤ꧀ꦱꦶꦁ': 3, + 'ꦤ꧀ꦱꦸ': 3, + 'ꦤ꧀ꦱꦺꦴ': 5, + 'ꦤ꧀ꦱꦼ': 3, + 'ꦤ꧀ꦲ': 3, + 'ꦤ꧀ꦲꦁ': 3, + 'ꦤ꧀ꦲꦶ': 3, + 'ꦤ꧀ꦲꦶꦁ': 3, + 'ꦤ꧀ꦲꦸ': 3, + 'ꦤ꧀ꦲꦺꦴ': 5, + 'ꦥ꦳꧀': 2, + 'ꦥꦺꦴ': 3, + 'ꦥꦿꦃ': 3, + 'ꦥꦿꦺꦴ': 4, + 'ꦥ꧀': 2, + 'ꦥ꧀ꦏ': 3, + 'ꦥ꧀ꦏꦁ': 3, + 'ꦥ꧀ꦠ': 3, + 'ꦥ꧀ꦠꦶ': 3, + 'ꦥ꧀ꦢꦸ': 3, + 'ꦥ꧀ꦤ': 3, + 'ꦥ꧀ꦤꦶ': 3, + 'ꦥ꧀ꦥ': 3, + 'ꦥ꧀ꦥꦶ': 3, + 'ꦥ꧀ꦥꦺ': 4, + 'ꦥ꧀ꦧꦺ': 4, + 'ꦥ꧀ꦩ': 3, + 'ꦥ꧀ꦩꦂ': 3, + 'ꦥ꧀ꦫꦺ': 4, + 'ꦥ꧀ꦭ': 3, + 'ꦥ꧀ꦭꦸ': 3, + 'ꦥ꧀ꦱ': 3, + 'ꦥ꧀ꦱꦶꦂ': 3, + 'ꦥ꧀ꦱꦼ': 3, + 'ꦥ꧀ꦲ': 3, + 'ꦧꦺꦃ': 3, + 'ꦧꦺꦴ': 3, + 'ꦧ꧀': 2, + 'ꦧ꧀ꦏ': 3, + 'ꦧ꧀ꦠꦸ': 3, + 'ꦧ꧀ꦥ': 3, + 'ꦧ꧀ꦧ': 3, + 'ꦧ꧀ꦧꦺ': 4, + 'ꦧ꧀ꦲ': 3, + 'ꦧ꧀ꦲꦶ': 3, + 'ꦩꦺꦃ': 3, + 'ꦩꦺꦴ': 3, + 'ꦩꦿꦃ': 3, + 'ꦩꦿꦶꦃ': 3, + 'ꦩ꧀': 2, + 'ꦩ꧀ꦏꦁ': 3, + 'ꦩ꧀ꦔꦼ': 3, + 'ꦩ꧀ꦠꦸ': 3, + 'ꦩ꧀ꦠꦺꦴ': 5, + 'ꦩ꧀ꦤꦶꦁ': 3, + 'ꦩ꧀ꦥ': 3, + 'ꦩ꧀ꦥꦶ': 3, + 'ꦩ꧀ꦥꦸ': 3, + 'ꦩ꧀ꦥꦼ': 3, + 'ꦩ꧀ꦧ': 3, + 'ꦩ꧀ꦧꦁ': 3, + 'ꦩ꧀ꦧꦂ': 3, + 'ꦩ꧀ꦧꦃ': 4, + 'ꦩ꧀ꦧꦶ': 3, + 'ꦩ꧀ꦧꦸ': 3, + 'ꦩ꧀ꦧꦸꦁ': 3, + 'ꦩ꧀ꦧꦺ': 4, + 'ꦩ꧀ꦧꦺꦂ': 4, + 'ꦩ꧀ꦧꦼꦂ': 3, + 'ꦩ꧀ꦧꦾꦸꦂ': 4, + 'ꦩ꧀ꦩ': 3, + 'ꦩ꧀ꦩꦶ': 3, + 'ꦩ꧀ꦫ': 3, + 'ꦩ꧀ꦫꦃ': 4, + 'ꦩ꧀ꦭ': 3, + 'ꦩ꧀ꦲꦶ': 3, + 'ꦪꦺꦴ': 3, + 'ꦫꦺꦴ': 3, + 'ꦭꦺꦃ': 3, + 'ꦭꦺꦴ': 3, + 'ꦭꦺꦴꦁ': 3, + 'ꦭ꧀': 2, + 'ꦭ꧀ꦏꦁ': 3, + 'ꦭ꧀ꦚꦼꦁ': 3, + 'ꦭ꧀ꦠꦸ': 3, + 'ꦭ꧀ꦧꦸ': 3, + 'ꦭ꧀ꦩꦸ': 3, + 'ꦭ꧀ꦭ': 3, + 'ꦭ꧀ꦭꦶ': 3, + 'ꦭ꧀ꦭꦶꦁ': 3, + 'ꦭ꧀ꦭꦺ': 4, + 'ꦭ꧀ꦮ': 3, + 'ꦭ꧀ꦱ': 3, + 'ꦭ꧀ꦱꦂ': 3, + 'ꦭ꧀ꦱꦶꦁ': 3, + 'ꦭ꧀ꦱꦸ': 3, + 'ꦭ꧀ꦲ': 3, + 'ꦭ꧀ꦲꦁ': 3, + 'ꦭ꧀ꦲꦶꦁ': 3, + 'ꦭ꧀ꦲꦸ': 3, + 'ꦮꦺꦴ': 3, + 'ꦮꦺꦴꦁ': 3, + 'ꦮꦺꦴꦃ': 4, + 'ꦮꦿꦸꦃ': 3, + 'ꦱꦺꦴ': 3, + 'ꦱꦿꦃ': 3, + 'ꦱ꧀': 2, + 'ꦱ꧀ꦏ': 3, + 'ꦱ꧀ꦏꦁ': 3, + 'ꦱ꧀ꦏꦿꦶ': 4, + 'ꦱ꧀ꦒ': 3, + 'ꦱ꧀ꦔꦸ': 3, + 'ꦱ꧀ꦔꦿ': 4, + 'ꦱ꧀ꦛꦶ': 3, + 'ꦱ꧀ꦠ': 3, + 'ꦱ꧀ꦠꦿ': 4, + 'ꦱ꧀ꦢꦂ': 3, + 'ꦱ꧀ꦢꦶ': 3, + 'ꦱ꧀ꦢꦸ': 3, + 'ꦱ꧀ꦥ': 3, + 'ꦱ꧀ꦧ': 3, + 'ꦱ꧀ꦧꦁ': 3, + 'ꦱ꧀ꦩ': 3, + 'ꦱ꧀ꦩꦶ': 3, + 'ꦱ꧀ꦩꦼ': 3, + 'ꦱ꧀ꦩꦿ': 4, + 'ꦱ꧀ꦭ': 3, + 'ꦱ꧀ꦮ': 3, + 'ꦱ꧀ꦱ': 3, + 'ꦱ꧀ꦱꦂ': 3, + 'ꦱ꧀ꦱꦶ': 3, + 'ꦱ꧀ꦱꦶꦁ': 3, + 'ꦱ꧀ꦱꦸ': 3, + 'ꦱ꧀ꦱꦺ': 4, + 'ꦱ꧀ꦲ': 3, + 'ꦱ꧀ꦲꦁ': 3, + 'ꦱ꧀ꦲꦶ': 3, + 'ꦱ꧀ꦲꦶꦁ': 3, + 'ꦱ꧀ꦲꦸ': 3, + 'ꦲꦺꦴ': 3, + '𑄇𑄳𑄠𑄬': 3, + '𑄈𑄳𑄠𑄬': 3, + '𑄌𑄳𑄠𑄬': 3, + '𑄎𑄳𑄠𑄬': 3, + '𑄑𑄳𑄢𑄬': 3, + '𑄖𑄳𑄠𑄬': 3, + '𑄖𑄳𑄢𑄬': 3, + '𑄘𑄳𑄠𑄬': 3, + '𑄚𑄳𑄠𑄬': 3, + '𑄝𑄳𑄢𑄬': 3, + '𑄟𑄳𑄠𑄬': 3, + '𑄡𑄳𑄠𑄬': 3, + '𑄣𑄳𑄦𑄬': 3, + '𑌕𑌾𑌂': 3, + '𑌕𑌾𑌃': 3, + '𑌕𑍍': 2, + '𑌗𑍍': 2, + '𑌚𑍍': 2, + '𑌜𑍍': 2, + '𑌞𑍍': 2, + '𑌟𑌾𑌂': 3, + '𑌟𑌾𑌃': 3, + '𑌟𑍍': 2, + '𑌠𑍈𑌃': 3, + '𑌣𑌾𑌂': 3, + '𑌣𑍍': 2, + '𑌤𑌾𑌂': 3, + '𑌤𑌾𑌃': 3, + '𑌤𑌿𑌂': 3, + '𑌤𑌿𑌃': 3, + '𑌤𑍁𑌂': 3, + '𑌤𑍇𑌃': 3, + '𑌤𑍍': 2, + '𑌥𑌾𑌂': 3, + '𑌦𑍍': 2, + '𑌧𑌾𑌃': 3, + '𑌧𑌿𑌂': 3, + '𑌧𑍇𑌃': 3, + '𑌧𑍈𑌃': 3, + '𑌧𑍍': 2, + '𑌨𑌾𑌂': 3, + '𑌨𑌾𑌃': 3, + '𑌨𑌿𑌃': 3, + '𑌨𑍈𑌃': 3, + '𑌨𑍍': 2, + '𑌪𑍍': 2, + '𑌬𑍍': 2, + '𑌭𑌿𑌃': 3, + '𑌭𑍍': 2, + '𑌮𑌿𑌂': 3, + '𑌮𑍍': 2, + '𑌯𑌾𑌂': 3, + '𑌯𑌾𑌃': 3, + '𑌯𑍁𑌃': 3, + '𑌯𑍈𑌃': 3, + '𑌯𑍋𑌃': 3, + '𑌯𑍍': 2, + '𑌰𑌾𑌃': 3, + '𑌰𑌿𑌂': 3, + '𑌰𑍍': 2, + '𑌲𑌾𑌃': 3, + '𑌲𑌿𑌂': 3, + '𑌲𑍍': 2, + '𑌵𑌾𑌂': 3, + '𑌵𑌾𑌃': 3, + '𑌵𑍍': 2, + '𑌶𑌾𑌃': 3, + '𑌶𑍍': 2, + '𑌷𑌾𑌂': 3, + '𑌷𑌾𑌃': 3, + '𑌷𑍍': 2, + '𑌸𑌾𑌂': 3, + '𑌸𑍍': 2, + '𑌹𑌾𑌃': 3, + '🍄‍🟫': 4, + '🍋‍🟩': 4, + '🏃‍♀️': 3, + '🏃‍♀️‍➡️': 4, + '🏃‍♂️': 3, + '🏃‍♂️‍➡️': 4, + '🏃‍➡️': 3, + '🏃🏻‍♀️': 5, + '🏃🏻‍♀️‍➡️': 6, + '🏃🏻‍♂️': 5, + '🏃🏻‍♂️‍➡️': 6, + '🏃🏻‍➡️': 5, + '🏃🏼‍♀️': 5, + '🏃🏼‍♀️‍➡️': 6, + '🏃🏼‍♂️': 5, + '🏃🏼‍♂️‍➡️': 6, + '🏃🏼‍➡️': 5, + '🏃🏽‍♀️': 5, + '🏃🏽‍♀️‍➡️': 6, + '🏃🏽‍♂️': 5, + '🏃🏽‍♂️‍➡️': 6, + '🏃🏽‍➡️': 5, + '🏃🏾‍♀️': 5, + '🏃🏾‍♀️‍➡️': 6, + '🏃🏾‍♂️': 5, + '🏃🏾‍♂️‍➡️': 6, + '🏃🏾‍➡️': 5, + '🏃🏿‍♀️': 5, + '🏃🏿‍♀️‍➡️': 6, + '🏃🏿‍♂️': 5, + '🏃🏿‍♂️‍➡️': 6, + '🏃🏿‍➡️': 5, + '🏄‍♀️': 3, + '🏄‍♂️': 3, + '🏄🏻‍♀️': 5, + '🏄🏻‍♂️': 5, + '🏄🏼‍♀️': 5, + '🏄🏼‍♂️': 5, + '🏄🏽‍♀️': 5, + '🏄🏽‍♂️': 5, + '🏄🏾‍♀️': 5, + '🏄🏾‍♂️': 5, + '🏄🏿‍♀️': 5, + '🏄🏿‍♂️': 5, + '🏊‍♀️': 3, + '🏊‍♂️': 3, + '🏊🏻‍♀️': 5, + '🏊🏻‍♂️': 5, + '🏊🏼‍♀️': 5, + '🏊🏼‍♂️': 5, + '🏊🏽‍♀️': 5, + '🏊🏽‍♂️': 5, + '🏊🏾‍♀️': 5, + '🏊🏾‍♂️': 5, + '🏊🏿‍♀️': 5, + '🏊🏿‍♂️': 5, + '🏋🏻‍♀️': 4, + '🏋🏻‍♂️': 4, + '🏋🏼‍♀️': 4, + '🏋🏼‍♂️': 4, + '🏋🏽‍♀️': 4, + '🏋🏽‍♂️': 4, + '🏋🏾‍♀️': 4, + '🏋🏾‍♂️': 4, + '🏋🏿‍♀️': 4, + '🏋🏿‍♂️': 4, + '🏌🏻‍♀️': 4, + '🏌🏻‍♂️': 4, + '🏌🏼‍♀️': 4, + '🏌🏼‍♂️': 4, + '🏌🏽‍♀️': 4, + '🏌🏽‍♂️': 4, + '🏌🏾‍♀️': 4, + '🏌🏾‍♂️': 4, + '🏌🏿‍♀️': 4, + '🏌🏿‍♂️': 4, + '🏳️‍🌈': 3, + '🏴‍☠️': 3, + '🐈‍⬛': 4, + '🐕‍🦺': 4, + '🐦‍⬛': 4, + '🐦‍🔥': 4, + '🐻‍❄️': 3, + '👨‍⚕️': 3, + '👨‍⚖️': 3, + '👨‍✈️': 3, + '👨‍❤️‍👨': 5, + '👨‍❤️‍💋‍👨': 7, + '👨‍🌾': 4, + '👨‍🍳': 4, + '👨‍🍼': 4, + '👨‍🎓': 4, + '👨‍🎤': 4, + '👨‍🎨': 4, + '👨‍🏫': 4, + '👨‍🏭': 4, + '👨‍👦': 4, + '👨‍👦‍👦': 6, + '👨‍👧': 4, + '👨‍👧‍👦': 6, + '👨‍👧‍👧': 6, + '👨‍👨‍👦': 6, + '👨‍👨‍👦‍👦': 8, + '👨‍👨‍👧': 6, + '👨‍👨‍👧‍👦': 8, + '👨‍👨‍👧‍👧': 8, + '👨‍👩‍👦': 6, + '👨‍👩‍👦‍👦': 8, + '👨‍👩‍👧': 6, + '👨‍👩‍👧‍👦': 8, + '👨‍👩‍👧‍👧': 8, + '👨‍💻': 4, + '👨‍💼': 4, + '👨‍🔧': 4, + '👨‍🔬': 4, + '👨‍🚀': 4, + '👨‍🚒': 4, + '👨‍🦯': 4, + '👨‍🦯‍➡️': 5, + '👨‍🦰': 4, + '👨‍🦱': 4, + '👨‍🦲': 4, + '👨‍🦳': 4, + '👨‍🦼': 4, + '👨‍🦼‍➡️': 5, + '👨‍🦽': 4, + '👨‍🦽‍➡️': 5, + '👨🏻‍⚕️': 5, + '👨🏻‍⚖️': 5, + '👨🏻‍✈️': 5, + '👨🏻‍❤️‍👨🏻': 9, + '👨🏻‍❤️‍👨🏽': 9, + '👨🏻‍❤️‍👨🏿': 9, + '👨🏻‍❤️‍💋‍👨🏻': 11, + '👨🏻‍❤️‍💋‍👨🏽': 11, + '👨🏻‍❤️‍💋‍👨🏾': 11, + '👨🏻‍❤️‍💋‍👨🏿': 11, + '👨🏻‍🌾': 6, + '👨🏻‍🍳': 6, + '👨🏻‍🍼': 6, + '👨🏻‍🎓': 6, + '👨🏻‍🎤': 6, + '👨🏻‍🎨': 6, + '👨🏻‍🏫': 6, + '👨🏻‍🏭': 6, + '👨🏻‍🐰‍👨🏼': 10, + '👨🏻‍🐰‍👨🏽': 10, + '👨🏻‍🐰‍👨🏾': 10, + '👨🏻‍🐰‍👨🏿': 10, + '👨🏻‍💻': 6, + '👨🏻‍💼': 6, + '👨🏻‍🔧': 6, + '👨🏻‍🔬': 6, + '👨🏻‍🚀': 6, + '👨🏻‍🚒': 6, + '👨🏻‍🤝‍👨🏼': 10, + '👨🏻‍🤝‍👨🏽': 10, + '👨🏻‍🤝‍👨🏾': 10, + '👨🏻‍🤝‍👨🏿': 10, + '👨🏻‍🦯': 6, + '👨🏻‍🦯‍➡️': 7, + '👨🏻‍🦰': 6, + '👨🏻‍🦱': 6, + '👨🏻‍🦲': 6, + '👨🏻‍🦳': 6, + '👨🏻‍🦼': 6, + '👨🏻‍🦼‍➡️': 7, + '👨🏻‍🦽': 6, + '👨🏻‍🦽‍➡️': 7, + '👨🏻‍🫯‍👨🏼': 10, + '👨🏻‍🫯‍👨🏽': 10, + '👨🏻‍🫯‍👨🏾': 10, + '👨🏻‍🫯‍👨🏿': 10, + '👨🏼‍⚕️': 5, + '👨🏼‍⚖️': 5, + '👨🏼‍✈️': 5, + '👨🏼‍❤️‍👨🏼': 9, + '👨🏼‍❤️‍💋‍👨🏼': 11, + '👨🏼‍❤️‍💋‍👨🏿': 11, + '👨🏼‍🌾': 6, + '👨🏼‍🍳': 6, + '👨🏼‍🍼': 6, + '👨🏼‍🎓': 6, + '👨🏼‍🎤': 6, + '👨🏼‍🎨': 6, + '👨🏼‍🏫': 6, + '👨🏼‍🏭': 6, + '👨🏼‍🐰‍👨🏻': 10, + '👨🏼‍🐰‍👨🏽': 10, + '👨🏼‍🐰‍👨🏿': 10, + '👨🏼‍💻': 6, + '👨🏼‍💼': 6, + '👨🏼‍🔧': 6, + '👨🏼‍🔬': 6, + '👨🏼‍🚀': 6, + '👨🏼‍🚒': 6, + '👨🏼‍🤝‍👨🏻': 10, + '👨🏼‍🤝‍👨🏽': 10, + '👨🏼‍🤝‍👨🏿': 10, + '👨🏼‍🦯': 6, + '👨🏼‍🦯‍➡️': 7, + '👨🏼‍🦰': 6, + '👨🏼‍🦱': 6, + '👨🏼‍🦲': 6, + '👨🏼‍🦳': 6, + '👨🏼‍🦼': 6, + '👨🏼‍🦽': 6, + '👨🏼‍🦽‍➡️': 7, + '👨🏼‍🫯‍👨🏻': 10, + '👨🏼‍🫯‍👨🏽': 10, + '👨🏼‍🫯‍👨🏾': 10, + '👨🏼‍🫯‍👨🏿': 10, + '👨🏽‍⚕️': 5, + '👨🏽‍⚖️': 5, + '👨🏽‍✈️': 5, + '👨🏽‍❤️‍👨🏻': 9, + '👨🏽‍❤️‍👨🏽': 9, + '👨🏽‍❤️‍👨🏿': 9, + '👨🏽‍❤️‍💋‍👨🏻': 11, + '👨🏽‍❤️‍💋‍👨🏽': 11, + '👨🏽‍❤️‍💋‍👨🏿': 11, + '👨🏽‍🌾': 6, + '👨🏽‍🍳': 6, + '👨🏽‍🍼': 6, + '👨🏽‍🎓': 6, + '👨🏽‍🎤': 6, + '👨🏽‍🎨': 6, + '👨🏽‍🏫': 6, + '👨🏽‍🏭': 6, + '👨🏽‍🐰‍👨🏻': 10, + '👨🏽‍🐰‍👨🏼': 10, + '👨🏽‍🐰‍👨🏾': 10, + '👨🏽‍🐰‍👨🏿': 10, + '👨🏽‍💻': 6, + '👨🏽‍💼': 6, + '👨🏽‍🔧': 6, + '👨🏽‍🔬': 6, + '👨🏽‍🚀': 6, + '👨🏽‍🚒': 6, + '👨🏽‍🤝‍👨🏻': 10, + '👨🏽‍🤝‍👨🏼': 10, + '👨🏽‍🤝‍👨🏾': 10, + '👨🏽‍🤝‍👨🏿': 10, + '👨🏽‍🦯': 6, + '👨🏽‍🦯‍➡️': 7, + '👨🏽‍🦰': 6, + '👨🏽‍🦱': 6, + '👨🏽‍🦲': 6, + '👨🏽‍🦳': 6, + '👨🏽‍🦼': 6, + '👨🏽‍🦼‍➡️': 7, + '👨🏽‍🦽': 6, + '👨🏽‍🦽‍➡️': 7, + '👨🏽‍🫯‍👨🏻': 10, + '👨🏽‍🫯‍👨🏼': 10, + '👨🏽‍🫯‍👨🏾': 10, + '👨🏽‍🫯‍👨🏿': 10, + '👨🏾‍⚕️': 5, + '👨🏾‍⚖️': 5, + '👨🏾‍✈️': 5, + '👨🏾‍❤️‍👨🏾': 9, + '👨🏾‍❤️‍💋‍👨🏻': 11, + '👨🏾‍❤️‍💋‍👨🏾': 11, + '👨🏾‍❤️‍💋‍👨🏿': 11, + '👨🏾‍🌾': 6, + '👨🏾‍🍳': 6, + '👨🏾‍🍼': 6, + '👨🏾‍🎓': 6, + '👨🏾‍🎤': 6, + '👨🏾‍🎨': 6, + '👨🏾‍🏫': 6, + '👨🏾‍🏭': 6, + '👨🏾‍🐰‍👨🏻': 10, + '👨🏾‍🐰‍👨🏽': 10, + '👨🏾‍🐰‍👨🏿': 10, + '👨🏾‍💻': 6, + '👨🏾‍💼': 6, + '👨🏾‍🔧': 6, + '👨🏾‍🔬': 6, + '👨🏾‍🚀': 6, + '👨🏾‍🚒': 6, + '👨🏾‍🤝‍👨🏻': 10, + '👨🏾‍🤝‍👨🏽': 10, + '👨🏾‍🤝‍👨🏿': 10, + '👨🏾‍🦯': 6, + '👨🏾‍🦯‍➡️': 7, + '👨🏾‍🦰': 6, + '👨🏾‍🦱': 6, + '👨🏾‍🦲': 6, + '👨🏾‍🦳': 6, + '👨🏾‍🦼': 6, + '👨🏾‍🦽': 6, + '👨🏾‍🦽‍➡️': 7, + '👨🏾‍🫯‍👨🏻': 10, + '👨🏾‍🫯‍👨🏼': 10, + '👨🏾‍🫯‍👨🏽': 10, + '👨🏾‍🫯‍👨🏿': 10, + '👨🏿‍⚕️': 5, + '👨🏿‍⚖️': 5, + '👨🏿‍✈️': 5, + '👨🏿‍❤️‍👨🏻': 9, + '👨🏿‍❤️‍👨🏽': 9, + '👨🏿‍❤️‍👨🏿': 9, + '👨🏿‍❤️‍💋‍👨🏻': 11, + '👨🏿‍❤️‍💋‍👨🏼': 11, + '👨🏿‍❤️‍💋‍👨🏽': 11, + '👨🏿‍❤️‍💋‍👨🏾': 11, + '👨🏿‍❤️‍💋‍👨🏿': 11, + '👨🏿‍🌾': 6, + '👨🏿‍🍳': 6, + '👨🏿‍🍼': 6, + '👨🏿‍🎓': 6, + '👨🏿‍🎤': 6, + '👨🏿‍🎨': 6, + '👨🏿‍🏫': 6, + '👨🏿‍🏭': 6, + '👨🏿‍🐰‍👨🏻': 10, + '👨🏿‍🐰‍👨🏼': 10, + '👨🏿‍🐰‍👨🏽': 10, + '👨🏿‍🐰‍👨🏾': 10, + '👨🏿‍💻': 6, + '👨🏿‍💼': 6, + '👨🏿‍🔧': 6, + '👨🏿‍🔬': 6, + '👨🏿‍🚀': 6, + '👨🏿‍🚒': 6, + '👨🏿‍🤝‍👨🏻': 10, + '👨🏿‍🤝‍👨🏼': 10, + '👨🏿‍🤝‍👨🏽': 10, + '👨🏿‍🤝‍👨🏾': 10, + '👨🏿‍🦯': 6, + '👨🏿‍🦯‍➡️': 7, + '👨🏿‍🦰': 6, + '👨🏿‍🦱': 6, + '👨🏿‍🦲': 6, + '👨🏿‍🦳': 6, + '👨🏿‍🦼': 6, + '👨🏿‍🦼‍➡️': 7, + '👨🏿‍🦽': 6, + '👨🏿‍🦽‍➡️': 7, + '👨🏿‍🫯‍👨🏻': 10, + '👨🏿‍🫯‍👨🏼': 10, + '👨🏿‍🫯‍👨🏽': 10, + '👨🏿‍🫯‍👨🏾': 10, + '👩‍⚕️': 3, + '👩‍⚖️': 3, + '👩‍✈️': 3, + '👩‍❤️‍👨': 5, + '👩‍❤️‍👩': 5, + '👩‍❤️‍💋‍👨': 7, + '👩‍❤️‍💋‍👩': 7, + '👩‍🌾': 4, + '👩‍🍳': 4, + '👩‍🍼': 4, + '👩‍🎓': 4, + '👩‍🎤': 4, + '👩‍🎨': 4, + '👩‍🏫': 4, + '👩‍🏭': 4, + '👩‍👦': 4, + '👩‍👦‍👦': 6, + '👩‍👧': 4, + '👩‍👧‍👦': 6, + '👩‍👧‍👧': 6, + '👩‍👩‍👦': 6, + '👩‍👩‍👦‍👦': 8, + '👩‍👩‍👧': 6, + '👩‍👩‍👧‍👦': 8, + '👩‍👩‍👧‍👧': 8, + '👩‍💻': 4, + '👩‍💼': 4, + '👩‍🔧': 4, + '👩‍🔬': 4, + '👩‍🚀': 4, + '👩‍🚒': 4, + '👩‍🦯': 4, + '👩‍🦯‍➡️': 5, + '👩‍🦰': 4, + '👩‍🦱': 4, + '👩‍🦲': 4, + '👩‍🦳': 4, + '👩‍🦼': 4, + '👩‍🦼‍➡️': 5, + '👩‍🦽': 4, + '👩‍🦽‍➡️': 5, + '👩🏻‍⚕️': 5, + '👩🏻‍⚖️': 5, + '👩🏻‍✈️': 5, + '👩🏻‍❤️‍👨🏻': 9, + '👩🏻‍❤️‍👨🏿': 9, + '👩🏻‍❤️‍👩🏻': 9, + '👩🏻‍❤️‍💋‍👨🏻': 11, + '👩🏻‍❤️‍💋‍👨🏽': 11, + '👩🏻‍❤️‍💋‍👨🏿': 11, + '👩🏻‍❤️‍💋‍👩🏻': 11, + '👩🏻‍❤️‍💋‍👩🏽': 11, + '👩🏻‍❤️‍💋‍👩🏿': 11, + '👩🏻‍🌾': 6, + '👩🏻‍🍳': 6, + '👩🏻‍🍼': 6, + '👩🏻‍🎓': 6, + '👩🏻‍🎤': 6, + '👩🏻‍🎨': 6, + '👩🏻‍🏫': 6, + '👩🏻‍🏭': 6, + '👩🏻‍🐰‍👩🏼': 10, + '👩🏻‍🐰‍👩🏽': 10, + '👩🏻‍🐰‍👩🏾': 10, + '👩🏻‍🐰‍👩🏿': 10, + '👩🏻‍💻': 6, + '👩🏻‍💼': 6, + '👩🏻‍🔧': 6, + '👩🏻‍🔬': 6, + '👩🏻‍🚀': 6, + '👩🏻‍🚒': 6, + '👩🏻‍🤝‍👨🏽': 10, + '👩🏻‍🤝‍👨🏿': 10, + '👩🏻‍🤝‍👩🏼': 10, + '👩🏻‍🤝‍👩🏽': 10, + '👩🏻‍🤝‍👩🏾': 10, + '👩🏻‍🤝‍👩🏿': 10, + '👩🏻‍🦯': 6, + '👩🏻‍🦯‍➡️': 7, + '👩🏻‍🦰': 6, + '👩🏻‍🦱': 6, + '👩🏻‍🦲': 6, + '👩🏻‍🦳': 6, + '👩🏻‍🦼': 6, + '👩🏻‍🦼‍➡️': 7, + '👩🏻‍🦽': 6, + '👩🏻‍🦽‍➡️': 7, + '👩🏻‍🫯‍👩🏼': 10, + '👩🏻‍🫯‍👩🏽': 10, + '👩🏻‍🫯‍👩🏾': 10, + '👩🏻‍🫯‍👩🏿': 10, + '👩🏼‍⚕️': 5, + '👩🏼‍⚖️': 5, + '👩🏼‍✈️': 5, + '👩🏼‍❤️‍👨🏼': 9, + '👩🏼‍❤️‍👩🏼': 9, + '👩🏼‍❤️‍💋‍👨🏼': 11, + '👩🏼‍❤️‍💋‍👩🏼': 11, + '👩🏼‍🌾': 6, + '👩🏼‍🍳': 6, + '👩🏼‍🍼': 6, + '👩🏼‍🎓': 6, + '👩🏼‍🎤': 6, + '👩🏼‍🎨': 6, + '👩🏼‍🏫': 6, + '👩🏼‍🏭': 6, + '👩🏼‍🐰‍👩🏻': 10, + '👩🏼‍🐰‍👩🏿': 10, + '👩🏼‍💻': 6, + '👩🏼‍💼': 6, + '👩🏼‍🔧': 6, + '👩🏼‍🔬': 6, + '👩🏼‍🚀': 6, + '👩🏼‍🚒': 6, + '👩🏼‍🤝‍👩🏻': 10, + '👩🏼‍🤝‍👩🏽': 10, + '👩🏼‍🤝‍👩🏿': 10, + '👩🏼‍🦯': 6, + '👩🏼‍🦯‍➡️': 7, + '👩🏼‍🦰': 6, + '👩🏼‍🦱': 6, + '👩🏼‍🦲': 6, + '👩🏼‍🦳': 6, + '👩🏼‍🦼': 6, + '👩🏼‍🦽': 6, + '👩🏼‍🫯‍👩🏻': 10, + '👩🏼‍🫯‍👩🏽': 10, + '👩🏼‍🫯‍👩🏾': 10, + '👩🏼‍🫯‍👩🏿': 10, + '👩🏽‍⚕️': 5, + '👩🏽‍⚖️': 5, + '👩🏽‍✈️': 5, + '👩🏽‍❤️‍👨🏽': 9, + '👩🏽‍❤️‍👩🏽': 9, + '👩🏽‍❤️‍💋‍👨🏻': 11, + '👩🏽‍❤️‍💋‍👨🏽': 11, + '👩🏽‍❤️‍💋‍👨🏿': 11, + '👩🏽‍❤️‍💋‍👩🏻': 11, + '👩🏽‍❤️‍💋‍👩🏽': 11, + '👩🏽‍❤️‍💋‍👩🏿': 11, + '👩🏽‍🌾': 6, + '👩🏽‍🍳': 6, + '👩🏽‍🍼': 6, + '👩🏽‍🎓': 6, + '👩🏽‍🎤': 6, + '👩🏽‍🎨': 6, + '👩🏽‍🏫': 6, + '👩🏽‍🏭': 6, + '👩🏽‍🐰‍👩🏻': 10, + '👩🏽‍🐰‍👩🏾': 10, + '👩🏽‍🐰‍👩🏿': 10, + '👩🏽‍💻': 6, + '👩🏽‍💼': 6, + '👩🏽‍🔧': 6, + '👩🏽‍🔬': 6, + '👩🏽‍🚀': 6, + '👩🏽‍🚒': 6, + '👩🏽‍🤝‍👨🏻': 10, + '👩🏽‍🤝‍👨🏿': 10, + '👩🏽‍🤝‍👩🏻': 10, + '👩🏽‍🤝‍👩🏼': 10, + '👩🏽‍🤝‍👩🏾': 10, + '👩🏽‍🤝‍👩🏿': 10, + '👩🏽‍🦯': 6, + '👩🏽‍🦯‍➡️': 7, + '👩🏽‍🦰': 6, + '👩🏽‍🦱': 6, + '👩🏽‍🦲': 6, + '👩🏽‍🦳': 6, + '👩🏽‍🦼': 6, + '👩🏽‍🦼‍➡️': 7, + '👩🏽‍🦽': 6, + '👩🏽‍🦽‍➡️': 7, + '👩🏽‍🫯‍👩🏻': 10, + '👩🏽‍🫯‍👩🏼': 10, + '👩🏽‍🫯‍👩🏾': 10, + '👩🏽‍🫯‍👩🏿': 10, + '👩🏾‍⚕️': 5, + '👩🏾‍⚖️': 5, + '👩🏾‍✈️': 5, + '👩🏾‍❤️‍👨🏾': 9, + '👩🏾‍❤️‍👩🏾': 9, + '👩🏾‍❤️‍💋‍👨🏾': 11, + '👩🏾‍❤️‍💋‍👩🏾': 11, + '👩🏾‍🌾': 6, + '👩🏾‍🍳': 6, + '👩🏾‍🍼': 6, + '👩🏾‍🎓': 6, + '👩🏾‍🎤': 6, + '👩🏾‍🎨': 6, + '👩🏾‍🏫': 6, + '👩🏾‍🏭': 6, + '👩🏾‍🐰‍👩🏻': 10, + '👩🏾‍🐰‍👩🏽': 10, + '👩🏾‍🐰‍👩🏿': 10, + '👩🏾‍💻': 6, + '👩🏾‍💼': 6, + '👩🏾‍🔧': 6, + '👩🏾‍🔬': 6, + '👩🏾‍🚀': 6, + '👩🏾‍🚒': 6, + '👩🏾‍🤝‍👩🏻': 10, + '👩🏾‍🤝‍👩🏽': 10, + '👩🏾‍🤝‍👩🏿': 10, + '👩🏾‍🦯': 6, + '👩🏾‍🦯‍➡️': 7, + '👩🏾‍🦰': 6, + '👩🏾‍🦱': 6, + '👩🏾‍🦲': 6, + '👩🏾‍🦳': 6, + '👩🏾‍🦼': 6, + '👩🏾‍🦽': 6, + '👩🏾‍🦽‍➡️': 7, + '👩🏾‍🫯‍👩🏻': 10, + '👩🏾‍🫯‍👩🏼': 10, + '👩🏾‍🫯‍👩🏽': 10, + '👩🏾‍🫯‍👩🏿': 10, + '👩🏿‍⚕️': 5, + '👩🏿‍⚖️': 5, + '👩🏿‍✈️': 5, + '👩🏿‍❤️‍👨🏻': 9, + '👩🏿‍❤️‍👨🏿': 9, + '👩🏿‍❤️‍👩🏿': 9, + '👩🏿‍❤️‍💋‍👨🏻': 11, + '👩🏿‍❤️‍💋‍👨🏽': 11, + '👩🏿‍❤️‍💋‍👨🏿': 11, + '👩🏿‍❤️‍💋‍👩🏻': 11, + '👩🏿‍❤️‍💋‍👩🏽': 11, + '👩🏿‍❤️‍💋‍👩🏿': 11, + '👩🏿‍🌾': 6, + '👩🏿‍🍳': 6, + '👩🏿‍🍼': 6, + '👩🏿‍🎓': 6, + '👩🏿‍🎤': 6, + '👩🏿‍🎨': 6, + '👩🏿‍🏫': 6, + '👩🏿‍🏭': 6, + '👩🏿‍🐰‍👩🏻': 10, + '👩🏿‍🐰‍👩🏼': 10, + '👩🏿‍🐰‍👩🏽': 10, + '👩🏿‍🐰‍👩🏾': 10, + '👩🏿‍💻': 6, + '👩🏿‍💼': 6, + '👩🏿‍🔧': 6, + '👩🏿‍🔬': 6, + '👩🏿‍🚀': 6, + '👩🏿‍🚒': 6, + '👩🏿‍🤝‍👨🏻': 10, + '👩🏿‍🤝‍👨🏽': 10, + '👩🏿‍🤝‍👩🏻': 10, + '👩🏿‍🤝‍👩🏼': 10, + '👩🏿‍🤝‍👩🏽': 10, + '👩🏿‍🤝‍👩🏾': 10, + '👩🏿‍🦯': 6, + '👩🏿‍🦯‍➡️': 7, + '👩🏿‍🦰': 6, + '👩🏿‍🦱': 6, + '👩🏿‍🦲': 6, + '👩🏿‍🦳': 6, + '👩🏿‍🦼': 6, + '👩🏿‍🦼‍➡️': 7, + '👩🏿‍🦽': 6, + '👩🏿‍🦽‍➡️': 7, + '👩🏿‍🫯‍👩🏻': 10, + '👩🏿‍🫯‍👩🏼': 10, + '👩🏿‍🫯‍👩🏽': 10, + '👩🏿‍🫯‍👩🏾': 10, + '👮‍♀️': 3, + '👮‍♂️': 3, + '👮🏻‍♀️': 5, + '👮🏻‍♂️': 5, + '👮🏼‍♀️': 5, + '👮🏼‍♂️': 5, + '👮🏽‍♀️': 5, + '👮🏽‍♂️': 5, + '👮🏾‍♀️': 5, + '👮🏾‍♂️': 5, + '👮🏿‍♀️': 5, + '👮🏿‍♂️': 5, + '👯‍♀️': 3, + '👯‍♂️': 3, + '👯🏻‍♀️': 5, + '👯🏻‍♂️': 5, + '👯🏼‍♀️': 5, + '👯🏼‍♂️': 5, + '👯🏽‍♀️': 5, + '👯🏽‍♂️': 5, + '👯🏾‍♀️': 5, + '👯🏾‍♂️': 5, + '👯🏿‍♀️': 5, + '👯🏿‍♂️': 5, + '👰‍♀️': 3, + '👰‍♂️': 3, + '👰🏻‍♀️': 5, + '👰🏻‍♂️': 5, + '👰🏼‍♀️': 5, + '👰🏼‍♂️': 5, + '👰🏽‍♀️': 5, + '👰🏽‍♂️': 5, + '👰🏾‍♀️': 5, + '👰🏾‍♂️': 5, + '👰🏿‍♀️': 5, + '👰🏿‍♂️': 5, + '👱‍♀️': 3, + '👱‍♂️': 3, + '👱🏻‍♀️': 5, + '👱🏻‍♂️': 5, + '👱🏼‍♀️': 5, + '👱🏼‍♂️': 5, + '👱🏽‍♀️': 5, + '👱🏽‍♂️': 5, + '👱🏾‍♀️': 5, + '👱🏾‍♂️': 5, + '👱🏿‍♀️': 5, + '👱🏿‍♂️': 5, + '👳‍♀️': 3, + '👳‍♂️': 3, + '👳🏻‍♀️': 5, + '👳🏻‍♂️': 5, + '👳🏼‍♀️': 5, + '👳🏼‍♂️': 5, + '👳🏽‍♀️': 5, + '👳🏽‍♂️': 5, + '👳🏾‍♀️': 5, + '👳🏾‍♂️': 5, + '👳🏿‍♀️': 5, + '👳🏿‍♂️': 5, + '👷‍♀️': 3, + '👷‍♂️': 3, + '👷🏻‍♀️': 5, + '👷🏻‍♂️': 5, + '👷🏼‍♀️': 5, + '👷🏼‍♂️': 5, + '👷🏽‍♀️': 5, + '👷🏽‍♂️': 5, + '👷🏾‍♀️': 5, + '👷🏾‍♂️': 5, + '👷🏿‍♀️': 5, + '👷🏿‍♂️': 5, + '💁‍♀️': 3, + '💁‍♂️': 3, + '💁🏻‍♀️': 5, + '💁🏻‍♂️': 5, + '💁🏼‍♀️': 5, + '💁🏼‍♂️': 5, + '💁🏽‍♀️': 5, + '💁🏽‍♂️': 5, + '💁🏾‍♀️': 5, + '💁🏾‍♂️': 5, + '💁🏿‍♀️': 5, + '💁🏿‍♂️': 5, + '💂‍♀️': 3, + '💂‍♂️': 3, + '💂🏻‍♀️': 5, + '💂🏻‍♂️': 5, + '💂🏼‍♀️': 5, + '💂🏼‍♂️': 5, + '💂🏽‍♀️': 5, + '💂🏽‍♂️': 5, + '💂🏾‍♀️': 5, + '💂🏾‍♂️': 5, + '💂🏿‍♀️': 5, + '💂🏿‍♂️': 5, + '💆‍♀️': 3, + '💆‍♂️': 3, + '💆🏻‍♀️': 5, + '💆🏻‍♂️': 5, + '💆🏼‍♀️': 5, + '💆🏼‍♂️': 5, + '💆🏽‍♀️': 5, + '💆🏽‍♂️': 5, + '💆🏾‍♀️': 5, + '💆🏾‍♂️': 5, + '💆🏿‍♀️': 5, + '💆🏿‍♂️': 5, + '💇‍♀️': 3, + '💇‍♂️': 3, + '💇🏻‍♀️': 5, + '💇🏻‍♂️': 5, + '💇🏼‍♀️': 5, + '💇🏼‍♂️': 5, + '💇🏽‍♀️': 5, + '💇🏽‍♂️': 5, + '💇🏾‍♀️': 5, + '💇🏾‍♂️': 5, + '💇🏿‍♀️': 5, + '💇🏿‍♂️': 5, + '🕵🏻‍♀️': 4, + '🕵🏻‍♂️': 4, + '🕵🏼‍♀️': 4, + '🕵🏼‍♂️': 4, + '🕵🏽‍♀️': 4, + '🕵🏽‍♂️': 4, + '🕵🏾‍♀️': 4, + '🕵🏾‍♂️': 4, + '🕵🏿‍♀️': 4, + '🕵🏿‍♂️': 4, + '😮‍💨': 4, + '😵‍💫': 4, + '😶‍🌫️': 3, + '🙂‍↔️': 3, + '🙂‍↕️': 3, + '🙅‍♀️': 3, + '🙅‍♂️': 3, + '🙅🏻‍♀️': 5, + '🙅🏻‍♂️': 5, + '🙅🏼‍♀️': 5, + '🙅🏼‍♂️': 5, + '🙅🏽‍♀️': 5, + '🙅🏽‍♂️': 5, + '🙅🏾‍♀️': 5, + '🙅🏾‍♂️': 5, + '🙅🏿‍♀️': 5, + '🙅🏿‍♂️': 5, + '🙆‍♀️': 3, + '🙆‍♂️': 3, + '🙆🏻‍♀️': 5, + '🙆🏻‍♂️': 5, + '🙆🏼‍♀️': 5, + '🙆🏼‍♂️': 5, + '🙆🏽‍♀️': 5, + '🙆🏽‍♂️': 5, + '🙆🏾‍♀️': 5, + '🙆🏾‍♂️': 5, + '🙆🏿‍♀️': 5, + '🙆🏿‍♂️': 5, + '🙇‍♀️': 3, + '🙇‍♂️': 3, + '🙇🏻‍♀️': 5, + '🙇🏻‍♂️': 5, + '🙇🏼‍♀️': 5, + '🙇🏼‍♂️': 5, + '🙇🏽‍♀️': 5, + '🙇🏽‍♂️': 5, + '🙇🏾‍♀️': 5, + '🙇🏾‍♂️': 5, + '🙇🏿‍♀️': 5, + '🙇🏿‍♂️': 5, + '🙋‍♀️': 3, + '🙋‍♂️': 3, + '🙋🏻‍♀️': 5, + '🙋🏻‍♂️': 5, + '🙋🏼‍♀️': 5, + '🙋🏼‍♂️': 5, + '🙋🏽‍♀️': 5, + '🙋🏽‍♂️': 5, + '🙋🏾‍♀️': 5, + '🙋🏾‍♂️': 5, + '🙋🏿‍♀️': 5, + '🙋🏿‍♂️': 5, + '🙍‍♀️': 3, + '🙍‍♂️': 3, + '🙍🏻‍♀️': 5, + '🙍🏻‍♂️': 5, + '🙍🏼‍♀️': 5, + '🙍🏼‍♂️': 5, + '🙍🏽‍♀️': 5, + '🙍🏽‍♂️': 5, + '🙍🏾‍♀️': 5, + '🙍🏾‍♂️': 5, + '🙍🏿‍♀️': 5, + '🙍🏿‍♂️': 5, + '🙎‍♀️': 3, + '🙎‍♂️': 3, + '🙎🏻‍♀️': 5, + '🙎🏻‍♂️': 5, + '🙎🏼‍♀️': 5, + '🙎🏼‍♂️': 5, + '🙎🏽‍♀️': 5, + '🙎🏽‍♂️': 5, + '🙎🏾‍♀️': 5, + '🙎🏾‍♂️': 5, + '🙎🏿‍♀️': 5, + '🙎🏿‍♂️': 5, + '🚣‍♀️': 3, + '🚣‍♂️': 3, + '🚣🏻‍♀️': 5, + '🚣🏻‍♂️': 5, + '🚣🏼‍♀️': 5, + '🚣🏼‍♂️': 5, + '🚣🏽‍♀️': 5, + '🚣🏽‍♂️': 5, + '🚣🏾‍♀️': 5, + '🚣🏾‍♂️': 5, + '🚣🏿‍♀️': 5, + '🚣🏿‍♂️': 5, + '🚴‍♀️': 3, + '🚴‍♂️': 3, + '🚴🏻‍♀️': 5, + '🚴🏻‍♂️': 5, + '🚴🏼‍♀️': 5, + '🚴🏼‍♂️': 5, + '🚴🏽‍♀️': 5, + '🚴🏽‍♂️': 5, + '🚴🏾‍♀️': 5, + '🚴🏾‍♂️': 5, + '🚴🏿‍♀️': 5, + '🚴🏿‍♂️': 5, + '🚵‍♀️': 3, + '🚵‍♂️': 3, + '🚵🏻‍♀️': 5, + '🚵🏻‍♂️': 5, + '🚵🏼‍♀️': 5, + '🚵🏼‍♂️': 5, + '🚵🏽‍♀️': 5, + '🚵🏽‍♂️': 5, + '🚵🏾‍♀️': 5, + '🚵🏾‍♂️': 5, + '🚵🏿‍♀️': 5, + '🚵🏿‍♂️': 5, + '🚶‍♀️': 3, + '🚶‍♀️‍➡️': 4, + '🚶‍♂️': 3, + '🚶‍♂️‍➡️': 4, + '🚶‍➡️': 3, + '🚶🏻‍♀️': 5, + '🚶🏻‍♀️‍➡️': 6, + '🚶🏻‍♂️': 5, + '🚶🏻‍♂️‍➡️': 6, + '🚶🏻‍➡️': 5, + '🚶🏼‍♀️': 5, + '🚶🏼‍♀️‍➡️': 6, + '🚶🏼‍♂️': 5, + '🚶🏼‍♂️‍➡️': 6, + '🚶🏼‍➡️': 5, + '🚶🏽‍♀️': 5, + '🚶🏽‍♀️‍➡️': 6, + '🚶🏽‍♂️': 5, + '🚶🏽‍♂️‍➡️': 6, + '🚶🏽‍➡️': 5, + '🚶🏾‍♀️': 5, + '🚶🏾‍♀️‍➡️': 6, + '🚶🏾‍♂️': 5, + '🚶🏾‍♂️‍➡️': 6, + '🚶🏾‍➡️': 5, + '🚶🏿‍♀️': 5, + '🚶🏿‍♀️‍➡️': 6, + '🚶🏿‍♂️': 5, + '🚶🏿‍♂️‍➡️': 6, + '🚶🏿‍➡️': 5, + '🤦‍♀️': 3, + '🤦‍♂️': 3, + '🤦🏻‍♀️': 5, + '🤦🏻‍♂️': 5, + '🤦🏼‍♀️': 5, + '🤦🏼‍♂️': 5, + '🤦🏽‍♀️': 5, + '🤦🏽‍♂️': 5, + '🤦🏾‍♀️': 5, + '🤦🏾‍♂️': 5, + '🤦🏿‍♀️': 5, + '🤦🏿‍♂️': 5, + '🤵‍♀️': 3, + '🤵‍♂️': 3, + '🤵🏻‍♀️': 5, + '🤵🏻‍♂️': 5, + '🤵🏼‍♀️': 5, + '🤵🏼‍♂️': 5, + '🤵🏽‍♀️': 5, + '🤵🏽‍♂️': 5, + '🤵🏾‍♀️': 5, + '🤵🏾‍♂️': 5, + '🤵🏿‍♀️': 5, + '🤵🏿‍♂️': 5, + '🤷‍♀️': 3, + '🤷‍♂️': 3, + '🤷🏻‍♀️': 5, + '🤷🏻‍♂️': 5, + '🤷🏼‍♀️': 5, + '🤷🏼‍♂️': 5, + '🤷🏽‍♀️': 5, + '🤷🏽‍♂️': 5, + '🤷🏾‍♀️': 5, + '🤷🏾‍♂️': 5, + '🤷🏿‍♀️': 5, + '🤷🏿‍♂️': 5, + '🤸‍♀️': 3, + '🤸‍♂️': 3, + '🤸🏻‍♀️': 5, + '🤸🏻‍♂️': 5, + '🤸🏼‍♀️': 5, + '🤸🏼‍♂️': 5, + '🤸🏽‍♀️': 5, + '🤸🏽‍♂️': 5, + '🤸🏾‍♀️': 5, + '🤸🏾‍♂️': 5, + '🤸🏿‍♀️': 5, + '🤸🏿‍♂️': 5, + '🤹‍♀️': 3, + '🤹‍♂️': 3, + '🤹🏻‍♀️': 5, + '🤹🏻‍♂️': 5, + '🤹🏼‍♀️': 5, + '🤹🏼‍♂️': 5, + '🤹🏽‍♀️': 5, + '🤹🏽‍♂️': 5, + '🤹🏾‍♀️': 5, + '🤹🏾‍♂️': 5, + '🤹🏿‍♀️': 5, + '🤹🏿‍♂️': 5, + '🤼‍♀️': 3, + '🤼‍♂️': 3, + '🤼🏻‍♀️': 5, + '🤼🏻‍♂️': 5, + '🤼🏼‍♀️': 5, + '🤼🏼‍♂️': 5, + '🤼🏽‍♀️': 5, + '🤼🏽‍♂️': 5, + '🤼🏾‍♀️': 5, + '🤼🏾‍♂️': 5, + '🤼🏿‍♀️': 5, + '🤼🏿‍♂️': 5, + '🤽‍♀️': 3, + '🤽‍♂️': 3, + '🤽🏻‍♀️': 5, + '🤽🏻‍♂️': 5, + '🤽🏼‍♀️': 5, + '🤽🏼‍♂️': 5, + '🤽🏽‍♀️': 5, + '🤽🏽‍♂️': 5, + '🤽🏾‍♀️': 5, + '🤽🏾‍♂️': 5, + '🤽🏿‍♀️': 5, + '🤽🏿‍♂️': 5, + '🤾‍♀️': 3, + '🤾‍♂️': 3, + '🤾🏻‍♀️': 5, + '🤾🏻‍♂️': 5, + '🤾🏼‍♀️': 5, + '🤾🏼‍♂️': 5, + '🤾🏽‍♀️': 5, + '🤾🏽‍♂️': 5, + '🤾🏾‍♀️': 5, + '🤾🏾‍♂️': 5, + '🤾🏿‍♀️': 5, + '🤾🏿‍♂️': 5, + '🦸‍♀️': 3, + '🦸‍♂️': 3, + '🦸🏻‍♀️': 5, + '🦸🏻‍♂️': 5, + '🦸🏼‍♀️': 5, + '🦸🏼‍♂️': 5, + '🦸🏽‍♀️': 5, + '🦸🏽‍♂️': 5, + '🦸🏾‍♀️': 5, + '🦸🏾‍♂️': 5, + '🦸🏿‍♀️': 5, + '🦸🏿‍♂️': 5, + '🦹‍♀️': 3, + '🦹‍♂️': 3, + '🦹🏻‍♀️': 5, + '🦹🏻‍♂️': 5, + '🦹🏼‍♀️': 5, + '🦹🏼‍♂️': 5, + '🦹🏽‍♀️': 5, + '🦹🏽‍♂️': 5, + '🦹🏾‍♀️': 5, + '🦹🏾‍♂️': 5, + '🦹🏿‍♀️': 5, + '🦹🏿‍♂️': 5, + '🧍‍♀️': 3, + '🧍‍♂️': 3, + '🧍🏻‍♀️': 5, + '🧍🏻‍♂️': 5, + '🧍🏼‍♀️': 5, + '🧍🏼‍♂️': 5, + '🧍🏽‍♀️': 5, + '🧍🏽‍♂️': 5, + '🧍🏾‍♀️': 5, + '🧍🏾‍♂️': 5, + '🧍🏿‍♀️': 5, + '🧍🏿‍♂️': 5, + '🧎‍♀️': 3, + '🧎‍♀️‍➡️': 4, + '🧎‍♂️': 3, + '🧎‍♂️‍➡️': 4, + '🧎‍➡️': 3, + '🧎🏻‍♀️': 5, + '🧎🏻‍♀️‍➡️': 6, + '🧎🏻‍♂️': 5, + '🧎🏻‍♂️‍➡️': 6, + '🧎🏻‍➡️': 5, + '🧎🏼‍♀️': 5, + '🧎🏼‍♀️‍➡️': 6, + '🧎🏼‍♂️': 5, + '🧎🏼‍♂️‍➡️': 6, + '🧎🏼‍➡️': 5, + '🧎🏽‍♀️': 5, + '🧎🏽‍♀️‍➡️': 6, + '🧎🏽‍♂️': 5, + '🧎🏽‍♂️‍➡️': 6, + '🧎🏽‍➡️': 5, + '🧎🏾‍♀️': 5, + '🧎🏾‍♀️‍➡️': 6, + '🧎🏾‍♂️': 5, + '🧎🏾‍♂️‍➡️': 6, + '🧎🏾‍➡️': 5, + '🧎🏿‍♀️': 5, + '🧎🏿‍♀️‍➡️': 6, + '🧎🏿‍♂️': 5, + '🧎🏿‍♂️‍➡️': 6, + '🧎🏿‍➡️': 5, + '🧏‍♀️': 3, + '🧏‍♂️': 3, + '🧏🏻‍♀️': 5, + '🧏🏻‍♂️': 5, + '🧏🏼‍♀️': 5, + '🧏🏼‍♂️': 5, + '🧏🏽‍♀️': 5, + '🧏🏽‍♂️': 5, + '🧏🏾‍♀️': 5, + '🧏🏾‍♂️': 5, + '🧏🏿‍♀️': 5, + '🧏🏿‍♂️': 5, + '🧑‍⚕️': 3, + '🧑‍⚖️': 3, + '🧑‍✈️': 3, + '🧑‍🌾': 4, + '🧑‍🍳': 4, + '🧑‍🍼': 4, + '🧑‍🎄': 4, + '🧑‍🎓': 4, + '🧑‍🎤': 4, + '🧑‍🎨': 4, + '🧑‍🏫': 4, + '🧑‍🏭': 4, + '🧑‍💻': 4, + '🧑‍💼': 4, + '🧑‍🔧': 4, + '🧑‍🔬': 4, + '🧑‍🚀': 4, + '🧑‍🚒': 4, + '🧑‍🤝‍🧑': 6, + '🧑‍🦯': 4, + '🧑‍🦯‍➡️': 5, + '🧑‍🦰': 4, + '🧑‍🦱': 4, + '🧑‍🦲': 4, + '🧑‍🦳': 4, + '🧑‍🦼': 4, + '🧑‍🦼‍➡️': 5, + '🧑‍🦽': 4, + '🧑‍🦽‍➡️': 5, + '🧑‍🧑‍🧒': 6, + '🧑‍🧑‍🧒‍🧒': 8, + '🧑‍🧒': 4, + '🧑‍🧒‍🧒': 6, + '🧑‍🩰': 4, + '🧑🏻‍⚕️': 5, + '🧑🏻‍⚖️': 5, + '🧑🏻‍✈️': 5, + '🧑🏻‍❤️‍💋‍🧑🏿': 11, + '🧑🏻‍🌾': 6, + '🧑🏻‍🍳': 6, + '🧑🏻‍🍼': 6, + '🧑🏻‍🎄': 6, + '🧑🏻‍🎓': 6, + '🧑🏻‍🎤': 6, + '🧑🏻‍🎨': 6, + '🧑🏻‍🏫': 6, + '🧑🏻‍🏭': 6, + '🧑🏻‍🐰‍🧑🏽': 10, + '🧑🏻‍🐰‍🧑🏾': 10, + '🧑🏻‍🐰‍🧑🏿': 10, + '🧑🏻‍💻': 6, + '🧑🏻‍💼': 6, + '🧑🏻‍🔧': 6, + '🧑🏻‍🔬': 6, + '🧑🏻‍🚀': 6, + '🧑🏻‍🚒': 6, + '🧑🏻‍🤝‍🧑🏻': 10, + '🧑🏻‍🤝‍🧑🏼': 10, + '🧑🏻‍🤝‍🧑🏽': 10, + '🧑🏻‍🤝‍🧑🏾': 10, + '🧑🏻‍🤝‍🧑🏿': 10, + '🧑🏻‍🦯': 6, + '🧑🏻‍🦯‍➡️': 7, + '🧑🏻‍🦰': 6, + '🧑🏻‍🦱': 6, + '🧑🏻‍🦲': 6, + '🧑🏻‍🦳': 6, + '🧑🏻‍🦼': 6, + '🧑🏻‍🦼‍➡️': 7, + '🧑🏻‍🦽': 6, + '🧑🏻‍🦽‍➡️': 7, + '🧑🏻‍🩰': 6, + '🧑🏻‍🫯‍🧑🏼': 10, + '🧑🏻‍🫯‍🧑🏽': 10, + '🧑🏻‍🫯‍🧑🏾': 10, + '🧑🏻‍🫯‍🧑🏿': 10, + '🧑🏼‍⚕️': 5, + '🧑🏼‍⚖️': 5, + '🧑🏼‍✈️': 5, + '🧑🏼‍🌾': 6, + '🧑🏼‍🍳': 6, + '🧑🏼‍🍼': 6, + '🧑🏼‍🎄': 6, + '🧑🏼‍🎓': 6, + '🧑🏼‍🎤': 6, + '🧑🏼‍🎨': 6, + '🧑🏼‍🏫': 6, + '🧑🏼‍🏭': 6, + '🧑🏼‍🐰‍🧑🏿': 10, + '🧑🏼‍💻': 6, + '🧑🏼‍💼': 6, + '🧑🏼‍🔧': 6, + '🧑🏼‍🔬': 6, + '🧑🏼‍🚀': 6, + '🧑🏼‍🚒': 6, + '🧑🏼‍🤝‍🧑🏻': 10, + '🧑🏼‍🤝‍🧑🏼': 10, + '🧑🏼‍🤝‍🧑🏽': 10, + '🧑🏼‍🤝‍🧑🏿': 10, + '🧑🏼‍🦯': 6, + '🧑🏼‍🦯‍➡️': 7, + '🧑🏼‍🦰': 6, + '🧑🏼‍🦱': 6, + '🧑🏼‍🦲': 6, + '🧑🏼‍🦳': 6, + '🧑🏼‍🦼': 6, + '🧑🏼‍🦽': 6, + '🧑🏼‍🩰': 6, + '🧑🏼‍🫯‍🧑🏻': 10, + '🧑🏼‍🫯‍🧑🏽': 10, + '🧑🏼‍🫯‍🧑🏿': 10, + '🧑🏽‍⚕️': 5, + '🧑🏽‍⚖️': 5, + '🧑🏽‍✈️': 5, + '🧑🏽‍❤️‍💋‍🧑🏿': 11, + '🧑🏽‍🌾': 6, + '🧑🏽‍🍳': 6, + '🧑🏽‍🍼': 6, + '🧑🏽‍🎄': 6, + '🧑🏽‍🎓': 6, + '🧑🏽‍🎤': 6, + '🧑🏽‍🎨': 6, + '🧑🏽‍🏫': 6, + '🧑🏽‍🏭': 6, + '🧑🏽‍🐰‍🧑🏻': 10, + '🧑🏽‍🐰‍🧑🏿': 10, + '🧑🏽‍💻': 6, + '🧑🏽‍💼': 6, + '🧑🏽‍🔧': 6, + '🧑🏽‍🔬': 6, + '🧑🏽‍🚀': 6, + '🧑🏽‍🚒': 6, + '🧑🏽‍🤝‍🧑🏻': 10, + '🧑🏽‍🤝‍🧑🏼': 10, + '🧑🏽‍🤝‍🧑🏽': 10, + '🧑🏽‍🤝‍🧑🏾': 10, + '🧑🏽‍🤝‍🧑🏿': 10, + '🧑🏽‍🦯': 6, + '🧑🏽‍🦯‍➡️': 7, + '🧑🏽‍🦰': 6, + '🧑🏽‍🦱': 6, + '🧑🏽‍🦲': 6, + '🧑🏽‍🦳': 6, + '🧑🏽‍🦼': 6, + '🧑🏽‍🦼‍➡️': 7, + '🧑🏽‍🦽': 6, + '🧑🏽‍🦽‍➡️': 7, + '🧑🏽‍🩰': 6, + '🧑🏽‍🫯‍🧑🏻': 10, + '🧑🏽‍🫯‍🧑🏼': 10, + '🧑🏽‍🫯‍🧑🏾': 10, + '🧑🏽‍🫯‍🧑🏿': 10, + '🧑🏾‍⚕️': 5, + '🧑🏾‍⚖️': 5, + '🧑🏾‍✈️': 5, + '🧑🏾‍🌾': 6, + '🧑🏾‍🍳': 6, + '🧑🏾‍🍼': 6, + '🧑🏾‍🎄': 6, + '🧑🏾‍🎓': 6, + '🧑🏾‍🎤': 6, + '🧑🏾‍🎨': 6, + '🧑🏾‍🏫': 6, + '🧑🏾‍🏭': 6, + '🧑🏾‍🐰‍🧑🏻': 10, + '🧑🏾‍🐰‍🧑🏿': 10, + '🧑🏾‍💻': 6, + '🧑🏾‍💼': 6, + '🧑🏾‍🔧': 6, + '🧑🏾‍🔬': 6, + '🧑🏾‍🚀': 6, + '🧑🏾‍🚒': 6, + '🧑🏾‍🤝‍🧑🏻': 10, + '🧑🏾‍🤝‍🧑🏽': 10, + '🧑🏾‍🤝‍🧑🏾': 10, + '🧑🏾‍🤝‍🧑🏿': 10, + '🧑🏾‍🦯': 6, + '🧑🏾‍🦯‍➡️': 7, + '🧑🏾‍🦰': 6, + '🧑🏾‍🦱': 6, + '🧑🏾‍🦲': 6, + '🧑🏾‍🦳': 6, + '🧑🏾‍🦼': 6, + '🧑🏾‍🦽': 6, + '🧑🏾‍🩰': 6, + '🧑🏾‍🫯‍🧑🏻': 10, + '🧑🏾‍🫯‍🧑🏽': 10, + '🧑🏾‍🫯‍🧑🏿': 10, + '🧑🏿‍⚕️': 5, + '🧑🏿‍⚖️': 5, + '🧑🏿‍✈️': 5, + '🧑🏿‍❤️‍💋‍🧑🏻': 11, + '🧑🏿‍❤️‍💋‍🧑🏽': 11, + '🧑🏿‍🌾': 6, + '🧑🏿‍🍳': 6, + '🧑🏿‍🍼': 6, + '🧑🏿‍🎄': 6, + '🧑🏿‍🎓': 6, + '🧑🏿‍🎤': 6, + '🧑🏿‍🎨': 6, + '🧑🏿‍🏫': 6, + '🧑🏿‍🏭': 6, + '🧑🏿‍🐰‍🧑🏻': 10, + '🧑🏿‍🐰‍🧑🏼': 10, + '🧑🏿‍🐰‍🧑🏽': 10, + '🧑🏿‍🐰‍🧑🏾': 10, + '🧑🏿‍💻': 6, + '🧑🏿‍💼': 6, + '🧑🏿‍🔧': 6, + '🧑🏿‍🔬': 6, + '🧑🏿‍🚀': 6, + '🧑🏿‍🚒': 6, + '🧑🏿‍🤝‍🧑🏻': 10, + '🧑🏿‍🤝‍🧑🏼': 10, + '🧑🏿‍🤝‍🧑🏽': 10, + '🧑🏿‍🤝‍🧑🏾': 10, + '🧑🏿‍🤝‍🧑🏿': 10, + '🧑🏿‍🦯': 6, + '🧑🏿‍🦯‍➡️': 7, + '🧑🏿‍🦰': 6, + '🧑🏿‍🦱': 6, + '🧑🏿‍🦲': 6, + '🧑🏿‍🦳': 6, + '🧑🏿‍🦼': 6, + '🧑🏿‍🦼‍➡️': 7, + '🧑🏿‍🦽': 6, + '🧑🏿‍🦽‍➡️': 7, + '🧑🏿‍🩰': 6, + '🧑🏿‍🫯‍🧑🏻': 10, + '🧑🏿‍🫯‍🧑🏼': 10, + '🧑🏿‍🫯‍🧑🏽': 10, + '🧑🏿‍🫯‍🧑🏾': 10, + '🧔‍♀️': 3, + '🧔‍♂️': 3, + '🧔🏻‍♀️': 5, + '🧔🏻‍♂️': 5, + '🧔🏼‍♀️': 5, + '🧔🏼‍♂️': 5, + '🧔🏽‍♀️': 5, + '🧔🏽‍♂️': 5, + '🧔🏾‍♀️': 5, + '🧔🏾‍♂️': 5, + '🧔🏿‍♀️': 5, + '🧔🏿‍♂️': 5, + '🧖‍♀️': 3, + '🧖‍♂️': 3, + '🧖🏻‍♀️': 5, + '🧖🏻‍♂️': 5, + '🧖🏼‍♀️': 5, + '🧖🏼‍♂️': 5, + '🧖🏽‍♀️': 5, + '🧖🏽‍♂️': 5, + '🧖🏾‍♀️': 5, + '🧖🏾‍♂️': 5, + '🧖🏿‍♀️': 5, + '🧖🏿‍♂️': 5, + '🧗‍♀️': 3, + '🧗‍♂️': 3, + '🧗🏻‍♀️': 5, + '🧗🏻‍♂️': 5, + '🧗🏼‍♀️': 5, + '🧗🏼‍♂️': 5, + '🧗🏽‍♀️': 5, + '🧗🏽‍♂️': 5, + '🧗🏾‍♀️': 5, + '🧗🏾‍♂️': 5, + '🧗🏿‍♀️': 5, + '🧗🏿‍♂️': 5, + '🧘‍♀️': 3, + '🧘‍♂️': 3, + '🧘🏻‍♀️': 5, + '🧘🏻‍♂️': 5, + '🧘🏼‍♀️': 5, + '🧘🏼‍♂️': 5, + '🧘🏽‍♀️': 5, + '🧘🏽‍♂️': 5, + '🧘🏾‍♀️': 5, + '🧘🏾‍♂️': 5, + '🧘🏿‍♀️': 5, + '🧘🏿‍♂️': 5, + '🧙‍♀️': 3, + '🧙‍♂️': 3, + '🧙🏻‍♀️': 5, + '🧙🏻‍♂️': 5, + '🧙🏼‍♀️': 5, + '🧙🏼‍♂️': 5, + '🧙🏽‍♀️': 5, + '🧙🏽‍♂️': 5, + '🧙🏾‍♀️': 5, + '🧙🏾‍♂️': 5, + '🧙🏿‍♀️': 5, + '🧙🏿‍♂️': 5, + '🧚‍♀️': 3, + '🧚‍♂️': 3, + '🧚🏻‍♀️': 5, + '🧚🏻‍♂️': 5, + '🧚🏼‍♀️': 5, + '🧚🏼‍♂️': 5, + '🧚🏽‍♀️': 5, + '🧚🏽‍♂️': 5, + '🧚🏾‍♀️': 5, + '🧚🏾‍♂️': 5, + '🧚🏿‍♀️': 5, + '🧚🏿‍♂️': 5, + '🧛‍♀️': 3, + '🧛‍♂️': 3, + '🧛🏻‍♀️': 5, + '🧛🏻‍♂️': 5, + '🧛🏼‍♀️': 5, + '🧛🏼‍♂️': 5, + '🧛🏽‍♀️': 5, + '🧛🏽‍♂️': 5, + '🧛🏾‍♀️': 5, + '🧛🏾‍♂️': 5, + '🧛🏿‍♀️': 5, + '🧛🏿‍♂️': 5, + '🧜‍♀️': 3, + '🧜‍♂️': 3, + '🧜🏻‍♀️': 5, + '🧜🏻‍♂️': 5, + '🧜🏼‍♀️': 5, + '🧜🏼‍♂️': 5, + '🧜🏽‍♀️': 5, + '🧜🏽‍♂️': 5, + '🧜🏾‍♀️': 5, + '🧜🏾‍♂️': 5, + '🧜🏿‍♀️': 5, + '🧜🏿‍♂️': 5, + '🧝‍♀️': 3, + '🧝‍♂️': 3, + '🧝🏻‍♀️': 5, + '🧝🏻‍♂️': 5, + '🧝🏼‍♀️': 5, + '🧝🏼‍♂️': 5, + '🧝🏽‍♀️': 5, + '🧝🏽‍♂️': 5, + '🧝🏾‍♀️': 5, + '🧝🏾‍♂️': 5, + '🧝🏿‍♀️': 5, + '🧝🏿‍♂️': 5, + '🧞‍♀️': 3, + '🧞‍♂️': 3, + '🧟‍♀️': 3, + '🧟‍♂️': 3, + '🫱🏻‍🫲🏼': 8, + '🫱🏻‍🫲🏽': 8, + '🫱🏻‍🫲🏾': 8, + '🫱🏻‍🫲🏿': 8, + '🫱🏼‍🫲🏻': 8, + '🫱🏼‍🫲🏽': 8, + '🫱🏼‍🫲🏾': 8, + '🫱🏼‍🫲🏿': 8, + '🫱🏽‍🫲🏻': 8, + '🫱🏽‍🫲🏼': 8, + '🫱🏽‍🫲🏾': 8, + '🫱🏽‍🫲🏿': 8, + '🫱🏾‍🫲🏻': 8, + '🫱🏾‍🫲🏼': 8, + '🫱🏾‍🫲🏽': 8, + '🫱🏾‍🫲🏿': 8, + '🫱🏿‍🫲🏻': 8, + '🫱🏿‍🫲🏼': 8, + '🫱🏿‍🫲🏽': 8, + '🫱🏿‍🫲🏾': 8, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_b6d33cf4.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_b6d33cf4.py new file mode 100644 index 0000000000000000000000000000000000000000..74b8614d5015ca8ce41d2ebb5b243a117e12b697 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_b6d33cf4.py @@ -0,0 +1,3374 @@ +""" +Grapheme overrides for _known_b6d33cf4. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: mlterm +""" +# pylint: skip-file +GRAPHEMES = { + 'ت‌': 2, + 'ن‌': 2, + 'ه‌': 2, + 'ی‌': 2, + 'ے‌': 2, + 'का': 1, + 'कां': 1, + 'कि': 1, + 'किं': 1, + 'की': 1, + 'केा': 1, + 'को': 1, + 'कौ': 1, + 'क्घ्घि्': 3, + 'क्त्योः': 3, + 'क्ष्ण': 3, + 'क्ष्य': 3, + 'क्ष्या': 3, + 'खा': 1, + 'खि': 1, + 'खी': 1, + 'खो': 1, + 'ख्‍ने': 3, + 'ग़ा': 1, + 'गा': 1, + 'गाँ': 1, + 'गां': 1, + 'गि': 1, + 'गी': 1, + 'गो': 1, + 'गों': 1, + 'गौ': 1, + 'ग्र्य': 3, + 'घा': 1, + 'घि': 1, + 'घी': 1, + 'घेि': 1, + 'घो': 1, + 'घ्र्व्य': 4, + 'घ्श्य': 3, + 'घ्स्ट': 3, + 'चा': 1, + 'चां': 1, + 'चि': 1, + 'ची': 1, + 'चो': 1, + 'चौ': 1, + 'छि': 1, + 'छुी': 1, + 'छो': 1, + 'जा': 1, + 'जि': 1, + 'जिं': 1, + 'जी': 1, + 'जो': 1, + 'ज्या‌': 3, + 'झा': 1, + 'टा': 1, + 'टां': 1, + 'टि': 1, + 'टी': 1, + 'टों': 1, + 'ठा': 1, + 'ठी': 1, + 'ठैः': 1, + 'ड़ा': 1, + 'डा': 1, + 'डि': 1, + 'डी': 1, + 'डो': 1, + 'ढ़ा': 1, + 'ढ़ि': 1, + 'ढ़ी': 1, + 'ढ़ो': 1, + 'ढा': 1, + 'ढाँ': 1, + 'ढि': 1, + 'णा': 1, + 'णां': 1, + 'णि': 1, + 'णी': 1, + 'णो': 1, + 'णों': 1, + 'तः': 1, + 'ता': 1, + 'तां': 1, + 'ताः': 1, + 'ति': 1, + 'तिं': 1, + 'ती': 1, + 'तो': 1, + 'तों': 1, + 'तौ': 1, + 'त्त्थि': 3, + 'त्त्व': 3, + 'त्त्वा': 3, + 'त्त्वे': 3, + 'त्र्त': 3, + 'त्र्य': 3, + 'त्र्या': 3, + 'त्र्ये': 3, + 'त्स्वा': 3, + 'था': 1, + 'थि': 1, + 'दः': 1, + 'दा': 1, + 'दां': 1, + 'दि': 1, + 'दी': 1, + 'दो': 1, + 'दौ': 1, + 'द्‌': 2, + 'धा': 1, + 'धां': 1, + 'धाः': 1, + 'धि': 1, + 'धी': 1, + 'धेः': 1, + 'धो': 1, + 'धों': 1, + 'नः': 1, + 'ना': 1, + 'नां': 1, + 'नाः': 1, + 'नि': 1, + 'निँ': 1, + 'निः': 1, + 'नी': 1, + 'नैः': 1, + 'नो': 1, + 'नों': 1, + 'नौ': 1, + 'न्ञ्या': 3, + 'न्त्र': 3, + 'न्त्रा': 3, + 'न्त्राः': 3, + 'न्त्रि': 3, + 'न्त्री': 3, + 'न्त्र्य': 4, + 'न्त्र्यं': 4, + 'न्त्र्या': 4, + 'न्त्र्ये': 4, + 'न्ह्यां': 3, + 'पा': 1, + 'पाँ': 1, + 'पां': 1, + 'पि': 1, + 'पी': 1, + 'पो': 1, + 'पों': 1, + 'फा': 1, + 'फाँ': 1, + 'फौ': 1, + 'बा': 1, + 'बाँ': 1, + 'बि': 1, + 'बी': 1, + 'बो': 1, + 'भा': 1, + 'भि': 1, + 'भिः': 1, + 'भी': 1, + 'भो': 1, + 'भौ': 1, + 'मा': 1, + 'मां': 1, + 'मि': 1, + 'मी': 1, + 'मो': 1, + 'मों': 1, + 'मौ': 1, + 'म्प्र': 3, + 'यः': 1, + 'या': 1, + 'यां': 1, + 'याः': 1, + 'यि': 1, + 'यी': 1, + 'यैः': 1, + 'यो': 1, + 'यों': 1, + 'रः': 1, + 'रा': 1, + 'रां': 1, + 'राः': 1, + 'रि': 1, + 'रिं': 1, + 'री': 1, + 'रो': 1, + 'रों': 1, + 'रौ': 1, + 'र्त्त': 3, + 'र्त्ति': 3, + 'र्द्ध': 3, + 'र्‍या': 3, + 'ला': 1, + 'लां': 1, + 'लाः': 1, + 'लि': 1, + 'लिं': 1, + 'ली': 1, + 'लीं': 1, + 'लो': 1, + 'लों': 1, + 'लौ': 1, + 'ळा': 1, + 'ळी': 1, + 'वः': 1, + 'वा': 1, + 'वां': 1, + 'वाः': 1, + 'वि': 1, + 'वी': 1, + 'वो': 1, + 'वों': 1, + 'शः': 1, + 'शा': 1, + 'शां': 1, + 'शाः': 1, + 'शि': 1, + 'शी': 1, + 'शो': 1, + 'शों': 1, + 'षा': 1, + 'षां': 1, + 'षाः': 1, + 'षि': 1, + 'षी': 1, + 'षों': 1, + 'ष्ट्र': 3, + 'ष्ट्रा': 3, + 'ष्ट्रां': 3, + 'ष्ट्रि': 3, + 'ष्ट्री': 3, + 'ष्ट्रे': 3, + 'ष्ट्रो': 3, + 'ष्ट्रों': 3, + 'ष्प्र': 3, + 'सः': 1, + 'सा': 1, + 'साँ': 1, + 'सां': 1, + 'सि': 1, + 'सी': 1, + 'सो': 1, + 'सौ': 1, + 'स्ट्या': 3, + 'स्त्र': 3, + 'स्त्रा': 3, + 'स्त्रि': 3, + 'स्त्री': 3, + 'स्थ्य': 3, + 'हा': 1, + 'हाँ': 1, + 'हां': 1, + 'हि': 1, + 'हिं': 1, + 'ही': 1, + 'हीं': 1, + 'हैः': 1, + 'हो': 1, + 'हों': 1, + 'हौ': 1, + 'क़ा': 1, + 'क़ि': 1, + 'ज़ा': 1, + 'ड़ा': 1, + 'ढ़ा': 1, + 'फ़ा': 1, + 'অং': 1, + 'আ‌': 2, + 'ই‌': 2, + 'এ‌': 2, + 'কা': 1, + 'কি': 1, + 'কিং': 1, + 'কে': 1, + 'কো': 1, + 'ক্ষ্য': 3, + 'ক্ষ্যে': 3, + 'খা': 1, + 'খি': 1, + 'খে': 1, + 'গি': 1, + 'গে': 1, + 'গো': 1, + 'ঘা': 1, + 'ঘে': 1, + 'ঘো': 1, + 'ঘো': 1, + 'চা': 1, + 'চি': 1, + 'চে': 1, + 'চো': 1, + 'চৌ': 1, + 'চ্ছা‌': 3, + 'ছা': 1, + 'ছি': 1, + 'ছে': 1, + 'জা': 1, + 'জি': 1, + 'জী': 1, + 'জে': 1, + 'ঝো': 1, + 'টা': 1, + 'টি': 1, + 'ঠি': 1, + 'ড়া': 1, + 'ণা': 1, + 'ণি': 1, + 'ণে': 1, + 'তঃ': 1, + 'তা': 1, + 'তাঁ': 1, + 'তি': 1, + 'তী': 1, + 'তে': 1, + 'ত্‍': 2, + 'ত্‍প': 3, + 'ত্‍পী': 3, + 'ত্‍সা': 3, + 'থা': 1, + 'থি': 1, + 'থে': 1, + 'দা': 1, + 'দি': 1, + 'দে': 1, + 'দৈ': 1, + 'দো': 1, + 'ধা': 1, + 'ধি': 1, + 'ধী': 1, + 'ধে': 1, + 'না': 1, + 'নি': 1, + 'নী': 1, + 'নে': 1, + 'নৈ': 1, + 'নো': 1, + 'ন্ত্রি': 3, + 'ন্ত্রে': 3, + 'ন‌': 2, + 'পা': 1, + 'পি': 1, + 'পী': 1, + 'পে': 1, + 'পো': 1, + 'ফে': 1, + 'ফৌ': 1, + 'বং': 1, + 'বা': 1, + 'বি': 1, + 'বী': 1, + 'বে': 1, + 'বৈ': 1, + 'বো': 1, + 'ভা': 1, + 'ভি': 1, + 'ভে': 1, + 'ভো': 1, + 'ভৌ': 1, + 'মা': 1, + 'মি': 1, + 'মে': 1, + 'মৌ': 1, + 'য়া': 1, + 'য়ি': 1, + 'য়ে': 1, + 'য়ো': 1, + 'যা': 1, + 'যে': 1, + 'যো': 1, + 'রা': 1, + 'রাং': 1, + 'রি': 1, + 'রী': 1, + 'রে': 1, + 'রো': 1, + 'র্ব্য': 3, + 'র‌': 2, + 'লা': 1, + 'লি': 1, + 'লী': 1, + 'লে': 1, + 'শং': 1, + 'শা': 1, + 'শি': 1, + 'শী': 1, + 'শৃং': 1, + 'শে': 1, + 'শৈ': 1, + 'ষা': 1, + 'ষি': 1, + 'ষী': 1, + 'ষে': 1, + 'ষ্ট্র': 3, + 'ষ্ট্রী': 3, + 'ষ্ট্রে': 3, + 'সং': 1, + 'সা': 1, + 'সাং': 1, + 'সি': 1, + 'সী': 1, + 'সে': 1, + 'স্তি‌': 3, + 'স্ত্র': 3, + 'স্থ্য': 3, + 'হা': 1, + 'হি': 1, + 'হে': 1, + 'হো': 1, + 'হ‌': 2, + 'য়ে': 1, + 'ਕਾ': 1, + 'ਕਾਂ': 1, + 'ਕਿ': 1, + 'ਕਿ੍': 1, + 'ਕਿੱ': 1, + 'ਕੀ': 1, + 'ਖਾ': 1, + 'ਖਾਂ': 1, + 'ਖਿ': 1, + 'ਖਿ਼': 1, + 'ਖੀ': 1, + 'ਗਾ': 1, + 'ਗਿ': 1, + 'ਗਿ੍': 1, + 'ਗੀ': 1, + 'ਚਾ': 1, + 'ਚਿ': 1, + 'ਚਿੱ': 1, + 'ਚੀ': 1, + 'ਜਾ': 1, + 'ਜਾਂ': 1, + 'ਜਿ': 1, + 'ਜਿ਼': 1, + 'ਜਿ਼ੰ': 1, + 'ਜੀ': 1, + 'ਝਿ': 1, + 'ਝੀ': 1, + 'ਟਾ': 1, + 'ਟਿ': 1, + 'ਟਿ੍': 1, + 'ਟੀ': 1, + 'ਠੀ': 1, + 'ਡਾ': 1, + 'ਣਾ': 1, + 'ਣਾਂ': 1, + 'ਣੀ': 1, + 'ਤਾ': 1, + 'ਤਾਂ': 1, + 'ਤਿ': 1, + 'ਤੀ': 1, + 'ਦਾ': 1, + 'ਦਾਂ': 1, + 'ਦਿ': 1, + 'ਦਿੱ': 1, + 'ਦੀ': 1, + 'ਧਾ': 1, + 'ਧਾਂ': 1, + 'ਧਿ': 1, + 'ਧੀ': 1, + 'ਨਾ': 1, + 'ਨਾਂ': 1, + 'ਨਿ': 1, + 'ਨੀ': 1, + 'ਨੀਂ': 1, + 'ਪਾ': 1, + 'ਪਿ': 1, + 'ਪੀ': 1, + 'ਫਿ': 1, + 'ਬਾ': 1, + 'ਬਿ': 1, + 'ਬੀ': 1, + 'ਭਾ': 1, + 'ਭਿ': 1, + 'ਮਾ': 1, + 'ਮਾਂ': 1, + 'ਮਿ': 1, + 'ਮੀ': 1, + 'ਯਾ': 1, + 'ਰਾ': 1, + 'ਰਾਂ': 1, + 'ਰਿ': 1, + 'ਰੀ': 1, + 'ਲਾ': 1, + 'ਲਾਂ': 1, + 'ਲਿ': 1, + 'ਲਿੰ': 1, + 'ਲੀ': 1, + 'ਵਾ': 1, + 'ਵਾਂ': 1, + 'ਵਿ': 1, + 'ਵਿੱ': 1, + 'ਵੀ': 1, + 'ਸ਼ਾ': 1, + 'ਸ਼ਾਂ': 1, + 'ਸ਼ਿ': 1, + 'ਸ਼ੀ': 1, + 'ਸਾ': 1, + 'ਸਾਂ': 1, + 'ਸਿ': 1, + 'ਸਿੱ': 1, + 'ਸੀ': 1, + 'ਹਾ': 1, + 'ਹਾਂ': 1, + 'ਹਿ': 1, + 'ਹਿੰ': 1, + 'ਹਿੱ': 1, + 'ਹੀ': 1, + 'ਹੀਂ': 1, + 'ਜ਼ਾ': 1, + 'ਜ਼ੀ': 1, + 'ੜਾ': 1, + 'ੜੀਂ': 1, + 'ਫ਼ਾ': 1, + 'કઃ': 1, + 'કા': 1, + 'કાં': 1, + 'કિ': 1, + 'કી': 1, + 'કો': 1, + 'ખા': 1, + 'ખી': 1, + 'ખો': 1, + 'ગા': 1, + 'ગિ': 1, + 'ગી': 1, + 'ગો': 1, + 'ઘા': 1, + 'ઘો': 1, + 'ચા': 1, + 'ચિ': 1, + 'ચી': 1, + 'છા': 1, + 'છો': 1, + 'જા': 1, + 'જાં': 1, + 'જિ': 1, + 'જી': 1, + 'જો': 1, + 'ટઃ': 1, + 'ડા': 1, + 'ડાં': 1, + 'ડી': 1, + 'ઢા': 1, + 'ઢિ': 1, + 'ણા': 1, + 'ણી': 1, + 'તઃ': 1, + 'તા': 1, + 'તાં': 1, + 'તિ': 1, + 'તી': 1, + 'તો': 1, + 'ત્ત્વ': 3, + 'ત્ત્વા': 3, + 'ત્ર્ય': 3, + 'થા': 1, + 'થી': 1, + 'દા': 1, + 'દી': 1, + 'દો': 1, + 'ધા': 1, + 'ધાં': 1, + 'ધિ': 1, + 'ધી': 1, + 'ધો': 1, + 'નઃ': 1, + 'ના': 1, + 'નાં': 1, + 'નિ': 1, + 'ની': 1, + 'નો': 1, + 'પા': 1, + 'પિ': 1, + 'પી': 1, + 'પો': 1, + 'ફા': 1, + 'ફો': 1, + 'બા': 1, + 'બાં': 1, + 'બી': 1, + 'ભા': 1, + 'ભાં': 1, + 'ભિ': 1, + 'ભો': 1, + 'ભૌ': 1, + 'મઃ': 1, + 'મા': 1, + 'માં': 1, + 'મિ': 1, + 'મી': 1, + 'મો': 1, + 'યા': 1, + 'યિ': 1, + 'યી': 1, + 'યો': 1, + 'રા': 1, + 'રિ': 1, + 'રી': 1, + 'રો': 1, + 'લા': 1, + 'લાં': 1, + 'લિ': 1, + 'લિં': 1, + 'લી': 1, + 'લો': 1, + 'ળા': 1, + 'ળી': 1, + 'વા': 1, + 'વાં': 1, + 'વિ': 1, + 'વી': 1, + 'વો': 1, + 'શા': 1, + 'શાં': 1, + 'શિ': 1, + 'શી': 1, + 'શો': 1, + 'ષા': 1, + 'ષી': 1, + 'ષો': 1, + 'ષ્ટ્ર': 3, + 'ષ્ટ્રી': 3, + 'ષ્ટ્રો': 3, + 'સા': 1, + 'સાં': 1, + 'સિ': 1, + 'સી': 1, + 'સો': 1, + 'સ્ત્રી': 3, + 'હા': 1, + 'હિ': 1, + 'હી': 1, + 'હો': 1, + 'கா': 1, + 'கி': 1, + 'கு': 1, + 'கூ': 1, + 'கெ': 1, + 'கே': 1, + 'கை': 1, + 'கொ': 1, + 'கோ': 1, + 'சா': 1, + 'சி': 1, + 'சு': 1, + 'சூ': 1, + 'செ': 1, + 'சே': 1, + 'சை': 1, + 'சொ': 1, + 'டா': 1, + 'டி': 1, + 'டு': 1, + 'டெ': 1, + 'டை': 1, + 'ணா': 1, + 'ணி': 1, + 'ணு': 1, + 'ணை': 1, + 'தா': 1, + 'தி': 1, + 'து': 1, + 'தூ': 1, + 'தெ': 1, + 'தே': 1, + 'தை': 1, + 'தொ': 1, + 'தோ': 1, + 'நா': 1, + 'நி': 1, + 'நு': 1, + 'நெ': 1, + 'நே': 1, + 'நோ': 1, + 'னா': 1, + 'னி': 1, + 'னு': 1, + 'னே': 1, + 'னை': 1, + 'னொ': 1, + 'பா': 1, + 'பி': 1, + 'பு': 1, + 'பெ': 1, + 'பே': 1, + 'பை': 1, + 'பொ': 1, + 'போ': 1, + 'மா': 1, + 'மி': 1, + 'மு': 1, + 'மூ': 1, + 'மெ': 1, + 'மே': 1, + 'மை': 1, + 'மொ': 1, + 'மோ': 1, + 'யா': 1, + 'யி': 1, + 'யு': 1, + 'யே': 1, + 'யை': 1, + 'யோ': 1, + 'ரா': 1, + 'ரி': 1, + 'ரு': 1, + 'ரெ': 1, + 'ரை': 1, + 'றா': 1, + 'றி': 1, + 'று': 1, + 'றே': 1, + 'றை': 1, + 'றொ': 1, + 'றோ': 1, + 'லா': 1, + 'லி': 1, + 'லு': 1, + 'லெ': 1, + 'லே': 1, + 'லை': 1, + 'லோ': 1, + 'ளா': 1, + 'ளி': 1, + 'ளு': 1, + 'ளெ': 1, + 'ளை': 1, + 'ழி': 1, + 'ழு': 1, + 'ழை': 1, + 'வா': 1, + 'வி': 1, + 'வு': 1, + 'வூ': 1, + 'வெ': 1, + 'வே': 1, + 'வை': 1, + 'வொ': 1, + 'வோ': 1, + 'అం': 1, + 'ఆం': 1, + 'ఒం': 1, + 'కం': 1, + 'కాం': 1, + 'కు': 1, + 'కుం': 1, + 'కూ': 1, + 'కృ': 1, + 'కెం': 1, + 'క్స్వా': 3, + 'గిం': 1, + 'గు': 1, + 'గూ': 1, + 'గృ': 1, + 'చు': 1, + 'చెం': 1, + 'టం': 1, + 'టిం': 1, + 'టు': 1, + 'టుం': 1, + 'డు': 1, + 'ణిం': 1, + 'తం': 1, + 'తః': 1, + 'తు': 1, + 'తృ': 1, + 'త్ర్య': 3, + 'దం': 1, + 'దిం': 1, + 'దు': 1, + 'దుం': 1, + 'దృ': 1, + 'ద్ర్య': 3, + 'ధిం': 1, + 'ధు': 1, + 'నం': 1, + 'నః': 1, + 'నాం': 1, + 'నిం': 1, + 'ను': 1, + 'నుం': 1, + 'నొం': 1, + 'పం': 1, + 'పిం': 1, + 'పు': 1, + 'పూ': 1, + 'పెం': 1, + 'పొం': 1, + 'బం': 1, + 'భం': 1, + 'భు': 1, + 'మిం': 1, + 'ము': 1, + 'మూ': 1, + 'యం': 1, + 'యః': 1, + 'యిం': 1, + 'యు': 1, + 'యుం': 1, + 'రం': 1, + 'రిం': 1, + 'రు': 1, + 'రూ': 1, + 'ఱు': 1, + 'లం': 1, + 'లిం': 1, + 'లు': 1, + 'విం': 1, + 'వు': 1, + 'వృ': 1, + 'శాం': 1, + 'శిం': 1, + 'శు': 1, + 'షిం': 1, + 'షు': 1, + 'ష్ట్ర': 3, + 'ష్ట్రీ': 3, + 'సం': 1, + 'సాం': 1, + 'సు': 1, + 'సూ': 1, + 'స్త్ర': 3, + 'స్త్రీ': 3, + 'స్థ్య': 3, + 'హిం': 1, + 'ಅಂ': 1, + 'ಇಂ': 1, + 'ಉಂ': 1, + 'ಎಂ': 1, + 'ಒಂ': 1, + 'ಕಾ': 1, + 'ಕಾಂ': 1, + 'ಕಿಂ': 1, + 'ಕೀ': 1, + 'ಕು': 1, + 'ಕುಂ': 1, + 'ಕೂ': 1, + 'ಕೃ': 1, + 'ಕೆಂ': 1, + 'ಕೇ': 1, + 'ಕೈ': 1, + 'ಕೊ': 1, + 'ಕೊಂ': 1, + 'ಕ್‌': 2, + 'ಖಾಂ': 1, + 'ಗಾ': 1, + 'ಗಾಂ': 1, + 'ಗೀ': 1, + 'ಗು': 1, + 'ಗೂ': 1, + 'ಗೈ': 1, + 'ಗೊ': 1, + 'ಗೊಂ': 1, + 'ಗೋ': 1, + 'ಚಾ': 1, + 'ಚೀ': 1, + 'ಚು': 1, + 'ಛಾ': 1, + 'ಜಾ': 1, + 'ಜೀ': 1, + 'ಟು': 1, + 'ಟುಂ': 1, + 'ಟೇ': 1, + 'ಠಾ': 1, + 'ಡಾ': 1, + 'ಡು': 1, + 'ಡೂ': 1, + 'ಢೀ': 1, + 'ಣಂ': 1, + 'ಣಾ': 1, + 'ಣು': 1, + 'ಣೈ': 1, + 'ತಂ': 1, + 'ತಃ': 1, + 'ತಾ': 1, + 'ತೀ': 1, + 'ತು': 1, + 'ತೃ': 1, + 'ತೊ': 1, + 'ತೋ': 1, + 'ಥಾ': 1, + 'ದಂ': 1, + 'ದಾ': 1, + 'ದಿಂ': 1, + 'ದು': 1, + 'ದೂ': 1, + 'ದೃ': 1, + 'ದೇ': 1, + 'ದೊ': 1, + 'ದೋ': 1, + 'ಧಾ': 1, + 'ಧೀ': 1, + 'ಧೂ': 1, + 'ನಃ': 1, + 'ನಾ': 1, + 'ನಾಂ': 1, + 'ನಿಂ': 1, + 'ನು': 1, + 'ನೂ': 1, + 'ನೇ': 1, + 'ನೈ': 1, + 'ನೊ': 1, + 'ಪಂ': 1, + 'ಪಾ': 1, + 'ಪು': 1, + 'ಪೂ': 1, + 'ಪೇ': 1, + 'ಬಂ': 1, + 'ಬಾ': 1, + 'ಬು': 1, + 'ಬೇ': 1, + 'ಬೋ': 1, + 'ಭಾ': 1, + 'ಭೀ': 1, + 'ಭು': 1, + 'ಭೇ': 1, + 'ಭೋ': 1, + 'ಮಾ': 1, + 'ಮೀ': 1, + 'ಮು': 1, + 'ಮೂ': 1, + 'ಮೇ': 1, + 'ಮೈ': 1, + 'ಯಂ': 1, + 'ಯಾ': 1, + 'ಯಿಂ': 1, + 'ಯು': 1, + 'ಯುಂ': 1, + 'ಯೂ': 1, + 'ಯೆಂ': 1, + 'ಯೇ': 1, + 'ಯೊ': 1, + 'ಯೋ': 1, + 'ರಂ': 1, + 'ರಾ': 1, + 'ರಾಂ': 1, + 'ರಿಂ': 1, + 'ರೀ': 1, + 'ರು': 1, + 'ರೂ': 1, + 'ರೆಂ': 1, + 'ರೊ': 1, + 'ರೋ': 1, + 'ಲಂ': 1, + 'ಲಾ': 1, + 'ಲೀ': 1, + 'ಲು': 1, + 'ಲೂ': 1, + 'ಲೆಂ': 1, + 'ಲೇ': 1, + 'ಲೋ': 1, + 'ಳಾ': 1, + 'ಳಿಂ': 1, + 'ಳು': 1, + 'ಳೂ': 1, + 'ವಾ': 1, + 'ವೀ': 1, + 'ವು': 1, + 'ವುಂ': 1, + 'ವೂ': 1, + 'ವೃ': 1, + 'ವೆಂ': 1, + 'ವೇ': 1, + 'ವೈ': 1, + 'ವೋ': 1, + 'ಶಾ': 1, + 'ಶಾಂ': 1, + 'ಶೀ': 1, + 'ಶೇ': 1, + 'ಷಾ': 1, + 'ಷೇ': 1, + 'ಸಂ': 1, + 'ಸಾ': 1, + 'ಸಾಂ': 1, + 'ಸು': 1, + 'ಸೂ': 1, + 'ಸೇ': 1, + 'ಹಾ': 1, + 'ಹು': 1, + 'ಹೇ': 1, + 'ಹೊ': 1, + 'ಹೊಂ': 1, + 'ಹೋ': 1, + 'അം': 1, + 'കാ': 1, + 'കി': 1, + 'കെ': 1, + 'കേ': 1, + 'കൈ': 1, + 'കൊ': 1, + 'കോ': 1, + 'ക്ക്‌': 3, + 'ഗം': 1, + 'ഗി': 1, + 'ഗീ': 1, + 'ഘി': 1, + 'ചാ': 1, + 'ചി': 1, + 'ചെ': 1, + 'ചേ': 1, + 'ചോ': 1, + 'ജാ': 1, + 'ജി': 1, + 'ജീ': 1, + 'ടാ': 1, + 'ടി': 1, + 'ടും': 1, + 'ടെ': 1, + 'ടേ': 1, + 'ട്‌': 2, + 'ഠി': 1, + 'ണം': 1, + 'ണാ': 1, + 'ണി': 1, + 'ണെ': 1, + 'ണ്ട്‌': 3, + 'ണ്‌': 2, + 'തം': 1, + 'താ': 1, + 'തി': 1, + 'തീ': 1, + 'തും': 1, + 'തെ': 1, + 'തേ': 1, + 'തൊ': 1, + 'തോ': 1, + 'ത്ത്‌': 3, + 'ത്‌': 2, + 'ദം': 1, + 'ദാ': 1, + 'ദി': 1, + 'ദേ': 1, + 'ധാ': 1, + 'ധി': 1, + 'നം': 1, + 'നാ': 1, + 'നി': 1, + 'നീ': 1, + 'നും': 1, + 'നെ': 1, + 'നേ': 1, + 'ന്ത്ര': 3, + 'ന്ത്ര്യ': 4, + 'ന്ത്ര്യം': 4, + 'ന്‌': 2, + 'ന്‍': 2, + 'ന്‍കൂ': 3, + 'ന്‍പി': 3, + 'പാ': 1, + 'പി': 1, + 'പീ': 1, + 'പെ': 1, + 'പൈ': 1, + 'പൊ': 1, + 'പോ': 1, + 'പൌ': 1, + 'പ്പ്‌': 3, + 'ബം': 1, + 'ബാ': 1, + 'ബോ': 1, + 'ഭാ': 1, + 'ഭി': 1, + 'ഭേ': 1, + 'ഭൌ': 1, + 'മം': 1, + 'മാ': 1, + 'മി': 1, + 'മെ': 1, + 'മേ': 1, + 'മൊ': 1, + 'മോ': 1, + 'മൌ': 1, + 'മ്പ്ര': 3, + 'യം': 1, + 'യാ': 1, + 'യി': 1, + 'യും': 1, + 'യെ': 1, + 'യേ': 1, + 'യോ': 1, + 'യ്ക്കു': 3, + 'രം': 1, + 'രാ': 1, + 'രി': 1, + 'രീ': 1, + 'രും': 1, + 'രെ': 1, + 'രേ': 1, + 'രോ': 1, + 'ര്‍ക്കു': 4, + 'ര്‍ക്കും': 4, + 'ര്‍ക്ക്‌': 5, + 'ര്‍ഗ്ഗം': 4, + 'ര്‍ച്ച': 4, + 'ര്‍ണ്ണ': 4, + 'ര്‍ത്ത': 4, + 'ര്‍ത്തി': 4, + 'ര്‍ത്തു': 4, + 'ര്‍ത്തേ': 4, + 'ര്‍ദേ': 3, + 'ര്‍ദ്ദ': 4, + 'ര്‍പ്പെ': 4, + 'ര്‍ബ': 3, + 'ര്‍ഭ': 3, + 'ര്‍മ്മി': 4, + 'ര്‍രാ': 3, + 'ര്‍വ്വ': 4, + 'ര്‍ഹ': 3, + 'ര്‍ഹി': 3, + 'റം': 1, + 'റി': 1, + 'ലം': 1, + 'ലാ': 1, + 'ലി': 1, + 'ലും': 1, + 'ലെ': 1, + 'ലേ': 1, + 'ലോ': 1, + 'ല്‍': 2, + 'ല്‍കി': 3, + 'ല്‍കു': 3, + 'ല്‍കേ': 3, + 'ല്‍ത': 3, + 'ല്‍നി': 3, + 'ല്‍പ്പ': 4, + 'ളം': 1, + 'ളാ': 1, + 'ളി': 1, + 'ളും': 1, + 'ളെ': 1, + 'ളേ': 1, + 'ളോ': 1, + 'ള്‍': 2, + 'ള്‍കൊ': 3, + 'ള്‍ക്ക': 4, + 'ള്‍ക്കി': 4, + 'ള്‍ക്കു': 4, + 'ള്‍ക്കും': 4, + 'ള്‍ക്കെ': 4, + 'ള്‍ക്ക്‌': 5, + 'ഴി': 1, + 'വാ': 1, + 'വി': 1, + 'വും': 1, + 'വെ': 1, + 'വേ': 1, + 'വൈ': 1, + 'വോ': 1, + 'ശാ': 1, + 'ശി': 1, + 'ശീ': 1, + 'ശേ': 1, + 'ഷം': 1, + 'ഷി': 1, + 'ഷ്ട്യാ': 3, + 'ഷ്ട്ര': 3, + 'ഷ്ട്രീ': 3, + 'സം': 1, + 'സാ': 1, + 'സാം': 1, + 'സി': 1, + 'സൌ': 1, + 'സ്ത്രം': 3, + 'സ്ത്രീ': 3, + 'സ്റ്റ്‌': 4, + 'ഹം': 1, + 'ഹാ': 1, + 'ഹി': 1, + 'ഹിം': 1, + 'ක්‍': 2, + 'කා': 1, + 'කැ': 1, + 'කෘ': 1, + 'කෙ': 1, + 'කො': 1, + 'කෝ': 1, + 'කෲ': 1, + 'ඛ්‍': 2, + 'ගා': 1, + 'ගැ': 1, + 'ගෙ': 1, + 'ගේ': 1, + 'චා': 1, + 'චැ': 1, + 'චෝ': 1, + 'ජ්‍': 2, + 'ජා': 1, + 'ඥා': 1, + 'ටා': 1, + 'ටේ': 1, + 'ඨා': 1, + 'ඩං': 1, + 'ඩා': 1, + 'ත්‍': 2, + 'තා': 1, + 'තැ': 1, + 'තෘ': 1, + 'තෙ': 1, + 'තේ': 1, + 'තො': 1, + 'තෝ': 1, + 'ථා': 1, + 'ද්‍': 2, + 'දා': 1, + 'දැ': 1, + 'දිං': 1, + 'දෙ': 1, + 'දේ': 1, + 'දෝ': 1, + 'ධ්‍': 2, + 'ධා': 1, + 'න්‍': 2, + 'නා': 1, + 'නැ': 1, + 'නෑ': 1, + 'නෙ': 1, + 'නේ': 1, + 'නො': 1, + 'ඳා': 1, + 'ප්‍': 2, + 'පා': 1, + 'පැ': 1, + 'පෑ': 1, + 'පෙ': 1, + 'පේ': 1, + 'පො': 1, + 'පෞ': 1, + 'බා': 1, + 'බැ': 1, + 'බෙ': 1, + 'බේ': 1, + 'බෝ': 1, + 'භා': 1, + 'භෞ': 1, + 'මා': 1, + 'මැ': 1, + 'මෙ': 1, + 'මේ': 1, + 'යා': 1, + 'යෙ': 1, + 'යේ': 1, + 'යො': 1, + 'යෝ': 1, + 'රා': 1, + 'රැ': 1, + 'රෙ': 1, + 'රේ': 1, + 'රෝ': 1, + 'ලං': 1, + 'ලා': 1, + 'ලැ': 1, + 'ලෙ': 1, + 'ලේ': 1, + 'ලෝ': 1, + 'වං': 1, + 'ව්‍': 2, + 'වා': 1, + 'වැ': 1, + 'වෘ': 1, + 'වෙ': 1, + 'වේ': 1, + 'වෝ': 1, + 'ශ්‍': 2, + 'ශේ': 1, + 'ෂ්‍': 2, + 'ෂා': 1, + 'සං': 1, + 'සා': 1, + 'සැ': 1, + 'සෑ': 1, + 'සෙ': 1, + 'සේ': 1, + 'සෞ': 1, + 'හා': 1, + 'හැ': 1, + 'හිං': 1, + 'හෘ': 1, + 'හෙ': 1, + 'හො': 1, + 'හෝ': 1, + 'ළැ': 1, + 'ကေ': 1, + 'ကေု': 1, + 'က်ျ': 1, + 'ကျ': 1, + 'ကျို': 1, + 'ကျူ': 1, + 'ကျေ': 1, + 'ကျွ': 1, + 'ကြ': 1, + 'ကြို': 1, + 'ကြီ': 1, + 'ကြု': 1, + 'ကြေ': 1, + 'ကြံ': 1, + 'ကြွေ': 1, + 'ကၠေ': 1, + 'ကၠေံ': 1, + 'ခေ': 1, + 'ချ': 1, + 'ချိ': 1, + 'ချို': 1, + 'ချို့': 1, + 'ချီ': 1, + 'ချု': 1, + 'ချေ': 1, + 'ချဳ': 1, + 'ခြ': 1, + 'ခြုံ': 1, + 'ခြေ': 1, + 'ဂျို': 1, + 'ဂၠေ': 1, + 'ငြ': 1, + 'ငြိ': 1, + 'ငွေ': 1, + 'ငႄ': 1, + 'စေ': 1, + 'စှ်ေ': 1, + 'စၞေ': 1, + 'စၠေ': 1, + 'ဆေ': 1, + 'ဇြ': 1, + 'ဇြေ': 1, + 'ဇြဳ': 1, + 'ဇၞေ': 1, + 'ညေ': 1, + 'တေ': 1, + 'တေံ': 1, + 'တြ': 1, + 'တြုံ': 1, + 'တွေ': 1, + 'တှ်ေ': 1, + 'တၟေ': 1, + 'ထေ': 1, + 'ထွေ': 1, + 'ဒေ': 1, + 'ဒေံ': 1, + 'ဒြ': 1, + 'နေ': 1, + 'နေ့': 1, + 'နှေ': 1, + 'ပေ': 1, + 'ပေဲ': 1, + 'ပျ': 1, + 'ပျေ': 1, + 'ပျဲ': 1, + 'ပြ': 1, + 'ပြီ': 1, + 'ပြု': 1, + 'ပြေ': 1, + 'ပြဳ': 1, + 'ပြံ': 1, + 'ဖေ': 1, + 'ဖျ': 1, + 'ဖျု': 1, + 'ဖျေံ': 1, + 'ဖြ': 1, + 'ဖြို': 1, + 'ဗျဵု': 1, + 'ဗြေ': 1, + 'ဗြဴ': 1, + 'ဗၠေ': 1, + 'ဘေ': 1, + 'မေ': 1, + 'မျ': 1, + 'မျို': 1, + 'မျီု': 1, + 'မျှ': 1, + 'မြ': 1, + 'မြေ': 1, + 'မြှ': 1, + 'မွေ': 1, + 'မွေ့': 1, + 'မှေ': 1, + 'မၠေ': 1, + 'မႄ': 1, + 'ယေ': 1, + 'ယျ': 1, + 'ယျဵု': 1, + 'ယြဴ': 1, + 'ရေ': 1, + 'ရေံ': 1, + 'ရွေ': 1, + 'ရွှေ့': 1, + 'ရှေ': 1, + 'ရှေ့': 1, + 'ရှ်ေ': 1, + 'လေ': 1, + 'လျ': 1, + 'လျို': 1, + 'လျေ': 1, + 'လျှ': 1, + 'လျှို့': 1, + 'လျှေ': 1, + 'လၟေ': 1, + 'လႄ': 1, + 'ဝေ': 1, + 'သေ': 1, + 'သြ': 1, + 'သြို': 1, + 'သှ်ေ': 1, + 'သၞေ': 1, + 'ဟေ': 1, + 'အေ': 1, + 'ၜေ': 1, + 'ၵေ': 1, + 'ၵႄ': 1, + 'ၶေ': 1, + 'ၼေ': 1, + 'ၼႄ': 1, + 'ၽႄ': 1, + 'ႁေ': 1, + 'ႁႄ': 1, + 'កា': 1, + 'កើ': 1, + 'កេ': 1, + 'កោ': 1, + 'ខា': 1, + 'ខែ': 1, + 'គា': 1, + 'គាំ': 1, + 'គេ': 1, + 'គោ': 1, + 'ឃា': 1, + 'ឃើ': 1, + 'ឃោ': 1, + 'ឃៅ': 1, + 'ងា': 1, + 'ចា': 1, + 'ចាំ': 1, + 'ចេ': 1, + 'ចែ': 1, + 'ចោ': 1, + 'ឆាំ': 1, + 'ជា': 1, + 'ជៀ': 1, + 'ឈា': 1, + 'ញុះ': 1, + 'ដា': 1, + 'ដើ': 1, + 'ដែ': 1, + 'ដៃ': 1, + 'ដោ': 1, + 'ដៅ': 1, + 'ឋា': 1, + 'ណា': 1, + 'ណើ': 1, + 'ណែ': 1, + 'ណោ': 1, + 'ណោះ': 1, + 'ណៈ': 1, + 'តា': 1, + 'តេ': 1, + 'តែ': 1, + 'ថា': 1, + 'ថែ': 1, + 'ទា': 1, + 'ទាំ': 1, + 'ទៀ': 1, + 'ទេ': 1, + 'ទៃ': 1, + 'ទោ': 1, + 'ទោះ': 1, + 'ទៅ': 1, + 'ធា': 1, + 'នា': 1, + 'នាំ': 1, + 'នឿ': 1, + 'នេះ': 1, + 'នៃ': 1, + 'នោះ': 1, + 'នៅ': 1, + 'នៈ': 1, + 'បា': 1, + 'បើ': 1, + 'បៀ': 1, + 'បែ': 1, + 'បោ': 1, + 'បោះ': 1, + 'បះ': 1, + 'ប៉ះ': 1, + 'ពា': 1, + 'ពើ': 1, + 'ពេ': 1, + 'ពោះ': 1, + 'ភា': 1, + 'ភេ': 1, + 'មា': 1, + 'មើ': 1, + 'មេ': 1, + 'មែ': 1, + 'ម៉ា': 1, + 'ម៉ោ': 1, + 'យា': 1, + 'យោ': 1, + 'យៈ': 1, + 'យ៉ា': 1, + 'រា': 1, + 'រាំ': 1, + 'រើ': 1, + 'រឿ': 1, + 'រៀ': 1, + 'រះ': 1, + 'រៈ': 1, + 'លា': 1, + 'លុះ': 1, + 'លើ': 1, + 'លេ': 1, + 'លោ': 1, + 'លៈ': 1, + 'វា': 1, + 'វេ': 1, + 'វៈ': 1, + 'សា': 1, + 'សើ': 1, + 'សេ': 1, + 'សៈ': 1, + 'ស្ដ្រី': 3, + 'ស្ត្រ': 3, + 'ហា': 1, + 'ហើ': 1, + 'ហេ': 1, + 'ហែ': 1, + 'ហោ': 1, + 'ឡា': 1, + 'ឡើ': 1, + 'អា': 1, + 'អើ': 1, + 'អៀ': 1, + 'ᨠᩮᩢ᩵': 1, + 'ᨠᩮ᩵': 1, + 'ᨠᩯ᩵': 1, + 'ᨡᩮᩢ': 1, + 'ᨡᩮᩢᩢ': 1, + 'ᨡᩱᩢ': 1, + 'ᨣᩕ': 1, + 'ᨣᩭ': 1, + 'ᨣᩮᩢᩢ': 1, + 'ᨤᩮᩢ': 1, + 'ᨤᩱ᩵': 1, + 'ᨧᩮ': 1, + 'ᨧᩮᩢᩢ': 1, + 'ᨧᩱ': 1, + 'ᨩᩭ᩵': 1, + 'ᨩᩱᩢ': 1, + 'ᨩ᩵ᩭ': 1, + 'ᨪᩮᩢ': 1, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 3, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 3, + 'ᨯᩪᩯ': 1, + 'ᨯᩱ': 1, + 'ᨯᩱᩢ': 1, + 'ᨲᩕ': 1, + 'ᨲᩕᩦ': 1, + 'ᨲᩕ᩼': 1, + 'ᨲᩯ᩵': 1, + 'ᨲᩱᩢ': 1, + 'ᨳᩮᩢᩢ': 1, + 'ᨴᩮᩢᩢ': 1, + 'ᨴᩮᩢ᩵': 1, + 'ᨴᩯᩢ': 1, + 'ᨶᩮ': 1, + 'ᨶᩱ': 1, + 'ᨷᩕ': 1, + 'ᨸᩮᩢ᩵': 1, + 'ᨹᩪᩢᩱ': 1, + 'ᨻᩱ': 1, + 'ᨾᩯ᩵': 1, + 'ᨾᩱ': 1, + 'ᨿᩰ': 1, + 'ᩁᩢᩭ': 1, + 'ᩃᩯ': 1, + 'ᩅᩮ': 1, + 'ᩅᩱᩢ': 1, + 'ᩈᩮ': 1, + 'ᩉᩕᩨ': 1, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 3, + 'ᩉᩮᩖᩨ': 1, + 'ᩉᩯ᩵': 1, + 'ᩣ᩠ᨠ': 1, + 'ᩣ᩠ᨦ': 1, + 'ᩣ᩠ᨧ': 1, + 'ᩣ᩠ᨩ': 1, + 'ᩣ᩠ᨯ': 1, + 'ᩣ᩠ᨲ': 1, + 'ᩣ᩠ᨲᩱ': 1, + 'ᩣ᩠ᨶ': 1, + 'ᩣ᩠ᨷ': 1, + 'ᩣ᩠ᨾ': 1, + 'ᩣ᩠ᨿ': 1, + 'ᩣ᩠ᩁ': 1, + 'ᩣ᩠ᩃ': 1, + 'ᩣ᩠ᩅ': 1, + 'ᩣ᩠ᩈ': 1, + 'ᩤ᩠ᨦ': 1, + 'ᩤ᩠ᨶᩢ': 1, + '⛓️‍💥': 4, + '⛹️‍♀️': 3, + '⛹️‍♂️': 3, + '⛹🏻‍♀️': 5, + '⛹🏻‍♂️': 5, + '⛹🏼‍♀️': 5, + '⛹🏼‍♂️': 5, + '⛹🏽‍♀️': 5, + '⛹🏽‍♂️': 5, + '⛹🏾‍♀️': 5, + '⛹🏾‍♂️': 5, + '⛹🏿‍♀️': 5, + '⛹🏿‍♂️': 5, + '❤️‍🔥': 4, + '❤️‍🩹': 4, + 'ꦏꦃ': 1, + 'ꦏꦺ': 1, + 'ꦏꦺꦴ': 1, + 'ꦏꦿ': 1, + 'ꦏꦿꦁ': 1, + 'ꦏꦿꦂ': 1, + 'ꦒꦸꦃ': 1, + 'ꦒꦺꦴ': 1, + 'ꦒꦿ': 1, + 'ꦒꦿꦺ': 1, + 'ꦔꦃ': 1, + 'ꦔꦺ': 1, + 'ꦔꦺꦴ': 1, + 'ꦔꦿ': 1, + 'ꦕꦃ': 1, + 'ꦕꦺꦴ': 1, + 'ꦗꦃ': 1, + 'ꦗꦺ': 1, + 'ꦗꦿꦺꦴ': 1, + 'ꦝꦃ': 1, + 'ꦝꦺ': 1, + 'ꦝꦺꦴ': 1, + 'ꦝꦺꦴꦂ': 1, + 'ꦠꦸꦃ': 1, + 'ꦠꦺ': 1, + 'ꦠꦺꦃ': 1, + 'ꦠꦺꦴ': 1, + 'ꦠꦾ': 1, + 'ꦠꦿ': 1, + 'ꦠꦿꦶ': 1, + 'ꦠ꧀ꦱ꧀ꦮ': 3, + 'ꦢꦃ': 1, + 'ꦢꦺ': 1, + 'ꦢꦺꦴ': 1, + 'ꦢꦾ': 1, + 'ꦢꦿ': 1, + 'ꦤꦺ': 1, + 'ꦤꦺꦃ': 1, + 'ꦤꦺꦴ': 1, + 'ꦥꦃ': 1, + 'ꦥꦺ': 1, + 'ꦥꦺꦴ': 1, + 'ꦥꦿ': 1, + 'ꦥꦿꦃ': 1, + 'ꦥꦿꦶ': 1, + 'ꦥꦿꦺꦴ': 1, + 'ꦧꦺ': 1, + 'ꦧꦺꦃ': 1, + 'ꦧꦺꦴ': 1, + 'ꦧꦿ': 1, + 'ꦩꦃ': 1, + 'ꦩꦺ': 1, + 'ꦩꦺꦃ': 1, + 'ꦩꦺꦴ': 1, + 'ꦩꦿ': 1, + 'ꦩꦿꦃ': 1, + 'ꦩꦿꦶꦃ': 1, + 'ꦪꦃ': 1, + 'ꦪꦸꦃ': 1, + 'ꦪꦺꦴ': 1, + 'ꦫꦶꦃ': 1, + 'ꦫꦺ': 1, + 'ꦫꦺꦴ': 1, + 'ꦫꦾ': 1, + 'ꦭꦃ': 1, + 'ꦭꦶꦃ': 1, + 'ꦭꦺ': 1, + 'ꦭꦺꦃ': 1, + 'ꦭꦺꦴ': 1, + 'ꦭꦺꦴꦁ': 1, + 'ꦮꦃ': 1, + 'ꦮꦶꦃ': 1, + 'ꦮꦸꦃ': 1, + 'ꦮꦺ': 1, + 'ꦮꦺꦴ': 1, + 'ꦮꦺꦴꦁ': 1, + 'ꦮꦺꦴꦃ': 1, + 'ꦮꦿꦸꦃ': 1, + 'ꦱꦶꦃ': 1, + 'ꦱꦺ': 1, + 'ꦱꦺꦴ': 1, + 'ꦱꦾ': 1, + 'ꦱꦿ': 1, + 'ꦱꦿꦃ': 1, + 'ꦲꦺ': 1, + 'ꦲꦺꦴ': 1, + '𑄃𑄬': 1, + '𑄃𑄬𑄭': 1, + '𑄇𑄬': 1, + '𑄈𑄬': 1, + '𑄉𑄬': 1, + '𑄉𑄬𑄭': 1, + '𑄊𑄬': 1, + '𑄌𑄬': 1, + '𑄎𑄬': 1, + '𑄎𑄬𑄭': 1, + '𑄏𑄬': 1, + '𑄑𑄬': 1, + '𑄖𑄬': 1, + '𑄗𑄬': 1, + '𑄘𑄬': 1, + '𑄙𑄬': 1, + '𑄚𑄬': 1, + '𑄚𑄬𑄭': 1, + '𑄛𑄬': 1, + '𑄜𑄬': 1, + '𑄝𑄬': 1, + '𑄞𑄬': 1, + '𑄞𑄬𑄭': 1, + '𑄟𑄬': 1, + '𑄠𑄬': 1, + '𑄠𑄬𑄭': 1, + '𑄡𑄬': 1, + '𑄡𑄬𑄭': 1, + '𑄢𑄬': 1, + '𑄢𑄬𑄭': 1, + '𑄣𑄬': 1, + '𑄣𑄬𑄭': 1, + '𑄥𑄬': 1, + '𑄦𑄬': 1, + '𑌅𑌂': 1, + '𑌕𑌂': 1, + '𑌕𑌾': 1, + '𑌕𑌾𑌂': 1, + '𑌕𑌾𑌃': 1, + '𑌕𑌿': 1, + '𑌕𑍂': 1, + '𑌕𑍃': 1, + '𑌕𑍇': 1, + '𑌕𑍋': 1, + '𑌗𑌾': 1, + '𑌗𑌿': 1, + '𑌗𑍁': 1, + '𑌗𑍃': 1, + '𑌗𑍇': 1, + '𑌗𑍌': 1, + '𑌘𑌾': 1, + '𑌘𑍇': 1, + '𑌘𑍋': 1, + '𑌚𑌾': 1, + '𑌚𑌿': 1, + '𑌚𑍇': 1, + '𑌚𑍈': 1, + '𑌛𑌾': 1, + '𑌛𑍁': 1, + '𑌛𑍇': 1, + '𑌜𑌾': 1, + '𑌜𑌿': 1, + '𑌜𑍇': 1, + '𑌞𑌾': 1, + '𑌟𑌃': 1, + '𑌟𑌾': 1, + '𑌟𑌾𑌂': 1, + '𑌟𑌾𑌃': 1, + '𑌠𑌾': 1, + '𑌠𑍇': 1, + '𑌠𑍈𑌃': 1, + '𑌡𑌂': 1, + '𑌡𑌃': 1, + '𑌡𑌿': 1, + '𑌣𑌂': 1, + '𑌣𑌾': 1, + '𑌣𑌾𑌂': 1, + '𑌣𑌿': 1, + '𑌣𑍁': 1, + '𑌣𑍇': 1, + '𑌤𑌂': 1, + '𑌤𑌃': 1, + '𑌤𑌾': 1, + '𑌤𑌾𑌂': 1, + '𑌤𑌾𑌃': 1, + '𑌤𑌿': 1, + '𑌤𑌿𑌂': 1, + '𑌤𑌿𑌃': 1, + '𑌤𑍁': 1, + '𑌤𑍁𑌂': 1, + '𑌤𑍃': 1, + '𑌤𑍇': 1, + '𑌤𑍇𑌃': 1, + '𑌤𑍈': 1, + '𑌤𑍋': 1, + '𑌤𑍌': 1, + '𑌥𑌂': 1, + '𑌥𑌾': 1, + '𑌥𑌾𑌂': 1, + '𑌥𑌿': 1, + '𑌦𑌂': 1, + '𑌦𑌃': 1, + '𑌦𑌾': 1, + '𑌦𑌿': 1, + '𑌦𑍁': 1, + '𑌦𑍃': 1, + '𑌦𑍇': 1, + '𑌦𑍋': 1, + '𑌧𑌃': 1, + '𑌧𑌾': 1, + '𑌧𑌾𑌃': 1, + '𑌧𑌿': 1, + '𑌧𑌿𑌂': 1, + '𑌧𑍁': 1, + '𑌧𑍃': 1, + '𑌧𑍇': 1, + '𑌧𑍇𑌃': 1, + '𑌧𑍈𑌃': 1, + '𑌨𑌂': 1, + '𑌨𑌃': 1, + '𑌨𑌾': 1, + '𑌨𑌾𑌂': 1, + '𑌨𑌾𑌃': 1, + '𑌨𑌿': 1, + '𑌨𑌿𑌃': 1, + '𑌨𑍁': 1, + '𑌨𑍂': 1, + '𑌨𑍇': 1, + '𑌨𑍈': 1, + '𑌨𑍈𑌃': 1, + '𑌨𑍋': 1, + '𑌪𑌂': 1, + '𑌪𑌾': 1, + '𑌪𑌿': 1, + '𑌪𑍁': 1, + '𑌪𑍂': 1, + '𑌪𑍇': 1, + '𑌪𑍋': 1, + '𑌬𑌾': 1, + '𑌬𑍃': 1, + '𑌭𑌾': 1, + '𑌭𑌿': 1, + '𑌭𑌿𑌃': 1, + '𑌭𑍁': 1, + '𑌭𑍂': 1, + '𑌭𑍇': 1, + '𑌮𑌂': 1, + '𑌮𑌾': 1, + '𑌮𑌿': 1, + '𑌮𑌿𑌂': 1, + '𑌮𑍁': 1, + '𑌮𑍂': 1, + '𑌮𑍇': 1, + '𑌮𑍈': 1, + '𑌮𑍋': 1, + '𑌮𑍌': 1, + '𑌯𑌂': 1, + '𑌯𑌃': 1, + '𑌯𑌾': 1, + '𑌯𑌾𑌂': 1, + '𑌯𑌾𑌃': 1, + '𑌯𑌿': 1, + '𑌯𑍁': 1, + '𑌯𑍁𑌃': 1, + '𑌯𑍇': 1, + '𑌯𑍈': 1, + '𑌯𑍈𑌃': 1, + '𑌯𑍋': 1, + '𑌯𑍋𑌃': 1, + '𑌰𑌂': 1, + '𑌰𑌃': 1, + '𑌰𑌾': 1, + '𑌰𑌾𑌃': 1, + '𑌰𑌿': 1, + '𑌰𑌿𑌂': 1, + '𑌰𑍁': 1, + '𑌰𑍂': 1, + '𑌰𑍇': 1, + '𑌰𑍋': 1, + '𑌰𑍌': 1, + '𑌲𑌂': 1, + '𑌲𑌾': 1, + '𑌲𑌾𑌃': 1, + '𑌲𑌿': 1, + '𑌲𑌿𑌂': 1, + '𑌲𑍇': 1, + '𑌲𑍈': 1, + '𑌲𑍋': 1, + '𑌵𑌂': 1, + '𑌵𑌃': 1, + '𑌵𑌾': 1, + '𑌵𑌾𑌂': 1, + '𑌵𑌾𑌃': 1, + '𑌵𑌿': 1, + '𑌵𑍃': 1, + '𑌵𑍇': 1, + '𑌵𑍈': 1, + '𑌵𑍋': 1, + '𑌶𑌂': 1, + '𑌶𑌃': 1, + '𑌶𑌾': 1, + '𑌶𑌾𑌃': 1, + '𑌶𑌿': 1, + '𑌶𑍁': 1, + '𑌶𑍂': 1, + '𑌶𑍇': 1, + '𑌶𑍋': 1, + '𑌷𑌂': 1, + '𑌷𑌾': 1, + '𑌷𑌾𑌂': 1, + '𑌷𑌾𑌃': 1, + '𑌷𑌿': 1, + '𑌷𑍁': 1, + '𑌷𑍇': 1, + '𑌷𑍈': 1, + '𑌷𑍋': 1, + '𑌸𑌂': 1, + '𑌸𑌃': 1, + '𑌸𑌾': 1, + '𑌸𑌾𑌂': 1, + '𑌸𑌿': 1, + '𑌸𑍁': 1, + '𑌸𑍂': 1, + '𑌸𑍇': 1, + '𑌸𑍋': 1, + '𑌸𑍌': 1, + '𑌹𑌾': 1, + '𑌹𑌾𑌃': 1, + '𑌹𑌿': 1, + '𑌹𑍇': 1, + '𑌹𑍋': 1, + '🍄‍🟫': 5, + '🍋‍🟩': 5, + '🏃‍♀️': 4, + '🏃‍♀️‍➡️': 6, + '🏃‍♂️': 4, + '🏃‍♂️‍➡️': 6, + '🏃‍➡️': 4, + '🏃🏻‍♀️': 6, + '🏃🏻‍♀️‍➡️': 8, + '🏃🏻‍♂️': 6, + '🏃🏻‍♂️‍➡️': 8, + '🏃🏻‍➡️': 6, + '🏃🏼‍♀️': 6, + '🏃🏼‍♀️‍➡️': 8, + '🏃🏼‍♂️': 6, + '🏃🏼‍♂️‍➡️': 8, + '🏃🏼‍➡️': 6, + '🏃🏽‍♀️': 6, + '🏃🏽‍♀️‍➡️': 8, + '🏃🏽‍♂️': 6, + '🏃🏽‍♂️‍➡️': 8, + '🏃🏽‍➡️': 6, + '🏃🏾‍♀️': 6, + '🏃🏾‍♀️‍➡️': 8, + '🏃🏾‍♂️': 6, + '🏃🏾‍♂️‍➡️': 8, + '🏃🏾‍➡️': 6, + '🏃🏿‍♀️': 6, + '🏃🏿‍♀️‍➡️': 8, + '🏃🏿‍♂️': 6, + '🏃🏿‍♂️‍➡️': 8, + '🏃🏿‍➡️': 6, + '🏄‍♀️': 4, + '🏄‍♂️': 4, + '🏄🏻‍♀️': 6, + '🏄🏻‍♂️': 6, + '🏄🏼‍♀️': 6, + '🏄🏼‍♂️': 6, + '🏄🏽‍♀️': 6, + '🏄🏽‍♂️': 6, + '🏄🏾‍♀️': 6, + '🏄🏾‍♂️': 6, + '🏄🏿‍♀️': 6, + '🏄🏿‍♂️': 6, + '🏊‍♀️': 4, + '🏊‍♂️': 4, + '🏊🏻‍♀️': 6, + '🏊🏻‍♂️': 6, + '🏊🏼‍♀️': 6, + '🏊🏼‍♂️': 6, + '🏊🏽‍♀️': 6, + '🏊🏽‍♂️': 6, + '🏊🏾‍♀️': 6, + '🏊🏾‍♂️': 6, + '🏊🏿‍♀️': 6, + '🏊🏿‍♂️': 6, + '🏋️‍♀️': 3, + '🏋️‍♂️': 3, + '🏋🏻‍♀️': 5, + '🏋🏻‍♂️': 5, + '🏋🏼‍♀️': 5, + '🏋🏼‍♂️': 5, + '🏋🏽‍♀️': 5, + '🏋🏽‍♂️': 5, + '🏋🏾‍♀️': 5, + '🏋🏾‍♂️': 5, + '🏋🏿‍♀️': 5, + '🏋🏿‍♂️': 5, + '🏌️‍♀️': 3, + '🏌️‍♂️': 3, + '🏌🏻‍♀️': 5, + '🏌🏻‍♂️': 5, + '🏌🏼‍♀️': 5, + '🏌🏼‍♂️': 5, + '🏌🏽‍♀️': 5, + '🏌🏽‍♂️': 5, + '🏌🏾‍♀️': 5, + '🏌🏾‍♂️': 5, + '🏌🏿‍♀️': 5, + '🏌🏿‍♂️': 5, + '🏳️‍⚧️': 3, + '🏳️‍🌈': 4, + '🏴‍☠️': 4, + '🏴󠁧󠁢󠁥󠁮󠁧󠁿': 8, + '🏴󠁧󠁢󠁳󠁣󠁴󠁿': 8, + '🏴󠁧󠁢󠁷󠁬󠁳󠁿': 8, + '🐈‍⬛': 5, + '🐕‍🦺': 5, + '🐦‍⬛': 5, + '🐦‍🔥': 5, + '🐻‍❄️': 4, + '👁️‍🗨️': 3, + '👨‍⚕️': 4, + '👨‍⚖️': 4, + '👨‍✈️': 4, + '👨‍❤️‍👨': 7, + '👨‍❤️‍💋‍👨': 10, + '👨‍🌾': 5, + '👨‍🍳': 5, + '👨‍🍼': 5, + '👨‍🎓': 5, + '👨‍🎤': 5, + '👨‍🎨': 5, + '👨‍🏫': 5, + '👨‍🏭': 5, + '👨‍👦': 5, + '👨‍👦‍👦': 8, + '👨‍👧': 5, + '👨‍👧‍👦': 8, + '👨‍👧‍👧': 8, + '👨‍👨‍👦': 8, + '👨‍👨‍👦‍👦': 11, + '👨‍👨‍👧': 8, + '👨‍👨‍👧‍👦': 11, + '👨‍👨‍👧‍👧': 11, + '👨‍👩‍👦': 8, + '👨‍👩‍👦‍👦': 11, + '👨‍👩‍👧': 8, + '👨‍👩‍👧‍👦': 11, + '👨‍👩‍👧‍👧': 11, + '👨‍💻': 5, + '👨‍💼': 5, + '👨‍🔧': 5, + '👨‍🔬': 5, + '👨‍🚀': 5, + '👨‍🚒': 5, + '👨‍🦯': 5, + '👨‍🦯‍➡️': 7, + '👨‍🦰': 5, + '👨‍🦱': 5, + '👨‍🦲': 5, + '👨‍🦳': 5, + '👨‍🦼': 5, + '👨‍🦼‍➡️': 7, + '👨‍🦽': 5, + '👨‍🦽‍➡️': 7, + '👨🏻‍⚕️': 6, + '👨🏻‍⚖️': 6, + '👨🏻‍✈️': 6, + '👨🏻‍❤️‍👨🏻': 11, + '👨🏻‍❤️‍👨🏽': 11, + '👨🏻‍❤️‍👨🏿': 11, + '👨🏻‍❤️‍💋‍👨🏻': 14, + '👨🏻‍❤️‍💋‍👨🏽': 14, + '👨🏻‍❤️‍💋‍👨🏾': 14, + '👨🏻‍❤️‍💋‍👨🏿': 14, + '👨🏻‍🌾': 7, + '👨🏻‍🍳': 7, + '👨🏻‍🍼': 7, + '👨🏻‍🎓': 7, + '👨🏻‍🎤': 7, + '👨🏻‍🎨': 7, + '👨🏻‍🏫': 7, + '👨🏻‍🏭': 7, + '👨🏻‍🐰‍👨🏼': 12, + '👨🏻‍🐰‍👨🏽': 12, + '👨🏻‍🐰‍👨🏾': 12, + '👨🏻‍🐰‍👨🏿': 12, + '👨🏻‍💻': 7, + '👨🏻‍💼': 7, + '👨🏻‍🔧': 7, + '👨🏻‍🔬': 7, + '👨🏻‍🚀': 7, + '👨🏻‍🚒': 7, + '👨🏻‍🤝‍👨🏼': 12, + '👨🏻‍🤝‍👨🏽': 12, + '👨🏻‍🤝‍👨🏾': 12, + '👨🏻‍🤝‍👨🏿': 12, + '👨🏻‍🦯': 7, + '👨🏻‍🦯‍➡️': 9, + '👨🏻‍🦰': 7, + '👨🏻‍🦱': 7, + '👨🏻‍🦲': 7, + '👨🏻‍🦳': 7, + '👨🏻‍🦼': 7, + '👨🏻‍🦼‍➡️': 9, + '👨🏻‍🦽': 7, + '👨🏻‍🦽‍➡️': 9, + '👨🏻‍🫯‍👨🏼': 11, + '👨🏻‍🫯‍👨🏽': 11, + '👨🏻‍🫯‍👨🏾': 11, + '👨🏻‍🫯‍👨🏿': 11, + '👨🏼‍⚕️': 6, + '👨🏼‍⚖️': 6, + '👨🏼‍✈️': 6, + '👨🏼‍❤️‍👨🏼': 11, + '👨🏼‍❤️‍💋‍👨🏼': 14, + '👨🏼‍❤️‍💋‍👨🏿': 14, + '👨🏼‍🌾': 7, + '👨🏼‍🍳': 7, + '👨🏼‍🍼': 7, + '👨🏼‍🎓': 7, + '👨🏼‍🎤': 7, + '👨🏼‍🎨': 7, + '👨🏼‍🏫': 7, + '👨🏼‍🏭': 7, + '👨🏼‍🐰‍👨🏻': 12, + '👨🏼‍🐰‍👨🏽': 12, + '👨🏼‍🐰‍👨🏿': 12, + '👨🏼‍💻': 7, + '👨🏼‍💼': 7, + '👨🏼‍🔧': 7, + '👨🏼‍🔬': 7, + '👨🏼‍🚀': 7, + '👨🏼‍🚒': 7, + '👨🏼‍🤝‍👨🏻': 12, + '👨🏼‍🤝‍👨🏽': 12, + '👨🏼‍🤝‍👨🏿': 12, + '👨🏼‍🦯': 7, + '👨🏼‍🦯‍➡️': 9, + '👨🏼‍🦰': 7, + '👨🏼‍🦱': 7, + '👨🏼‍🦲': 7, + '👨🏼‍🦳': 7, + '👨🏼‍🦼': 7, + '👨🏼‍🦽': 7, + '👨🏼‍🦽‍➡️': 9, + '👨🏼‍🫯‍👨🏻': 11, + '👨🏼‍🫯‍👨🏽': 11, + '👨🏼‍🫯‍👨🏾': 11, + '👨🏼‍🫯‍👨🏿': 11, + '👨🏽‍⚕️': 6, + '👨🏽‍⚖️': 6, + '👨🏽‍✈️': 6, + '👨🏽‍❤️‍👨🏻': 11, + '👨🏽‍❤️‍👨🏽': 11, + '👨🏽‍❤️‍👨🏿': 11, + '👨🏽‍❤️‍💋‍👨🏻': 14, + '👨🏽‍❤️‍💋‍👨🏽': 14, + '👨🏽‍❤️‍💋‍👨🏿': 14, + '👨🏽‍🌾': 7, + '👨🏽‍🍳': 7, + '👨🏽‍🍼': 7, + '👨🏽‍🎓': 7, + '👨🏽‍🎤': 7, + '👨🏽‍🎨': 7, + '👨🏽‍🏫': 7, + '👨🏽‍🏭': 7, + '👨🏽‍🐰‍👨🏻': 12, + '👨🏽‍🐰‍👨🏼': 12, + '👨🏽‍🐰‍👨🏾': 12, + '👨🏽‍🐰‍👨🏿': 12, + '👨🏽‍💻': 7, + '👨🏽‍💼': 7, + '👨🏽‍🔧': 7, + '👨🏽‍🔬': 7, + '👨🏽‍🚀': 7, + '👨🏽‍🚒': 7, + '👨🏽‍🤝‍👨🏻': 12, + '👨🏽‍🤝‍👨🏼': 12, + '👨🏽‍🤝‍👨🏾': 12, + '👨🏽‍🤝‍👨🏿': 12, + '👨🏽‍🦯': 7, + '👨🏽‍🦯‍➡️': 9, + '👨🏽‍🦰': 7, + '👨🏽‍🦱': 7, + '👨🏽‍🦲': 7, + '👨🏽‍🦳': 7, + '👨🏽‍🦼': 7, + '👨🏽‍🦼‍➡️': 9, + '👨🏽‍🦽': 7, + '👨🏽‍🦽‍➡️': 9, + '👨🏽‍🫯‍👨🏻': 11, + '👨🏽‍🫯‍👨🏼': 11, + '👨🏽‍🫯‍👨🏾': 11, + '👨🏽‍🫯‍👨🏿': 11, + '👨🏾‍⚕️': 6, + '👨🏾‍⚖️': 6, + '👨🏾‍✈️': 6, + '👨🏾‍❤️‍👨🏾': 11, + '👨🏾‍❤️‍💋‍👨🏻': 14, + '👨🏾‍❤️‍💋‍👨🏾': 14, + '👨🏾‍❤️‍💋‍👨🏿': 14, + '👨🏾‍🌾': 7, + '👨🏾‍🍳': 7, + '👨🏾‍🍼': 7, + '👨🏾‍🎓': 7, + '👨🏾‍🎤': 7, + '👨🏾‍🎨': 7, + '👨🏾‍🏫': 7, + '👨🏾‍🏭': 7, + '👨🏾‍🐰‍👨🏻': 12, + '👨🏾‍🐰‍👨🏽': 12, + '👨🏾‍🐰‍👨🏿': 12, + '👨🏾‍💻': 7, + '👨🏾‍💼': 7, + '👨🏾‍🔧': 7, + '👨🏾‍🔬': 7, + '👨🏾‍🚀': 7, + '👨🏾‍🚒': 7, + '👨🏾‍🤝‍👨🏻': 12, + '👨🏾‍🤝‍👨🏽': 12, + '👨🏾‍🤝‍👨🏿': 12, + '👨🏾‍🦯': 7, + '👨🏾‍🦯‍➡️': 9, + '👨🏾‍🦰': 7, + '👨🏾‍🦱': 7, + '👨🏾‍🦲': 7, + '👨🏾‍🦳': 7, + '👨🏾‍🦼': 7, + '👨🏾‍🦽': 7, + '👨🏾‍🦽‍➡️': 9, + '👨🏾‍🫯‍👨🏻': 11, + '👨🏾‍🫯‍👨🏼': 11, + '👨🏾‍🫯‍👨🏽': 11, + '👨🏾‍🫯‍👨🏿': 11, + '👨🏿‍⚕️': 6, + '👨🏿‍⚖️': 6, + '👨🏿‍✈️': 6, + '👨🏿‍❤️‍👨🏻': 11, + '👨🏿‍❤️‍👨🏽': 11, + '👨🏿‍❤️‍👨🏿': 11, + '👨🏿‍❤️‍💋‍👨🏻': 14, + '👨🏿‍❤️‍💋‍👨🏼': 14, + '👨🏿‍❤️‍💋‍👨🏽': 14, + '👨🏿‍❤️‍💋‍👨🏾': 14, + '👨🏿‍❤️‍💋‍👨🏿': 14, + '👨🏿‍🌾': 7, + '👨🏿‍🍳': 7, + '👨🏿‍🍼': 7, + '👨🏿‍🎓': 7, + '👨🏿‍🎤': 7, + '👨🏿‍🎨': 7, + '👨🏿‍🏫': 7, + '👨🏿‍🏭': 7, + '👨🏿‍🐰‍👨🏻': 12, + '👨🏿‍🐰‍👨🏼': 12, + '👨🏿‍🐰‍👨🏽': 12, + '👨🏿‍🐰‍👨🏾': 12, + '👨🏿‍💻': 7, + '👨🏿‍💼': 7, + '👨🏿‍🔧': 7, + '👨🏿‍🔬': 7, + '👨🏿‍🚀': 7, + '👨🏿‍🚒': 7, + '👨🏿‍🤝‍👨🏻': 12, + '👨🏿‍🤝‍👨🏼': 12, + '👨🏿‍🤝‍👨🏽': 12, + '👨🏿‍🤝‍👨🏾': 12, + '👨🏿‍🦯': 7, + '👨🏿‍🦯‍➡️': 9, + '👨🏿‍🦰': 7, + '👨🏿‍🦱': 7, + '👨🏿‍🦲': 7, + '👨🏿‍🦳': 7, + '👨🏿‍🦼': 7, + '👨🏿‍🦼‍➡️': 9, + '👨🏿‍🦽': 7, + '👨🏿‍🦽‍➡️': 9, + '👨🏿‍🫯‍👨🏻': 11, + '👨🏿‍🫯‍👨🏼': 11, + '👨🏿‍🫯‍👨🏽': 11, + '👨🏿‍🫯‍👨🏾': 11, + '👩‍⚕️': 4, + '👩‍⚖️': 4, + '👩‍✈️': 4, + '👩‍❤️‍👨': 7, + '👩‍❤️‍👩': 7, + '👩‍❤️‍💋‍👨': 10, + '👩‍❤️‍💋‍👩': 10, + '👩‍🌾': 5, + '👩‍🍳': 5, + '👩‍🍼': 5, + '👩‍🎓': 5, + '👩‍🎤': 5, + '👩‍🎨': 5, + '👩‍🏫': 5, + '👩‍🏭': 5, + '👩‍👦': 5, + '👩‍👦‍👦': 8, + '👩‍👧': 5, + '👩‍👧‍👦': 8, + '👩‍👧‍👧': 8, + '👩‍👩‍👦': 8, + '👩‍👩‍👦‍👦': 11, + '👩‍👩‍👧': 8, + '👩‍👩‍👧‍👦': 11, + '👩‍👩‍👧‍👧': 11, + '👩‍💻': 5, + '👩‍💼': 5, + '👩‍🔧': 5, + '👩‍🔬': 5, + '👩‍🚀': 5, + '👩‍🚒': 5, + '👩‍🦯': 5, + '👩‍🦯‍➡️': 7, + '👩‍🦰': 5, + '👩‍🦱': 5, + '👩‍🦲': 5, + '👩‍🦳': 5, + '👩‍🦼': 5, + '👩‍🦼‍➡️': 7, + '👩‍🦽': 5, + '👩‍🦽‍➡️': 7, + '👩🏻‍⚕️': 6, + '👩🏻‍⚖️': 6, + '👩🏻‍✈️': 6, + '👩🏻‍❤️‍👨🏻': 11, + '👩🏻‍❤️‍👨🏿': 11, + '👩🏻‍❤️‍👩🏻': 11, + '👩🏻‍❤️‍💋‍👨🏻': 14, + '👩🏻‍❤️‍💋‍👨🏽': 14, + '👩🏻‍❤️‍💋‍👨🏿': 14, + '👩🏻‍❤️‍💋‍👩🏻': 14, + '👩🏻‍❤️‍💋‍👩🏽': 14, + '👩🏻‍❤️‍💋‍👩🏿': 14, + '👩🏻‍🌾': 7, + '👩🏻‍🍳': 7, + '👩🏻‍🍼': 7, + '👩🏻‍🎓': 7, + '👩🏻‍🎤': 7, + '👩🏻‍🎨': 7, + '👩🏻‍🏫': 7, + '👩🏻‍🏭': 7, + '👩🏻‍🐰‍👩🏼': 12, + '👩🏻‍🐰‍👩🏽': 12, + '👩🏻‍🐰‍👩🏾': 12, + '👩🏻‍🐰‍👩🏿': 12, + '👩🏻‍💻': 7, + '👩🏻‍💼': 7, + '👩🏻‍🔧': 7, + '👩🏻‍🔬': 7, + '👩🏻‍🚀': 7, + '👩🏻‍🚒': 7, + '👩🏻‍🤝‍👨🏽': 12, + '👩🏻‍🤝‍👨🏿': 12, + '👩🏻‍🤝‍👩🏼': 12, + '👩🏻‍🤝‍👩🏽': 12, + '👩🏻‍🤝‍👩🏾': 12, + '👩🏻‍🤝‍👩🏿': 12, + '👩🏻‍🦯': 7, + '👩🏻‍🦯‍➡️': 9, + '👩🏻‍🦰': 7, + '👩🏻‍🦱': 7, + '👩🏻‍🦲': 7, + '👩🏻‍🦳': 7, + '👩🏻‍🦼': 7, + '👩🏻‍🦼‍➡️': 9, + '👩🏻‍🦽': 7, + '👩🏻‍🦽‍➡️': 9, + '👩🏻‍🫯‍👩🏼': 11, + '👩🏻‍🫯‍👩🏽': 11, + '👩🏻‍🫯‍👩🏾': 11, + '👩🏻‍🫯‍👩🏿': 11, + '👩🏼‍⚕️': 6, + '👩🏼‍⚖️': 6, + '👩🏼‍✈️': 6, + '👩🏼‍❤️‍👨🏼': 11, + '👩🏼‍❤️‍👩🏼': 11, + '👩🏼‍❤️‍💋‍👨🏼': 14, + '👩🏼‍❤️‍💋‍👩🏼': 14, + '👩🏼‍🌾': 7, + '👩🏼‍🍳': 7, + '👩🏼‍🍼': 7, + '👩🏼‍🎓': 7, + '👩🏼‍🎤': 7, + '👩🏼‍🎨': 7, + '👩🏼‍🏫': 7, + '👩🏼‍🏭': 7, + '👩🏼‍🐰‍👩🏻': 12, + '👩🏼‍🐰‍👩🏿': 12, + '👩🏼‍💻': 7, + '👩🏼‍💼': 7, + '👩🏼‍🔧': 7, + '👩🏼‍🔬': 7, + '👩🏼‍🚀': 7, + '👩🏼‍🚒': 7, + '👩🏼‍🤝‍👩🏻': 12, + '👩🏼‍🤝‍👩🏽': 12, + '👩🏼‍🤝‍👩🏿': 12, + '👩🏼‍🦯': 7, + '👩🏼‍🦯‍➡️': 9, + '👩🏼‍🦰': 7, + '👩🏼‍🦱': 7, + '👩🏼‍🦲': 7, + '👩🏼‍🦳': 7, + '👩🏼‍🦼': 7, + '👩🏼‍🦽': 7, + '👩🏼‍🫯‍👩🏻': 11, + '👩🏼‍🫯‍👩🏽': 11, + '👩🏼‍🫯‍👩🏾': 11, + '👩🏼‍🫯‍👩🏿': 11, + '👩🏽‍⚕️': 6, + '👩🏽‍⚖️': 6, + '👩🏽‍✈️': 6, + '👩🏽‍❤️‍👨🏽': 11, + '👩🏽‍❤️‍👩🏽': 11, + '👩🏽‍❤️‍💋‍👨🏻': 14, + '👩🏽‍❤️‍💋‍👨🏽': 14, + '👩🏽‍❤️‍💋‍👨🏿': 14, + '👩🏽‍❤️‍💋‍👩🏻': 14, + '👩🏽‍❤️‍💋‍👩🏽': 14, + '👩🏽‍❤️‍💋‍👩🏿': 14, + '👩🏽‍🌾': 7, + '👩🏽‍🍳': 7, + '👩🏽‍🍼': 7, + '👩🏽‍🎓': 7, + '👩🏽‍🎤': 7, + '👩🏽‍🎨': 7, + '👩🏽‍🏫': 7, + '👩🏽‍🏭': 7, + '👩🏽‍🐰‍👩🏻': 12, + '👩🏽‍🐰‍👩🏾': 12, + '👩🏽‍🐰‍👩🏿': 12, + '👩🏽‍💻': 7, + '👩🏽‍💼': 7, + '👩🏽‍🔧': 7, + '👩🏽‍🔬': 7, + '👩🏽‍🚀': 7, + '👩🏽‍🚒': 7, + '👩🏽‍🤝‍👨🏻': 12, + '👩🏽‍🤝‍👨🏿': 12, + '👩🏽‍🤝‍👩🏻': 12, + '👩🏽‍🤝‍👩🏼': 12, + '👩🏽‍🤝‍👩🏾': 12, + '👩🏽‍🤝‍👩🏿': 12, + '👩🏽‍🦯': 7, + '👩🏽‍🦯‍➡️': 9, + '👩🏽‍🦰': 7, + '👩🏽‍🦱': 7, + '👩🏽‍🦲': 7, + '👩🏽‍🦳': 7, + '👩🏽‍🦼': 7, + '👩🏽‍🦼‍➡️': 9, + '👩🏽‍🦽': 7, + '👩🏽‍🦽‍➡️': 9, + '👩🏽‍🫯‍👩🏻': 11, + '👩🏽‍🫯‍👩🏼': 11, + '👩🏽‍🫯‍👩🏾': 11, + '👩🏽‍🫯‍👩🏿': 11, + '👩🏾‍⚕️': 6, + '👩🏾‍⚖️': 6, + '👩🏾‍✈️': 6, + '👩🏾‍❤️‍👨🏾': 11, + '👩🏾‍❤️‍👩🏾': 11, + '👩🏾‍❤️‍💋‍👨🏾': 14, + '👩🏾‍❤️‍💋‍👩🏾': 14, + '👩🏾‍🌾': 7, + '👩🏾‍🍳': 7, + '👩🏾‍🍼': 7, + '👩🏾‍🎓': 7, + '👩🏾‍🎤': 7, + '👩🏾‍🎨': 7, + '👩🏾‍🏫': 7, + '👩🏾‍🏭': 7, + '👩🏾‍🐰‍👩🏻': 12, + '👩🏾‍🐰‍👩🏽': 12, + '👩🏾‍🐰‍👩🏿': 12, + '👩🏾‍💻': 7, + '👩🏾‍💼': 7, + '👩🏾‍🔧': 7, + '👩🏾‍🔬': 7, + '👩🏾‍🚀': 7, + '👩🏾‍🚒': 7, + '👩🏾‍🤝‍👩🏻': 12, + '👩🏾‍🤝‍👩🏽': 12, + '👩🏾‍🤝‍👩🏿': 12, + '👩🏾‍🦯': 7, + '👩🏾‍🦯‍➡️': 9, + '👩🏾‍🦰': 7, + '👩🏾‍🦱': 7, + '👩🏾‍🦲': 7, + '👩🏾‍🦳': 7, + '👩🏾‍🦼': 7, + '👩🏾‍🦽': 7, + '👩🏾‍🦽‍➡️': 9, + '👩🏾‍🫯‍👩🏻': 11, + '👩🏾‍🫯‍👩🏼': 11, + '👩🏾‍🫯‍👩🏽': 11, + '👩🏾‍🫯‍👩🏿': 11, + '👩🏿‍⚕️': 6, + '👩🏿‍⚖️': 6, + '👩🏿‍✈️': 6, + '👩🏿‍❤️‍👨🏻': 11, + '👩🏿‍❤️‍👨🏿': 11, + '👩🏿‍❤️‍👩🏿': 11, + '👩🏿‍❤️‍💋‍👨🏻': 14, + '👩🏿‍❤️‍💋‍👨🏽': 14, + '👩🏿‍❤️‍💋‍👨🏿': 14, + '👩🏿‍❤️‍💋‍👩🏻': 14, + '👩🏿‍❤️‍💋‍👩🏽': 14, + '👩🏿‍❤️‍💋‍👩🏿': 14, + '👩🏿‍🌾': 7, + '👩🏿‍🍳': 7, + '👩🏿‍🍼': 7, + '👩🏿‍🎓': 7, + '👩🏿‍🎤': 7, + '👩🏿‍🎨': 7, + '👩🏿‍🏫': 7, + '👩🏿‍🏭': 7, + '👩🏿‍🐰‍👩🏻': 12, + '👩🏿‍🐰‍👩🏼': 12, + '👩🏿‍🐰‍👩🏽': 12, + '👩🏿‍🐰‍👩🏾': 12, + '👩🏿‍💻': 7, + '👩🏿‍💼': 7, + '👩🏿‍🔧': 7, + '👩🏿‍🔬': 7, + '👩🏿‍🚀': 7, + '👩🏿‍🚒': 7, + '👩🏿‍🤝‍👨🏻': 12, + '👩🏿‍🤝‍👨🏽': 12, + '👩🏿‍🤝‍👩🏻': 12, + '👩🏿‍🤝‍👩🏼': 12, + '👩🏿‍🤝‍👩🏽': 12, + '👩🏿‍🤝‍👩🏾': 12, + '👩🏿‍🦯': 7, + '👩🏿‍🦯‍➡️': 9, + '👩🏿‍🦰': 7, + '👩🏿‍🦱': 7, + '👩🏿‍🦲': 7, + '👩🏿‍🦳': 7, + '👩🏿‍🦼': 7, + '👩🏿‍🦼‍➡️': 9, + '👩🏿‍🦽': 7, + '👩🏿‍🦽‍➡️': 9, + '👩🏿‍🫯‍👩🏻': 11, + '👩🏿‍🫯‍👩🏼': 11, + '👩🏿‍🫯‍👩🏽': 11, + '👩🏿‍🫯‍👩🏾': 11, + '👮‍♀️': 4, + '👮‍♂️': 4, + '👮🏻‍♀️': 6, + '👮🏻‍♂️': 6, + '👮🏼‍♀️': 6, + '👮🏼‍♂️': 6, + '👮🏽‍♀️': 6, + '👮🏽‍♂️': 6, + '👮🏾‍♀️': 6, + '👮🏾‍♂️': 6, + '👮🏿‍♀️': 6, + '👮🏿‍♂️': 6, + '👯‍♀️': 4, + '👯‍♂️': 4, + '👯🏻‍♀️': 6, + '👯🏻‍♂️': 6, + '👯🏼‍♀️': 6, + '👯🏼‍♂️': 6, + '👯🏽‍♀️': 6, + '👯🏽‍♂️': 6, + '👯🏾‍♀️': 6, + '👯🏾‍♂️': 6, + '👯🏿‍♀️': 6, + '👯🏿‍♂️': 6, + '👰‍♀️': 4, + '👰‍♂️': 4, + '👰🏻‍♀️': 6, + '👰🏻‍♂️': 6, + '👰🏼‍♀️': 6, + '👰🏼‍♂️': 6, + '👰🏽‍♀️': 6, + '👰🏽‍♂️': 6, + '👰🏾‍♀️': 6, + '👰🏾‍♂️': 6, + '👰🏿‍♀️': 6, + '👰🏿‍♂️': 6, + '👱‍♀️': 4, + '👱‍♂️': 4, + '👱🏻‍♀️': 6, + '👱🏻‍♂️': 6, + '👱🏼‍♀️': 6, + '👱🏼‍♂️': 6, + '👱🏽‍♀️': 6, + '👱🏽‍♂️': 6, + '👱🏾‍♀️': 6, + '👱🏾‍♂️': 6, + '👱🏿‍♀️': 6, + '👱🏿‍♂️': 6, + '👳‍♀️': 4, + '👳‍♂️': 4, + '👳🏻‍♀️': 6, + '👳🏻‍♂️': 6, + '👳🏼‍♀️': 6, + '👳🏼‍♂️': 6, + '👳🏽‍♀️': 6, + '👳🏽‍♂️': 6, + '👳🏾‍♀️': 6, + '👳🏾‍♂️': 6, + '👳🏿‍♀️': 6, + '👳🏿‍♂️': 6, + '👷‍♀️': 4, + '👷‍♂️': 4, + '👷🏻‍♀️': 6, + '👷🏻‍♂️': 6, + '👷🏼‍♀️': 6, + '👷🏼‍♂️': 6, + '👷🏽‍♀️': 6, + '👷🏽‍♂️': 6, + '👷🏾‍♀️': 6, + '👷🏾‍♂️': 6, + '👷🏿‍♀️': 6, + '👷🏿‍♂️': 6, + '💁‍♀️': 4, + '💁‍♂️': 4, + '💁🏻‍♀️': 6, + '💁🏻‍♂️': 6, + '💁🏼‍♀️': 6, + '💁🏼‍♂️': 6, + '💁🏽‍♀️': 6, + '💁🏽‍♂️': 6, + '💁🏾‍♀️': 6, + '💁🏾‍♂️': 6, + '💁🏿‍♀️': 6, + '💁🏿‍♂️': 6, + '💂‍♀️': 4, + '💂‍♂️': 4, + '💂🏻‍♀️': 6, + '💂🏻‍♂️': 6, + '💂🏼‍♀️': 6, + '💂🏼‍♂️': 6, + '💂🏽‍♀️': 6, + '💂🏽‍♂️': 6, + '💂🏾‍♀️': 6, + '💂🏾‍♂️': 6, + '💂🏿‍♀️': 6, + '💂🏿‍♂️': 6, + '💆‍♀️': 4, + '💆‍♂️': 4, + '💆🏻‍♀️': 6, + '💆🏻‍♂️': 6, + '💆🏼‍♀️': 6, + '💆🏼‍♂️': 6, + '💆🏽‍♀️': 6, + '💆🏽‍♂️': 6, + '💆🏾‍♀️': 6, + '💆🏾‍♂️': 6, + '💆🏿‍♀️': 6, + '💆🏿‍♂️': 6, + '💇‍♀️': 4, + '💇‍♂️': 4, + '💇🏻‍♀️': 6, + '💇🏻‍♂️': 6, + '💇🏼‍♀️': 6, + '💇🏼‍♂️': 6, + '💇🏽‍♀️': 6, + '💇🏽‍♂️': 6, + '💇🏾‍♀️': 6, + '💇🏾‍♂️': 6, + '💇🏿‍♀️': 6, + '💇🏿‍♂️': 6, + '🕵️‍♀️': 3, + '🕵️‍♂️': 3, + '🕵🏻‍♀️': 5, + '🕵🏻‍♂️': 5, + '🕵🏼‍♀️': 5, + '🕵🏼‍♂️': 5, + '🕵🏽‍♀️': 5, + '🕵🏽‍♂️': 5, + '🕵🏾‍♀️': 5, + '🕵🏾‍♂️': 5, + '🕵🏿‍♀️': 5, + '🕵🏿‍♂️': 5, + '😮‍💨': 5, + '😵‍💫': 5, + '😶‍🌫️': 4, + '🙂‍↔️': 4, + '🙂‍↕️': 4, + '🙅‍♀️': 4, + '🙅‍♂️': 4, + '🙅🏻‍♀️': 6, + '🙅🏻‍♂️': 6, + '🙅🏼‍♀️': 6, + '🙅🏼‍♂️': 6, + '🙅🏽‍♀️': 6, + '🙅🏽‍♂️': 6, + '🙅🏾‍♀️': 6, + '🙅🏾‍♂️': 6, + '🙅🏿‍♀️': 6, + '🙅🏿‍♂️': 6, + '🙆‍♀️': 4, + '🙆‍♂️': 4, + '🙆🏻‍♀️': 6, + '🙆🏻‍♂️': 6, + '🙆🏼‍♀️': 6, + '🙆🏼‍♂️': 6, + '🙆🏽‍♀️': 6, + '🙆🏽‍♂️': 6, + '🙆🏾‍♀️': 6, + '🙆🏾‍♂️': 6, + '🙆🏿‍♀️': 6, + '🙆🏿‍♂️': 6, + '🙇‍♀️': 4, + '🙇‍♂️': 4, + '🙇🏻‍♀️': 6, + '🙇🏻‍♂️': 6, + '🙇🏼‍♀️': 6, + '🙇🏼‍♂️': 6, + '🙇🏽‍♀️': 6, + '🙇🏽‍♂️': 6, + '🙇🏾‍♀️': 6, + '🙇🏾‍♂️': 6, + '🙇🏿‍♀️': 6, + '🙇🏿‍♂️': 6, + '🙋‍♀️': 4, + '🙋‍♂️': 4, + '🙋🏻‍♀️': 6, + '🙋🏻‍♂️': 6, + '🙋🏼‍♀️': 6, + '🙋🏼‍♂️': 6, + '🙋🏽‍♀️': 6, + '🙋🏽‍♂️': 6, + '🙋🏾‍♀️': 6, + '🙋🏾‍♂️': 6, + '🙋🏿‍♀️': 6, + '🙋🏿‍♂️': 6, + '🙍‍♀️': 4, + '🙍‍♂️': 4, + '🙍🏻‍♀️': 6, + '🙍🏻‍♂️': 6, + '🙍🏼‍♀️': 6, + '🙍🏼‍♂️': 6, + '🙍🏽‍♀️': 6, + '🙍🏽‍♂️': 6, + '🙍🏾‍♀️': 6, + '🙍🏾‍♂️': 6, + '🙍🏿‍♀️': 6, + '🙍🏿‍♂️': 6, + '🙎‍♀️': 4, + '🙎‍♂️': 4, + '🙎🏻‍♀️': 6, + '🙎🏻‍♂️': 6, + '🙎🏼‍♀️': 6, + '🙎🏼‍♂️': 6, + '🙎🏽‍♀️': 6, + '🙎🏽‍♂️': 6, + '🙎🏾‍♀️': 6, + '🙎🏾‍♂️': 6, + '🙎🏿‍♀️': 6, + '🙎🏿‍♂️': 6, + '🚣‍♀️': 4, + '🚣‍♂️': 4, + '🚣🏻‍♀️': 6, + '🚣🏻‍♂️': 6, + '🚣🏼‍♀️': 6, + '🚣🏼‍♂️': 6, + '🚣🏽‍♀️': 6, + '🚣🏽‍♂️': 6, + '🚣🏾‍♀️': 6, + '🚣🏾‍♂️': 6, + '🚣🏿‍♀️': 6, + '🚣🏿‍♂️': 6, + '🚴‍♀️': 4, + '🚴‍♂️': 4, + '🚴🏻‍♀️': 6, + '🚴🏻‍♂️': 6, + '🚴🏼‍♀️': 6, + '🚴🏼‍♂️': 6, + '🚴🏽‍♀️': 6, + '🚴🏽‍♂️': 6, + '🚴🏾‍♀️': 6, + '🚴🏾‍♂️': 6, + '🚴🏿‍♀️': 6, + '🚴🏿‍♂️': 6, + '🚵‍♀️': 4, + '🚵‍♂️': 4, + '🚵🏻‍♀️': 6, + '🚵🏻‍♂️': 6, + '🚵🏼‍♀️': 6, + '🚵🏼‍♂️': 6, + '🚵🏽‍♀️': 6, + '🚵🏽‍♂️': 6, + '🚵🏾‍♀️': 6, + '🚵🏾‍♂️': 6, + '🚵🏿‍♀️': 6, + '🚵🏿‍♂️': 6, + '🚶‍♀️': 4, + '🚶‍♀️‍➡️': 6, + '🚶‍♂️': 4, + '🚶‍♂️‍➡️': 6, + '🚶‍➡️': 4, + '🚶🏻‍♀️': 6, + '🚶🏻‍♀️‍➡️': 8, + '🚶🏻‍♂️': 6, + '🚶🏻‍♂️‍➡️': 8, + '🚶🏻‍➡️': 6, + '🚶🏼‍♀️': 6, + '🚶🏼‍♀️‍➡️': 8, + '🚶🏼‍♂️': 6, + '🚶🏼‍♂️‍➡️': 8, + '🚶🏼‍➡️': 6, + '🚶🏽‍♀️': 6, + '🚶🏽‍♀️‍➡️': 8, + '🚶🏽‍♂️': 6, + '🚶🏽‍♂️‍➡️': 8, + '🚶🏽‍➡️': 6, + '🚶🏾‍♀️': 6, + '🚶🏾‍♀️‍➡️': 8, + '🚶🏾‍♂️': 6, + '🚶🏾‍♂️‍➡️': 8, + '🚶🏾‍➡️': 6, + '🚶🏿‍♀️': 6, + '🚶🏿‍♀️‍➡️': 8, + '🚶🏿‍♂️': 6, + '🚶🏿‍♂️‍➡️': 8, + '🚶🏿‍➡️': 6, + '🤦‍♀️': 4, + '🤦‍♂️': 4, + '🤦🏻‍♀️': 6, + '🤦🏻‍♂️': 6, + '🤦🏼‍♀️': 6, + '🤦🏼‍♂️': 6, + '🤦🏽‍♀️': 6, + '🤦🏽‍♂️': 6, + '🤦🏾‍♀️': 6, + '🤦🏾‍♂️': 6, + '🤦🏿‍♀️': 6, + '🤦🏿‍♂️': 6, + '🤵‍♀️': 4, + '🤵‍♂️': 4, + '🤵🏻‍♀️': 6, + '🤵🏻‍♂️': 6, + '🤵🏼‍♀️': 6, + '🤵🏼‍♂️': 6, + '🤵🏽‍♀️': 6, + '🤵🏽‍♂️': 6, + '🤵🏾‍♀️': 6, + '🤵🏾‍♂️': 6, + '🤵🏿‍♀️': 6, + '🤵🏿‍♂️': 6, + '🤷‍♀️': 4, + '🤷‍♂️': 4, + '🤷🏻‍♀️': 6, + '🤷🏻‍♂️': 6, + '🤷🏼‍♀️': 6, + '🤷🏼‍♂️': 6, + '🤷🏽‍♀️': 6, + '🤷🏽‍♂️': 6, + '🤷🏾‍♀️': 6, + '🤷🏾‍♂️': 6, + '🤷🏿‍♀️': 6, + '🤷🏿‍♂️': 6, + '🤸‍♀️': 4, + '🤸‍♂️': 4, + '🤸🏻‍♀️': 6, + '🤸🏻‍♂️': 6, + '🤸🏼‍♀️': 6, + '🤸🏼‍♂️': 6, + '🤸🏽‍♀️': 6, + '🤸🏽‍♂️': 6, + '🤸🏾‍♀️': 6, + '🤸🏾‍♂️': 6, + '🤸🏿‍♀️': 6, + '🤸🏿‍♂️': 6, + '🤹‍♀️': 4, + '🤹‍♂️': 4, + '🤹🏻‍♀️': 6, + '🤹🏻‍♂️': 6, + '🤹🏼‍♀️': 6, + '🤹🏼‍♂️': 6, + '🤹🏽‍♀️': 6, + '🤹🏽‍♂️': 6, + '🤹🏾‍♀️': 6, + '🤹🏾‍♂️': 6, + '🤹🏿‍♀️': 6, + '🤹🏿‍♂️': 6, + '🤼‍♀️': 4, + '🤼‍♂️': 4, + '🤼🏻‍♀️': 6, + '🤼🏻‍♂️': 6, + '🤼🏼‍♀️': 6, + '🤼🏼‍♂️': 6, + '🤼🏽‍♀️': 6, + '🤼🏽‍♂️': 6, + '🤼🏾‍♀️': 6, + '🤼🏾‍♂️': 6, + '🤼🏿‍♀️': 6, + '🤼🏿‍♂️': 6, + '🤽‍♀️': 4, + '🤽‍♂️': 4, + '🤽🏻‍♀️': 6, + '🤽🏻‍♂️': 6, + '🤽🏼‍♀️': 6, + '🤽🏼‍♂️': 6, + '🤽🏽‍♀️': 6, + '🤽🏽‍♂️': 6, + '🤽🏾‍♀️': 6, + '🤽🏾‍♂️': 6, + '🤽🏿‍♀️': 6, + '🤽🏿‍♂️': 6, + '🤾‍♀️': 4, + '🤾‍♂️': 4, + '🤾🏻‍♀️': 6, + '🤾🏻‍♂️': 6, + '🤾🏼‍♀️': 6, + '🤾🏼‍♂️': 6, + '🤾🏽‍♀️': 6, + '🤾🏽‍♂️': 6, + '🤾🏾‍♀️': 6, + '🤾🏾‍♂️': 6, + '🤾🏿‍♀️': 6, + '🤾🏿‍♂️': 6, + '🦸‍♀️': 4, + '🦸‍♂️': 4, + '🦸🏻‍♀️': 6, + '🦸🏻‍♂️': 6, + '🦸🏼‍♀️': 6, + '🦸🏼‍♂️': 6, + '🦸🏽‍♀️': 6, + '🦸🏽‍♂️': 6, + '🦸🏾‍♀️': 6, + '🦸🏾‍♂️': 6, + '🦸🏿‍♀️': 6, + '🦸🏿‍♂️': 6, + '🦹‍♀️': 4, + '🦹‍♂️': 4, + '🦹🏻‍♀️': 6, + '🦹🏻‍♂️': 6, + '🦹🏼‍♀️': 6, + '🦹🏼‍♂️': 6, + '🦹🏽‍♀️': 6, + '🦹🏽‍♂️': 6, + '🦹🏾‍♀️': 6, + '🦹🏾‍♂️': 6, + '🦹🏿‍♀️': 6, + '🦹🏿‍♂️': 6, + '🧍‍♀️': 4, + '🧍‍♂️': 4, + '🧍🏻‍♀️': 6, + '🧍🏻‍♂️': 6, + '🧍🏼‍♀️': 6, + '🧍🏼‍♂️': 6, + '🧍🏽‍♀️': 6, + '🧍🏽‍♂️': 6, + '🧍🏾‍♀️': 6, + '🧍🏾‍♂️': 6, + '🧍🏿‍♀️': 6, + '🧍🏿‍♂️': 6, + '🧎‍♀️': 4, + '🧎‍♀️‍➡️': 6, + '🧎‍♂️': 4, + '🧎‍♂️‍➡️': 6, + '🧎‍➡️': 4, + '🧎🏻‍♀️': 6, + '🧎🏻‍♀️‍➡️': 8, + '🧎🏻‍♂️': 6, + '🧎🏻‍♂️‍➡️': 8, + '🧎🏻‍➡️': 6, + '🧎🏼‍♀️': 6, + '🧎🏼‍♀️‍➡️': 8, + '🧎🏼‍♂️': 6, + '🧎🏼‍♂️‍➡️': 8, + '🧎🏼‍➡️': 6, + '🧎🏽‍♀️': 6, + '🧎🏽‍♀️‍➡️': 8, + '🧎🏽‍♂️': 6, + '🧎🏽‍♂️‍➡️': 8, + '🧎🏽‍➡️': 6, + '🧎🏾‍♀️': 6, + '🧎🏾‍♀️‍➡️': 8, + '🧎🏾‍♂️': 6, + '🧎🏾‍♂️‍➡️': 8, + '🧎🏾‍➡️': 6, + '🧎🏿‍♀️': 6, + '🧎🏿‍♀️‍➡️': 8, + '🧎🏿‍♂️': 6, + '🧎🏿‍♂️‍➡️': 8, + '🧎🏿‍➡️': 6, + '🧏‍♀️': 4, + '🧏‍♂️': 4, + '🧏🏻‍♀️': 6, + '🧏🏻‍♂️': 6, + '🧏🏼‍♀️': 6, + '🧏🏼‍♂️': 6, + '🧏🏽‍♀️': 6, + '🧏🏽‍♂️': 6, + '🧏🏾‍♀️': 6, + '🧏🏾‍♂️': 6, + '🧏🏿‍♀️': 6, + '🧏🏿‍♂️': 6, + '🧑‍⚕️': 4, + '🧑‍⚖️': 4, + '🧑‍✈️': 4, + '🧑‍🌾': 5, + '🧑‍🍳': 5, + '🧑‍🍼': 5, + '🧑‍🎄': 5, + '🧑‍🎓': 5, + '🧑‍🎤': 5, + '🧑‍🎨': 5, + '🧑‍🏫': 5, + '🧑‍🏭': 5, + '🧑‍💻': 5, + '🧑‍💼': 5, + '🧑‍🔧': 5, + '🧑‍🔬': 5, + '🧑‍🚀': 5, + '🧑‍🚒': 5, + '🧑‍🤝‍🧑': 8, + '🧑‍🦯': 5, + '🧑‍🦯‍➡️': 7, + '🧑‍🦰': 5, + '🧑‍🦱': 5, + '🧑‍🦲': 5, + '🧑‍🦳': 5, + '🧑‍🦼': 5, + '🧑‍🦼‍➡️': 7, + '🧑‍🦽': 5, + '🧑‍🦽‍➡️': 7, + '🧑‍🧑‍🧒': 8, + '🧑‍🧑‍🧒‍🧒': 11, + '🧑‍🧒': 5, + '🧑‍🧒‍🧒': 8, + '🧑‍🩰': 5, + '🧑🏻‍⚕️': 6, + '🧑🏻‍⚖️': 6, + '🧑🏻‍✈️': 6, + '🧑🏻‍❤️‍💋‍🧑🏿': 14, + '🧑🏻‍🌾': 7, + '🧑🏻‍🍳': 7, + '🧑🏻‍🍼': 7, + '🧑🏻‍🎄': 7, + '🧑🏻‍🎓': 7, + '🧑🏻‍🎤': 7, + '🧑🏻‍🎨': 7, + '🧑🏻‍🏫': 7, + '🧑🏻‍🏭': 7, + '🧑🏻‍🐰‍🧑🏽': 12, + '🧑🏻‍🐰‍🧑🏾': 12, + '🧑🏻‍🐰‍🧑🏿': 12, + '🧑🏻‍💻': 7, + '🧑🏻‍💼': 7, + '🧑🏻‍🔧': 7, + '🧑🏻‍🔬': 7, + '🧑🏻‍🚀': 7, + '🧑🏻‍🚒': 7, + '🧑🏻‍🤝‍🧑🏻': 12, + '🧑🏻‍🤝‍🧑🏼': 12, + '🧑🏻‍🤝‍🧑🏽': 12, + '🧑🏻‍🤝‍🧑🏾': 12, + '🧑🏻‍🤝‍🧑🏿': 12, + '🧑🏻‍🦯': 7, + '🧑🏻‍🦯‍➡️': 9, + '🧑🏻‍🦰': 7, + '🧑🏻‍🦱': 7, + '🧑🏻‍🦲': 7, + '🧑🏻‍🦳': 7, + '🧑🏻‍🦼': 7, + '🧑🏻‍🦼‍➡️': 9, + '🧑🏻‍🦽': 7, + '🧑🏻‍🦽‍➡️': 9, + '🧑🏻‍🩰': 7, + '🧑🏻‍🫯‍🧑🏼': 11, + '🧑🏻‍🫯‍🧑🏽': 11, + '🧑🏻‍🫯‍🧑🏾': 11, + '🧑🏻‍🫯‍🧑🏿': 11, + '🧑🏼‍⚕️': 6, + '🧑🏼‍⚖️': 6, + '🧑🏼‍✈️': 6, + '🧑🏼‍🌾': 7, + '🧑🏼‍🍳': 7, + '🧑🏼‍🍼': 7, + '🧑🏼‍🎄': 7, + '🧑🏼‍🎓': 7, + '🧑🏼‍🎤': 7, + '🧑🏼‍🎨': 7, + '🧑🏼‍🏫': 7, + '🧑🏼‍🏭': 7, + '🧑🏼‍🐰‍🧑🏿': 12, + '🧑🏼‍💻': 7, + '🧑🏼‍💼': 7, + '🧑🏼‍🔧': 7, + '🧑🏼‍🔬': 7, + '🧑🏼‍🚀': 7, + '🧑🏼‍🚒': 7, + '🧑🏼‍🤝‍🧑🏻': 12, + '🧑🏼‍🤝‍🧑🏼': 12, + '🧑🏼‍🤝‍🧑🏽': 12, + '🧑🏼‍🤝‍🧑🏿': 12, + '🧑🏼‍🦯': 7, + '🧑🏼‍🦯‍➡️': 9, + '🧑🏼‍🦰': 7, + '🧑🏼‍🦱': 7, + '🧑🏼‍🦲': 7, + '🧑🏼‍🦳': 7, + '🧑🏼‍🦼': 7, + '🧑🏼‍🦽': 7, + '🧑🏼‍🩰': 7, + '🧑🏼‍🫯‍🧑🏻': 11, + '🧑🏼‍🫯‍🧑🏽': 11, + '🧑🏼‍🫯‍🧑🏿': 11, + '🧑🏽‍⚕️': 6, + '🧑🏽‍⚖️': 6, + '🧑🏽‍✈️': 6, + '🧑🏽‍❤️‍💋‍🧑🏿': 14, + '🧑🏽‍🌾': 7, + '🧑🏽‍🍳': 7, + '🧑🏽‍🍼': 7, + '🧑🏽‍🎄': 7, + '🧑🏽‍🎓': 7, + '🧑🏽‍🎤': 7, + '🧑🏽‍🎨': 7, + '🧑🏽‍🏫': 7, + '🧑🏽‍🏭': 7, + '🧑🏽‍🐰‍🧑🏻': 12, + '🧑🏽‍🐰‍🧑🏿': 12, + '🧑🏽‍💻': 7, + '🧑🏽‍💼': 7, + '🧑🏽‍🔧': 7, + '🧑🏽‍🔬': 7, + '🧑🏽‍🚀': 7, + '🧑🏽‍🚒': 7, + '🧑🏽‍🤝‍🧑🏻': 12, + '🧑🏽‍🤝‍🧑🏼': 12, + '🧑🏽‍🤝‍🧑🏽': 12, + '🧑🏽‍🤝‍🧑🏾': 12, + '🧑🏽‍🤝‍🧑🏿': 12, + '🧑🏽‍🦯': 7, + '🧑🏽‍🦯‍➡️': 9, + '🧑🏽‍🦰': 7, + '🧑🏽‍🦱': 7, + '🧑🏽‍🦲': 7, + '🧑🏽‍🦳': 7, + '🧑🏽‍🦼': 7, + '🧑🏽‍🦼‍➡️': 9, + '🧑🏽‍🦽': 7, + '🧑🏽‍🦽‍➡️': 9, + '🧑🏽‍🩰': 7, + '🧑🏽‍🫯‍🧑🏻': 11, + '🧑🏽‍🫯‍🧑🏼': 11, + '🧑🏽‍🫯‍🧑🏾': 11, + '🧑🏽‍🫯‍🧑🏿': 11, + '🧑🏾‍⚕️': 6, + '🧑🏾‍⚖️': 6, + '🧑🏾‍✈️': 6, + '🧑🏾‍🌾': 7, + '🧑🏾‍🍳': 7, + '🧑🏾‍🍼': 7, + '🧑🏾‍🎄': 7, + '🧑🏾‍🎓': 7, + '🧑🏾‍🎤': 7, + '🧑🏾‍🎨': 7, + '🧑🏾‍🏫': 7, + '🧑🏾‍🏭': 7, + '🧑🏾‍🐰‍🧑🏻': 12, + '🧑🏾‍🐰‍🧑🏿': 12, + '🧑🏾‍💻': 7, + '🧑🏾‍💼': 7, + '🧑🏾‍🔧': 7, + '🧑🏾‍🔬': 7, + '🧑🏾‍🚀': 7, + '🧑🏾‍🚒': 7, + '🧑🏾‍🤝‍🧑🏻': 12, + '🧑🏾‍🤝‍🧑🏽': 12, + '🧑🏾‍🤝‍🧑🏾': 12, + '🧑🏾‍🤝‍🧑🏿': 12, + '🧑🏾‍🦯': 7, + '🧑🏾‍🦯‍➡️': 9, + '🧑🏾‍🦰': 7, + '🧑🏾‍🦱': 7, + '🧑🏾‍🦲': 7, + '🧑🏾‍🦳': 7, + '🧑🏾‍🦼': 7, + '🧑🏾‍🦽': 7, + '🧑🏾‍🩰': 7, + '🧑🏾‍🫯‍🧑🏻': 11, + '🧑🏾‍🫯‍🧑🏽': 11, + '🧑🏾‍🫯‍🧑🏿': 11, + '🧑🏿‍⚕️': 6, + '🧑🏿‍⚖️': 6, + '🧑🏿‍✈️': 6, + '🧑🏿‍❤️‍💋‍🧑🏻': 14, + '🧑🏿‍❤️‍💋‍🧑🏽': 14, + '🧑🏿‍🌾': 7, + '🧑🏿‍🍳': 7, + '🧑🏿‍🍼': 7, + '🧑🏿‍🎄': 7, + '🧑🏿‍🎓': 7, + '🧑🏿‍🎤': 7, + '🧑🏿‍🎨': 7, + '🧑🏿‍🏫': 7, + '🧑🏿‍🏭': 7, + '🧑🏿‍🐰‍🧑🏻': 12, + '🧑🏿‍🐰‍🧑🏼': 12, + '🧑🏿‍🐰‍🧑🏽': 12, + '🧑🏿‍🐰‍🧑🏾': 12, + '🧑🏿‍💻': 7, + '🧑🏿‍💼': 7, + '🧑🏿‍🔧': 7, + '🧑🏿‍🔬': 7, + '🧑🏿‍🚀': 7, + '🧑🏿‍🚒': 7, + '🧑🏿‍🤝‍🧑🏻': 12, + '🧑🏿‍🤝‍🧑🏼': 12, + '🧑🏿‍🤝‍🧑🏽': 12, + '🧑🏿‍🤝‍🧑🏾': 12, + '🧑🏿‍🤝‍🧑🏿': 12, + '🧑🏿‍🦯': 7, + '🧑🏿‍🦯‍➡️': 9, + '🧑🏿‍🦰': 7, + '🧑🏿‍🦱': 7, + '🧑🏿‍🦲': 7, + '🧑🏿‍🦳': 7, + '🧑🏿‍🦼': 7, + '🧑🏿‍🦼‍➡️': 9, + '🧑🏿‍🦽': 7, + '🧑🏿‍🦽‍➡️': 9, + '🧑🏿‍🩰': 7, + '🧑🏿‍🫯‍🧑🏻': 11, + '🧑🏿‍🫯‍🧑🏼': 11, + '🧑🏿‍🫯‍🧑🏽': 11, + '🧑🏿‍🫯‍🧑🏾': 11, + '🧔‍♀️': 4, + '🧔‍♂️': 4, + '🧔🏻‍♀️': 6, + '🧔🏻‍♂️': 6, + '🧔🏼‍♀️': 6, + '🧔🏼‍♂️': 6, + '🧔🏽‍♀️': 6, + '🧔🏽‍♂️': 6, + '🧔🏾‍♀️': 6, + '🧔🏾‍♂️': 6, + '🧔🏿‍♀️': 6, + '🧔🏿‍♂️': 6, + '🧖‍♀️': 4, + '🧖‍♂️': 4, + '🧖🏻‍♀️': 6, + '🧖🏻‍♂️': 6, + '🧖🏼‍♀️': 6, + '🧖🏼‍♂️': 6, + '🧖🏽‍♀️': 6, + '🧖🏽‍♂️': 6, + '🧖🏾‍♀️': 6, + '🧖🏾‍♂️': 6, + '🧖🏿‍♀️': 6, + '🧖🏿‍♂️': 6, + '🧗‍♀️': 4, + '🧗‍♂️': 4, + '🧗🏻‍♀️': 6, + '🧗🏻‍♂️': 6, + '🧗🏼‍♀️': 6, + '🧗🏼‍♂️': 6, + '🧗🏽‍♀️': 6, + '🧗🏽‍♂️': 6, + '🧗🏾‍♀️': 6, + '🧗🏾‍♂️': 6, + '🧗🏿‍♀️': 6, + '🧗🏿‍♂️': 6, + '🧘‍♀️': 4, + '🧘‍♂️': 4, + '🧘🏻‍♀️': 6, + '🧘🏻‍♂️': 6, + '🧘🏼‍♀️': 6, + '🧘🏼‍♂️': 6, + '🧘🏽‍♀️': 6, + '🧘🏽‍♂️': 6, + '🧘🏾‍♀️': 6, + '🧘🏾‍♂️': 6, + '🧘🏿‍♀️': 6, + '🧘🏿‍♂️': 6, + '🧙‍♀️': 4, + '🧙‍♂️': 4, + '🧙🏻‍♀️': 6, + '🧙🏻‍♂️': 6, + '🧙🏼‍♀️': 6, + '🧙🏼‍♂️': 6, + '🧙🏽‍♀️': 6, + '🧙🏽‍♂️': 6, + '🧙🏾‍♀️': 6, + '🧙🏾‍♂️': 6, + '🧙🏿‍♀️': 6, + '🧙🏿‍♂️': 6, + '🧚‍♀️': 4, + '🧚‍♂️': 4, + '🧚🏻‍♀️': 6, + '🧚🏻‍♂️': 6, + '🧚🏼‍♀️': 6, + '🧚🏼‍♂️': 6, + '🧚🏽‍♀️': 6, + '🧚🏽‍♂️': 6, + '🧚🏾‍♀️': 6, + '🧚🏾‍♂️': 6, + '🧚🏿‍♀️': 6, + '🧚🏿‍♂️': 6, + '🧛‍♀️': 4, + '🧛‍♂️': 4, + '🧛🏻‍♀️': 6, + '🧛🏻‍♂️': 6, + '🧛🏼‍♀️': 6, + '🧛🏼‍♂️': 6, + '🧛🏽‍♀️': 6, + '🧛🏽‍♂️': 6, + '🧛🏾‍♀️': 6, + '🧛🏾‍♂️': 6, + '🧛🏿‍♀️': 6, + '🧛🏿‍♂️': 6, + '🧜‍♀️': 4, + '🧜‍♂️': 4, + '🧜🏻‍♀️': 6, + '🧜🏻‍♂️': 6, + '🧜🏼‍♀️': 6, + '🧜🏼‍♂️': 6, + '🧜🏽‍♀️': 6, + '🧜🏽‍♂️': 6, + '🧜🏾‍♀️': 6, + '🧜🏾‍♂️': 6, + '🧜🏿‍♀️': 6, + '🧜🏿‍♂️': 6, + '🧝‍♀️': 4, + '🧝‍♂️': 4, + '🧝🏻‍♀️': 6, + '🧝🏻‍♂️': 6, + '🧝🏼‍♀️': 6, + '🧝🏼‍♂️': 6, + '🧝🏽‍♀️': 6, + '🧝🏽‍♂️': 6, + '🧝🏾‍♀️': 6, + '🧝🏾‍♂️': 6, + '🧝🏿‍♀️': 6, + '🧝🏿‍♂️': 6, + '🧞‍♀️': 4, + '🧞‍♂️': 4, + '🧟‍♀️': 4, + '🧟‍♂️': 4, + '🫱🏻‍🫲🏼': 9, + '🫱🏻‍🫲🏽': 9, + '🫱🏻‍🫲🏾': 9, + '🫱🏻‍🫲🏿': 9, + '🫱🏼‍🫲🏻': 9, + '🫱🏼‍🫲🏽': 9, + '🫱🏼‍🫲🏾': 9, + '🫱🏼‍🫲🏿': 9, + '🫱🏽‍🫲🏻': 9, + '🫱🏽‍🫲🏼': 9, + '🫱🏽‍🫲🏾': 9, + '🫱🏽‍🫲🏿': 9, + '🫱🏾‍🫲🏻': 9, + '🫱🏾‍🫲🏼': 9, + '🫱🏾‍🫲🏽': 9, + '🫱🏾‍🫲🏿': 9, + '🫱🏿‍🫲🏻': 9, + '🫱🏿‍🫲🏼': 9, + '🫱🏿‍🫲🏽': 9, + '🫱🏿‍🫲🏾': 9, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_c57c295b.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_c57c295b.py new file mode 100644 index 0000000000000000000000000000000000000000..658a0f02405ee215415d9ddb637d41f070cdefbb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_c57c295b.py @@ -0,0 +1,6422 @@ +""" +Grapheme overrides for _known_c57c295b. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: terminology +""" +# pylint: skip-file +GRAPHEMES = { + ' ོ': 2, + 'אַ': 2, + 'אָ': 2, + 'בֿ': 2, + 'וּ': 2, + 'יִ': 2, + 'כּ': 2, + 'פּ': 2, + 'פֿ': 2, + 'תּ': 2, + 'ײַ': 2, + 'اً': 2, + 'اُ': 2, + 'اّ': 2, + 'أ': 2, + 'إ': 2, + 'بَ': 2, + 'تُ': 2, + 'ثّ': 2, + 'جُ': 2, + 'دّ': 2, + 'رً': 2, + 'رِ': 2, + 'رّ': 2, + 'صّ': 2, + 'ضً': 2, + 'فّ': 2, + 'قِ': 2, + 'لِ': 2, + 'مً': 2, + 'مِ': 2, + 'مّ': 2, + 'نِ': 2, + 'نّ': 2, + 'هٔ': 2, + 'وَ': 2, + 'وّ': 2, + 'ؤ': 2, + 'يُ': 2, + 'پُ': 2, + 'چّ': 2, + 'کُ': 2, + 'کِ': 2, + 'ھُ': 2, + 'ھٔ': 2, + 'ہِ': 2, + 'ہٰ': 2, + 'یِ': 2, + 'یّ': 2, + 'یٔ': 2, + 'یٰ': 2, + 'ܒ݂': 2, + 'ܓ݂': 2, + 'ܝܼ': 2, + 'ܟ݂': 2, + 'ܡܹ': 2, + 'ܬܵ': 2, + 'ހަ': 2, + 'ހާ': 2, + 'ހި': 2, + 'ހީ': 2, + 'ހު': 2, + 'ހެ': 2, + 'ހޭ': 2, + 'ހޮ': 2, + 'ހޯ': 2, + 'ށަ': 2, + 'ށާ': 2, + 'ށި': 2, + 'ށު': 2, + 'ށެ': 2, + 'ށޭ': 2, + 'ށް': 2, + 'ނަ': 2, + 'ނާ': 2, + 'ނި': 2, + 'ނީ': 2, + 'ނު': 2, + 'ނޫ': 2, + 'ނެ': 2, + 'ނޭ': 2, + 'ން': 2, + 'ރަ': 2, + 'ރާ': 2, + 'ރި': 2, + 'ރީ': 2, + 'ރު': 2, + 'ރޫ': 2, + 'ރެ': 2, + 'ރޭ': 2, + 'ރޮ': 2, + 'ބަ': 2, + 'ބާ': 2, + 'ބި': 2, + 'ބީ': 2, + 'ބު': 2, + 'ބޫ': 2, + 'ބެ': 2, + 'ބޭ': 2, + 'ބޮ': 2, + 'ބް': 2, + 'ޅަ': 2, + 'ޅާ': 2, + 'ޅި': 2, + 'ޅު': 2, + 'ޅެ': 2, + 'ޅޭ': 2, + 'ކަ': 2, + 'ކާ': 2, + 'ކި': 2, + 'ކީ': 2, + 'ކު': 2, + 'ކެ': 2, + 'ކޮ': 2, + 'ކް': 2, + 'އަ': 2, + 'އާ': 2, + 'އި': 2, + 'އީ': 2, + 'އު': 2, + 'އޫ': 2, + 'އެ': 2, + 'އޭ': 2, + 'އޮ': 2, + 'އޯ': 2, + 'އް': 2, + 'ވަ': 2, + 'ވާ': 2, + 'ވި': 2, + 'ވީ': 2, + 'ވު': 2, + 'ވެ': 2, + 'ވޭ': 2, + 'ވޮ': 2, + 'ވޯ': 2, + 'މަ': 2, + 'މާ': 2, + 'މި': 2, + 'މީ': 2, + 'މު': 2, + 'މުި': 3, + 'މެ': 2, + 'މޭ': 2, + 'މް': 2, + 'ފަ': 2, + 'ފާ': 2, + 'ފި': 2, + 'ފީ': 2, + 'ފު': 2, + 'ފޫ': 2, + 'ފެ': 2, + 'ފޯ': 2, + 'ފް': 2, + 'ދަ': 2, + 'ދާ': 2, + 'ދި': 2, + 'ދީ': 2, + 'ދު': 2, + 'ދޫ': 2, + 'ދެ': 2, + 'ދޭ': 2, + 'ދޮ': 2, + 'ތަ': 2, + 'ތާ': 2, + 'ތި': 2, + 'ތީ': 2, + 'ތު': 2, + 'ތެ': 2, + 'ތް': 2, + 'ލަ': 2, + 'ލާ': 2, + 'ލި': 2, + 'ލީ': 2, + 'ލު': 2, + 'ލޫ': 2, + 'ލެ': 2, + 'ލޭ': 2, + 'ލް': 2, + 'ގަ': 2, + 'ގާ': 2, + 'ގި': 2, + 'ގު': 2, + 'ގެ': 2, + 'ގޮ': 2, + 'ޏަ': 2, + 'ޏެ': 2, + 'ސަ': 2, + 'ސާ': 2, + 'ސި': 2, + 'ސީ': 2, + 'ސު': 2, + 'ސޫ': 2, + 'ސެ': 2, + 'ސް': 2, + 'ޑަ': 2, + 'ޑާ': 2, + 'ޑި': 2, + 'ޑު': 2, + 'ޑެ': 2, + 'ޒަ': 2, + 'ޒާ': 2, + 'ޒި': 2, + 'ޒީ': 2, + 'ޒު': 2, + 'ޒެ': 2, + 'ޓަ': 2, + 'ޓި': 2, + 'ޓީ': 2, + 'ޓު': 2, + 'ޓެ': 2, + 'ޔަ': 2, + 'ޔާ': 2, + 'ޔި': 2, + 'ޔު': 2, + 'ޔެ': 2, + 'ޔޭ': 2, + 'ޔޮ': 2, + 'ޕް': 2, + 'ޖަ': 2, + 'ޖާ': 2, + 'ޖި': 2, + 'ޖު': 2, + 'ޖޫ': 2, + 'ޖެ': 2, + 'ޖޭ': 2, + 'ޖް': 2, + 'ޗަ': 2, + 'ޗު': 2, + 'ޗެ': 2, + 'ޘަ': 2, + 'ޙަ': 2, + 'ޙާ': 2, + 'ޙި': 2, + 'ޙީ': 2, + 'ޙު': 2, + 'ޙެ': 2, + 'ޙް': 2, + 'ޚާ': 2, + 'ޚި': 2, + 'ޚު': 2, + 'ޚް': 2, + 'ޛަ': 2, + 'ޝަ': 2, + 'ޞަ': 2, + 'ޞާ': 2, + 'ޞި': 2, + 'ޞު': 2, + 'ޞޫ': 2, + 'ޞް': 2, + 'ޟު': 2, + 'ޠަ': 2, + 'ޠީ': 2, + 'ޢަ': 2, + 'ޢާ': 2, + 'ޢީ': 2, + 'ޢު': 2, + 'ޢެ': 2, + 'ޢް': 2, + 'ޣާ': 2, + 'ޤަ': 2, + 'ޤާ': 2, + 'ޤި': 2, + 'ޤީ': 2, + 'ޤު': 2, + 'ޤެ': 2, + 'ޤް': 2, + 'अं': 2, + 'आं': 2, + 'इँ': 2, + 'इं': 2, + 'ऊं': 2, + 'एं': 2, + 'ओं': 2, + 'कं': 2, + 'कां': 3, + 'किं': 3, + 'कु': 2, + 'कू': 2, + 'कृ': 2, + 'के': 2, + 'केँ': 3, + 'कें': 3, + 'केा': 3, + 'कै': 2, + 'क्': 2, + 'क्क': 3, + 'क्का': 4, + 'क्कां': 5, + 'क्को': 4, + 'क्घ्घि्': 7, + 'क्छ': 3, + 'क्त': 3, + 'क्ता': 4, + 'क्ति': 4, + 'क्ती': 4, + 'क्तीं': 5, + 'क्तुं': 5, + 'क्तेः': 5, + 'क्त्योः': 7, + 'क्ना': 4, + 'क्नि': 4, + 'क्य': 3, + 'क्या': 4, + 'क्र': 3, + 'क्रा': 4, + 'क्रि': 4, + 'क्रू': 4, + 'क्ष': 3, + 'क्षं': 4, + 'क्षा': 4, + 'क्षां': 5, + 'क्षाः': 5, + 'क्षि': 4, + 'क्षे': 4, + 'क्षै': 4, + 'क्षो': 4, + 'क्ष्ण': 5, + 'क्ष्य': 5, + 'क्ष्या': 6, + 'क्सा': 4, + 'खु': 2, + 'खे': 2, + 'खै': 2, + 'ख्त': 3, + 'ख्ने': 4, + 'ख्य': 3, + 'ख्यः': 4, + 'ख्या': 4, + 'ख्‍ने': 4, + 'गं': 2, + 'ग़': 2, + 'ग़ा': 3, + 'ग़ु': 3, + 'गाँ': 3, + 'गां': 3, + 'गु': 2, + 'गू': 2, + 'गृ': 2, + 'गे': 2, + 'गै': 2, + 'गों': 3, + 'ग्ण': 3, + 'ग्न': 3, + 'ग्ने': 4, + 'ग्भे': 4, + 'ग्य': 3, + 'ग्या': 4, + 'ग्ये': 4, + 'ग्यैः': 5, + 'ग्र': 3, + 'ग्रे': 4, + 'ग्र्य': 5, + 'घं': 2, + 'घू': 2, + 'घृ': 2, + 'घे': 2, + 'घेि': 3, + 'घ्': 2, + 'घ्ंत': 4, + 'घ्का': 4, + 'घ्त': 3, + 'घ्र': 3, + 'घ्र्व्य': 7, + 'घ्लि': 4, + 'घ्व': 3, + 'घ्श्य': 5, + 'घ्स्ट': 5, + 'ङ्ग': 3, + 'ङ्घ': 3, + 'चां': 3, + 'चु': 2, + 'चूं': 3, + 'चे': 2, + 'चै': 2, + 'च्च': 3, + 'च्चा': 4, + 'च्चे': 4, + 'च्चों': 5, + 'च्छ': 3, + 'च्छं': 4, + 'च्छा': 4, + 'च्छि': 4, + 'च्छु': 4, + 'च्छे': 4, + 'च्या': 4, + 'च्यां': 5, + 'च्यो': 4, + 'छु': 2, + 'छुी': 3, + 'छै': 2, + 'जँ': 2, + 'जिं': 3, + 'जु': 2, + 'जे': 2, + 'जेँ': 3, + 'ज्ज': 3, + 'ज्ञा': 4, + 'ज्ञे': 4, + 'ज्ने': 4, + 'ज्य': 3, + 'ज्या': 4, + 'ज्या‌': 4, + 'ज्रा': 4, + 'झे': 2, + 'ञ्च': 3, + 'ञ्चा': 4, + 'ञ्चि': 4, + 'टां': 3, + 'टुँ': 3, + 'टुं': 3, + 'टू': 2, + 'टे': 2, + 'टै': 2, + 'टों': 3, + 'ट्ज़': 4, + 'ट्टि': 4, + 'ट्टी': 4, + 'ट्या': 4, + 'ट्र': 3, + 'ट्रा': 4, + 'ट्रे': 4, + 'ठे': 2, + 'ठैः': 3, + 'ड़': 2, + 'ड़ा': 3, + 'ड़े': 3, + 'डू': 2, + 'डे़': 3, + 'ढं': 2, + 'ढ़': 2, + 'ढ़ा': 3, + 'ढ़ि': 3, + 'ढ़ी': 3, + 'ढ़ो': 3, + 'ढाँ': 3, + 'ढे': 2, + 'णं': 2, + 'णां': 3, + 'णु': 2, + 'णू': 2, + 'णे': 2, + 'णेँ': 3, + 'णों': 3, + 'ण्ड': 3, + 'ण्डं': 4, + 'ण्डः': 4, + 'ण्डि': 4, + 'ण्य': 3, + 'ण्या': 4, + 'ण्यां': 5, + 'तँ': 2, + 'तं': 2, + 'तां': 3, + 'ताः': 3, + 'तिं': 3, + 'तु': 2, + 'तुं': 3, + 'तू': 2, + 'तृ': 2, + 'ते': 2, + 'तेँ': 3, + 'तै': 2, + 'तों': 3, + 'त्': 2, + 'त्का': 4, + 'त्त': 3, + 'त्ता': 4, + 'त्ति': 4, + 'त्ते': 4, + 'त्त्थि': 6, + 'त्त्व': 5, + 'त्त्वा': 6, + 'त्त्वे': 6, + 'त्न': 3, + 'त्नी': 4, + 'त्नों': 5, + 'त्प': 3, + 'त्पा': 4, + 'त्पी': 4, + 'त्पू': 4, + 'त्म': 3, + 'त्मा': 4, + 'त्य': 3, + 'त्यं': 4, + 'त्या': 4, + 'त्यां': 5, + 'त्यि': 4, + 'त्ये': 4, + 'त्यै': 4, + 'त्र': 3, + 'त्रा': 4, + 'त्राा': 5, + 'त्राि': 5, + 'त्रि': 4, + 'त्री': 4, + 'त्रे': 4, + 'त्र्त': 5, + 'त्र्य': 5, + 'त्र्या': 6, + 'त्र्ये': 6, + 'त्व': 3, + 'त्वं': 4, + 'त्वा': 4, + 'त्वां': 5, + 'त्वे': 4, + 'त्सं': 4, + 'त्सा': 4, + 'त्सो': 4, + 'त्स्वा': 6, + 'थु': 2, + 'थे': 2, + 'थै': 2, + 'थ्य': 3, + 'दं': 2, + 'दां': 3, + 'दु': 2, + 'दू': 2, + 'दृ': 2, + 'दे': 2, + 'दै': 2, + 'द्घ': 3, + 'द्घि': 4, + 'द्घो': 4, + 'द्द': 3, + 'द्दा': 4, + 'द्दि': 4, + 'द्दी': 4, + 'द्दे': 4, + 'द्ध': 3, + 'द्धः': 4, + 'द्धा': 4, + 'द्धां': 5, + 'द्धि': 4, + 'द्धिं': 5, + 'द्धी': 4, + 'द्धीं': 5, + 'द्धैः': 5, + 'द्भ': 3, + 'द्भा': 4, + 'द्य': 3, + 'द्या': 4, + 'द्र': 3, + 'द्रो': 4, + 'द्व': 3, + 'द्वा': 4, + 'द्वि': 4, + 'द्वे': 4, + 'द्स': 3, + 'द्‌': 2, + 'धां': 3, + 'धाः': 3, + 'धु': 2, + 'धृ': 2, + 'धे': 2, + 'धेः': 3, + 'धों': 3, + 'ध्य': 3, + 'ध्या': 4, + 'ध्ये': 4, + 'ध्व': 3, + 'नं': 2, + 'नां': 3, + 'नाः': 3, + 'निँ': 3, + 'निः': 3, + 'नु': 2, + 'नू': 2, + 'नृ': 2, + 'ने': 2, + 'नै': 2, + 'नैः': 3, + 'नों': 3, + 'न्': 2, + 'न्का': 4, + 'न्चि': 4, + 'न्छे': 4, + 'न्जे': 4, + 'न्ञ्या': 6, + 'न्त': 3, + 'न्तं': 4, + 'न्तः': 4, + 'न्ता': 4, + 'न्ति': 4, + 'न्तु': 4, + 'न्तुं': 5, + 'न्ते': 4, + 'न्तो': 4, + 'न्तों': 5, + 'न्त्र': 5, + 'न्त्रा': 6, + 'न्त्राः': 7, + 'न्त्रि': 6, + 'न्त्री': 6, + 'न्त्र्य': 7, + 'न्त्र्यं': 8, + 'न्त्र्या': 8, + 'न्त्र्ये': 8, + 'न्द': 3, + 'न्दा': 4, + 'न्दी': 4, + 'न्दो': 4, + 'न्ध': 3, + 'न्धा': 4, + 'न्धि': 4, + 'न्धी': 4, + 'न्धु': 4, + 'न्धों': 5, + 'न्न': 3, + 'न्ना': 4, + 'न्नाः': 5, + 'न्नि': 4, + 'न्ने': 4, + 'न्म': 3, + 'न्मा': 4, + 'न्मु': 4, + 'न्मे': 4, + 'न्य': 3, + 'न्या': 4, + 'न्ये': 4, + 'न्यै': 4, + 'न्यो': 4, + 'न्व': 3, + 'न्वे': 4, + 'न्स': 3, + 'न्हा': 4, + 'न्हें': 5, + 'न्ह्यां': 7, + 'पं': 2, + 'पाँ': 3, + 'पां': 3, + 'पु': 2, + 'पू': 2, + 'पृ': 2, + 'पे': 2, + 'पेँ': 3, + 'पै': 2, + 'पों': 3, + 'प्त': 3, + 'प्तं': 4, + 'प्ति': 4, + 'प्तुं': 5, + 'प्तौ': 4, + 'प्य': 3, + 'प्यं': 4, + 'प्या': 4, + 'प्र': 3, + 'प्रा': 4, + 'फ़': 2, + 'फाँ': 3, + 'फु': 2, + 'फे': 2, + 'फ्त': 3, + 'फ्ता': 4, + 'फ्ना': 4, + 'फ्नो': 4, + 'फ्रां': 5, + 'बँ': 2, + 'बं': 2, + 'बाँ': 3, + 'बु': 2, + 'बू': 2, + 'बृ': 2, + 'बे': 2, + 'बै': 2, + 'ब्द': 3, + 'ब्ध': 3, + 'ब्धि': 4, + 'ब्यू': 4, + 'भं': 2, + 'भिः': 3, + 'भु': 2, + 'भू': 2, + 'भे': 2, + 'भै': 2, + 'भ्य': 3, + 'भ्यः': 4, + 'भ्या': 4, + 'भ्यां': 5, + 'भ्यु': 4, + 'भ्यो': 4, + 'भ्र': 3, + 'मं': 2, + 'मां': 3, + 'मु': 2, + 'मू': 2, + 'मे': 2, + 'मेँ': 3, + 'में': 3, + 'मै': 2, + 'मों': 3, + 'म्': 2, + 'म्ति': 4, + 'म्न': 3, + 'म्नि': 4, + 'म्प': 3, + 'म्पा': 4, + 'म्प्र': 5, + 'म्ब': 3, + 'म्बु': 4, + 'म्भि': 4, + 'म्म': 3, + 'म्मा': 4, + 'म्मि': 4, + 'म्मे': 4, + 'म्या': 4, + 'म्से': 4, + 'म्ह': 3, + 'म्ही': 4, + 'म्हो': 4, + 'यं': 2, + 'यां': 3, + 'याः': 3, + 'यु': 2, + 'यू': 2, + 'ये': 2, + 'यै': 2, + 'यैः': 3, + 'यों': 3, + 'य्य': 3, + 'य्यो': 4, + 'रं': 2, + 'रां': 3, + 'राः': 3, + 'रिं': 3, + 'रु': 2, + 'रू': 2, + 'रे': 2, + 'रें': 3, + 'रै': 2, + 'रों': 3, + 'र्क': 3, + 'र्कि': 4, + 'र्ग': 3, + 'र्गी': 4, + 'र्गे': 4, + 'र्चि': 4, + 'र्छ': 3, + 'र्ज': 3, + 'र्जा': 4, + 'र्जि': 4, + 'र्जी': 4, + 'र्ट': 3, + 'र्ढ': 3, + 'र्ण': 3, + 'र्णं': 4, + 'र्णां': 5, + 'र्णी': 4, + 'र्त': 3, + 'र्ता': 4, + 'र्ति': 4, + 'र्तिः': 5, + 'र्ती': 4, + 'र्तुं': 5, + 'र्त्त': 5, + 'र्त्ति': 6, + 'र्थ': 3, + 'र्थं': 4, + 'र्थि': 4, + 'र्थी': 4, + 'र्द': 3, + 'र्दा': 4, + 'र्दि': 4, + 'र्दु': 4, + 'र्दे': 4, + 'र्दै': 4, + 'र्दो': 4, + 'र्द्ध': 5, + 'र्ध': 3, + 'र्धा': 4, + 'र्धि': 4, + 'र्न': 3, + 'र्नि': 4, + 'र्नु': 4, + 'र्नू': 4, + 'र्ने': 4, + 'र्फ': 3, + 'र्ब': 3, + 'र्बं': 4, + 'र्बा': 4, + 'र्भ': 3, + 'र्भा': 4, + 'र्म': 3, + 'र्मं': 4, + 'र्मा': 4, + 'र्मि': 4, + 'र्य': 3, + 'र्यं': 4, + 'र्या': 4, + 'र्यां': 5, + 'र्ये': 4, + 'र्यों': 5, + 'र्रा': 4, + 'र्व': 3, + 'र्वा': 4, + 'र्वां': 5, + 'र्वृ': 4, + 'र्वे': 4, + 'र्वो': 4, + 'र्श': 3, + 'र्ष': 3, + 'र्षे': 4, + 'र्स': 3, + 'र्सा': 4, + 'र्ह': 3, + 'र्हाः': 5, + 'र्हि': 4, + 'र्हो': 4, + 'र्‍या': 4, + 'लां': 3, + 'लाः': 3, + 'लिं': 3, + 'लीं': 3, + 'लु': 2, + 'लू': 2, + 'ले': 2, + 'लै': 2, + 'लों': 3, + 'ल्क': 3, + 'ल्का': 4, + 'ल्ने': 4, + 'ल्प': 3, + 'ल्पि': 4, + 'ल्म': 3, + 'ल्य': 3, + 'ल्यं': 4, + 'ल्या': 4, + 'ल्यां': 5, + 'ल्याः': 5, + 'ल्ये': 4, + 'ल्ल': 3, + 'ल्लं': 4, + 'ल्ला': 4, + 'ल्लि': 4, + 'ल्ले': 4, + 'ल्ह': 3, + 'ळे': 2, + 'वं': 2, + 'वां': 3, + 'वाः': 3, + 'वू': 2, + 'वृ': 2, + 'वे': 2, + 'वै': 2, + 'वों': 3, + 'व्य': 3, + 'व्या': 4, + 'व्ये': 4, + 'व्यों': 5, + 'शं': 2, + 'शां': 3, + 'शाः': 3, + 'शु': 2, + 'शू': 2, + 'शे': 2, + 'शों': 3, + 'श्च': 3, + 'श्चि': 4, + 'श्य': 3, + 'श्या': 4, + 'श्यि': 4, + 'श्यों': 5, + 'श्र': 3, + 'श्रा': 4, + 'श्रां': 5, + 'श्रु': 4, + 'श्व': 3, + 'श्वा': 4, + 'श्वि': 4, + 'षां': 3, + 'षाः': 3, + 'षु': 2, + 'षे': 2, + 'षों': 3, + 'ष्का': 4, + 'ष्ट': 3, + 'ष्टः': 4, + 'ष्टा': 4, + 'ष्टां': 5, + 'ष्टाः': 5, + 'ष्टि': 4, + 'ष्टी': 4, + 'ष्टीं': 5, + 'ष्ट्र': 5, + 'ष्ट्रा': 6, + 'ष्ट्रां': 7, + 'ष्ट्रि': 6, + 'ष्ट्री': 6, + 'ष्ट्रे': 6, + 'ष्ट्रो': 6, + 'ष्ट्रों': 7, + 'ष्ठा': 4, + 'ष्ठे': 4, + 'ष्ठों': 5, + 'ष्णु': 4, + 'ष्प': 3, + 'ष्प्र': 5, + 'ष्य': 3, + 'ष्यः': 4, + 'ष्यों': 5, + 'सँ': 2, + 'सं': 2, + 'साँ': 3, + 'सां': 3, + 'सु': 2, + 'सू': 2, + 'सृ': 2, + 'से': 2, + 'सै': 2, + 'स्क': 3, + 'स्का': 4, + 'स्काः': 5, + 'स्कु': 4, + 'स्कू': 4, + 'स्कृ': 4, + 'स्ट': 3, + 'स्ट्या': 6, + 'स्त': 3, + 'स्ता': 4, + 'स्ति': 4, + 'स्ती': 4, + 'स्तु': 4, + 'स्तुं': 5, + 'स्तै': 4, + 'स्तो': 4, + 'स्त्र': 5, + 'स्त्रा': 6, + 'स्त्रि': 6, + 'स्त्री': 6, + 'स्थ': 3, + 'स्था': 4, + 'स्थां': 5, + 'स्थि': 4, + 'स्थी': 4, + 'स्थे': 4, + 'स्थ्य': 5, + 'स्धी': 4, + 'स्प': 3, + 'स्पे': 4, + 'स्म': 3, + 'स्मि': 4, + 'स्मिं': 5, + 'स्मै': 4, + 'स्य': 3, + 'स्या': 4, + 'स्यां': 5, + 'स्याः': 5, + 'स्युः': 5, + 'स्यों': 5, + 'स्रो': 4, + 'स्ल': 3, + 'स्व': 3, + 'स्वं': 4, + 'स्वा': 4, + 'स्वी': 4, + 'स्वे': 4, + 'स्स': 3, + 'स्सा': 4, + 'हाँ': 3, + 'हां': 3, + 'हिं': 3, + 'हीं': 3, + 'हु': 2, + 'हुँ': 3, + 'हू': 2, + 'हे': 2, + 'है': 2, + 'हैं': 3, + 'हैः': 3, + 'हों': 3, + 'ह्या': 4, + 'ह्रा': 4, + 'फ़्ता': 4, + 'কিং': 3, + 'কু': 2, + 'কূ': 2, + 'কৃ': 2, + 'ক্ত': 3, + 'ক্তি': 4, + 'ক্য': 3, + 'ক্র': 3, + 'ক্রী': 4, + 'ক্ষ': 3, + 'ক্ষা': 4, + 'ক্ষি': 4, + 'ক্ষে': 4, + 'ক্ষ্য': 5, + 'ক্ষ্যে': 6, + 'খু': 2, + 'খ্যা': 4, + 'গু': 2, + 'গৃ': 2, + 'গ্য': 3, + 'গ্র': 3, + 'গ্রা': 4, + 'গ্রে': 4, + 'ঘৃ': 2, + 'ঘো': 3, + 'ঙ্খা': 4, + 'ঙ্গ': 3, + 'ঙ্গী': 4, + 'ঙ্গে': 4, + 'ঙ্ঘ': 3, + 'চ্চ': 3, + 'চ্ছ': 3, + 'চ্ছা': 4, + 'চ্ছা‌': 4, + 'চ্ছু': 4, + 'চ্ছে': 4, + 'ছু': 2, + 'জ্ঞ': 3, + 'জ্ঞা': 4, + 'জ্য': 3, + 'ঞ্চি': 4, + 'ঞ্ছি': 4, + 'ট্রে': 4, + 'ড়': 2, + 'ড়া': 3, + 'ঢ়': 2, + 'ণ্ড': 3, + 'ণ্ডে': 4, + 'ণ্য': 3, + 'তাঁ': 3, + 'তু': 2, + 'তৃ': 2, + 'ত্ত': 3, + 'ত্তা': 4, + 'ত্তি': 4, + 'ত্ন': 3, + 'ত্ব': 3, + 'ত্বে': 4, + 'ত্ম': 3, + 'ত্য': 3, + 'ত্যা': 4, + 'ত্যি': 4, + 'ত্যে': 4, + 'ত্র': 3, + 'ত্রা': 4, + 'ত্রে': 4, + 'ত্‍': 2, + 'ত্‍প': 3, + 'ত্‍পী': 4, + 'ত্‍সা': 4, + 'থ্য': 3, + 'দৃ': 2, + 'দ্দি': 4, + 'দ্দে': 4, + 'দ্ধ': 3, + 'দ্ধা': 4, + 'দ্ধি': 4, + 'দ্ধে': 4, + 'দ্বা': 4, + 'দ্ভ': 3, + 'দ্ভূ': 4, + 'দ্য': 3, + 'দ্রো': 4, + 'ধ্য': 3, + 'ধ্যে': 4, + 'নু': 2, + 'ন্ড': 3, + 'ন্ত': 3, + 'ন্তা': 4, + 'ন্তি': 4, + 'ন্তে': 4, + 'ন্ত্রি': 6, + 'ন্ত্রে': 6, + 'ন্থী': 4, + 'ন্ধ': 3, + 'ন্ধা': 4, + 'ন্ধু': 4, + 'ন্ন': 3, + 'ন্ম': 3, + 'ন্মা': 4, + 'ন্মু': 4, + 'ন্য': 3, + 'ন্যা': 4, + 'ন্যে': 4, + 'পু': 2, + 'পূ': 2, + 'পৃ': 2, + 'প্ত': 3, + 'প্তা': 4, + 'প্র': 3, + 'প্রা': 4, + 'বু': 2, + 'বৃ': 2, + 'ব্ধি': 4, + 'ব্য': 3, + 'ব্যা': 4, + 'ব্র': 3, + 'ভূ': 2, + 'ভ্য': 3, + 'ভ্রা': 4, + 'মু': 2, + 'মূ': 2, + 'ম্প': 3, + 'ম্পা': 4, + 'ম্ব': 3, + 'ম্ভ': 3, + 'ম্ম': 3, + 'ম্মা': 4, + 'ম্য': 3, + 'য়': 2, + 'য়া': 3, + 'য়ি': 3, + 'য়ে': 3, + 'য়ো': 3, + 'যু': 2, + 'য্য': 3, + 'রাং': 3, + 'রু': 2, + 'রূ': 2, + 'র্ক': 3, + 'র্জ': 3, + 'র্জা': 4, + 'র্ণ': 3, + 'র্ত': 3, + 'র্থ': 3, + 'র্থে': 4, + 'র্দো': 4, + 'র্ধ': 3, + 'র্ধা': 4, + 'র্নী': 4, + 'র্ব': 3, + 'র্বা': 4, + 'র্বি': 4, + 'র্বো': 4, + 'র্ব্য': 5, + 'র্ভূ': 4, + 'র্ম': 3, + 'র্মে': 4, + 'র্য': 3, + 'র্যা': 4, + 'ল্প': 3, + 'ল্য': 3, + 'ল্যা': 4, + 'ল্যে': 4, + 'ল্লে': 4, + 'শু': 2, + 'শৃং': 3, + 'শ্চ': 3, + 'শ্চি': 4, + 'শ্বা': 4, + 'শ্বে': 4, + 'শ্য': 3, + 'শ্যে': 4, + 'শ্র': 3, + 'শ্রা': 4, + 'ষ্ট': 3, + 'ষ্টা': 4, + 'ষ্টি': 4, + 'ষ্ট্র': 5, + 'ষ্ট্রী': 6, + 'ষ্ট্রে': 6, + 'ষ্ঠা': 4, + 'ষ্ঠি': 4, + 'ষ্ঠী': 4, + 'ষ্ঠু': 4, + 'ষ্ণু': 4, + 'সাং': 3, + 'সু': 2, + 'সৃ': 2, + 'স্ক': 3, + 'স্কৃ': 4, + 'স্ত': 3, + 'স্তি': 4, + 'স্তি‌': 4, + 'স্ত্র': 5, + 'স্থ': 3, + 'স্থা': 4, + 'স্থ্য': 5, + 'স্ব': 3, + 'স্বা': 4, + 'স্বী': 4, + 'স্য': 3, + 'স্যা': 4, + 'স্যে': 4, + 'হ্য': 3, + 'ਅੰ': 2, + 'ਅੱ': 2, + 'ਆਂ': 2, + 'ਇੰ': 2, + 'ਉਂ': 2, + 'ਉੱ': 2, + 'ਕਾਂ': 3, + 'ਕਿ੍': 3, + 'ਕਿੱ': 3, + 'ਕੁ': 2, + 'ਕੂ': 2, + 'ਕੇ': 2, + 'ਕੋ': 2, + 'ਕੌ': 2, + 'ਕੰ': 2, + 'ਕੱ': 2, + 'ਖਾਂ': 3, + 'ਖਿ਼': 3, + 'ਖੁ': 2, + 'ਖੁੱ': 3, + 'ਖੇ': 2, + 'ਖੋ': 2, + 'ਖੋਂ': 3, + 'ਗਿ੍': 3, + 'ਗੁ': 2, + 'ਗੇ': 2, + 'ਗੈ': 2, + 'ਗੱ': 2, + 'ਘੁੰ': 3, + 'ਘੰ': 2, + 'ਚਿੱ': 3, + 'ਚੁ': 2, + 'ਚੇ': 2, + 'ਚੋ': 2, + 'ਚੋਂ': 3, + 'ਚੰ': 2, + 'ਛੁ': 2, + 'ਛੋਂ': 3, + 'ਜਾਂ': 3, + 'ਜਿ਼': 3, + 'ਜਿ਼ੰ': 4, + 'ਜੁ': 2, + 'ਜੇ': 2, + 'ਜੋ': 2, + 'ਜੋਂ': 3, + 'ਜੰ': 2, + 'ਜੱ': 2, + 'ਝੰ': 2, + 'ਟਿ੍': 3, + 'ਟੇ': 2, + 'ਢੇ': 2, + 'ਢੰ': 2, + 'ਣਾਂ': 3, + 'ਣੇ': 2, + 'ਤਾਂ': 3, + 'ਤੇ': 2, + 'ਤੋਂ': 3, + 'ਤੰ': 2, + 'ਤੱ': 2, + 'ਥੇ': 2, + 'ਥੋਂ': 3, + 'ਦਾਂ': 3, + 'ਦਿੱ': 3, + 'ਦੁ': 2, + 'ਦੂ': 2, + 'ਦੇ': 2, + 'ਦੋ': 2, + 'ਦੋਂ': 3, + 'ਦੰ': 2, + 'ਧਾਂ': 3, + 'ਧੁ': 2, + 'ਧੇ': 2, + 'ਧੱ': 2, + 'ਨਾਂ': 3, + 'ਨੀਂ': 3, + 'ਨੁ': 2, + 'ਨੁੱ': 3, + 'ਨੂੰ': 3, + 'ਨੇ': 2, + 'ਨੋ': 2, + 'ਨੌ': 2, + 'ਨ੍': 2, + 'ਨੰ': 2, + 'ਪੁ': 2, + 'ਪੂ': 2, + 'ਪੈ': 2, + 'ਪ੍': 2, + 'ਪੰ': 2, + 'ਪੱ': 2, + 'ਫੌ': 2, + 'ਬੁ': 2, + 'ਬੂ': 2, + 'ਬੇ': 2, + 'ਬੋ': 2, + 'ਬੰ': 2, + 'ਬੱ': 2, + 'ਭੂ': 2, + 'ਭੇ': 2, + 'ਮਾਂ': 3, + 'ਮੁ': 2, + 'ਮੁੱ': 3, + 'ਮੂ': 2, + 'ਮੇ': 2, + 'ਮੇਂ': 3, + 'ਮੈਂ': 3, + 'ਮੌ': 2, + 'ਮੰ': 2, + 'ਯੁ': 2, + 'ਯੂ': 2, + 'ਯੋ': 2, + 'ਰਾਂ': 3, + 'ਰੁ': 2, + 'ਰੁੱ': 3, + 'ਰੂ': 2, + 'ਰੇ': 2, + 'ਰੋ': 2, + 'ਰ੍': 2, + 'ਰੰ': 2, + 'ਰੱ': 2, + 'ਲਾਂ': 3, + 'ਲਿੰ': 3, + 'ਲੇ': 2, + 'ਲੈ': 2, + 'ਲੋ': 2, + 'ਲ੍': 2, + 'ਲੰ': 2, + 'ਵਾਂ': 3, + 'ਵਿੱ': 3, + 'ਵੇ': 2, + 'ਵੇਂ': 3, + 'ਵੈ': 2, + 'ਵੰ': 2, + 'ਵੱ': 2, + 'ਸ਼ਾਂ': 3, + 'ਸ਼ੇ': 2, + 'ਸ਼ੋ': 2, + 'ਸ਼ੌ': 2, + 'ਸਾਂ': 3, + 'ਸਿੱ': 3, + 'ਸੁ': 2, + 'ਸੁੰ': 3, + 'ਸੂ': 2, + 'ਸੇ': 2, + 'ਸੇੇ': 3, + 'ਸੈਂ': 3, + 'ਸੌ': 2, + 'ਸੰ': 2, + 'ਸੱ': 2, + 'ਹਾਂ': 3, + 'ਹਿੰ': 3, + 'ਹਿੱ': 3, + 'ਹੀਂ': 3, + 'ਹੁ': 2, + 'ਹੁੰ': 3, + 'ਹੂ': 2, + 'ਹੇ': 2, + 'ਹੈ': 2, + 'ਹੋ': 2, + 'ਹੋਂ': 3, + 'ਹੱ': 2, + 'ਜ਼ੁ': 2, + 'ੜੀਂ': 3, + 'ੜੇ': 2, + 'ੜ੍': 2, + 'ਫ਼ੁ': 2, + 'અં': 2, + 'આં': 2, + 'ઊં': 2, + 'કાં': 3, + 'કુ': 2, + 'કૃ': 2, + 'કે': 2, + 'ક્ક': 3, + 'ક્કા': 4, + 'ક્કો': 4, + 'ક્તિ': 4, + 'ક્ર': 3, + 'ક્ષ': 3, + 'ક્ષા': 4, + 'ખુ': 2, + 'ખૂ': 2, + 'ખ્ત': 3, + 'ગુ': 2, + 'ગે': 2, + 'ગ્ન': 3, + 'ગ્ય': 3, + 'ચૂં': 3, + 'ચ્ચ': 3, + 'ચ્ચા': 4, + 'ચ્ચે': 4, + 'ચ્છા': 4, + 'ચ્છે': 4, + 'છું': 3, + 'છૂ': 2, + 'છે': 2, + 'જં': 2, + 'જાં': 3, + 'જુ': 2, + 'જૂ': 2, + 'જે': 2, + 'જ્ઞા': 4, + 'જ્ય': 3, + 'જ્યો': 4, + 'ઝૂં': 3, + 'ટું': 3, + 'ટે': 2, + 'ટ્ર': 3, + 'ટ્રે': 4, + 'ડાં': 3, + 'ડે': 2, + 'ણુ': 2, + 'ણે': 2, + 'તં': 2, + 'તાં': 3, + 'તુ': 2, + 'તૃ': 2, + 'તે': 2, + 'ત્તા': 4, + 'ત્તિ': 4, + 'ત્ત્વ': 5, + 'ત્ત્વા': 6, + 'ત્ન': 3, + 'ત્મ': 3, + 'ત્ય': 3, + 'ત્યા': 4, + 'ત્યાં': 5, + 'ત્યિ': 4, + 'ત્યે': 4, + 'ત્યો': 4, + 'ત્ર': 3, + 'ત્રી': 4, + 'ત્ર્ય': 5, + 'ત્વ': 3, + 'થે': 2, + 'દુ': 2, + 'દૃ': 2, + 'દે': 2, + 'દ્ધ': 3, + 'દ્ધા': 4, + 'દ્ધાં': 5, + 'દ્ધિ': 4, + 'દ્ભ': 3, + 'દ્વા': 4, + 'ધાં': 3, + 'ધુ': 2, + 'ધ્ય': 3, + 'ધ્યા': 4, + 'નં': 2, + 'નાં': 3, + 'નુ': 2, + 'નું': 3, + 'ને': 2, + 'નૈ': 2, + 'ન્ત': 3, + 'ન્તો': 4, + 'ન્મ': 3, + 'ન્મા': 4, + 'ન્મે': 4, + 'ન્ય': 3, + 'ન્યા': 4, + 'ન્યૂં': 5, + 'પુ': 2, + 'પૂ': 2, + 'પે': 2, + 'પ્ત': 3, + 'પ્ર': 3, + 'પ્રા': 4, + 'ફે': 2, + 'બં': 2, + 'બાં': 3, + 'બે': 2, + 'બ્ધ': 3, + 'ભં': 2, + 'ભાં': 3, + 'ભૂ': 2, + 'ભે': 2, + 'ભ્ય': 3, + 'મં': 2, + 'માં': 3, + 'મુ': 2, + 'મૂ': 2, + 'મૃ': 2, + 'મે': 2, + 'મૈ': 2, + 'મ્ય': 3, + 'મ્યાં': 5, + 'યુ': 2, + 'રં': 2, + 'રુ': 2, + 'રૂ': 2, + 'રે': 2, + 'ર્જ': 3, + 'ર્ણ': 3, + 'ર્ત': 3, + 'ર્તા': 4, + 'ર્થ': 3, + 'ર્થિ': 4, + 'ર્દો': 4, + 'ર્મ': 3, + 'ર્મિ': 4, + 'ર્મે': 4, + 'ર્ય': 3, + 'ર્યા': 4, + 'ર્યો': 4, + 'ર્વ': 3, + 'લાં': 3, + 'લિં': 3, + 'લે': 2, + 'લ્મ': 3, + 'લ્ય': 3, + 'ળે': 2, + 'વં': 2, + 'વાં': 3, + 'વું': 3, + 'વૃ': 2, + 'વે': 2, + 'વૈ': 2, + 'વ્ય': 3, + 'વ્યા': 4, + 'વ્યો': 4, + 'શાં': 3, + 'શુ': 2, + 'શે': 2, + 'શ્કે': 4, + 'શ્ચ': 3, + 'શ્ય': 3, + 'શ્ર': 3, + 'શ્વ': 3, + 'ષ્ટિ': 4, + 'ષ્ટ્ર': 5, + 'ષ્ટ્રી': 6, + 'ષ્ટ્રો': 6, + 'ષ્ઠા': 4, + 'ષ્ણુ': 4, + 'ષ્પ': 3, + 'સં': 2, + 'સાં': 3, + 'સુ': 2, + 'સું': 3, + 'સૂ': 2, + 'સે': 2, + 'સ્કૃ': 4, + 'સ્ટ': 3, + 'સ્તિ': 4, + 'સ્તી': 4, + 'સ્ત્રી': 6, + 'સ્થા': 4, + 'સ્થિ': 4, + 'સ્પ': 3, + 'સ્રી': 4, + 'સ્વ': 3, + 'સ્વા': 4, + 'સ્વી': 4, + 'સ્સા': 4, + 'હુ': 2, + 'હે': 2, + 'கீ': 2, + 'க்': 2, + 'ங்': 2, + 'சீ': 2, + 'ச்': 2, + 'ஞ்': 2, + 'ட்': 2, + 'ண்': 2, + 'தீ': 2, + 'த்': 2, + 'நீ': 2, + 'ந்': 2, + 'ன்': 2, + 'ப்': 2, + 'மீ': 2, + 'ம்': 2, + 'யீ': 2, + 'ய்': 2, + 'ர்': 2, + 'ற்': 2, + 'ல்': 2, + 'ள்': 2, + 'ழ்': 2, + 'வீ': 2, + 'வ்': 2, + 'ஸ்': 2, + 'కా': 2, + 'కాం': 3, + 'కి': 2, + 'కీ': 2, + 'కుం': 3, + 'కె': 2, + 'కెం': 3, + 'కై': 2, + 'కొ': 2, + 'క్క': 3, + 'క్కు': 4, + 'క్త': 3, + 'క్తి': 4, + 'క్తీ': 4, + 'క్తు': 4, + 'క్య': 3, + 'క్ర': 3, + 'క్రాం': 5, + 'క్రి': 4, + 'క్రూ': 4, + 'క్ష': 3, + 'క్షా': 4, + 'క్షి': 4, + 'క్షిం': 5, + 'క్షే': 4, + 'క్షో': 4, + 'క్స్వా': 6, + 'ఖా': 2, + 'ఖ్య': 3, + 'ఖ్యా': 4, + 'గా': 2, + 'గి': 2, + 'గిం': 3, + 'గీ': 2, + 'గౌ': 2, + 'గ్భా': 4, + 'గ్మ': 3, + 'గ్య': 3, + 'గ్ర': 3, + 'గ్రి': 4, + 'ఘి': 2, + 'ఘో': 2, + 'చా': 2, + 'చి': 2, + 'చెం': 3, + 'చే': 2, + 'చో': 2, + 'చ్చు': 4, + 'చ్ఛ': 3, + 'చ్ఛా': 4, + 'చ్ఛే': 4, + 'ఛ్ఛా': 4, + 'జా': 2, + 'జి': 2, + 'జీ': 2, + 'జే': 2, + 'జో': 2, + 'జ్ఞ': 3, + 'జ్ఞా': 4, + 'జ్య': 3, + 'టి': 2, + 'టిం': 3, + 'టుం': 3, + 'టే': 2, + 'ట్టి': 4, + 'ట్లు': 4, + 'డి': 2, + 'డ్డ': 3, + 'డ్రు': 4, + 'ణా': 2, + 'ణిం': 3, + 'ణీ': 2, + 'తా': 2, + 'తి': 2, + 'తీ': 2, + 'తె': 2, + 'తొ': 2, + 'తో': 2, + 'త్కా': 4, + 'త్త': 3, + 'త్తి': 4, + 'త్తు': 4, + 'త్న': 3, + 'త్నిం': 5, + 'త్ప': 3, + 'త్ఫ': 3, + 'త్య': 3, + 'త్యం': 4, + 'త్యా': 4, + 'త్ర': 3, + 'త్రు': 4, + 'త్ర్య': 5, + 'త్వ': 3, + 'త్వా': 4, + 'త్స': 3, + 'థా': 2, + 'దా': 2, + 'ది': 2, + 'దిం': 3, + 'దుం': 3, + 'దే': 2, + 'దై': 2, + 'దో': 2, + 'ద్ఘో': 4, + 'ద్ది': 4, + 'ద్దు': 4, + 'ద్దే': 4, + 'ద్ధ': 3, + 'ద్ధి': 4, + 'ద్ధిం': 5, + 'ద్య': 3, + 'ద్యా': 4, + 'ద్యో': 4, + 'ద్ర్య': 5, + 'ద్వా': 4, + 'ధా': 2, + 'ధి': 2, + 'ధిం': 3, + 'ధీ': 2, + 'ధ్య': 3, + 'నా': 2, + 'నాం': 3, + 'ని': 2, + 'నిం': 3, + 'నీ': 2, + 'నుం': 3, + 'నె': 2, + 'నే': 2, + 'నై': 2, + 'నొ': 2, + 'నొం': 3, + 'న్ధ': 3, + 'న్న': 3, + 'న్నా': 4, + 'న్ని': 4, + 'న్ను': 4, + 'న్మ': 3, + 'న్య': 3, + 'న్యా': 4, + 'న్వే': 4, + 'పా': 2, + 'పిం': 3, + 'పీ': 2, + 'పె': 2, + 'పెం': 3, + 'పే': 2, + 'పై': 2, + 'పొం': 3, + 'ప్త': 3, + 'ప్ర': 3, + 'ప్రా': 4, + 'ప్రే': 4, + 'బా': 2, + 'బి': 2, + 'బో': 2, + 'బ్ర': 3, + 'భా': 2, + 'భి': 2, + 'భే': 2, + 'భ్య': 3, + 'భ్యు': 4, + 'భ్ర': 3, + 'భ్రా': 4, + 'మా': 2, + 'మి': 2, + 'మిం': 3, + 'మే': 2, + 'మై': 2, + 'మో': 2, + 'మ్య': 3, + 'యా': 2, + 'యి': 2, + 'యిం': 3, + 'యుం': 3, + 'యె': 2, + 'యే': 2, + 'యొ': 2, + 'యో': 2, + 'రా': 2, + 'రి': 2, + 'రిం': 3, + 'రై': 2, + 'రో': 2, + 'ర్': 2, + 'ర్గ': 3, + 'ర్చి': 4, + 'ర్చు': 4, + 'ర్ణ': 3, + 'ర్ణాం': 5, + 'ర్ణు': 4, + 'ర్త': 3, + 'ర్తి': 4, + 'ర్తిం': 5, + 'ర్తృ': 4, + 'ర్థ': 3, + 'ర్థి': 4, + 'ర్థిం': 5, + 'ర్ద': 3, + 'ర్దో': 4, + 'ర్ధ': 3, + 'ర్ప': 3, + 'ర్బం': 4, + 'ర్భ': 3, + 'ర్భా': 4, + 'ర్య': 3, + 'ర్యా': 4, + 'ర్రా': 4, + 'ర్వ': 3, + 'ర్వా': 4, + 'ర్హ': 3, + 'ర్హాం': 5, + 'ర్హు': 4, + 'లా': 2, + 'లి': 2, + 'లిం': 3, + 'లీ': 2, + 'లె': 2, + 'లే': 2, + 'లో': 2, + 'లౌ': 2, + 'ల్క': 3, + 'ల్గొ': 4, + 'ల్ప': 3, + 'ల్ల': 3, + 'ల్లి': 4, + 'ళా': 2, + 'వా': 2, + 'వి': 2, + 'విం': 3, + 'వీ': 2, + 'వే': 2, + 'వై': 2, + 'వ్య': 3, + 'వ్యా': 4, + 'వ్వ': 3, + 'శా': 2, + 'శాం': 3, + 'శి': 2, + 'శిం': 3, + 'శై': 2, + 'శ్చ': 3, + 'శ్చి': 4, + 'శ్య': 3, + 'శ్ర': 3, + 'శ్రాం': 5, + 'శ్లే': 4, + 'శ్వా': 4, + 'షా': 2, + 'షి': 2, + 'షిం': 3, + 'షే': 2, + 'ష్ట': 3, + 'ష్టు': 4, + 'ష్ట్ర': 5, + 'ష్ట్రీ': 6, + 'ష్ఠ': 3, + 'ష్ఠా': 4, + 'ష్ఠు': 4, + 'ష్థ': 3, + 'ష్ప': 3, + 'సా': 2, + 'సాం': 3, + 'సి': 2, + 'సీ': 2, + 'సె': 2, + 'సే': 2, + 'సౌ': 2, + 'స్కృ': 4, + 'స్తా': 4, + 'స్తి': 4, + 'స్త్ర': 5, + 'స్త్రీ': 6, + 'స్థ': 3, + 'స్థా': 4, + 'స్థి': 4, + 'స్థ్య': 5, + 'స్ప': 3, + 'స్య': 3, + 'స్వ': 3, + 'స్వా': 4, + 'స్వీ': 4, + 'స్వే': 4, + 'హా': 2, + 'హి': 2, + 'హిం': 3, + 'హో': 2, + 'ಕಾಂ': 3, + 'ಕಿಂ': 3, + 'ಕುಂ': 3, + 'ಕೆ': 2, + 'ಕೆಂ': 3, + 'ಕೊಂ': 3, + 'ಕೌ': 2, + 'ಕ್': 2, + 'ಕ್‌': 2, + 'ಖಾಂ': 3, + 'ಖ್': 2, + 'ಗಾಂ': 3, + 'ಗಿ': 2, + 'ಗೆ': 2, + 'ಗೊಂ': 3, + 'ಗೌ': 2, + 'ಗ್': 2, + 'ಘಿ': 2, + 'ಚಿ': 2, + 'ಚ್': 2, + 'ಛಿ': 2, + 'ಛೆ': 2, + 'ಜಿ': 2, + 'ಜೆ': 2, + 'ಜ್': 2, + 'ಞೆ': 2, + 'ಞೌ': 2, + 'ಟಿ': 2, + 'ಟುಂ': 3, + 'ಟ್': 2, + 'ಠಿ': 2, + 'ಡಿ': 2, + 'ಡೆ': 2, + 'ಡ್': 2, + 'ಢಿ': 2, + 'ಣಿ': 2, + 'ಣೆ': 2, + 'ತಿ': 2, + 'ತೆ': 2, + 'ತ್': 2, + 'ಥಿ': 2, + 'ಥೆ': 2, + 'ದಿ': 2, + 'ದಿಂ': 3, + 'ದೆ': 2, + 'ದೌ': 2, + 'ದ್': 2, + 'ಧಿ': 2, + 'ಧೆ': 2, + 'ಧ್': 2, + 'ನಾಂ': 3, + 'ನಿ': 2, + 'ನಿಂ': 3, + 'ನೆ': 2, + 'ನೌ': 2, + 'ನ್': 2, + 'ಪಿ': 2, + 'ಪ್': 2, + 'ಬೆ': 2, + 'ಬ್': 2, + 'ಭಿ': 2, + 'ಭೆ': 2, + 'ಭೌ': 2, + 'ಮಿ': 2, + 'ಮೆ': 2, + 'ಮ್': 2, + 'ಯಿ': 2, + 'ಯಿಂ': 3, + 'ಯುಂ': 3, + 'ಯೆ': 2, + 'ಯೆಂ': 3, + 'ಯ್': 2, + 'ರಾಂ': 3, + 'ರಿ': 2, + 'ರಿಂ': 3, + 'ರೆ': 2, + 'ರೆಂ': 3, + 'ರ್': 2, + 'ಲಿ': 2, + 'ಲೆ': 2, + 'ಲೆಂ': 3, + 'ಲ್': 2, + 'ಳಿ': 2, + 'ಳಿಂ': 3, + 'ಳೆ': 2, + 'ಳ್': 2, + 'ವಿ': 2, + 'ವುಂ': 3, + 'ವೆ': 2, + 'ವೆಂ': 3, + 'ವ್': 2, + 'ಶಾಂ': 3, + 'ಶಿ': 2, + 'ಶ್': 2, + 'ಷಿ': 2, + 'ಷೆ': 2, + 'ಷ್': 2, + 'ಸಾಂ': 3, + 'ಸಿ': 2, + 'ಸೆ': 2, + 'ಸ್': 2, + 'ಹಿ': 2, + 'ಹೆ': 2, + 'ಹೊಂ': 3, + 'കു': 2, + 'കൂ': 2, + 'കൃ': 2, + 'ക്ക': 3, + 'ക്കാ': 4, + 'ക്കി': 4, + 'ക്കു': 4, + 'ക്കും': 5, + 'ക്കെ': 4, + 'ക്കേ': 4, + 'ക്കൊ': 4, + 'ക്കോ': 4, + 'ക്ക്‌': 4, + 'ക്തി': 4, + 'ക്യ': 3, + 'ക്യം': 4, + 'ക്ര': 3, + 'ക്രൂ': 4, + 'ക്ഷ': 3, + 'ക്ഷാ': 4, + 'ക്ഷി': 4, + 'ക്ഷേ': 4, + 'ഖ്യാ': 4, + 'ഗു': 2, + 'ഗ്ഗം': 4, + 'ഗ്ദാ': 4, + 'ഗ്യ': 3, + 'ഗ്യം': 4, + 'ഗ്ര': 3, + 'ങ്കി': 4, + 'ങ്കെ': 4, + 'ങ്കേ': 4, + 'ങ്ങ': 3, + 'ങ്ങി': 4, + 'ച്ച': 3, + 'ച്ചി': 4, + 'ച്ചു': 4, + 'ച്ചും': 5, + 'ച്ചെ': 4, + 'ച്ചേ': 4, + 'ജ്യ': 3, + 'ജ്യാ': 4, + 'ഞ്ച': 3, + 'ഞ്ഞ': 3, + 'ഞ്ഞി': 4, + 'ഞ്ഞെ': 4, + 'ടു': 2, + 'ടും': 3, + 'ട്ട': 3, + 'ട്ടാ': 4, + 'ട്ടി': 4, + 'ട്ടു': 4, + 'ട്ടോ': 4, + 'ട്‌': 2, + 'ണ്ട': 3, + 'ണ്ടാ': 4, + 'ണ്ടി': 4, + 'ണ്ടു': 4, + 'ണ്ടും': 5, + 'ണ്ടെ': 4, + 'ണ്ട്‌': 4, + 'ണ്ഡ': 3, + 'ണ്ണ': 3, + 'ണ്‌': 2, + 'തു': 2, + 'തും': 3, + 'തൃ': 2, + 'ത്ത': 3, + 'ത്താ': 4, + 'ത്തി': 4, + 'ത്തു': 4, + 'ത്തും': 5, + 'ത്തെ': 4, + 'ത്തേ': 4, + 'ത്തോ': 4, + 'ത്ത്‌': 4, + 'ത്ന': 3, + 'ത്നം': 4, + 'ത്നി': 4, + 'ത്യ': 3, + 'ത്യാ': 4, + 'ത്യേ': 4, + 'ത്ര': 3, + 'ത്വ': 3, + 'ത്വം': 4, + 'ത്‌': 2, + 'ദൃ': 2, + 'ദ്ദ': 3, + 'ദ്ധ': 3, + 'ദ്ധി': 4, + 'ദ്യ': 3, + 'ദ്യാ': 4, + 'ദ്ര': 3, + 'ധൂ': 2, + 'ധ്യ': 3, + 'നു': 2, + 'നും': 3, + 'ന്ത': 3, + 'ന്തം': 4, + 'ന്തെ': 4, + 'ന്ത്ര': 5, + 'ന്ത്ര്യ': 7, + 'ന്ത്ര്യം': 8, + 'ന്ഥ': 3, + 'ന്ദ': 3, + 'ന്ധ': 3, + 'ന്ധി': 4, + 'ന്ന': 3, + 'ന്നാ': 4, + 'ന്നി': 4, + 'ന്നീ': 4, + 'ന്നു': 4, + 'ന്നും': 5, + 'ന്നെ': 4, + 'ന്നേ': 4, + 'ന്നോ': 4, + 'ന്ന്': 4, + 'ന്മ': 3, + 'ന്മാ': 4, + 'ന്മു': 4, + 'ന്മൂ': 4, + 'ന്യ': 3, + 'ന്യം': 4, + 'ന്യാ': 4, + 'ന്യേ': 4, + 'ന്യോ': 4, + 'ന്റെ': 4, + 'ന്‌': 2, + 'ന്‍': 2, + 'ന്‍കൂ': 4, + 'ന്‍പി': 4, + 'പു': 2, + 'പൂ': 2, + 'പ്പ': 3, + 'പ്പി': 4, + 'പ്പു': 4, + 'പ്പെ': 4, + 'പ്പോ': 4, + 'പ്പ്‌': 4, + 'പ്ര': 3, + 'പ്രാ': 4, + 'ബു': 2, + 'ബ്ലി': 4, + 'ഭ്യാ': 4, + 'ഭ്രാ': 4, + 'മു': 2, + 'മൃ': 2, + 'മ്പ': 3, + 'മ്പാ': 4, + 'മ്പ്ര': 5, + 'മ്മ': 3, + 'മ്മി': 4, + 'യു': 2, + 'യും': 3, + 'യ്ക്കു': 6, + 'യ്തി': 4, + 'യ്തു': 4, + 'യ്മ': 3, + 'യ്യാ': 4, + 'യ്യി': 4, + 'രു': 2, + 'രും': 3, + 'രൂ': 2, + 'ര്യ': 3, + 'ര്യം': 4, + 'ര്‍ക്കു': 6, + 'ര്‍ക്കും': 7, + 'ര്‍ക്ക്‌': 6, + 'ര്‍ഗ്ഗം': 6, + 'ര്‍ച്ച': 5, + 'ര്‍ണ്ണ': 5, + 'ര്‍ത്ത': 5, + 'ര്‍ത്തി': 6, + 'ര്‍ത്തു': 6, + 'ര്‍ത്തേ': 6, + 'ര്‍ദേ': 4, + 'ര്‍ദ്ദ': 5, + 'ര്‍പ്പെ': 6, + 'ര്‍ബ': 3, + 'ര്‍ഭ': 3, + 'ര്‍മ്മി': 6, + 'ര്‍രാ': 4, + 'ര്‍വ്വ': 5, + 'ര്‍ഹ': 3, + 'ര്‍ഹി': 4, + 'റു': 2, + 'റ്റ': 3, + 'റ്റം': 4, + 'റ്റു': 4, + 'റ്റേ': 4, + 'ലു': 2, + 'ലും': 3, + 'ല്യ': 3, + 'ല്യാ': 4, + 'ല്ല': 3, + 'ല്ലാ': 4, + 'ല്ലാം': 5, + 'ല്ലെ': 4, + 'ല്‍': 2, + 'ല്‍കി': 4, + 'ല്‍കു': 4, + 'ല്‍കേ': 4, + 'ല്‍ത': 3, + 'ല്‍നി': 4, + 'ല്‍പ്പ': 5, + 'ളു': 2, + 'ളും': 3, + 'ള്ള': 3, + 'ള്ളാ': 4, + 'ള്ളി': 4, + 'ള്ളൂ': 4, + 'ള്‍': 2, + 'ള്‍കൊ': 4, + 'ള്‍ക്ക': 5, + 'ള്‍ക്കി': 6, + 'ള്‍ക്കു': 6, + 'ള്‍ക്കും': 7, + 'ള്‍ക്കെ': 6, + 'ള്‍ക്ക്‌': 6, + 'ഴു': 2, + 'വു': 2, + 'വും': 3, + 'വൃ': 2, + 'വ്യ': 3, + 'വ്യം': 4, + 'വ്യാ': 4, + 'വ്വ': 3, + 'ശു': 2, + 'ശ്യ': 3, + 'ശ്ര': 3, + 'ശ്വാ': 4, + 'ഷ്ട': 3, + 'ഷ്ട്യാ': 6, + 'ഷ്ട്ര': 5, + 'ഷ്ട്രീ': 6, + 'ഷ്ണു': 4, + 'ഷ്യ': 3, + 'ഷ്യാ': 4, + 'സാം': 3, + 'സു': 2, + 'സൃ': 2, + 'സ്കാ': 4, + 'സ്തു': 4, + 'സ്ത്രം': 6, + 'സ്ത്രീ': 6, + 'സ്ഥ': 3, + 'സ്ഥാ': 4, + 'സ്ഥി': 4, + 'സ്യ': 3, + 'സ്റ്റ്‌': 6, + 'സ്വ': 3, + 'സ്വാ': 4, + 'സ്വീ': 4, + 'സ്സ': 3, + 'സ്സാ': 4, + 'സ്സി': 4, + 'സ്സും': 5, + 'സ്സോ': 4, + 'ഹിം': 3, + 'ഹു': 2, + 'ഹൃ': 2, + 'ൻ്റെ': 4, + 'ක්': 2, + 'ක්‍': 2, + 'කි': 2, + 'කී': 2, + 'කු': 2, + 'කූ': 2, + 'ඛ්‍': 2, + 'ගි': 2, + 'ගී': 2, + 'ගු': 2, + 'ඟි': 2, + 'ඟී': 2, + 'ච්': 2, + 'චි': 2, + 'ජ්‍': 2, + 'ජි': 2, + 'ජී': 2, + 'ටි': 2, + 'ටී': 2, + 'ටු': 2, + 'ඩි': 2, + 'ඩු': 2, + 'ණ්': 2, + 'ණි': 2, + 'ණී': 2, + 'ණු': 2, + 'ඬු': 2, + 'ත්': 2, + 'ත්‍': 2, + 'ති': 2, + 'තී': 2, + 'තු': 2, + 'ථි': 2, + 'ද්': 2, + 'ද්‍': 2, + 'දි': 2, + 'දිං': 3, + 'දී': 2, + 'දු': 2, + 'ධ්‍': 2, + 'ධි': 2, + 'ධී': 2, + 'න්': 2, + 'න්‍': 2, + 'නි': 2, + 'නී': 2, + 'නු': 2, + 'ඳි': 2, + 'ඳී': 2, + 'ඳු': 2, + 'ප්': 2, + 'ප්‍': 2, + 'පි': 2, + 'පී': 2, + 'පු': 2, + 'පූ': 2, + 'බි': 2, + 'බී': 2, + 'භු': 2, + 'ම්': 2, + 'මි': 2, + 'මී': 2, + 'මු': 2, + 'මූ': 2, + 'ඹී': 2, + 'ඹු': 2, + 'යි': 2, + 'යු': 2, + 'ර්': 2, + 'රි': 2, + 'රී': 2, + 'රු': 2, + 'රූ': 2, + 'ල්': 2, + 'ලි': 2, + 'ලී': 2, + 'ලු': 2, + 'ව්': 2, + 'ව්‍': 2, + 'වි': 2, + 'වී': 2, + 'වු': 2, + 'වූ': 2, + 'ශ්': 2, + 'ශ්‍': 2, + 'ශී': 2, + 'ෂ්': 2, + 'ෂ්‍': 2, + 'ෂි': 2, + 'ස්': 2, + 'සි': 2, + 'සී': 2, + 'සු': 2, + 'හි': 2, + 'හිං': 3, + 'හී': 2, + 'හු': 2, + 'ළි': 2, + 'ළු': 2, + 'กั': 2, + 'กิ': 2, + 'กี': 2, + 'กุ': 2, + 'ก็': 2, + 'ก่': 2, + 'ก้': 2, + 'ขั': 2, + 'ขั้': 3, + 'ขี่': 3, + 'ขึ้': 3, + 'ขื': 2, + 'ข็': 2, + 'ข่': 2, + 'ข้': 2, + 'คั': 2, + 'คิ': 2, + 'คุ': 2, + 'คุ้': 3, + 'คู่': 3, + 'ค่': 2, + 'ค้': 2, + 'ค์': 2, + 'งิ': 2, + 'งื่': 3, + 'จั': 2, + 'จิ': 2, + 'จึ': 2, + 'จุ': 2, + 'จ็': 2, + 'จ่': 2, + 'จ้': 2, + 'ฉั': 2, + 'ชั้': 3, + 'ชิ': 2, + 'ชี': 2, + 'ชื่': 3, + 'ชื้': 3, + 'ชุ': 2, + 'ช่': 2, + 'ช้': 2, + 'ซี่': 3, + 'ซึ่': 3, + 'ญิ': 2, + 'ฎิ': 2, + 'ฏิ': 2, + 'ฒิ': 2, + 'ณิ': 2, + 'ณี': 2, + 'ณ์': 2, + 'ดั': 2, + 'ดั่': 3, + 'ดิ': 2, + 'ดิ์': 3, + 'ดี': 2, + 'ดู': 2, + 'ด็': 2, + 'ด้': 2, + 'ตั': 2, + 'ตั้': 3, + 'ติ': 2, + 'ตี': 2, + 'ตุ': 2, + 'ต็': 2, + 'ต่': 2, + 'ต่ำ': 3, + 'ต้': 2, + 'ถิ่': 3, + 'ถี': 2, + 'ถึ': 2, + 'ถื': 2, + 'ถื่': 3, + 'ถุ': 2, + 'ถู': 2, + 'ถ้': 2, + 'ทั': 2, + 'ทั่': 3, + 'ทั้': 3, + 'ทิ': 2, + 'ที': 2, + 'ที่': 3, + 'ทุ': 2, + 'ท่': 2, + 'ท้': 2, + 'ธั': 2, + 'ธิ': 2, + 'ธิ์': 3, + 'ธี': 2, + 'ธุ์': 3, + 'ธ์': 2, + 'นั': 2, + 'นั้': 3, + 'นิ': 2, + 'นี้': 3, + 'นึ': 2, + 'นึ่': 3, + 'นื': 2, + 'นื่': 3, + 'นุ': 2, + 'นุ่': 3, + 'นู': 2, + 'น่': 2, + 'น้': 2, + 'น์': 2, + 'บั': 2, + 'บั่': 3, + 'บิ': 2, + 'บี': 2, + 'บื้': 3, + 'บุ': 2, + 'บู': 2, + 'บ่': 2, + 'ปั': 2, + 'ปิ': 2, + 'ป็': 2, + 'ป่': 2, + 'ผิ': 2, + 'ผู้': 3, + 'ผ่': 2, + 'พั': 2, + 'พิ': 2, + 'พิ่': 3, + 'พี': 2, + 'พื่': 3, + 'พื้': 3, + 'พู': 2, + 'พ้': 2, + 'ภั': 2, + 'มั': 2, + 'มั่': 3, + 'มิ': 2, + 'มิ่': 3, + 'มี': 2, + 'มื': 2, + 'มุ่': 3, + 'มู': 2, + 'มู่': 3, + 'ม่': 2, + 'ม้': 2, + 'ยั': 2, + 'ยิ': 2, + 'ยิ่': 3, + 'ยี': 2, + 'ยึ': 2, + 'ยื': 2, + 'ยุ': 2, + 'ยู่': 3, + 'ย่': 2, + 'ย่ำ': 3, + 'ย้': 2, + 'ย์': 2, + 'รั': 2, + 'รั้': 3, + 'ริ': 2, + 'รี': 2, + 'รื': 2, + 'รื่': 3, + 'รุ': 2, + 'รู': 2, + 'ร็': 2, + 'ร่': 2, + 'ร้': 2, + 'ร์': 2, + 'ลั': 2, + 'ลิ': 2, + 'ลี่': 3, + 'ลี้': 3, + 'ลึ': 2, + 'ลื': 2, + 'ลื่': 3, + 'ลุ': 2, + 'ลุ่': 3, + 'ลู่': 3, + 'ล่': 2, + 'ล้': 2, + 'วั': 2, + 'วิ': 2, + 'วุ': 2, + 'ว่': 2, + 'ว้': 2, + 'ศั': 2, + 'ศิ': 2, + 'ศี': 2, + 'ศึ': 2, + 'ษ์': 2, + 'สั': 2, + 'สิ': 2, + 'สิ่': 3, + 'สิ้': 3, + 'สี': 2, + 'สื': 2, + 'สื่': 3, + 'สุ': 2, + 'สู': 2, + 'สู่': 3, + 'สู้': 3, + 'ส่': 2, + 'หั': 2, + 'ห็': 2, + 'ห่': 2, + 'ห้': 2, + 'อั': 2, + 'อิ': 2, + 'อี': 2, + 'อื่': 3, + 'อื้': 3, + 'อ้': 2, + 'ກັ': 2, + 'ກິ': 2, + 'ກີ': 2, + 'ກຸ': 2, + 'ກຸ່': 3, + 'ກົ': 2, + 'ກ່': 2, + 'ກ້': 2, + 'ກໍ': 2, + 'ກໍ່': 3, + 'ຂັ': 2, + 'ຂັ້': 3, + 'ຂີ່': 3, + 'ຂື້': 3, + 'ຂົ': 2, + 'ຂົ່': 3, + 'ຂົ້': 3, + 'ຂ່': 2, + 'ຂ້': 2, + 'ຂໍ': 2, + 'ຂໍ້': 3, + 'ຄັ': 2, + 'ຄິ': 2, + 'ຄື': 2, + 'ຄື່': 3, + 'ຄຸ': 2, + 'ຄຸ້': 3, + 'ຄູ່': 3, + 'ຄົ': 2, + 'ຄົ້': 3, + 'ຄ່': 2, + 'ຄ້': 2, + 'ງົ': 2, + 'ຈັ': 2, + 'ຈັ້': 3, + 'ຈິ': 2, + 'ຈື່': 3, + 'ຈຸ': 2, + 'ຈົ': 2, + 'ຈົ່': 3, + 'ຈົ້': 3, + 'ຈ່': 2, + 'ຈ້': 2, + 'ຊັ': 2, + 'ຊັ່': 3, + 'ຊັ້': 3, + 'ຊິ': 2, + 'ຊີ': 2, + 'ຊີ້': 3, + 'ຊື່': 3, + 'ຊື້': 3, + 'ຊຸ': 2, + 'ຊູ': 2, + 'ຊົ': 2, + 'ຊົ່': 3, + 'ຊ່': 2, + 'ຊ້': 2, + 'ຍິ': 2, + 'ຍີ່': 3, + 'ຍຸ': 2, + 'ຍົ': 2, + 'ຍ່': 2, + 'ຍ້': 2, + 'ດັ': 2, + 'ດັ່': 3, + 'ດິ': 2, + 'ດີ': 2, + 'ດົ': 2, + 'ດ້': 2, + 'ຕັ': 2, + 'ຕັ້': 3, + 'ຕິ': 2, + 'ຕີ': 2, + 'ຕົ': 2, + 'ຕົ້': 3, + 'ຕ່': 2, + 'ຕ້': 2, + 'ຕໍ່': 3, + 'ຖິ': 2, + 'ຖື': 2, + 'ຖື່': 3, + 'ຖຸ': 2, + 'ຖົ້': 3, + 'ຖ້': 2, + 'ທັ': 2, + 'ທິ': 2, + 'ທີ': 2, + 'ທີ່': 3, + 'ທຸ': 2, + 'ທົ່': 3, + 'ທ່': 2, + 'ທ້': 2, + 'ທໍ': 2, + 'ນັ': 2, + 'ນັ້': 3, + 'ນິ': 2, + 'ນີ': 2, + 'ນີ້': 3, + 'ນື': 2, + 'ນື່': 3, + 'ນື້': 3, + 'ນຸ': 2, + 'ນຸ່': 3, + 'ນູ': 2, + 'ນົ': 2, + 'ນ້': 2, + 'ບັ': 2, + 'ບີ': 2, + 'ບຸ': 2, + 'ບູ': 2, + 'ບົ': 2, + 'ບ່': 2, + 'ບໍ': 2, + 'ບໍ່': 3, + 'ປັ': 2, + 'ປີ': 2, + 'ປົ': 2, + 'ປ່': 2, + 'ປ້': 2, + 'ຜັ': 2, + 'ຜິ': 2, + 'ຜີ': 2, + 'ຜູ້': 3, + 'ຜົ': 2, + 'ຜ່': 2, + 'ພັ': 2, + 'ພິ': 2, + 'ພີ': 2, + 'ພີ່': 3, + 'ພຶ': 2, + 'ພື່': 3, + 'ພູ': 2, + 'ພົ': 2, + 'ພົ້': 3, + 'ພ້': 2, + 'ພໍ': 2, + 'ພໍ່': 3, + 'ຟັ': 2, + 'ຟ້': 2, + 'ມັ': 2, + 'ມິ': 2, + 'ມີ': 2, + 'ມື': 2, + 'ມື່': 3, + 'ມຸ້': 3, + 'ມູ': 2, + 'ມົ': 2, + 'ມ່': 2, + 'ຢັ': 2, + 'ຢື': 2, + 'ຢູ່': 3, + 'ຢູ້': 3, + 'ຢ່': 2, + 'ຢ້': 2, + 'ລັ': 2, + 'ລິ': 2, + 'ລີ': 2, + 'ລື': 2, + 'ລຸ': 2, + 'ລຸ້': 3, + 'ລູ': 2, + 'ລົ': 2, + 'ລ້': 2, + 'ວັ': 2, + 'ວັ່': 3, + 'ວິ': 2, + 'ວຸ': 2, + 'ວົ': 2, + 'ວົ້': 3, + 'ວ່': 2, + 'ວ້': 2, + 'ສັ': 2, + 'ສິ': 2, + 'ສີ່': 3, + 'ສີ້': 3, + 'ສຶ': 2, + 'ສື': 2, + 'ສຸ': 2, + 'ສູ້': 3, + 'ສົ': 2, + 'ສ່': 2, + 'ສ້': 2, + 'ຫັ': 2, + 'ຫຼ': 2, + 'ຫຼັ': 3, + 'ຫຼິ': 3, + 'ຫຼື': 3, + 'ຫຼົ': 3, + 'ຫຼົ່': 4, + 'ຫ່': 2, + 'ຫ້': 2, + 'ອັ': 2, + 'ອິ': 2, + 'ອີ': 2, + 'ອື່': 3, + 'ອຸ': 2, + 'ອົ': 2, + 'ອ່': 2, + 'ອ້': 2, + 'ຮັ': 2, + 'ຮີ': 2, + 'ຮູ້': 3, + 'ຮົ': 2, + 'ຮົ່': 3, + 'ຮ່': 2, + 'ຮ້': 2, + 'ໜັ': 2, + 'ໜີ່': 3, + 'ໜື່': 3, + 'ໜູ': 2, + 'ໜ່': 2, + 'ໜ້': 2, + 'ໝັ້': 3, + 'ໝີ': 2, + 'ໝູ່': 3, + 'ໝ່': 2, + 'ໝ້': 2, + 'ཀུ': 2, + 'ཀོ': 2, + 'ཀྱ': 2, + 'ཀྱི': 3, + 'ཀླ': 2, + 'ཀློ': 3, + 'ཁུ': 2, + 'ཁེ': 2, + 'ཁོ': 2, + 'ཁྱ': 2, + 'ཁྱི': 3, + 'ཁྲི': 3, + 'ཁྲོ': 3, + 'གི': 2, + 'གུ': 2, + 'གེ': 2, + 'གོ': 2, + 'གྱ': 2, + 'གྱི': 3, + 'གྱུ': 3, + 'གྱོ': 3, + 'གྲ': 2, + 'གྲི': 3, + 'གྲུ': 3, + 'གྲེ': 3, + 'གྲོ': 3, + 'གླ': 2, + 'གླི': 3, + 'གླེ': 3, + 'ངུ': 2, + 'ངེ': 2, + 'ངོ': 2, + 'ཅི': 2, + 'ཅུ': 2, + 'ཅོ': 2, + 'ཆུ': 2, + 'ཆེ': 2, + 'ཆོ': 2, + 'ཇི': 2, + 'ཇུ': 2, + 'ཇོ': 2, + 'ཉི': 2, + 'ཉེ': 2, + 'ཉོ': 2, + 'ཏུ': 2, + 'ཏེ': 2, + 'ཏོ': 2, + 'ཐི': 2, + 'ཐུ': 2, + 'ཐེ': 2, + 'ཐོ': 2, + 'དི': 2, + 'དུ': 2, + 'དེ': 2, + 'དོ': 2, + 'དྲ': 2, + 'དྲི': 3, + 'དྲུ': 3, + 'དྲོ': 3, + 'ནི': 2, + 'ནུ': 2, + 'ནོ': 2, + 'པེ': 2, + 'པོ': 2, + 'པྱ': 2, + 'པྱོ': 3, + 'ཕེ': 2, + 'ཕོ': 2, + 'ཕྱི': 3, + 'ཕྱེ': 3, + 'ཕྱོ': 3, + 'ཕྲུ': 3, + 'ཕྲོ': 3, + 'བུ': 2, + 'བེ': 2, + 'བོ': 2, + 'བྱ': 2, + 'བྱི': 3, + 'བྱུ': 3, + 'བྱེ': 3, + 'བྱོ': 3, + 'བྲ': 2, + 'བྲེ': 3, + 'བླ': 2, + 'བློ': 3, + 'མི': 2, + 'མེ': 2, + 'མོ': 2, + 'མྱོ': 3, + 'ཙུ': 2, + 'ཙོ': 2, + 'ཚུ': 2, + 'ཚེ': 2, + 'ཚོ': 2, + 'ཛི': 2, + 'ཛུ': 2, + 'ཛོ': 2, + 'ཞི': 2, + 'ཞུ': 2, + 'ཟི': 2, + 'ཟུ': 2, + 'ཟེ': 2, + 'ཟོ': 2, + 'ཟླ': 2, + 'ཟློ': 3, + 'འི': 2, + 'འུ': 2, + 'འོ': 2, + 'ཡི': 2, + 'ཡུ': 2, + 'ཡོ': 2, + 'རི': 2, + 'རུ': 2, + 'རེ': 2, + 'རོ': 2, + 'རྐྱ': 3, + 'རྐྱེ': 4, + 'རྒ': 2, + 'རྒོ': 3, + 'རྒྱ': 3, + 'རྒྱུ': 4, + 'རྗེ': 3, + 'རྗོ': 3, + 'རྟ': 2, + 'རྟེ': 3, + 'རྟོ': 3, + 'རྡ': 2, + 'རྣ': 2, + 'རྩ': 2, + 'རྩི': 3, + 'རྩུ': 3, + 'རྩོ': 3, + 'རྫ': 2, + 'ལཱ': 2, + 'ལུ': 2, + 'ལེ': 2, + 'ལོ': 2, + 'ལྔ': 2, + 'ལྕི': 3, + 'ལྕོ': 3, + 'ལྟ': 2, + 'ལྟེ': 3, + 'ལྡ': 2, + 'ལྡེ': 3, + 'ལྷ': 2, + 'ལྷུ': 3, + 'ལྷོ': 3, + 'ཤི': 2, + 'ཤུ': 2, + 'ཤེ': 2, + 'ཤོ': 2, + 'སུ': 2, + 'སེ': 2, + 'སོ': 2, + 'སྐ': 2, + 'སྐི': 3, + 'སྐུ': 3, + 'སྐོ': 3, + 'སྐྱ': 3, + 'སྐྱི': 4, + 'སྐྱུ': 4, + 'སྐྱེ': 4, + 'སྐྱོ': 4, + 'སྒེ': 3, + 'སྒོ': 3, + 'སྒྱུ': 4, + 'སྒྲ': 3, + 'སྒྲི': 4, + 'སྒྲུ': 4, + 'སྔ': 2, + 'སྔོ': 3, + 'སྙི': 3, + 'སྟ': 2, + 'སྟུ': 3, + 'སྟེ': 3, + 'སྟོ': 3, + 'སྡ': 2, + 'སྡི': 3, + 'སྡུ': 3, + 'སྡེ': 3, + 'སྡོ': 3, + 'སྣ': 2, + 'སྣོ': 3, + 'སྤུ': 3, + 'སྤེ': 3, + 'སྤྱ': 3, + 'སྤྱི': 4, + 'སྤྱོ': 4, + 'སྤྲ': 3, + 'སྤྲོ': 4, + 'སྦེ': 3, + 'སྦྱ': 3, + 'སྦྱི': 4, + 'སྦྱོ': 4, + 'སྦྲེ': 4, + 'སྨ': 2, + 'སྨྲ': 3, + 'སྲ': 2, + 'སྲི': 3, + 'སྲུ': 3, + 'སྲོ': 3, + 'སླ': 2, + 'སློ': 3, + 'ཧྲི': 3, + 'ཧྲེ': 3, + 'ཨི': 2, + 'ཨུ': 2, + 'ကိ': 2, + 'ကို': 3, + 'ကီု': 3, + 'ကု': 2, + 'ကူ': 2, + 'ကေု': 3, + 'ကဲ့': 3, + 'ကဵု': 3, + 'ကံ': 2, + 'က္က': 3, + 'က္ခ': 3, + 'က္ဍ': 3, + 'က္ဍို': 5, + 'က်': 2, + 'က်ျ': 3, + 'ကျို': 4, + 'ကျူ': 3, + 'ကျေ': 3, + 'ကျွ': 3, + 'ကြို': 4, + 'ကြီ': 3, + 'ကြု': 3, + 'ကြေ': 3, + 'ကြံ': 3, + 'ကြွေ': 4, + 'ကွ': 2, + 'ကၟ': 2, + 'ကၟိ': 3, + 'ကၟို': 4, + 'ကၟဲ': 3, + 'ကၠ': 2, + 'ကၠို': 4, + 'ကၠီု': 4, + 'ကၠု': 3, + 'ကၠေ': 3, + 'ကၠေံ': 4, + 'ကၠဳ': 3, + 'ခိ': 2, + 'ခို': 3, + 'ခု': 2, + 'ခဲ့': 3, + 'ခဳ': 2, + 'ခံ': 2, + 'ချိ': 3, + 'ချို': 4, + 'ချို့': 5, + 'ချီ': 3, + 'ချု': 3, + 'ချေ': 3, + 'ချဳ': 3, + 'ခြုံ': 4, + 'ခြေ': 3, + 'ခွ': 2, + 'ခွဲ': 3, + 'ခၞံ': 3, + 'ခၠ': 2, + 'ဂိ': 2, + 'ဂို': 3, + 'ဂီု': 3, + 'ဂု': 2, + 'ဂဵု': 3, + 'ဂ္ဂ': 3, + 'ဂ္ဂို': 5, + 'ဂျို': 4, + 'ဂွံ': 3, + 'ဂှ်': 3, + 'ဂၞ': 2, + 'ဂၞဴ': 3, + 'ဂၟံ': 3, + 'ဂၠ': 2, + 'ဂၠိ': 3, + 'ဂၠို': 4, + 'ဂၠေ': 3, + 'ဂၠံ': 3, + 'ငိ': 2, + 'ငို': 3, + 'ငဲ့': 3, + 'ငံ': 2, + 'င့်': 3, + 'င်': 2, + 'င်္ဂ': 4, + 'ငြိ': 3, + 'ငွေ': 3, + 'ငှ': 2, + 'စိ': 2, + 'စို': 3, + 'စီ': 2, + 'စု': 2, + 'စုံ': 3, + 'စဳ': 2, + 'စဴ': 2, + 'စဵု': 3, + 'စံ': 2, + 'စ္စ': 3, + 'စ်': 2, + 'စွ': 2, + 'စွဲ': 3, + 'စွံ': 3, + 'စှ်': 3, + 'စှ်ေ': 4, + 'စၞ': 2, + 'စၞေ': 3, + 'စၟ': 2, + 'စၠေ': 3, + 'ဆို': 3, + 'ဆီ': 2, + 'ဆုဲ': 3, + 'ဆုံ': 3, + 'ဆံ': 2, + 'ဆွဲ': 3, + 'ဇို': 3, + 'ဇူ': 2, + 'ဇြေ': 3, + 'ဇြဳ': 3, + 'ဇၞ': 2, + 'ဇၞေ': 3, + 'ဇၟ': 2, + 'ဉ်': 2, + 'ညိ': 2, + 'ညီ': 2, + 'ညဳ': 2, + 'ညံ': 2, + 'ည်': 2, + 'ည့်': 3, + 'ညှ': 2, + 'ဋိ': 2, + 'ဋ္ဌ': 3, + 'ဍိ': 2, + 'ဍို': 3, + 'ဍု': 2, + 'ဍဵု': 3, + 'ဏီ': 2, + 'ဏံ': 2, + 'ဏ်': 2, + 'ဏှ': 2, + 'တိ': 2, + 'တို': 3, + 'တို့': 4, + 'တိူ': 3, + 'တီ': 2, + 'တု': 2, + 'တုဲ': 3, + 'တူ': 2, + 'တေံ': 3, + 'တဲ': 2, + 'တဴ': 2, + 'တဵ': 2, + 'တံ': 2, + 'တံ့': 3, + 'တ္တ': 3, + 'တ္ၚဲ': 4, + 'တ်': 2, + 'တ်ို': 4, + 'တြုံ': 4, + 'တွ': 2, + 'တွေ': 3, + 'တွဵု': 4, + 'တှ်ေ': 4, + 'တၞ': 2, + 'တၟ': 2, + 'တၟိ': 3, + 'တၟို': 4, + 'တၟေ': 3, + 'တၟံ': 3, + 'တၠု': 3, + 'တႂ်': 3, + 'တႅ': 2, + 'ထိ': 2, + 'ထို': 3, + 'ထို့': 4, + 'ထီ': 2, + 'ထု': 2, + 'ထုဲ': 3, + 'ထူ': 2, + 'ထဵ': 2, + 'ထံ': 2, + 'ထ္ၜ': 3, + 'ထွ': 2, + 'ထွေ': 3, + 'ဒို': 3, + 'ဒီ': 2, + 'ဒီု': 3, + 'ဒု': 2, + 'ဒေံ': 3, + 'ဒဳ': 2, + 'ဒဵု': 3, + 'ဒ္ဂေ': 4, + 'ဒ်': 2, + 'ဒှ်': 3, + 'ဒၞ': 2, + 'ဒၟံ': 3, + 'ဓိ': 2, + 'ဓု': 2, + 'နိ': 2, + 'နို': 3, + 'နု': 2, + 'နူ': 2, + 'နေ့': 3, + 'န္ဒ': 3, + 'န္နိ': 4, + 'န်': 2, + 'န့်': 3, + 'နွ': 2, + 'နွံ': 3, + 'နှ': 2, + 'နှိ': 3, + 'နှီ': 3, + 'နှေ': 3, + 'ပိ': 2, + 'ပို': 3, + 'ပိုဲ': 4, + 'ပိူ': 3, + 'ပီ': 2, + 'ပု': 2, + 'ပုံ': 3, + 'ပူ': 2, + 'ပေဲ': 3, + 'ပဲ': 2, + 'ပဵ': 2, + 'ပံ': 2, + 'ပံ့': 3, + 'ပ္ဍဲ': 4, + 'ပ္တံ': 4, + 'ပ္ပ': 3, + 'ပ္ပံ': 4, + 'ပ်': 2, + 'ပျေ': 3, + 'ပျဲ': 3, + 'ပြီ': 3, + 'ပြု': 3, + 'ပြေ': 3, + 'ပြဳ': 3, + 'ပြံ': 3, + 'ပွ': 2, + 'ပွဲ': 3, + 'ပွႆ': 3, + 'ပၟိ': 3, + 'ပၠ': 2, + 'ပႂ်': 3, + 'ပႅ': 2, + 'ပႆ': 2, + 'ဖိ': 2, + 'ဖီ': 2, + 'ဖဵု': 3, + 'ဖံ': 2, + 'ဖျု': 3, + 'ဖျေံ': 4, + 'ဖြို': 4, + 'ဖွ': 2, + 'ဖွဲ့': 4, + 'ဖွံ့': 4, + 'ဗီု': 3, + 'ဗု': 2, + 'ဗ္တေ': 4, + 'ဗ္ၜေ': 4, + 'ဗျဵု': 4, + 'ဗြေ': 3, + 'ဗြဴ': 3, + 'ဗွို': 4, + 'ဗွဲ': 3, + 'ဗၠ': 2, + 'ဗၠေ': 3, + 'ဘူ': 2, + 'ဘဲ': 2, + 'ဘဴ': 2, + 'မိ': 2, + 'မို': 3, + 'မိူ': 3, + 'မီ': 2, + 'မု': 2, + 'မူ': 2, + 'မဲ': 2, + 'မဲ့': 3, + 'မဳ': 2, + 'မဵု': 3, + 'မံ': 2, + 'မ္ဂ': 3, + 'မ္တီ': 4, + 'မ္ဘ': 3, + 'မ္မ': 3, + 'မ္ၚဵု': 5, + 'မ်': 2, + 'မ့်': 3, + 'မျို': 4, + 'မျီု': 4, + 'မျှ': 3, + 'မြေ': 3, + 'မြှ': 3, + 'မွ': 2, + 'မွေ': 3, + 'မွေ့': 4, + 'မွဲ': 3, + 'မှ': 2, + 'မှီ': 3, + 'မှု': 3, + 'မှေ': 3, + 'မၞိ': 3, + 'မၞု': 3, + 'မၞုံ': 4, + 'မၠို': 4, + 'မၠေ': 3, + 'မႂ်': 3, + 'မႅ': 2, + 'မႆ': 2, + 'ယိ': 2, + 'ယို': 3, + 'ယိူ': 3, + 'ယု': 2, + 'ယုံ': 3, + 'ယူ': 2, + 'ယဲ': 2, + 'ယဵ': 2, + 'ယံ': 2, + 'ယ်': 2, + 'ယျဵု': 4, + 'ယြဴ': 3, + 'ယွ': 2, + 'ယှ': 2, + 'ယႂ်': 3, + 'ယႅ': 2, + 'ရို': 3, + 'ရီု': 3, + 'ရု': 2, + 'ရုဲ': 3, + 'ရုံ': 3, + 'ရူ': 2, + 'ရေံ': 3, + 'ရဲ': 2, + 'ရဴ': 2, + 'ရံ': 2, + 'ရ်': 2, + 'ရွ': 2, + 'ရွေ': 3, + 'ရွံ့': 4, + 'ရွှေ့': 5, + 'ရှ': 2, + 'ရှိ': 3, + 'ရှေ': 3, + 'ရှေ့': 4, + 'ရှ်ေ': 4, + 'လိ': 2, + 'လို': 3, + 'လို့': 4, + 'လိူ': 3, + 'လီ': 2, + 'လီု': 3, + 'လု': 2, + 'လုံ': 3, + 'လူ': 2, + 'လူ့': 3, + 'လဲ': 2, + 'လဵ': 2, + 'လဵု': 3, + 'လံ': 2, + 'လ္ပ': 3, + 'လ္ၚ': 3, + 'လ်': 2, + 'လျို': 4, + 'လျေ': 3, + 'လျှ': 3, + 'လျှို့': 6, + 'လျှေ': 4, + 'လွ': 2, + 'လွဳ': 3, + 'လွှ': 3, + 'လွှဲ': 4, + 'လှ': 2, + 'လှုံ': 4, + 'လၟေ': 3, + 'လႂ်': 3, + 'လႅ': 2, + 'လႆ': 2, + 'ဝူ': 2, + 'ဝဲ': 2, + 'ဝဳ': 2, + 'ဝဵု': 3, + 'ဝ်': 2, + 'ဝွံ': 3, + 'ဝှ': 2, + 'ဝႆ': 2, + 'သိ': 2, + 'သို': 3, + 'သို့': 4, + 'သိူ': 3, + 'သီ': 2, + 'သီု': 3, + 'သု': 2, + 'သုံ': 3, + 'သူ': 2, + 'သူ့': 3, + 'သဳ': 2, + 'သဵ': 2, + 'သဵု': 3, + 'သ္က': 3, + 'သ္ကံ': 4, + 'သ္ဂု': 4, + 'သ္ဂေ': 4, + 'သ္ဇို': 5, + 'သ္ဒ': 3, + 'သ္ပ': 3, + 'သ္ၚိ': 4, + 'သ်': 2, + 'သြို': 4, + 'သွ': 2, + 'သွံ': 3, + 'သှ်': 3, + 'သှ်ေ': 4, + 'သၞ': 2, + 'သၞေ': 3, + 'သၟ': 2, + 'သၠ': 2, + 'သၠု': 3, + 'သႂ်': 3, + 'သႅ': 2, + 'ဟို': 3, + 'ဟီု': 3, + 'ဟု': 2, + 'ဟူ': 2, + 'ဟ်': 2, + 'ဟွံ': 3, + 'အိ': 2, + 'အို': 3, + 'အု': 2, + 'အံ': 2, + 'အ်': 2, + 'ဢိ': 2, + 'ဢို': 3, + 'ဢွ': 2, + 'ဿီု': 3, + 'ၚု': 2, + 'ၚ်': 2, + 'ၜို': 3, + 'ၵိ': 2, + 'ၵို': 3, + 'ၵိူ': 3, + 'ၵု': 2, + 'ၵူ': 2, + 'ၵဵ': 2, + 'ၵ်': 2, + 'ၵွ': 2, + 'ၵႂ': 2, + 'ၵႅ': 2, + 'ၶိ': 2, + 'ၶို': 3, + 'ၶိူ': 3, + 'ၶီ': 2, + 'ၶု': 2, + 'ၶူ': 2, + 'ၶွ': 2, + 'ၶႂ': 2, + 'ၶႅ': 2, + 'ၶႆ': 2, + 'ၸိ': 2, + 'ၸို': 3, + 'ၸိူ': 3, + 'ၸု': 2, + 'ၸူ': 2, + 'ၸဵ': 2, + 'ၸွ': 2, + 'ၸွႆ': 3, + 'ၸႂ်': 3, + 'ၸႅ': 2, + 'ၺ်': 2, + 'ၺွ': 2, + 'ၼို': 3, + 'ၼိူ': 3, + 'ၼု': 2, + 'ၼဵ': 2, + 'ၼ်': 2, + 'ၼွ': 2, + 'ၼႂ်': 3, + 'ၼႆ': 2, + 'ၽိ': 2, + 'ၽို': 3, + 'ၽု': 2, + 'ၽူ': 2, + 'ၽဵ': 2, + 'ၽွ': 2, + 'ၽႂ်': 3, + 'ၾိ': 2, + 'ႁို': 3, + 'ႁိူ': 3, + 'ႁု': 2, + 'ႁူ': 2, + 'ႁဵ': 2, + 'ႁွ': 2, + 'ႁႂ်': 3, + 'ႁႅ': 2, + 'ᜄ᜔': 2, + 'ᜆᜒ': 2, + 'ᜆ᜔': 2, + 'ᜇᜒ': 2, + 'ᜇᜓ': 2, + 'ᜇ᜔': 2, + 'ᜈᜒ': 2, + 'ᜈ᜔': 2, + 'ᜉᜒ': 2, + 'ᜊᜓ': 2, + 'ᜋ᜔': 2, + 'ᜌ᜔': 2, + 'ᜎᜓ': 2, + 'ᜏᜒ': 2, + 'ᜐᜒ': 2, + 'ᜑᜒ': 2, + 'កិ': 2, + 'កុ': 2, + 'កុំ': 3, + 'កំ': 2, + 'ក់': 2, + 'ក៏': 2, + 'ក្ខ': 3, + 'ក្ដិ': 4, + 'ក្ដី': 4, + 'ក្ដៅ': 4, + 'ក្នុ': 4, + 'ក្រ': 3, + 'ក្រុ': 4, + 'ក្រោ': 4, + 'ក្ស': 3, + 'ក្សា': 4, + 'ខិ': 2, + 'ខុ': 2, + 'ខំ': 2, + 'ខ្ជា': 4, + 'ខ្ព': 3, + 'ខ្លា': 4, + 'ខ្លួ': 4, + 'គាំ': 3, + 'គិ': 2, + 'គឺ': 2, + 'គំ': 2, + 'គ៌': 2, + 'គ្គ': 3, + 'គ្នា': 4, + 'គ្មា': 4, + 'គ្រ': 3, + 'គ្រា': 4, + 'គ្រឹះ': 5, + 'គ្រួ': 4, + 'ឃុំ': 3, + 'ឃ្ន': 3, + 'ងឺ': 2, + 'ង់': 2, + 'ង្ក': 3, + 'ង្កើ': 4, + 'ង្ខិ': 4, + 'ង្ខំ': 4, + 'ង្គ': 3, + 'ង្រី': 4, + 'ង្រឹ': 4, + 'ង្រៀ': 4, + 'ង្ហា': 4, + 'ង្អ': 3, + 'ចាំ': 3, + 'ចិ': 2, + 'ចុ': 2, + 'ចូ': 2, + 'ចំ': 2, + 'ច់': 2, + 'ច្ច': 3, + 'ច្ចេ': 4, + 'ច្បា': 4, + 'ឆាំ': 3, + 'ឆ្នាំ': 5, + 'ឆ្នោ': 4, + 'ឆ្ល': 3, + 'ឆ្លើ': 4, + 'ជិ': 2, + 'ជី': 2, + 'ជុំ': 3, + 'ជំ': 2, + 'ជ្ជ': 3, + 'ជ្ជា': 4, + 'ជ្ញា': 4, + 'ជ្យ': 3, + 'ជ្រ': 3, + 'ជ្រើ': 4, + 'ជ្រៀ': 4, + 'ជ្រែ': 4, + 'ឈ្មោះ': 5, + 'ញុះ': 3, + 'ញ្ចូ': 4, + 'ញ្ជា': 4, + 'ញ្ញ': 3, + 'ញ្ញា': 4, + 'ញ្ញៈ': 4, + 'ដី': 2, + 'ដឹ': 2, + 'ដូ': 2, + 'ដំ': 2, + 'ដ៏': 2, + 'ដ្ឋ': 3, + 'ដ្ឋា': 4, + 'ឌ្ឍ': 3, + 'ណិ': 2, + 'ណី': 2, + 'ណោះ': 3, + 'ណ៌': 2, + 'ណ៍': 2, + 'ណ្ដា': 4, + 'ណ្ដុះ': 5, + 'ណ្ឌ': 3, + 'ណ្ណោះ': 5, + 'តិ': 2, + 'តី': 2, + 'តុ': 2, + 'តំ': 2, + 'ត់': 2, + 'ត់់': 3, + 'ត៌': 2, + 'ត្ដ': 3, + 'ត្ដិ': 4, + 'ត្ថ': 3, + 'ត្ថិ': 4, + 'ត្យ': 3, + 'ត្រ': 3, + 'ត្រា': 4, + 'ត្រឹ': 4, + 'ត្រូ': 4, + 'ត្ស': 3, + 'ថ្ងៃ': 4, + 'ថ្នា': 4, + 'ថ្នូ': 4, + 'ថ្មី': 4, + 'ថ្លៃ': 4, + 'ទាំ': 3, + 'ទិ': 2, + 'ទិ៍': 3, + 'ទី': 2, + 'ទឹ': 2, + 'ទុ': 2, + 'ទូ': 2, + 'ទួ': 2, + 'ទោះ': 3, + 'ទំ': 2, + 'ទ្ធ': 3, + 'ទ្ធិ': 4, + 'ទ្យា': 4, + 'ទ្រ': 3, + 'ធិ': 2, + 'ធី': 2, + 'ធ្ង': 3, + 'ធ្នា': 4, + 'ធ្នូ': 4, + 'ធ្យា': 4, + 'ធ្យោ': 4, + 'ធ្វើ': 4, + 'នាំ': 3, + 'និ': 2, + 'នី': 2, + 'នឹ': 2, + 'នុ': 2, + 'នូ': 2, + 'នួ': 2, + 'នេះ': 3, + 'នោះ': 3, + 'ន់': 2, + 'ន៍': 2, + 'ន្ដ': 3, + 'ន្ដិ': 4, + 'ន្ថែ': 4, + 'ន្ថោ': 4, + 'ន្ទា': 4, + 'ន្ទៈ': 4, + 'ន្ធ': 3, + 'ន្និ': 4, + 'ន្ម': 3, + 'ន្យា': 4, + 'ន្លែ': 4, + 'បិ': 2, + 'បី': 2, + 'បុ': 2, + 'បូ': 2, + 'បោះ': 3, + 'បំ': 2, + 'ប៉ុ': 3, + 'ប៉ះ': 3, + 'ប់': 2, + 'ប្ដី': 4, + 'ប្ដូ': 4, + 'ប្ដេ': 4, + 'ប្ប': 3, + 'ប្បី': 4, + 'ប្រ': 3, + 'ប្រា': 4, + 'ប្រឹ': 4, + 'ប្រុ': 4, + 'ប្រើ': 4, + 'ប្រែ': 4, + 'ប្អូ': 4, + 'ផុ': 2, + 'ផ្ដ': 3, + 'ផ្ដា': 4, + 'ផ្ទា': 4, + 'ផ្ទុ': 4, + 'ផ្ទេ': 4, + 'ផ្នែ': 4, + 'ផ្លា': 4, + 'ផ្លិ': 4, + 'ផ្ស': 3, + 'ផ្សា': 4, + 'ផ្សេ': 4, + 'ផ្សៃ': 4, + 'ពិ': 2, + 'ពី': 2, + 'ពុ': 2, + 'ពូ': 2, + 'ពោះ': 3, + 'ព័': 2, + 'ព្យ': 3, + 'ព្យា': 4, + 'ព្រ': 3, + 'ព្រឹ': 4, + 'ព្រៀ': 4, + 'ព្រៃ': 4, + 'ព្រំ': 4, + 'ព្វ': 3, + 'ភិ': 2, + 'ភ័': 2, + 'មិ': 2, + 'មុ': 2, + 'មូ': 2, + 'មួ': 2, + 'ម៉ា': 3, + 'ម៉ោ': 3, + 'ម៌': 2, + 'ម័': 2, + 'ម្ងា': 4, + 'ម្ចា': 4, + 'ម្ដា': 4, + 'ម្ដែ': 4, + 'ម្នា': 4, + 'ម្នេ': 4, + 'ម្ប': 3, + 'ម្បី': 4, + 'ម្បុ': 4, + 'ម្ភា': 4, + 'ម្ម': 3, + 'ម្រ': 3, + 'ម្រា': 4, + 'ម្រិ': 4, + 'ម្រូ': 4, + 'ម្រើ': 4, + 'ម្រេ': 4, + 'ម្លៀ': 4, + 'ម្លៃ': 4, + 'យុ': 2, + 'យ៉ា': 3, + 'យ្យ': 3, + 'រាំ': 3, + 'រិ': 2, + 'រី': 2, + 'រុ': 2, + 'រូ': 2, + 'រួ': 2, + 'រំ': 2, + 'រ្ដិ៍': 5, + 'លិ': 2, + 'លុះ': 3, + 'លូ': 2, + 'លំ': 2, + 'ល់': 2, + 'ល្បៈ': 4, + 'ល្មើ': 4, + 'វិ': 2, + 'សិ': 2, + 'សី': 2, + 'សុ': 2, + 'សុំ': 3, + 'សំ': 2, + 'ស់': 2, + 'ស័': 2, + 'ស្គា': 4, + 'ស្ដី': 4, + 'ស្ដ្រី': 6, + 'ស្ត្រ': 5, + 'ស្ថា': 4, + 'ស្ថិ': 4, + 'ស្ទួ': 4, + 'ស្នា': 4, + 'ស្មា': 4, + 'ស្មើ': 4, + 'ស្រ': 3, + 'ស្រា': 4, + 'ស្រី': 4, + 'ស្រ័': 4, + 'ស្លា': 4, + 'ស្វែ': 4, + 'ស្វ័': 4, + 'ស្ស': 3, + 'ហូ': 2, + 'ហ៍': 2, + 'ហ្ម': 3, + 'ឡុ': 2, + 'អំ': 2, + 'អ្ន': 3, + 'អ្វី': 4, + 'ឱ្យ': 3, + 'ᨠ᩠ᨠ': 3, + 'ᨠ᩠ᨦᩢᩢ': 5, + 'ᨠ᩠ᨦᩨ᩵': 5, + 'ᨠ᩠ᨭᩫ': 4, + 'ᨠ᩠ᨯᩢ': 4, + 'ᨠ᩠ᨶᩢ': 4, + 'ᨠ᩠ᨶᩥ': 4, + 'ᨠ᩠ᩅ': 3, + 'ᨠ᩠ᩅᩢ': 4, + 'ᨠ᩠ᩅᩫ': 4, + 'ᨠ᩠ᩋ᩵': 4, + 'ᨠᩢ': 2, + 'ᨠᩢ᩠ᨷ': 4, + 'ᨠᩥ': 2, + 'ᨠᩩ': 2, + 'ᨠᩮ᩠ᨯᩨ': 5, + 'ᨠᩮᩢ᩵': 4, + 'ᨠᩮ᩵': 3, + 'ᨠᩯ᩠ᨯ': 4, + 'ᨠᩯ᩠ᨶ᩵': 5, + 'ᨠᩯ᩵': 3, + 'ᨠᩳ᩵': 3, + 'ᨠ᩵': 2, + 'ᨠ᩵ᩴ': 3, + 'ᨡ᩠ᨦᩢ': 4, + 'ᨡ᩠ᨯᩢ': 4, + 'ᨡ᩠ᨶ': 3, + 'ᨡ᩠ᨶᩢ': 4, + 'ᨡ᩠ᨶᩨ᩶': 5, + 'ᨡ᩠ᩅ': 3, + 'ᨡ᩠ᩋ': 3, + 'ᨡᩢ': 2, + 'ᨡᩮ᩠ᨲ': 4, + 'ᨡᩮᩢ': 3, + 'ᨡᩮᩢᩢ': 4, + 'ᨡᩯ᩠ᨠ': 4, + 'ᨡᩯ᩠ᨦ': 4, + 'ᨡᩱᩢ': 3, + 'ᨡᩳ᩶': 3, + 'ᨡ᩵': 2, + 'ᨣᩕ᩠ᩋ': 4, + 'ᨣᩕᩮ᩠ᨦᩨ᩵': 7, + 'ᨣ᩠ᨣ': 3, + 'ᨣ᩠ᨯᩧ': 4, + 'ᨣ᩠ᨶᩢ': 4, + 'ᨣ᩠ᨾᩫ': 4, + 'ᨣ᩠ᩅ': 3, + 'ᨣ᩠ᩋᩢ': 4, + 'ᨣᩢ': 2, + 'ᨣᩢ᩠ᨷ': 4, + 'ᨣᩢᩴ': 3, + 'ᨣᩩ': 2, + 'ᨣᩩᩢ': 3, + 'ᨣᩮᩢᩢ': 4, + 'ᨣᩯ᩠ᨶᩢ': 5, + 'ᨣᩯ᩠ᩅ': 4, + 'ᨣᩳ᩶': 3, + 'ᨣᩴ': 2, + 'ᨤ᩠ᨯᩥ': 4, + 'ᨤ᩠ᨶᩨ': 4, + 'ᨤ᩠ᨶᩫ': 4, + 'ᨤ᩠ᩅᩫ': 4, + 'ᨤ᩠ᩋ': 3, + 'ᨤᩢ᩠ᨬ': 4, + 'ᨤᩮᩢ': 3, + 'ᨤᩱ᩵': 3, + 'ᨥᩢ': 2, + 'ᨧ᩠ᨦᩥ᩵': 5, + 'ᨧ᩠ᨯᩢ': 4, + 'ᨧᩢ': 2, + 'ᨧᩮ᩠ᨷ': 4, + 'ᨧᩮᩢᩢ': 4, + 'ᨧᩱ᩠ᨿ': 4, + 'ᨧᩴ': 2, + 'ᨧ᩵ᩴ': 3, + 'ᨨ᩠ᨶᩢ': 4, + 'ᨩ᩠ᨶᩢᩢ': 5, + 'ᨩ᩠ᨶ᩼': 4, + 'ᨩᩢ': 2, + 'ᨩᩦ': 2, + 'ᨩᩨ᩵': 3, + 'ᨩᩩ': 2, + 'ᨩᩭ᩵': 3, + 'ᨩᩮ᩠ᩋᩨ': 5, + 'ᨩᩮ᩠ᩋᩨ᩵': 6, + 'ᨩᩮ᩠ᩋᩨ᩶': 6, + 'ᨩᩱᩢ': 3, + 'ᨩ᩵ᩭ': 3, + 'ᨪ᩠ᨦᩨ᩵': 5, + 'ᨪᩨ᩵': 3, + 'ᨪᩩ': 2, + 'ᨪᩮᩢ': 3, + 'ᨬ᩠ᨬ': 3, + 'ᨭᩛ': 2, + 'ᨭᩥ': 2, + 'ᨯ᩠ᨦᩢ᩵': 5, + 'ᨯ᩠ᨰ': 3, + 'ᨯ᩠ᨶᩥ': 4, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 6, + 'ᨯᩢ': 2, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 6, + 'ᨯᩦ': 2, + 'ᨯᩪ': 2, + 'ᨯᩪᩯ': 3, + 'ᨯᩯ᩠ᨦ': 4, + 'ᨯᩯ᩠ᨶ': 4, + 'ᨯᩰ᩠ᨿ': 4, + 'ᨯᩱᩢ': 3, + 'ᨯᩴ᩠ᨿ': 4, + 'ᨱ᩠ᨱ': 3, + 'ᨲᩕᩦ': 3, + 'ᨲᩕ᩼': 3, + 'ᨲ᩠ᨠᩫ': 4, + 'ᨲ᩠ᨦᩢᩢ': 5, + 'ᨲ᩠ᨯᩢ': 4, + 'ᨲ᩠ᨲᩥ': 4, + 'ᨲ᩠ᨳᩩ': 4, + 'ᨲ᩠ᨶᩫ': 4, + 'ᨲ᩠ᨶᩫᩢ': 5, + 'ᨲ᩠ᩅᩫ': 4, + 'ᨲ᩠ᩋᩢ': 4, + 'ᨲᩥ': 2, + 'ᨲᩮ᩠ᨠ': 4, + 'ᨲᩮ᩠ᨦ': 4, + 'ᨲᩮ᩠ᨾ': 4, + 'ᨲᩮ᩠ᨾᩨ᩵': 6, + 'ᨲᩯ᩠ᨠ': 4, + 'ᨲᩯ᩠ᨦ᩵': 5, + 'ᨲᩯ᩠ᨾᩢ': 5, + 'ᨲᩯ᩵': 3, + 'ᨲᩱ᩠ᨿ': 4, + 'ᨲᩱᩢ': 3, + 'ᨲᩳ᩵': 3, + 'ᨲ᩵': 2, + 'ᨲ᩵ᩴ': 3, + 'ᨳ᩠ᨦᩨ': 4, + 'ᨳ᩠ᩅᩢ': 4, + 'ᨳᩨ': 2, + 'ᨳᩪ': 2, + 'ᨳᩫ᩠ᨷ': 4, + 'ᨳᩮ᩠ᨶᩨ᩵': 6, + 'ᨳᩮᩢᩢ': 4, + 'ᨳᩯ᩠ᨦᩢ': 5, + 'ᨳᩯ᩠ᨾ': 4, + 'ᨴ᩠ᨦᩢ': 4, + 'ᨴ᩠ᨦᩨ': 4, + 'ᨴ᩠ᨵᩥ': 4, + 'ᨴ᩠ᨿ': 3, + 'ᨴ᩠ᨿ᩵': 4, + 'ᨴ᩠ᩅᩢ': 4, + 'ᨴ᩠ᩅᩫ᩵': 5, + 'ᨴᩦ᩵': 3, + 'ᨴᩩ': 2, + 'ᨴᩮ᩠ᩈ': 4, + 'ᨴᩮ᩠ᩈᩱ': 5, + 'ᨴᩮᩢᩢ': 4, + 'ᨴᩮᩢ᩵': 4, + 'ᨴᩯ᩠ᨶ': 4, + 'ᨴᩯᩢ': 3, + 'ᨴᩰ᩠ᩈ': 4, + 'ᨵᩥ': 2, + 'ᨵᩦ': 2, + 'ᨶ᩠ᨲᩥ': 4, + 'ᨶ᩠ᨶᩢᩢ': 5, + 'ᨶ᩠ᨶᩥ': 4, + 'ᨶ᩠ᩋ': 3, + 'ᨶ᩠ᩋᩢ': 4, + 'ᨶᩢ᩠ᨷ': 4, + 'ᨶᩦ᩶': 3, + 'ᨶᩩ': 2, + 'ᨶᩩ᩵': 3, + 'ᨶᩯ᩠ᨶ': 4, + 'ᨷ᩠ᨦᩢ': 4, + 'ᨷ᩠ᨯᩢ': 4, + 'ᨷ᩠ᨲᩢ': 4, + 'ᨷ᩠ᨲᩥ': 4, + 'ᨷ᩠ᨴᩫ': 4, + 'ᨷ᩠ᨿ': 3, + 'ᨷ᩠ᩅᩫ': 4, + 'ᨷ᩠ᩋ': 3, + 'ᨷᩢ': 2, + 'ᨷᩥ': 2, + 'ᨷᩩ': 2, + 'ᨷᩪ': 2, + 'ᨷᩮ᩠ᨦᩨ᩶': 6, + 'ᨸ᩠ᨠᩫ': 4, + 'ᨸ᩠ᨯᩨ': 4, + 'ᨸ᩠ᨶᩢ': 4, + 'ᨸ᩠ᩋ': 3, + 'ᨸᩮ᩠ᨦᩨ': 5, + 'ᨸᩮ᩠ᨶ': 4, + 'ᨸᩮᩢ᩵': 4, + 'ᨸ᩵': 2, + 'ᨸ᩠᩵ᨿ': 4, + 'ᨹ᩠ᨯᩥ': 4, + 'ᨹ᩠ᨿ᩵': 4, + 'ᨹ᩠ᩅᩥ': 4, + 'ᨹᩪᩢ': 3, + 'ᨹᩪᩢᩱ': 4, + 'ᨹᩫ᩠ᩃ': 4, + 'ᨹᩮᩨ᩠ᨿ': 5, + 'ᨹ᩵': 2, + 'ᨻᩕ᩠ᩋᩢ': 5, + 'ᨻ᩠ᨦ': 3, + 'ᨻ᩠ᨶᩨ᩶': 5, + 'ᨻ᩠ᨶᩫ᩶': 5, + 'ᨻ᩠ᨿ': 3, + 'ᨻ᩠ᩋ': 3, + 'ᨻᩥ': 2, + 'ᨻᩦ᩵': 3, + 'ᨻᩮ᩠ᩋᩨ᩵': 6, + 'ᨻᩳ': 2, + 'ᨽᩱ᩠ᨿ': 4, + 'ᨾ᩠ᨲᩥ': 4, + 'ᨾ᩠ᨾ': 3, + 'ᨾ᩠ᨾ᩼': 4, + 'ᨾ᩠ᩅ': 3, + 'ᨾ᩠ᩅ᩵': 4, + 'ᨾᩢ': 2, + 'ᨾᩦ': 2, + 'ᨾᩨ': 2, + 'ᨾᩩ': 2, + 'ᨾᩪ': 2, + 'ᨾᩮ᩠ᨠᩨ': 5, + 'ᨾᩮ᩠ᨦᩨ': 5, + 'ᨾᩮ᩠ᩋᩨ᩵': 6, + 'ᨾᩯ᩵': 3, + 'ᨿ᩠ᨦᩢ': 4, + 'ᨿ᩠ᨦᩢᩢ': 5, + 'ᨿ᩠ᨦᩥ': 4, + 'ᨿ᩠ᨦᩥ᩵': 5, + 'ᨿ᩠ᩋ': 3, + 'ᨿᩢ᩠ᨷ': 4, + 'ᨿᩩ': 2, + 'ᨿᩫ᩠ᩈ': 4, + 'ᨿᩮ᩠ᨶ': 4, + 'ᨿᩮ᩠ᨾᩨ': 5, + 'ᩀᩪ᩵': 3, + 'ᩀ᩵': 2, + 'ᩁ᩠ᨠᩢ': 4, + 'ᩁ᩠ᨮᩢ': 4, + 'ᩁ᩠ᨾᩫ': 4, + 'ᩁ᩠ᨿ': 3, + 'ᩁ᩠ᩅ': 3, + 'ᩁ᩠ᩅ᩵': 4, + 'ᩁ᩠ᩋ': 3, + 'ᩁᩢ': 2, + 'ᩁᩢ᩠ᨷ': 4, + 'ᩁᩢᩭ': 3, + 'ᩁᩥ': 2, + 'ᩁᩦ': 2, + 'ᩁᩪᩢ': 3, + 'ᩁᩫ᩠ᨷ': 4, + 'ᩁᩮ᩠ᨦᩨ᩵': 6, + 'ᩁᩮ᩠ᨧ': 4, + 'ᩁᩮ᩠ᨶᩨ': 5, + 'ᩁᩮᩨ᩠ᨬ': 5, + 'ᩁᩯ᩠ᨦ': 4, + 'ᩃ᩠ᨦᩫ': 4, + 'ᩃ᩠ᩅ᩵': 4, + 'ᩃᩢ᩠ᨿ': 4, + 'ᩃᩢᩴ': 3, + 'ᩃᩥ': 2, + 'ᩃᩨ᩠ᨷ': 4, + 'ᩃᩩ': 2, + 'ᩃᩪ': 2, + 'ᩃᩮ᩠ᨠᩨ': 5, + 'ᩃᩮ᩠ᨦᩨ': 5, + 'ᩃᩰ᩠ᨠ': 4, + 'ᩅ᩠ᨲᩥ': 4, + 'ᩅ᩠ᨶᩢ': 4, + 'ᩅ᩠ᨿ': 3, + 'ᩅ᩠ᩅ᩵': 4, + 'ᩅᩢ': 2, + 'ᩅᩥ': 2, + 'ᩅᩮ᩠ᨶ': 4, + 'ᩅᩮ᩠ᨶᩢ': 5, + 'ᩅᩱᩢ': 3, + 'ᩈ᩠ᨠᩢ': 4, + 'ᩈ᩠ᨠᩧ': 4, + 'ᩈ᩠ᨦᩢ': 4, + 'ᩈ᩠ᨦᩥ᩵': 5, + 'ᩈ᩠ᨦᩫ': 4, + 'ᩈ᩠ᨶᩫ': 4, + 'ᩈ᩠ᨾᩫ': 4, + 'ᩈ᩠ᨿ': 3, + 'ᩈ᩠ᩅ᩵': 4, + 'ᩈ᩠ᩋ': 3, + 'ᩈᩢ': 2, + 'ᩈᩢ᩠ᨿ': 4, + 'ᩈᩥ': 2, + 'ᩈᩦ': 2, + 'ᩈᩨ᩵': 3, + 'ᩈᩩ': 2, + 'ᩈᩪ': 2, + 'ᩈᩪᩢ': 3, + 'ᩈᩫ᩠ᨾ': 4, + 'ᩈᩮ᩠ᩈ': 4, + 'ᩈᩯ᩠ᩅ': 4, + 'ᩈᩱ᩠ᨿ': 4, + 'ᩈᩳ᩵': 3, + 'ᩈ᩵ᩴ': 3, + 'ᩉᩕᩨ': 3, + 'ᩉᩖ': 2, + 'ᩉᩖᩢ': 3, + 'ᩉ᩠ᨶᩢ': 4, + 'ᩉ᩠ᨶᩦ': 4, + 'ᩉ᩠ᨶᩧ': 4, + 'ᩉ᩠ᨶᩧ᩵': 5, + 'ᩉ᩠ᨶᩫ': 4, + 'ᩉ᩠ᨾ': 3, + 'ᩉ᩠ᨾᩢ': 4, + 'ᩉ᩠ᨾᩢᩢ': 5, + 'ᩉ᩠ᨾᩪ᩵': 5, + 'ᩉ᩠ᨾᩳ': 4, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 6, + 'ᩉ᩠ᨿᩩ': 4, + 'ᩉ᩠ᩅᩫ': 4, + 'ᩉ᩠ᩅ᩵': 4, + 'ᩉᩢ': 2, + 'ᩉᩨᩢ': 3, + 'ᩉᩨ᩶': 3, + 'ᩉᩮᩖᩨ': 4, + 'ᩉᩮ᩠ᨦᩢᩢ': 6, + 'ᩉᩮ᩠ᨯ': 4, + 'ᩉᩮ᩠ᨲᩩ': 5, + 'ᩉᩮ᩠ᨶᩨ': 5, + 'ᩉᩮ᩠ᨾᩨ': 5, + 'ᩉᩮ᩠ᨾᩨᩨ': 6, + 'ᩉᩯ᩠ᨦ᩵': 5, + 'ᩉᩯ᩠ᨶᩢ': 5, + 'ᩉᩯ᩠ᨾ': 4, + 'ᩉᩯ᩵': 3, + 'ᩉᩱ᩠ᨾ᩵': 5, + 'ᩉᩱ᩠ᨿ᩵': 5, + 'ᩉᩳ': 2, + 'ᩋ᩠ᨶᩢ': 4, + 'ᩋ᩠ᨶᩨ᩵': 5, + 'ᩋ᩠ᩋ': 3, + 'ᩋᩢ': 2, + 'ᩋᩪᩢ': 3, + 'ᩋᩴ': 2, + 'ᩐᩢ': 2, + 'ᩓ᩠ᩅᩢ': 4, + 'ᩓᩢ': 2, + 'ᩔ᩼': 2, + 'ᩣ᩠ᨠ': 3, + 'ᩣ᩠ᨦ': 3, + 'ᩣ᩠ᨧ': 3, + 'ᩣ᩠ᨩ': 3, + 'ᩣ᩠ᨯ': 3, + 'ᩣ᩠ᨲ': 3, + 'ᩣ᩠ᨲᩱ': 4, + 'ᩣ᩠ᨶ': 3, + 'ᩣ᩠ᨷ': 3, + 'ᩣ᩠ᨾ': 3, + 'ᩣ᩠ᨿ': 3, + 'ᩣ᩠ᩁ': 3, + 'ᩣ᩠ᩃ': 3, + 'ᩣ᩠ᩅ': 3, + 'ᩣ᩠ᩈ': 3, + 'ᩤ᩠ᨦ': 3, + 'ᩤ᩠ᨶᩢ': 4, + '⛓️‍💥': 3, + '⛹🏻‍♀️': 4, + '⛹🏻‍♂️': 4, + '⛹🏼‍♀️': 4, + '⛹🏼‍♂️': 4, + '⛹🏽‍♀️': 4, + '⛹🏽‍♂️': 4, + '⛹🏾‍♀️': 4, + '⛹🏾‍♂️': 4, + '⛹🏿‍♀️': 4, + '⛹🏿‍♂️': 4, + '❤️‍🔥': 3, + '❤️‍🩹': 3, + 'ꦉꦁ': 2, + 'ꦏꦁ': 2, + 'ꦏꦂ': 2, + 'ꦏꦶ': 2, + 'ꦏꦶꦂ': 3, + 'ꦏꦸ': 2, + 'ꦏꦸꦂ': 3, + 'ꦏꦺꦴ': 3, + 'ꦏꦼ': 2, + 'ꦏꦿꦁ': 3, + 'ꦏꦿꦂ': 3, + 'ꦏ꧀': 2, + 'ꦏ꧀ꦏ': 3, + 'ꦏ꧀ꦏꦁ': 4, + 'ꦏ꧀ꦏꦺ': 4, + 'ꦏ꧀ꦏꦼ': 4, + 'ꦏ꧀ꦔ': 3, + 'ꦏ꧀ꦔꦸ': 4, + 'ꦏ꧀ꦔꦿ': 4, + 'ꦏ꧀ꦕ': 3, + 'ꦏ꧀ꦠ': 3, + 'ꦏ꧀ꦠꦶ': 4, + 'ꦏ꧀ꦠꦸ': 4, + 'ꦏ꧀ꦠꦺ': 4, + 'ꦏ꧀ꦢ': 3, + 'ꦏ꧀ꦢꦂ': 4, + 'ꦏ꧀ꦢꦶ': 4, + 'ꦏ꧀ꦤ': 3, + 'ꦏ꧀ꦤꦶꦁ': 5, + 'ꦏ꧀ꦥ': 3, + 'ꦏ꧀ꦥꦶ': 4, + 'ꦏ꧀ꦥꦿꦶ': 5, + 'ꦏ꧀ꦧ': 3, + 'ꦏ꧀ꦧꦶ': 4, + 'ꦏ꧀ꦧꦺ': 4, + 'ꦏ꧀ꦩ': 3, + 'ꦏ꧀ꦩꦸ': 4, + 'ꦏ꧀ꦪ': 3, + 'ꦏ꧀ꦭ': 3, + 'ꦏ꧀ꦮ': 3, + 'ꦏ꧀ꦱ': 3, + 'ꦏ꧀ꦱꦂ': 4, + 'ꦏ꧀ꦱꦶ': 4, + 'ꦏ꧀ꦱꦸ': 4, + 'ꦏ꧀ꦱꦺ': 4, + 'ꦏ꧀ꦲ': 3, + 'ꦏ꧀ꦲꦁ': 4, + 'ꦏ꧀ꦲꦶꦁ': 5, + 'ꦏ꧀ꦲꦸ': 4, + 'ꦏ꧀ꦲꦺ': 4, + 'ꦏ꧀ꦲꦺꦴ': 5, + 'ꦒꦁ': 2, + 'ꦒꦂ': 2, + 'ꦒꦸ': 2, + 'ꦒꦸꦁ': 3, + 'ꦒꦸꦂ': 3, + 'ꦒꦸꦃ': 3, + 'ꦒꦺꦴ': 3, + 'ꦒꦼ': 2, + 'ꦒꦼꦂ': 3, + 'ꦒꦿꦺ': 3, + 'ꦒ꧀ꦒ': 3, + 'ꦔꦁ': 2, + 'ꦔꦶ': 2, + 'ꦔꦶꦁ': 3, + 'ꦔꦸ': 2, + 'ꦔꦺꦴ': 3, + 'ꦔꦼ': 2, + 'ꦔꦼꦂ': 3, + 'ꦔꦽ': 2, + 'ꦔ꧀ꦒꦼ': 4, + 'ꦔ꧀ꦒꦿꦼꦁ': 6, + 'ꦔ꧀ꦭ': 3, + 'ꦔ꧀ꦭꦁ': 4, + 'ꦔ꧀ꦭꦸ': 4, + 'ꦔ꧀ꦭꦼ': 4, + 'ꦕꦶ': 2, + 'ꦕꦶꦁ': 3, + 'ꦕꦸ': 2, + 'ꦕꦺꦴ': 3, + 'ꦗꦶ': 2, + 'ꦗꦸ': 2, + 'ꦗꦼ': 2, + 'ꦗꦿꦺꦴ': 4, + 'ꦚꦁ': 2, + 'ꦚꦶꦁ': 3, + 'ꦚ꧀ꦕ': 3, + 'ꦚ꧀ꦕꦶ': 4, + 'ꦚ꧀ꦗ': 3, + 'ꦚ꧀ꦗꦶ': 4, + 'ꦚ꧀ꦗꦸꦁ': 5, + 'ꦚ꧀ꦗꦸꦂ': 5, + 'ꦝꦁ': 2, + 'ꦝꦂ': 2, + 'ꦝꦶ': 2, + 'ꦝꦺꦴ': 3, + 'ꦝꦺꦴꦂ': 4, + 'ꦝꦼ': 2, + 'ꦝꦼꦁ': 3, + 'ꦠꦁ': 2, + 'ꦠꦶ': 2, + 'ꦠꦸ': 2, + 'ꦠꦸꦁ': 3, + 'ꦠꦸꦂ': 3, + 'ꦠꦸꦃ': 3, + 'ꦠꦺꦃ': 3, + 'ꦠꦺꦴ': 3, + 'ꦠꦼ': 2, + 'ꦠꦼꦂ': 3, + 'ꦠꦽ': 2, + 'ꦠꦿꦶ': 3, + 'ꦠ꧀': 2, + 'ꦠ꧀ꦏꦁ': 4, + 'ꦠ꧀ꦏꦸ': 4, + 'ꦠ꧀ꦒ': 3, + 'ꦠ꧀ꦔꦸ': 4, + 'ꦠ꧀ꦚ': 3, + 'ꦠ꧀ꦠ': 3, + 'ꦠ꧀ꦠꦶ': 4, + 'ꦠ꧀ꦠꦶꦁ': 5, + 'ꦠ꧀ꦠꦸ': 4, + 'ꦠ꧀ꦠꦺ': 4, + 'ꦠ꧀ꦤ': 3, + 'ꦠ꧀ꦤꦶ': 4, + 'ꦠ꧀ꦩ': 3, + 'ꦠ꧀ꦩꦼ': 4, + 'ꦠ꧀ꦭ': 3, + 'ꦠ꧀ꦭꦺ': 4, + 'ꦠ꧀ꦱ': 3, + 'ꦠ꧀ꦱꦶꦁ': 5, + 'ꦠ꧀ꦱꦶꦃ': 5, + 'ꦠ꧀ꦱꦾ': 4, + 'ꦠ꧀ꦱ꧀ꦮ': 5, + 'ꦠ꧀ꦲ': 3, + 'ꦠ꧀ꦲꦶꦁ': 5, + 'ꦠ꧀ꦲꦺꦴ': 5, + 'ꦢꦂ': 2, + 'ꦢꦶ': 2, + 'ꦢꦸ': 2, + 'ꦢꦸꦂ': 3, + 'ꦢꦺꦴ': 3, + 'ꦢꦼ': 2, + 'ꦢ꧀': 2, + 'ꦢ꧀ꦏ': 3, + 'ꦢ꧀ꦠ': 3, + 'ꦢ꧀ꦠꦶꦁ': 5, + 'ꦢ꧀ꦢ': 3, + 'ꦢ꧀ꦥ': 3, + 'ꦢ꧀ꦩꦺꦴ': 5, + 'ꦢ꧀ꦲ': 3, + 'ꦤꦁ': 2, + 'ꦤꦂ': 2, + 'ꦤꦶ': 2, + 'ꦤꦶꦁ': 3, + 'ꦤꦸ': 2, + 'ꦤꦸꦁ': 3, + 'ꦤꦺꦃ': 3, + 'ꦤꦺꦴ': 3, + 'ꦤꦼ': 2, + 'ꦤꦼꦁ': 3, + 'ꦤꦼꦂ': 3, + 'ꦤ꧀': 2, + 'ꦤ꧀ꦏ': 3, + 'ꦤ꧀ꦏꦁ': 4, + 'ꦤ꧀ꦏꦸ': 4, + 'ꦤ꧀ꦏꦼ': 4, + 'ꦤ꧀ꦒ': 3, + 'ꦤ꧀ꦔ': 3, + 'ꦤ꧀ꦔꦁ': 4, + 'ꦤ꧀ꦔꦶ': 4, + 'ꦤ꧀ꦔꦸ': 4, + 'ꦤ꧀ꦔꦸꦂ': 5, + 'ꦤ꧀ꦔꦺ': 4, + 'ꦤ꧀ꦔꦼ': 4, + 'ꦤ꧀ꦔꦿꦸ': 5, + 'ꦤ꧀ꦗ': 3, + 'ꦤ꧀ꦗꦸ': 4, + 'ꦤ꧀ꦗꦼ': 4, + 'ꦤ꧀ꦚꦶ': 4, + 'ꦤ꧀ꦛꦃ': 4, + 'ꦤ꧀ꦛꦶ': 4, + 'ꦤ꧀ꦝ': 3, + 'ꦤ꧀ꦝꦁ': 4, + 'ꦤ꧀ꦝꦶ': 4, + 'ꦤ꧀ꦝꦸ': 4, + 'ꦤ꧀ꦝꦸꦁ': 5, + 'ꦤ꧀ꦝꦺꦁ': 5, + 'ꦤ꧀ꦝꦺꦴꦁ': 6, + 'ꦤ꧀ꦝꦼ': 4, + 'ꦤ꧀ꦠ': 3, + 'ꦤ꧀ꦠꦂ': 4, + 'ꦤ꧀ꦠꦃ': 4, + 'ꦤ꧀ꦠꦶ': 4, + 'ꦤ꧀ꦠꦸ': 4, + 'ꦤ꧀ꦠꦸꦁ': 5, + 'ꦤ꧀ꦠꦺ': 4, + 'ꦤ꧀ꦠꦼ': 4, + 'ꦤ꧀ꦠꦼꦂ': 5, + 'ꦤ꧀ꦠꦽ': 4, + 'ꦤ꧀ꦢ': 3, + 'ꦤ꧀ꦢꦁ': 4, + 'ꦤ꧀ꦢꦂ': 4, + 'ꦤ꧀ꦢꦶ': 4, + 'ꦤ꧀ꦢꦸ': 4, + 'ꦤ꧀ꦢꦺ': 4, + 'ꦤ꧀ꦢꦼ': 4, + 'ꦤ꧀ꦤ': 3, + 'ꦤ꧀ꦤꦶ': 4, + 'ꦤ꧀ꦤꦶꦁ': 5, + 'ꦤ꧀ꦤꦺ': 4, + 'ꦤ꧀ꦤꦼ': 4, + 'ꦤ꧀ꦥ': 3, + 'ꦤ꧀ꦥꦁ': 4, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 7, + 'ꦤ꧀ꦥꦶ': 4, + 'ꦤ꧀ꦥꦸ': 4, + 'ꦤ꧀ꦥꦼ': 4, + 'ꦤ꧀ꦥꦿ': 4, + 'ꦤ꧀ꦥꦿꦶ': 5, + 'ꦤ꧀ꦧ': 3, + 'ꦤ꧀ꦧꦁ': 4, + 'ꦤ꧀ꦧꦶ': 4, + 'ꦤ꧀ꦧꦸ': 4, + 'ꦤ꧀ꦧꦺ': 4, + 'ꦤ꧀ꦧꦺꦴ': 5, + 'ꦤ꧀ꦧꦼ': 4, + 'ꦤ꧀ꦩ': 3, + 'ꦤ꧀ꦩꦂ': 4, + 'ꦤ꧀ꦩꦶ': 4, + 'ꦤ꧀ꦩꦸꦂ': 5, + 'ꦤ꧀ꦩꦼ': 4, + 'ꦤ꧀ꦭ': 3, + 'ꦤ꧀ꦭꦶ': 4, + 'ꦤ꧀ꦭꦸ': 4, + 'ꦤ꧀ꦮ': 3, + 'ꦤ꧀ꦮꦂ': 4, + 'ꦤ꧀ꦮꦶ': 4, + 'ꦤ꧀ꦮꦸ': 4, + 'ꦤ꧀ꦮꦼ': 4, + 'ꦤ꧀ꦱ': 3, + 'ꦤ꧀ꦱꦂ': 4, + 'ꦤ꧀ꦱꦃ': 4, + 'ꦤ꧀ꦱꦶ': 4, + 'ꦤ꧀ꦱꦶꦁ': 5, + 'ꦤ꧀ꦱꦸ': 4, + 'ꦤ꧀ꦱꦺꦴ': 5, + 'ꦤ꧀ꦱꦼ': 4, + 'ꦤ꧀ꦲ': 3, + 'ꦤ꧀ꦲꦁ': 4, + 'ꦤ꧀ꦲꦶ': 4, + 'ꦤ꧀ꦲꦶꦁ': 5, + 'ꦤ꧀ꦲꦸ': 4, + 'ꦤ꧀ꦲꦺꦴ': 5, + 'ꦥꦁ': 2, + 'ꦥ꦳ꦼ': 3, + 'ꦥ꦳꧀': 3, + 'ꦥꦶ': 2, + 'ꦥꦸ': 2, + 'ꦥꦸꦁ': 3, + 'ꦥꦺꦴ': 3, + 'ꦥꦼ': 2, + 'ꦥꦼꦂ': 3, + 'ꦥꦿꦃ': 3, + 'ꦥꦿꦶ': 3, + 'ꦥꦿꦺꦴ': 4, + 'ꦥ꧀': 2, + 'ꦥ꧀ꦏ': 3, + 'ꦥ꧀ꦏꦁ': 4, + 'ꦥ꧀ꦠ': 3, + 'ꦥ꧀ꦠꦶ': 4, + 'ꦥ꧀ꦢꦸ': 4, + 'ꦥ꧀ꦤ': 3, + 'ꦥ꧀ꦤꦶ': 4, + 'ꦥ꧀ꦥ': 3, + 'ꦥ꧀ꦥꦶ': 4, + 'ꦥ꧀ꦥꦺ': 4, + 'ꦥ꧀ꦧꦺ': 4, + 'ꦥ꧀ꦩ': 3, + 'ꦥ꧀ꦩꦂ': 4, + 'ꦥ꧀ꦫꦺ': 4, + 'ꦥ꧀ꦭ': 3, + 'ꦥ꧀ꦭꦸ': 4, + 'ꦥ꧀ꦱ': 3, + 'ꦥ꧀ꦱꦶꦂ': 5, + 'ꦥ꧀ꦱꦼ': 4, + 'ꦥ꧀ꦲ': 3, + 'ꦧꦁ': 2, + 'ꦧꦶ': 2, + 'ꦧꦸ': 2, + 'ꦧꦸꦂ': 3, + 'ꦧꦺꦃ': 3, + 'ꦧꦺꦴ': 3, + 'ꦧꦼ': 2, + 'ꦧ꧀': 2, + 'ꦧ꧀ꦏ': 3, + 'ꦧ꧀ꦠꦸ': 4, + 'ꦧ꧀ꦥ': 3, + 'ꦧ꧀ꦧ': 3, + 'ꦧ꧀ꦧꦺ': 4, + 'ꦧ꧀ꦲ': 3, + 'ꦧ꧀ꦲꦶ': 4, + 'ꦩꦁ': 2, + 'ꦩꦂ': 2, + 'ꦩꦶ': 2, + 'ꦩꦸ': 2, + 'ꦩꦸꦁ': 3, + 'ꦩꦸꦂ': 3, + 'ꦩꦺꦃ': 3, + 'ꦩꦺꦴ': 3, + 'ꦩꦼ': 2, + 'ꦩꦼꦂ': 3, + 'ꦩꦿꦃ': 3, + 'ꦩꦿꦶꦃ': 4, + 'ꦩ꧀': 2, + 'ꦩ꧀ꦏꦁ': 4, + 'ꦩ꧀ꦔꦼ': 4, + 'ꦩ꧀ꦠꦸ': 4, + 'ꦩ꧀ꦠꦺꦴ': 5, + 'ꦩ꧀ꦤꦶꦁ': 5, + 'ꦩ꧀ꦥ': 3, + 'ꦩ꧀ꦥꦶ': 4, + 'ꦩ꧀ꦥꦸ': 4, + 'ꦩ꧀ꦥꦼ': 4, + 'ꦩ꧀ꦧ': 3, + 'ꦩ꧀ꦧꦁ': 4, + 'ꦩ꧀ꦧꦂ': 4, + 'ꦩ꧀ꦧꦃ': 4, + 'ꦩ꧀ꦧꦶ': 4, + 'ꦩ꧀ꦧꦸ': 4, + 'ꦩ꧀ꦧꦸꦁ': 5, + 'ꦩ꧀ꦧꦺ': 4, + 'ꦩ꧀ꦧꦺꦂ': 5, + 'ꦩ꧀ꦧꦼꦂ': 5, + 'ꦩ꧀ꦧꦾꦸꦂ': 6, + 'ꦩ꧀ꦩ': 3, + 'ꦩ꧀ꦩꦶ': 4, + 'ꦩ꧀ꦫ': 3, + 'ꦩ꧀ꦫꦃ': 4, + 'ꦩ꧀ꦭ': 3, + 'ꦩ꧀ꦲꦶ': 4, + 'ꦪꦁ': 2, + 'ꦪꦶ': 2, + 'ꦪꦸ': 2, + 'ꦪꦸꦁ': 3, + 'ꦪꦸꦃ': 3, + 'ꦪꦺꦴ': 3, + 'ꦫꦁ': 2, + 'ꦫꦶ': 2, + 'ꦫꦶꦁ': 3, + 'ꦫꦶꦃ': 3, + 'ꦫꦸ': 2, + 'ꦫꦸꦁ': 3, + 'ꦫꦺꦴ': 3, + 'ꦭꦁ': 2, + 'ꦭꦂ': 2, + 'ꦭꦶ': 2, + 'ꦭꦶꦁ': 3, + 'ꦭꦶꦃ': 3, + 'ꦭꦸ': 2, + 'ꦭꦸꦁ': 3, + 'ꦭꦸꦂ': 3, + 'ꦭꦺꦃ': 3, + 'ꦭꦺꦴ': 3, + 'ꦭꦺꦴꦁ': 4, + 'ꦭ꧀': 2, + 'ꦭ꧀ꦏꦁ': 4, + 'ꦭ꧀ꦚꦼꦁ': 5, + 'ꦭ꧀ꦠꦸ': 4, + 'ꦭ꧀ꦧꦸ': 4, + 'ꦭ꧀ꦩꦸ': 4, + 'ꦭ꧀ꦭ': 3, + 'ꦭ꧀ꦭꦶ': 4, + 'ꦭ꧀ꦭꦶꦁ': 5, + 'ꦭ꧀ꦭꦺ': 4, + 'ꦭ꧀ꦮ': 3, + 'ꦭ꧀ꦱ': 3, + 'ꦭ꧀ꦱꦂ': 4, + 'ꦭ꧀ꦱꦶꦁ': 5, + 'ꦭ꧀ꦱꦸ': 4, + 'ꦭ꧀ꦲ': 3, + 'ꦭ꧀ꦲꦁ': 4, + 'ꦭ꧀ꦲꦶꦁ': 5, + 'ꦭ꧀ꦲꦸ': 4, + 'ꦮꦂ': 2, + 'ꦮ꦳ꦼꦂ': 4, + 'ꦮꦶ': 2, + 'ꦮꦶꦃ': 3, + 'ꦮꦸ': 2, + 'ꦮꦸꦁ': 3, + 'ꦮꦸꦃ': 3, + 'ꦮꦺꦴ': 3, + 'ꦮꦺꦴꦁ': 4, + 'ꦮꦺꦴꦃ': 4, + 'ꦮꦼ': 2, + 'ꦮꦼꦁ': 3, + 'ꦮꦼꦂ': 3, + 'ꦮꦿꦸꦃ': 4, + 'ꦱꦂ': 2, + 'ꦱꦶ': 2, + 'ꦱꦶꦁ': 3, + 'ꦱꦶꦂ': 3, + 'ꦱꦶꦃ': 3, + 'ꦱꦸ': 2, + 'ꦱꦸꦁ': 3, + 'ꦱꦺꦴ': 3, + 'ꦱꦼ': 2, + 'ꦱꦼꦁ': 3, + 'ꦱꦿꦃ': 3, + 'ꦱ꧀': 2, + 'ꦱ꧀ꦏ': 3, + 'ꦱ꧀ꦏꦁ': 4, + 'ꦱ꧀ꦏꦿꦶ': 5, + 'ꦱ꧀ꦒ': 3, + 'ꦱ꧀ꦔꦸ': 4, + 'ꦱ꧀ꦔꦿ': 4, + 'ꦱ꧀ꦛꦶ': 4, + 'ꦱ꧀ꦠ': 3, + 'ꦱ꧀ꦠꦿ': 4, + 'ꦱ꧀ꦢꦂ': 4, + 'ꦱ꧀ꦢꦶ': 4, + 'ꦱ꧀ꦢꦸ': 4, + 'ꦱ꧀ꦥ': 3, + 'ꦱ꧀ꦧ': 3, + 'ꦱ꧀ꦧꦁ': 4, + 'ꦱ꧀ꦩ': 3, + 'ꦱ꧀ꦩꦶ': 4, + 'ꦱ꧀ꦩꦼ': 4, + 'ꦱ꧀ꦩꦿ': 4, + 'ꦱ꧀ꦭ': 3, + 'ꦱ꧀ꦮ': 3, + 'ꦱ꧀ꦱ': 3, + 'ꦱ꧀ꦱꦂ': 4, + 'ꦱ꧀ꦱꦶ': 4, + 'ꦱ꧀ꦱꦶꦁ': 5, + 'ꦱ꧀ꦱꦸ': 4, + 'ꦱ꧀ꦱꦺ': 4, + 'ꦱ꧀ꦲ': 3, + 'ꦱ꧀ꦲꦁ': 4, + 'ꦱ꧀ꦲꦶ': 4, + 'ꦱ꧀ꦲꦶꦁ': 5, + 'ꦱ꧀ꦲꦸ': 4, + 'ꦲꦁ': 2, + 'ꦲꦶ': 2, + 'ꦲꦶꦁ': 3, + 'ꦲꦶꦂ': 3, + 'ꦲꦸ': 2, + 'ꦲꦸꦂ': 3, + 'ꦲꦺꦴ': 3, + 'ꦲꦼ': 2, + 'ꪀꪰ': 2, + 'ꪀꪲ': 2, + 'ꪀꪳ': 2, + 'ꪀꪴ': 2, + 'ꪀꪷ': 2, + 'ꪀꪾ': 2, + 'ꪁꪴ': 2, + 'ꪁꪷ': 2, + 'ꪁꪸ': 2, + 'ꪁꪾ': 2, + 'ꪄꪰ': 2, + 'ꪄꪲ': 2, + 'ꪄꪳ': 2, + 'ꪄꪴ': 2, + 'ꪄꪷ': 2, + 'ꪅꪰ': 2, + 'ꪈꪲ': 2, + 'ꪈꪸ': 2, + 'ꪈꪾ': 2, + 'ꪉꪷ': 2, + 'ꪉꪸ': 2, + 'ꪊꪰ': 2, + 'ꪊꪲ': 2, + 'ꪊꪴ': 2, + 'ꪊꪸ': 2, + 'ꪋꪲ': 2, + 'ꪋꪳ': 2, + 'ꪋꪴ': 2, + 'ꪋꪷ': 2, + 'ꪋꪸ': 2, + 'ꪎꪰ': 2, + 'ꪎꪲ': 2, + 'ꪎꪳ': 2, + 'ꪎꪴ': 2, + 'ꪎꪷ': 2, + 'ꪎꪸ': 2, + 'ꪏꪴ': 2, + 'ꪏꪷ': 2, + 'ꪏꪸ': 2, + 'ꪑꪰ': 2, + 'ꪑꪲ': 2, + 'ꪑꪷ': 2, + 'ꪒꪰ': 2, + 'ꪒꪲ': 2, + 'ꪒꪴ': 2, + 'ꪒꪷ': 2, + 'ꪒꪸ': 2, + 'ꪔꪰ': 2, + 'ꪔꪲ': 2, + 'ꪔꪳ': 2, + 'ꪔꪷ': 2, + 'ꪔꪸ': 2, + 'ꪔꪾ': 2, + 'ꪕꪰ': 2, + 'ꪕꪲ': 2, + 'ꪕꪳ': 2, + 'ꪕꪴ': 2, + 'ꪕꪷ': 2, + 'ꪕꪸ': 2, + 'ꪕꪾ': 2, + 'ꪖꪸ': 2, + 'ꪘꪰ': 2, + 'ꪘꪳ': 2, + 'ꪙꪲ': 2, + 'ꪙꪴ': 2, + 'ꪙꪾ': 2, + 'ꪚꪰ': 2, + 'ꪚꪴ': 2, + 'ꪚꪷ': 2, + 'ꪜꪰ': 2, + 'ꪜꪲ': 2, + 'ꪜꪴ': 2, + 'ꪜꪸ': 2, + 'ꪝꪰ': 2, + 'ꪝꪲ': 2, + 'ꪝꪳ': 2, + 'ꪝꪷ': 2, + 'ꪝꪸ': 2, + 'ꪠꪲ': 2, + 'ꪠꪴ': 2, + 'ꪠꪸ': 2, + 'ꪢꪲ': 2, + 'ꪢꪴ': 2, + 'ꪢꪸ': 2, + 'ꪣꪰ': 2, + 'ꪣꪲ': 2, + 'ꪣꪳ': 2, + 'ꪣꪷ': 2, + 'ꪣꪸ': 2, + 'ꪤꪰ': 2, + 'ꪤꪴ': 2, + 'ꪤꪷ': 2, + 'ꪤꪸ': 2, + 'ꪤꪾ': 2, + 'ꪥꪰ': 2, + 'ꪥꪴ': 2, + 'ꪥꪸ': 2, + 'ꪨꪰ': 2, + 'ꪨꪷ': 2, + 'ꪨꪸ': 2, + 'ꪩꪰ': 2, + 'ꪩꪳ': 2, + 'ꪩꪴ': 2, + 'ꪩꪷ': 2, + 'ꪩꪾ': 2, + 'ꪪꪴ': 2, + 'ꪫꪸ': 2, + 'ꪬꪷ': 2, + 'ꪬꪸ': 2, + 'ꪭꪰ': 2, + 'ꪭꪲ': 2, + 'ꪭꪳ': 2, + 'ꪭꪴ': 2, + 'ꪭꪷ': 2, + 'ꪭꪸ': 2, + 'ꪮꪲ': 2, + 'ꪮꪳ': 2, + 'ꪮꪴ': 2, + 'ꪮꪸ': 2, + 'ꪯꪸ': 2, + '𑄃𑄧': 2, + '𑄃𑄧𑄁': 3, + '𑄃𑄨': 2, + '𑄃𑄪': 2, + '𑄃𑄬𑄭': 3, + '𑄃𑄮': 2, + '𑄃𑄰': 2, + '𑄃𑄳𑄃': 3, + '𑄃𑄳𑄦𑄧': 4, + '𑄃𑄳𑄦𑄨': 4, + '𑄅𑄪': 2, + '𑄅𑄫': 2, + '𑄇𑄧': 2, + '𑄇𑄧𑄧': 3, + '𑄇𑄧𑄧𑄱': 4, + '𑄇𑄨': 2, + '𑄇𑄨𑄁': 3, + '𑄇𑄪': 2, + '𑄇𑄭𑄭': 3, + '𑄇𑄳𑄠': 3, + '𑄇𑄳𑄠𑄬': 4, + '𑄇𑄳𑄠𑄴': 4, + '𑄇𑄳𑄢𑄨': 4, + '𑄇𑄳𑄦𑄧': 4, + '𑄇𑄳𑄦𑄴': 4, + '𑄇𑄴': 2, + '𑄈𑄧': 2, + '𑄈𑄪': 2, + '𑄈𑄳𑄠': 3, + '𑄈𑄳𑄠𑄬': 4, + '𑄉𑄧': 2, + '𑄉𑄨': 2, + '𑄉𑄩': 2, + '𑄉𑄪': 2, + '𑄉𑄬𑄭': 3, + '𑄉𑄭': 2, + '𑄉𑄮': 2, + '𑄉𑄳𑄠': 3, + '𑄉𑄳𑄢𑄧': 4, + '𑄊𑄧': 2, + '𑄊𑄨': 2, + '𑄋𑄧': 2, + '𑄋𑄨': 2, + '𑄌𑄧': 2, + '𑄌𑄨': 2, + '𑄌𑄮': 2, + '𑄌𑄯': 2, + '𑄌𑄳𑄠𑄬': 4, + '𑄌𑄳𑄠𑄴': 4, + '𑄌𑄴': 2, + '𑄍𑄨': 2, + '𑄍𑄪': 2, + '𑄎𑄧': 2, + '𑄎𑄨': 2, + '𑄎𑄨𑄁': 3, + '𑄎𑄩': 2, + '𑄎𑄩𑄁': 3, + '𑄎𑄪': 2, + '𑄎𑄪𑄁': 3, + '𑄎𑄬𑄭': 3, + '𑄎𑄮': 2, + '𑄎𑄳𑄠𑄧': 4, + '𑄎𑄳𑄠𑄬': 4, + '𑄏𑄨': 2, + '𑄏𑄮': 2, + '𑄑𑄨': 2, + '𑄑𑄳𑄢𑄬': 4, + '𑄒𑄨': 2, + '𑄓𑄧': 2, + '𑄓𑄨': 2, + '𑄓𑄮': 2, + '𑄕𑄧': 2, + '𑄖𑄧': 2, + '𑄖𑄧𑄧': 3, + '𑄖𑄧𑄧𑄱': 4, + '𑄖𑄨': 2, + '𑄖𑄨𑄨': 3, + '𑄖𑄨𑄨𑄪': 4, + '𑄖𑄩': 2, + '𑄖𑄪': 2, + '𑄖𑄳𑄠𑄧': 4, + '𑄖𑄳𑄠𑄬': 4, + '𑄖𑄳𑄠𑄴': 4, + '𑄖𑄳𑄢𑄨': 4, + '𑄖𑄳𑄢𑄬': 4, + '𑄖𑄳𑄦𑄴': 4, + '𑄖𑄴': 2, + '𑄗𑄧': 2, + '𑄗𑄪': 2, + '𑄗𑄭': 2, + '𑄘𑄁': 2, + '𑄘𑄧': 2, + '𑄘𑄨': 2, + '𑄘𑄪': 2, + '𑄘𑄮': 2, + '𑄘𑄳𑄠𑄧': 4, + '𑄘𑄳𑄠𑄬': 4, + '𑄙𑄧': 2, + '𑄙𑄨': 2, + '𑄙𑄩': 2, + '𑄙𑄪': 2, + '𑄙𑄮': 2, + '𑄙𑄳𑄠': 3, + '𑄙𑄳𑄠𑄧': 4, + '𑄚𑄧': 2, + '𑄚𑄧𑄧𑄱': 4, + '𑄚𑄨': 2, + '𑄚𑄩': 2, + '𑄚𑄪': 2, + '𑄚𑄬𑄭': 3, + '𑄚𑄮': 2, + '𑄚𑄳𑄠𑄧': 4, + '𑄚𑄳𑄠𑄬': 4, + '𑄚𑄳𑄠𑄴': 4, + '𑄚𑄳𑄢𑄧𑄧': 5, + '𑄚𑄳𑄦𑄧': 4, + '𑄚𑄳𑄦𑄨': 4, + '𑄚𑄳𑄦𑄴': 4, + '𑄚𑄴': 2, + '𑄛𑄧': 2, + '𑄛𑄨': 2, + '𑄛𑄪': 2, + '𑄛𑄭': 2, + '𑄛𑄮': 2, + '𑄛𑄱': 2, + '𑄛𑄳𑄢': 3, + '𑄛𑄳𑄢𑄧': 4, + '𑄛𑄳𑄦': 3, + '𑄛𑄴': 2, + '𑄜𑄧': 2, + '𑄜𑄨': 2, + '𑄜𑄪': 2, + '𑄜𑄯': 2, + '𑄝𑄧': 2, + '𑄝𑄧𑄧': 3, + '𑄝𑄨': 2, + '𑄝𑄪': 2, + '𑄝𑄮': 2, + '𑄝𑄰': 2, + '𑄝𑄳𑄠': 3, + '𑄝𑄳𑄢𑄨': 4, + '𑄝𑄳𑄢𑄬': 4, + '𑄞𑄧': 2, + '𑄞𑄨': 2, + '𑄞𑄩': 2, + '𑄞𑄪': 2, + '𑄞𑄬𑄭': 3, + '𑄞𑄮': 2, + '𑄞𑄯': 2, + '𑄟𑄧': 2, + '𑄟𑄨': 2, + '𑄟𑄪': 2, + '𑄟𑄫': 2, + '𑄟𑄮': 2, + '𑄟𑄱': 2, + '𑄟𑄳𑄠𑄬': 4, + '𑄟𑄴': 2, + '𑄠𑄧': 2, + '𑄠𑄨': 2, + '𑄠𑄬𑄭': 3, + '𑄠𑄮': 2, + '𑄠𑄴': 2, + '𑄡𑄧': 2, + '𑄡𑄨': 2, + '𑄡𑄪': 2, + '𑄡𑄬𑄭': 3, + '𑄡𑄳𑄠𑄬': 4, + '𑄢𑄁': 2, + '𑄢𑄧': 2, + '𑄢𑄨': 2, + '𑄢𑄩': 2, + '𑄢𑄪': 2, + '𑄢𑄬𑄭': 3, + '𑄢𑄮': 2, + '𑄢𑄳𑄦𑄧𑄱𑄱': 6, + '𑄢𑄴': 2, + '𑄣𑄧': 2, + '𑄣𑄨': 2, + '𑄣𑄩': 2, + '𑄣𑄪': 2, + '𑄣𑄬𑄭': 3, + '𑄣𑄮': 2, + '𑄣𑄰𑄱': 3, + '𑄣𑄳𑄦𑄬': 4, + '𑄣𑄳𑄦𑄴': 4, + '𑄣𑄴': 2, + '𑄥𑄁': 2, + '𑄥𑄧': 2, + '𑄥𑄧𑄁': 3, + '𑄥𑄨': 2, + '𑄥𑄩': 2, + '𑄥𑄪': 2, + '𑄥𑄳𑄠': 3, + '𑄥𑄳𑄠𑄧': 4, + '𑄥𑄳𑄢𑄧': 4, + '𑄥𑄳𑄢𑄨𑄁': 5, + '𑄦𑄧': 2, + '𑄦𑄨': 2, + '𑄦𑄮': 2, + '𑄦𑄰': 2, + '𑌕𑌾𑌂': 3, + '𑌕𑌾𑌃': 3, + '𑌕𑍀': 2, + '𑌕𑍍': 2, + '𑌗𑍀': 2, + '𑌗𑍍': 2, + '𑌚𑍍': 2, + '𑌜𑌼': 2, + '𑌜𑍀': 2, + '𑌜𑍍': 2, + '𑌞𑍍': 2, + '𑌟𑌾𑌂': 3, + '𑌟𑌾𑌃': 3, + '𑌟𑍍': 2, + '𑌠𑍈𑌃': 3, + '𑌢𑌼𑍀': 3, + '𑌣𑌾𑌂': 3, + '𑌣𑍀': 2, + '𑌣𑍍': 2, + '𑌤𑌾𑌂': 3, + '𑌤𑌾𑌃': 3, + '𑌤𑌿𑌂': 3, + '𑌤𑌿𑌃': 3, + '𑌤𑍀': 2, + '𑌤𑍁𑌂': 3, + '𑌤𑍇𑌃': 3, + '𑌤𑍍': 2, + '𑌥𑌾𑌂': 3, + '𑌦𑍀': 2, + '𑌦𑍍': 2, + '𑌧𑌾𑌃': 3, + '𑌧𑌿𑌂': 3, + '𑌧𑍀': 2, + '𑌧𑍇𑌃': 3, + '𑌧𑍈𑌃': 3, + '𑌧𑍍': 2, + '𑌨𑌾𑌂': 3, + '𑌨𑌾𑌃': 3, + '𑌨𑌿𑌃': 3, + '𑌨𑍀': 2, + '𑌨𑍈𑌃': 3, + '𑌨𑍍': 2, + '𑌪𑍀': 2, + '𑌪𑍍': 2, + '𑌬𑍍': 2, + '𑌭𑌿𑌃': 3, + '𑌭𑍍': 2, + '𑌮𑌿𑌂': 3, + '𑌮𑍀': 2, + '𑌮𑍍': 2, + '𑌯𑌾𑌂': 3, + '𑌯𑌾𑌃': 3, + '𑌯𑍀': 2, + '𑌯𑍁𑌃': 3, + '𑌯𑍈𑌃': 3, + '𑌯𑍋𑌃': 3, + '𑌯𑍍': 2, + '𑌰𑌾𑌃': 3, + '𑌰𑌿𑌂': 3, + '𑌰𑍀': 2, + '𑌰𑍍': 2, + '𑌲𑌾𑌃': 3, + '𑌲𑌿𑌂': 3, + '𑌲𑍍': 2, + '𑌵𑌾𑌂': 3, + '𑌵𑌾𑌃': 3, + '𑌵𑍀': 2, + '𑌵𑍍': 2, + '𑌶𑌾𑌃': 3, + '𑌶𑍀': 2, + '𑌶𑍍': 2, + '𑌷𑌾𑌂': 3, + '𑌷𑌾𑌃': 3, + '𑌷𑍍': 2, + '𑌸𑌾𑌂': 3, + '𑌸𑍀': 2, + '𑌸𑍍': 2, + '𑌹𑌾𑌃': 3, + '𑌹𑍀': 2, + '𞤀𞥄': 2, + '𞤢𞥄': 2, + '𞤣𞥆': 2, + '𞤂𞥆': 2, + '𞤤𞥆': 2, + '𞤥𞥆': 2, + '𞤦𞥆': 2, + '𞤨𞥆': 2, + '𞤩𞥆': 2, + '𞤫𞥅': 2, + '𞤭𞥅': 2, + '𞤌𞥅': 2, + '𞤮𞥅': 2, + '𞤍𞥆': 2, + '𞤯𞥆': 2, + '𞤰𞥆': 2, + '𞤲𞥆': 2, + '𞤳𞥆': 2, + '𞤵𞥅': 2, + '𞤔𞥆': 2, + '𞤶𞥆': 2, + '𞤷𞥆': 2, + '𞤺𞥆': 2, + '𞤼𞥆': 2, + '🍄‍🟫': 4, + '🍋‍🟩': 4, + '🏃‍♀️': 3, + '🏃‍♀️‍➡️': 4, + '🏃‍♂️': 3, + '🏃‍♂️‍➡️': 4, + '🏃‍➡️': 3, + '🏃🏻‍♀️': 5, + '🏃🏻‍♀️‍➡️': 6, + '🏃🏻‍♂️': 5, + '🏃🏻‍♂️‍➡️': 6, + '🏃🏻‍➡️': 5, + '🏃🏼‍♀️': 5, + '🏃🏼‍♀️‍➡️': 6, + '🏃🏼‍♂️': 5, + '🏃🏼‍♂️‍➡️': 6, + '🏃🏼‍➡️': 5, + '🏃🏽‍♀️': 5, + '🏃🏽‍♀️‍➡️': 6, + '🏃🏽‍♂️': 5, + '🏃🏽‍♂️‍➡️': 6, + '🏃🏽‍➡️': 5, + '🏃🏾‍♀️': 5, + '🏃🏾‍♀️‍➡️': 6, + '🏃🏾‍♂️': 5, + '🏃🏾‍♂️‍➡️': 6, + '🏃🏾‍➡️': 5, + '🏃🏿‍♀️': 5, + '🏃🏿‍♀️‍➡️': 6, + '🏃🏿‍♂️': 5, + '🏃🏿‍♂️‍➡️': 6, + '🏃🏿‍➡️': 5, + '🏄‍♀️': 3, + '🏄‍♂️': 3, + '🏄🏻‍♀️': 5, + '🏄🏻‍♂️': 5, + '🏄🏼‍♀️': 5, + '🏄🏼‍♂️': 5, + '🏄🏽‍♀️': 5, + '🏄🏽‍♂️': 5, + '🏄🏾‍♀️': 5, + '🏄🏾‍♂️': 5, + '🏄🏿‍♀️': 5, + '🏄🏿‍♂️': 5, + '🏊‍♀️': 3, + '🏊‍♂️': 3, + '🏊🏻‍♀️': 5, + '🏊🏻‍♂️': 5, + '🏊🏼‍♀️': 5, + '🏊🏼‍♂️': 5, + '🏊🏽‍♀️': 5, + '🏊🏽‍♂️': 5, + '🏊🏾‍♀️': 5, + '🏊🏾‍♂️': 5, + '🏊🏿‍♀️': 5, + '🏊🏿‍♂️': 5, + '🏋🏻‍♀️': 4, + '🏋🏻‍♂️': 4, + '🏋🏼‍♀️': 4, + '🏋🏼‍♂️': 4, + '🏋🏽‍♀️': 4, + '🏋🏽‍♂️': 4, + '🏋🏾‍♀️': 4, + '🏋🏾‍♂️': 4, + '🏋🏿‍♀️': 4, + '🏋🏿‍♂️': 4, + '🏌🏻‍♀️': 4, + '🏌🏻‍♂️': 4, + '🏌🏼‍♀️': 4, + '🏌🏼‍♂️': 4, + '🏌🏽‍♀️': 4, + '🏌🏽‍♂️': 4, + '🏌🏾‍♀️': 4, + '🏌🏾‍♂️': 4, + '🏌🏿‍♀️': 4, + '🏌🏿‍♂️': 4, + '🏳️‍🌈': 3, + '🏴‍☠️': 3, + '🏴󠁧󠁢󠁥󠁮󠁧󠁿': 8, + '🏴󠁧󠁢󠁳󠁣󠁴󠁿': 8, + '🏴󠁧󠁢󠁷󠁬󠁳󠁿': 8, + '🐈‍⬛': 4, + '🐕‍🦺': 4, + '🐦‍⬛': 4, + '🐦‍🔥': 4, + '🐻‍❄️': 3, + '👨‍⚕️': 3, + '👨‍⚖️': 3, + '👨‍✈️': 3, + '👨‍❤️‍👨': 5, + '👨‍❤️‍💋‍👨': 7, + '👨‍🌾': 4, + '👨‍🍳': 4, + '👨‍🍼': 4, + '👨‍🎓': 4, + '👨‍🎤': 4, + '👨‍🎨': 4, + '👨‍🏫': 4, + '👨‍🏭': 4, + '👨‍👦': 4, + '👨‍👦‍👦': 6, + '👨‍👧': 4, + '👨‍👧‍👦': 6, + '👨‍👧‍👧': 6, + '👨‍👨‍👦': 6, + '👨‍👨‍👦‍👦': 8, + '👨‍👨‍👧': 6, + '👨‍👨‍👧‍👦': 8, + '👨‍👨‍👧‍👧': 8, + '👨‍👩‍👦': 6, + '👨‍👩‍👦‍👦': 8, + '👨‍👩‍👧': 6, + '👨‍👩‍👧‍👦': 8, + '👨‍👩‍👧‍👧': 8, + '👨‍💻': 4, + '👨‍💼': 4, + '👨‍🔧': 4, + '👨‍🔬': 4, + '👨‍🚀': 4, + '👨‍🚒': 4, + '👨‍🦯': 4, + '👨‍🦯‍➡️': 5, + '👨‍🦰': 4, + '👨‍🦱': 4, + '👨‍🦲': 4, + '👨‍🦳': 4, + '👨‍🦼': 4, + '👨‍🦼‍➡️': 5, + '👨‍🦽': 4, + '👨‍🦽‍➡️': 5, + '👨🏻‍⚕️': 5, + '👨🏻‍⚖️': 5, + '👨🏻‍✈️': 5, + '👨🏻‍❤️‍👨🏻': 9, + '👨🏻‍❤️‍👨🏽': 9, + '👨🏻‍❤️‍👨🏿': 9, + '👨🏻‍❤️‍💋‍👨🏻': 11, + '👨🏻‍❤️‍💋‍👨🏽': 11, + '👨🏻‍❤️‍💋‍👨🏾': 11, + '👨🏻‍❤️‍💋‍👨🏿': 11, + '👨🏻‍🌾': 6, + '👨🏻‍🍳': 6, + '👨🏻‍🍼': 6, + '👨🏻‍🎓': 6, + '👨🏻‍🎤': 6, + '👨🏻‍🎨': 6, + '👨🏻‍🏫': 6, + '👨🏻‍🏭': 6, + '👨🏻‍🐰‍👨🏼': 10, + '👨🏻‍🐰‍👨🏽': 10, + '👨🏻‍🐰‍👨🏾': 10, + '👨🏻‍🐰‍👨🏿': 10, + '👨🏻‍💻': 6, + '👨🏻‍💼': 6, + '👨🏻‍🔧': 6, + '👨🏻‍🔬': 6, + '👨🏻‍🚀': 6, + '👨🏻‍🚒': 6, + '👨🏻‍🤝‍👨🏼': 10, + '👨🏻‍🤝‍👨🏽': 10, + '👨🏻‍🤝‍👨🏾': 10, + '👨🏻‍🤝‍👨🏿': 10, + '👨🏻‍🦯': 6, + '👨🏻‍🦯‍➡️': 7, + '👨🏻‍🦰': 6, + '👨🏻‍🦱': 6, + '👨🏻‍🦲': 6, + '👨🏻‍🦳': 6, + '👨🏻‍🦼': 6, + '👨🏻‍🦼‍➡️': 7, + '👨🏻‍🦽': 6, + '👨🏻‍🦽‍➡️': 7, + '👨🏻‍🫯‍👨🏼': 9, + '👨🏻‍🫯‍👨🏽': 9, + '👨🏻‍🫯‍👨🏾': 9, + '👨🏻‍🫯‍👨🏿': 9, + '👨🏼‍⚕️': 5, + '👨🏼‍⚖️': 5, + '👨🏼‍✈️': 5, + '👨🏼‍❤️‍👨🏼': 9, + '👨🏼‍❤️‍💋‍👨🏼': 11, + '👨🏼‍❤️‍💋‍👨🏿': 11, + '👨🏼‍🌾': 6, + '👨🏼‍🍳': 6, + '👨🏼‍🍼': 6, + '👨🏼‍🎓': 6, + '👨🏼‍🎤': 6, + '👨🏼‍🎨': 6, + '👨🏼‍🏫': 6, + '👨🏼‍🏭': 6, + '👨🏼‍🐰‍👨🏻': 10, + '👨🏼‍🐰‍👨🏽': 10, + '👨🏼‍🐰‍👨🏿': 10, + '👨🏼‍💻': 6, + '👨🏼‍💼': 6, + '👨🏼‍🔧': 6, + '👨🏼‍🔬': 6, + '👨🏼‍🚀': 6, + '👨🏼‍🚒': 6, + '👨🏼‍🤝‍👨🏻': 10, + '👨🏼‍🤝‍👨🏽': 10, + '👨🏼‍🤝‍👨🏿': 10, + '👨🏼‍🦯': 6, + '👨🏼‍🦯‍➡️': 7, + '👨🏼‍🦰': 6, + '👨🏼‍🦱': 6, + '👨🏼‍🦲': 6, + '👨🏼‍🦳': 6, + '👨🏼‍🦼': 6, + '👨🏼‍🦽': 6, + '👨🏼‍🦽‍➡️': 7, + '👨🏼‍🫯‍👨🏻': 9, + '👨🏼‍🫯‍👨🏽': 9, + '👨🏼‍🫯‍👨🏾': 9, + '👨🏼‍🫯‍👨🏿': 9, + '👨🏽‍⚕️': 5, + '👨🏽‍⚖️': 5, + '👨🏽‍✈️': 5, + '👨🏽‍❤️‍👨🏻': 9, + '👨🏽‍❤️‍👨🏽': 9, + '👨🏽‍❤️‍👨🏿': 9, + '👨🏽‍❤️‍💋‍👨🏻': 11, + '👨🏽‍❤️‍💋‍👨🏽': 11, + '👨🏽‍❤️‍💋‍👨🏿': 11, + '👨🏽‍🌾': 6, + '👨🏽‍🍳': 6, + '👨🏽‍🍼': 6, + '👨🏽‍🎓': 6, + '👨🏽‍🎤': 6, + '👨🏽‍🎨': 6, + '👨🏽‍🏫': 6, + '👨🏽‍🏭': 6, + '👨🏽‍🐰‍👨🏻': 10, + '👨🏽‍🐰‍👨🏼': 10, + '👨🏽‍🐰‍👨🏾': 10, + '👨🏽‍🐰‍👨🏿': 10, + '👨🏽‍💻': 6, + '👨🏽‍💼': 6, + '👨🏽‍🔧': 6, + '👨🏽‍🔬': 6, + '👨🏽‍🚀': 6, + '👨🏽‍🚒': 6, + '👨🏽‍🤝‍👨🏻': 10, + '👨🏽‍🤝‍👨🏼': 10, + '👨🏽‍🤝‍👨🏾': 10, + '👨🏽‍🤝‍👨🏿': 10, + '👨🏽‍🦯': 6, + '👨🏽‍🦯‍➡️': 7, + '👨🏽‍🦰': 6, + '👨🏽‍🦱': 6, + '👨🏽‍🦲': 6, + '👨🏽‍🦳': 6, + '👨🏽‍🦼': 6, + '👨🏽‍🦼‍➡️': 7, + '👨🏽‍🦽': 6, + '👨🏽‍🦽‍➡️': 7, + '👨🏽‍🫯‍👨🏻': 9, + '👨🏽‍🫯‍👨🏼': 9, + '👨🏽‍🫯‍👨🏾': 9, + '👨🏽‍🫯‍👨🏿': 9, + '👨🏾‍⚕️': 5, + '👨🏾‍⚖️': 5, + '👨🏾‍✈️': 5, + '👨🏾‍❤️‍👨🏾': 9, + '👨🏾‍❤️‍💋‍👨🏻': 11, + '👨🏾‍❤️‍💋‍👨🏾': 11, + '👨🏾‍❤️‍💋‍👨🏿': 11, + '👨🏾‍🌾': 6, + '👨🏾‍🍳': 6, + '👨🏾‍🍼': 6, + '👨🏾‍🎓': 6, + '👨🏾‍🎤': 6, + '👨🏾‍🎨': 6, + '👨🏾‍🏫': 6, + '👨🏾‍🏭': 6, + '👨🏾‍🐰‍👨🏻': 10, + '👨🏾‍🐰‍👨🏽': 10, + '👨🏾‍🐰‍👨🏿': 10, + '👨🏾‍💻': 6, + '👨🏾‍💼': 6, + '👨🏾‍🔧': 6, + '👨🏾‍🔬': 6, + '👨🏾‍🚀': 6, + '👨🏾‍🚒': 6, + '👨🏾‍🤝‍👨🏻': 10, + '👨🏾‍🤝‍👨🏽': 10, + '👨🏾‍🤝‍👨🏿': 10, + '👨🏾‍🦯': 6, + '👨🏾‍🦯‍➡️': 7, + '👨🏾‍🦰': 6, + '👨🏾‍🦱': 6, + '👨🏾‍🦲': 6, + '👨🏾‍🦳': 6, + '👨🏾‍🦼': 6, + '👨🏾‍🦽': 6, + '👨🏾‍🦽‍➡️': 7, + '👨🏾‍🫯‍👨🏻': 9, + '👨🏾‍🫯‍👨🏼': 9, + '👨🏾‍🫯‍👨🏽': 9, + '👨🏾‍🫯‍👨🏿': 9, + '👨🏿‍⚕️': 5, + '👨🏿‍⚖️': 5, + '👨🏿‍✈️': 5, + '👨🏿‍❤️‍👨🏻': 9, + '👨🏿‍❤️‍👨🏽': 9, + '👨🏿‍❤️‍👨🏿': 9, + '👨🏿‍❤️‍💋‍👨🏻': 11, + '👨🏿‍❤️‍💋‍👨🏼': 11, + '👨🏿‍❤️‍💋‍👨🏽': 11, + '👨🏿‍❤️‍💋‍👨🏾': 11, + '👨🏿‍❤️‍💋‍👨🏿': 11, + '👨🏿‍🌾': 6, + '👨🏿‍🍳': 6, + '👨🏿‍🍼': 6, + '👨🏿‍🎓': 6, + '👨🏿‍🎤': 6, + '👨🏿‍🎨': 6, + '👨🏿‍🏫': 6, + '👨🏿‍🏭': 6, + '👨🏿‍🐰‍👨🏻': 10, + '👨🏿‍🐰‍👨🏼': 10, + '👨🏿‍🐰‍👨🏽': 10, + '👨🏿‍🐰‍👨🏾': 10, + '👨🏿‍💻': 6, + '👨🏿‍💼': 6, + '👨🏿‍🔧': 6, + '👨🏿‍🔬': 6, + '👨🏿‍🚀': 6, + '👨🏿‍🚒': 6, + '👨🏿‍🤝‍👨🏻': 10, + '👨🏿‍🤝‍👨🏼': 10, + '👨🏿‍🤝‍👨🏽': 10, + '👨🏿‍🤝‍👨🏾': 10, + '👨🏿‍🦯': 6, + '👨🏿‍🦯‍➡️': 7, + '👨🏿‍🦰': 6, + '👨🏿‍🦱': 6, + '👨🏿‍🦲': 6, + '👨🏿‍🦳': 6, + '👨🏿‍🦼': 6, + '👨🏿‍🦼‍➡️': 7, + '👨🏿‍🦽': 6, + '👨🏿‍🦽‍➡️': 7, + '👨🏿‍🫯‍👨🏻': 9, + '👨🏿‍🫯‍👨🏼': 9, + '👨🏿‍🫯‍👨🏽': 9, + '👨🏿‍🫯‍👨🏾': 9, + '👩‍⚕️': 3, + '👩‍⚖️': 3, + '👩‍✈️': 3, + '👩‍❤️‍👨': 5, + '👩‍❤️‍👩': 5, + '👩‍❤️‍💋‍👨': 7, + '👩‍❤️‍💋‍👩': 7, + '👩‍🌾': 4, + '👩‍🍳': 4, + '👩‍🍼': 4, + '👩‍🎓': 4, + '👩‍🎤': 4, + '👩‍🎨': 4, + '👩‍🏫': 4, + '👩‍🏭': 4, + '👩‍👦': 4, + '👩‍👦‍👦': 6, + '👩‍👧': 4, + '👩‍👧‍👦': 6, + '👩‍👧‍👧': 6, + '👩‍👩‍👦': 6, + '👩‍👩‍👦‍👦': 8, + '👩‍👩‍👧': 6, + '👩‍👩‍👧‍👦': 8, + '👩‍👩‍👧‍👧': 8, + '👩‍💻': 4, + '👩‍💼': 4, + '👩‍🔧': 4, + '👩‍🔬': 4, + '👩‍🚀': 4, + '👩‍🚒': 4, + '👩‍🦯': 4, + '👩‍🦯‍➡️': 5, + '👩‍🦰': 4, + '👩‍🦱': 4, + '👩‍🦲': 4, + '👩‍🦳': 4, + '👩‍🦼': 4, + '👩‍🦼‍➡️': 5, + '👩‍🦽': 4, + '👩‍🦽‍➡️': 5, + '👩🏻‍⚕️': 5, + '👩🏻‍⚖️': 5, + '👩🏻‍✈️': 5, + '👩🏻‍❤️‍👨🏻': 9, + '👩🏻‍❤️‍👨🏿': 9, + '👩🏻‍❤️‍👩🏻': 9, + '👩🏻‍❤️‍💋‍👨🏻': 11, + '👩🏻‍❤️‍💋‍👨🏽': 11, + '👩🏻‍❤️‍💋‍👨🏿': 11, + '👩🏻‍❤️‍💋‍👩🏻': 11, + '👩🏻‍❤️‍💋‍👩🏽': 11, + '👩🏻‍❤️‍💋‍👩🏿': 11, + '👩🏻‍🌾': 6, + '👩🏻‍🍳': 6, + '👩🏻‍🍼': 6, + '👩🏻‍🎓': 6, + '👩🏻‍🎤': 6, + '👩🏻‍🎨': 6, + '👩🏻‍🏫': 6, + '👩🏻‍🏭': 6, + '👩🏻‍🐰‍👩🏼': 10, + '👩🏻‍🐰‍👩🏽': 10, + '👩🏻‍🐰‍👩🏾': 10, + '👩🏻‍🐰‍👩🏿': 10, + '👩🏻‍💻': 6, + '👩🏻‍💼': 6, + '👩🏻‍🔧': 6, + '👩🏻‍🔬': 6, + '👩🏻‍🚀': 6, + '👩🏻‍🚒': 6, + '👩🏻‍🤝‍👨🏽': 10, + '👩🏻‍🤝‍👨🏿': 10, + '👩🏻‍🤝‍👩🏼': 10, + '👩🏻‍🤝‍👩🏽': 10, + '👩🏻‍🤝‍👩🏾': 10, + '👩🏻‍🤝‍👩🏿': 10, + '👩🏻‍🦯': 6, + '👩🏻‍🦯‍➡️': 7, + '👩🏻‍🦰': 6, + '👩🏻‍🦱': 6, + '👩🏻‍🦲': 6, + '👩🏻‍🦳': 6, + '👩🏻‍🦼': 6, + '👩🏻‍🦼‍➡️': 7, + '👩🏻‍🦽': 6, + '👩🏻‍🦽‍➡️': 7, + '👩🏻‍🫯‍👩🏼': 9, + '👩🏻‍🫯‍👩🏽': 9, + '👩🏻‍🫯‍👩🏾': 9, + '👩🏻‍🫯‍👩🏿': 9, + '👩🏼‍⚕️': 5, + '👩🏼‍⚖️': 5, + '👩🏼‍✈️': 5, + '👩🏼‍❤️‍👨🏼': 9, + '👩🏼‍❤️‍👩🏼': 9, + '👩🏼‍❤️‍💋‍👨🏼': 11, + '👩🏼‍❤️‍💋‍👩🏼': 11, + '👩🏼‍🌾': 6, + '👩🏼‍🍳': 6, + '👩🏼‍🍼': 6, + '👩🏼‍🎓': 6, + '👩🏼‍🎤': 6, + '👩🏼‍🎨': 6, + '👩🏼‍🏫': 6, + '👩🏼‍🏭': 6, + '👩🏼‍🐰‍👩🏻': 10, + '👩🏼‍🐰‍👩🏿': 10, + '👩🏼‍💻': 6, + '👩🏼‍💼': 6, + '👩🏼‍🔧': 6, + '👩🏼‍🔬': 6, + '👩🏼‍🚀': 6, + '👩🏼‍🚒': 6, + '👩🏼‍🤝‍👩🏻': 10, + '👩🏼‍🤝‍👩🏽': 10, + '👩🏼‍🤝‍👩🏿': 10, + '👩🏼‍🦯': 6, + '👩🏼‍🦯‍➡️': 7, + '👩🏼‍🦰': 6, + '👩🏼‍🦱': 6, + '👩🏼‍🦲': 6, + '👩🏼‍🦳': 6, + '👩🏼‍🦼': 6, + '👩🏼‍🦽': 6, + '👩🏼‍🫯‍👩🏻': 9, + '👩🏼‍🫯‍👩🏽': 9, + '👩🏼‍🫯‍👩🏾': 9, + '👩🏼‍🫯‍👩🏿': 9, + '👩🏽‍⚕️': 5, + '👩🏽‍⚖️': 5, + '👩🏽‍✈️': 5, + '👩🏽‍❤️‍👨🏽': 9, + '👩🏽‍❤️‍👩🏽': 9, + '👩🏽‍❤️‍💋‍👨🏻': 11, + '👩🏽‍❤️‍💋‍👨🏽': 11, + '👩🏽‍❤️‍💋‍👨🏿': 11, + '👩🏽‍❤️‍💋‍👩🏻': 11, + '👩🏽‍❤️‍💋‍👩🏽': 11, + '👩🏽‍❤️‍💋‍👩🏿': 11, + '👩🏽‍🌾': 6, + '👩🏽‍🍳': 6, + '👩🏽‍🍼': 6, + '👩🏽‍🎓': 6, + '👩🏽‍🎤': 6, + '👩🏽‍🎨': 6, + '👩🏽‍🏫': 6, + '👩🏽‍🏭': 6, + '👩🏽‍🐰‍👩🏻': 10, + '👩🏽‍🐰‍👩🏾': 10, + '👩🏽‍🐰‍👩🏿': 10, + '👩🏽‍💻': 6, + '👩🏽‍💼': 6, + '👩🏽‍🔧': 6, + '👩🏽‍🔬': 6, + '👩🏽‍🚀': 6, + '👩🏽‍🚒': 6, + '👩🏽‍🤝‍👨🏻': 10, + '👩🏽‍🤝‍👨🏿': 10, + '👩🏽‍🤝‍👩🏻': 10, + '👩🏽‍🤝‍👩🏼': 10, + '👩🏽‍🤝‍👩🏾': 10, + '👩🏽‍🤝‍👩🏿': 10, + '👩🏽‍🦯': 6, + '👩🏽‍🦯‍➡️': 7, + '👩🏽‍🦰': 6, + '👩🏽‍🦱': 6, + '👩🏽‍🦲': 6, + '👩🏽‍🦳': 6, + '👩🏽‍🦼': 6, + '👩🏽‍🦼‍➡️': 7, + '👩🏽‍🦽': 6, + '👩🏽‍🦽‍➡️': 7, + '👩🏽‍🫯‍👩🏻': 9, + '👩🏽‍🫯‍👩🏼': 9, + '👩🏽‍🫯‍👩🏾': 9, + '👩🏽‍🫯‍👩🏿': 9, + '👩🏾‍⚕️': 5, + '👩🏾‍⚖️': 5, + '👩🏾‍✈️': 5, + '👩🏾‍❤️‍👨🏾': 9, + '👩🏾‍❤️‍👩🏾': 9, + '👩🏾‍❤️‍💋‍👨🏾': 11, + '👩🏾‍❤️‍💋‍👩🏾': 11, + '👩🏾‍🌾': 6, + '👩🏾‍🍳': 6, + '👩🏾‍🍼': 6, + '👩🏾‍🎓': 6, + '👩🏾‍🎤': 6, + '👩🏾‍🎨': 6, + '👩🏾‍🏫': 6, + '👩🏾‍🏭': 6, + '👩🏾‍🐰‍👩🏻': 10, + '👩🏾‍🐰‍👩🏽': 10, + '👩🏾‍🐰‍👩🏿': 10, + '👩🏾‍💻': 6, + '👩🏾‍💼': 6, + '👩🏾‍🔧': 6, + '👩🏾‍🔬': 6, + '👩🏾‍🚀': 6, + '👩🏾‍🚒': 6, + '👩🏾‍🤝‍👩🏻': 10, + '👩🏾‍🤝‍👩🏽': 10, + '👩🏾‍🤝‍👩🏿': 10, + '👩🏾‍🦯': 6, + '👩🏾‍🦯‍➡️': 7, + '👩🏾‍🦰': 6, + '👩🏾‍🦱': 6, + '👩🏾‍🦲': 6, + '👩🏾‍🦳': 6, + '👩🏾‍🦼': 6, + '👩🏾‍🦽': 6, + '👩🏾‍🦽‍➡️': 7, + '👩🏾‍🫯‍👩🏻': 9, + '👩🏾‍🫯‍👩🏼': 9, + '👩🏾‍🫯‍👩🏽': 9, + '👩🏾‍🫯‍👩🏿': 9, + '👩🏿‍⚕️': 5, + '👩🏿‍⚖️': 5, + '👩🏿‍✈️': 5, + '👩🏿‍❤️‍👨🏻': 9, + '👩🏿‍❤️‍👨🏿': 9, + '👩🏿‍❤️‍👩🏿': 9, + '👩🏿‍❤️‍💋‍👨🏻': 11, + '👩🏿‍❤️‍💋‍👨🏽': 11, + '👩🏿‍❤️‍💋‍👨🏿': 11, + '👩🏿‍❤️‍💋‍👩🏻': 11, + '👩🏿‍❤️‍💋‍👩🏽': 11, + '👩🏿‍❤️‍💋‍👩🏿': 11, + '👩🏿‍🌾': 6, + '👩🏿‍🍳': 6, + '👩🏿‍🍼': 6, + '👩🏿‍🎓': 6, + '👩🏿‍🎤': 6, + '👩🏿‍🎨': 6, + '👩🏿‍🏫': 6, + '👩🏿‍🏭': 6, + '👩🏿‍🐰‍👩🏻': 10, + '👩🏿‍🐰‍👩🏼': 10, + '👩🏿‍🐰‍👩🏽': 10, + '👩🏿‍🐰‍👩🏾': 10, + '👩🏿‍💻': 6, + '👩🏿‍💼': 6, + '👩🏿‍🔧': 6, + '👩🏿‍🔬': 6, + '👩🏿‍🚀': 6, + '👩🏿‍🚒': 6, + '👩🏿‍🤝‍👨🏻': 10, + '👩🏿‍🤝‍👨🏽': 10, + '👩🏿‍🤝‍👩🏻': 10, + '👩🏿‍🤝‍👩🏼': 10, + '👩🏿‍🤝‍👩🏽': 10, + '👩🏿‍🤝‍👩🏾': 10, + '👩🏿‍🦯': 6, + '👩🏿‍🦯‍➡️': 7, + '👩🏿‍🦰': 6, + '👩🏿‍🦱': 6, + '👩🏿‍🦲': 6, + '👩🏿‍🦳': 6, + '👩🏿‍🦼': 6, + '👩🏿‍🦼‍➡️': 7, + '👩🏿‍🦽': 6, + '👩🏿‍🦽‍➡️': 7, + '👩🏿‍🫯‍👩🏻': 9, + '👩🏿‍🫯‍👩🏼': 9, + '👩🏿‍🫯‍👩🏽': 9, + '👩🏿‍🫯‍👩🏾': 9, + '👮‍♀️': 3, + '👮‍♂️': 3, + '👮🏻‍♀️': 5, + '👮🏻‍♂️': 5, + '👮🏼‍♀️': 5, + '👮🏼‍♂️': 5, + '👮🏽‍♀️': 5, + '👮🏽‍♂️': 5, + '👮🏾‍♀️': 5, + '👮🏾‍♂️': 5, + '👮🏿‍♀️': 5, + '👮🏿‍♂️': 5, + '👯‍♀️': 3, + '👯‍♂️': 3, + '👯🏻‍♀️': 5, + '👯🏻‍♂️': 5, + '👯🏼‍♀️': 5, + '👯🏼‍♂️': 5, + '👯🏽‍♀️': 5, + '👯🏽‍♂️': 5, + '👯🏾‍♀️': 5, + '👯🏾‍♂️': 5, + '👯🏿‍♀️': 5, + '👯🏿‍♂️': 5, + '👰‍♀️': 3, + '👰‍♂️': 3, + '👰🏻‍♀️': 5, + '👰🏻‍♂️': 5, + '👰🏼‍♀️': 5, + '👰🏼‍♂️': 5, + '👰🏽‍♀️': 5, + '👰🏽‍♂️': 5, + '👰🏾‍♀️': 5, + '👰🏾‍♂️': 5, + '👰🏿‍♀️': 5, + '👰🏿‍♂️': 5, + '👱‍♀️': 3, + '👱‍♂️': 3, + '👱🏻‍♀️': 5, + '👱🏻‍♂️': 5, + '👱🏼‍♀️': 5, + '👱🏼‍♂️': 5, + '👱🏽‍♀️': 5, + '👱🏽‍♂️': 5, + '👱🏾‍♀️': 5, + '👱🏾‍♂️': 5, + '👱🏿‍♀️': 5, + '👱🏿‍♂️': 5, + '👳‍♀️': 3, + '👳‍♂️': 3, + '👳🏻‍♀️': 5, + '👳🏻‍♂️': 5, + '👳🏼‍♀️': 5, + '👳🏼‍♂️': 5, + '👳🏽‍♀️': 5, + '👳🏽‍♂️': 5, + '👳🏾‍♀️': 5, + '👳🏾‍♂️': 5, + '👳🏿‍♀️': 5, + '👳🏿‍♂️': 5, + '👷‍♀️': 3, + '👷‍♂️': 3, + '👷🏻‍♀️': 5, + '👷🏻‍♂️': 5, + '👷🏼‍♀️': 5, + '👷🏼‍♂️': 5, + '👷🏽‍♀️': 5, + '👷🏽‍♂️': 5, + '👷🏾‍♀️': 5, + '👷🏾‍♂️': 5, + '👷🏿‍♀️': 5, + '👷🏿‍♂️': 5, + '💁‍♀️': 3, + '💁‍♂️': 3, + '💁🏻‍♀️': 5, + '💁🏻‍♂️': 5, + '💁🏼‍♀️': 5, + '💁🏼‍♂️': 5, + '💁🏽‍♀️': 5, + '💁🏽‍♂️': 5, + '💁🏾‍♀️': 5, + '💁🏾‍♂️': 5, + '💁🏿‍♀️': 5, + '💁🏿‍♂️': 5, + '💂‍♀️': 3, + '💂‍♂️': 3, + '💂🏻‍♀️': 5, + '💂🏻‍♂️': 5, + '💂🏼‍♀️': 5, + '💂🏼‍♂️': 5, + '💂🏽‍♀️': 5, + '💂🏽‍♂️': 5, + '💂🏾‍♀️': 5, + '💂🏾‍♂️': 5, + '💂🏿‍♀️': 5, + '💂🏿‍♂️': 5, + '💆‍♀️': 3, + '💆‍♂️': 3, + '💆🏻‍♀️': 5, + '💆🏻‍♂️': 5, + '💆🏼‍♀️': 5, + '💆🏼‍♂️': 5, + '💆🏽‍♀️': 5, + '💆🏽‍♂️': 5, + '💆🏾‍♀️': 5, + '💆🏾‍♂️': 5, + '💆🏿‍♀️': 5, + '💆🏿‍♂️': 5, + '💇‍♀️': 3, + '💇‍♂️': 3, + '💇🏻‍♀️': 5, + '💇🏻‍♂️': 5, + '💇🏼‍♀️': 5, + '💇🏼‍♂️': 5, + '💇🏽‍♀️': 5, + '💇🏽‍♂️': 5, + '💇🏾‍♀️': 5, + '💇🏾‍♂️': 5, + '💇🏿‍♀️': 5, + '💇🏿‍♂️': 5, + '🕵🏻‍♀️': 4, + '🕵🏻‍♂️': 4, + '🕵🏼‍♀️': 4, + '🕵🏼‍♂️': 4, + '🕵🏽‍♀️': 4, + '🕵🏽‍♂️': 4, + '🕵🏾‍♀️': 4, + '🕵🏾‍♂️': 4, + '🕵🏿‍♀️': 4, + '🕵🏿‍♂️': 4, + '😮‍💨': 4, + '😵‍💫': 4, + '😶‍🌫️': 3, + '🙂‍↔️': 3, + '🙂‍↕️': 3, + '🙅‍♀️': 3, + '🙅‍♂️': 3, + '🙅🏻‍♀️': 5, + '🙅🏻‍♂️': 5, + '🙅🏼‍♀️': 5, + '🙅🏼‍♂️': 5, + '🙅🏽‍♀️': 5, + '🙅🏽‍♂️': 5, + '🙅🏾‍♀️': 5, + '🙅🏾‍♂️': 5, + '🙅🏿‍♀️': 5, + '🙅🏿‍♂️': 5, + '🙆‍♀️': 3, + '🙆‍♂️': 3, + '🙆🏻‍♀️': 5, + '🙆🏻‍♂️': 5, + '🙆🏼‍♀️': 5, + '🙆🏼‍♂️': 5, + '🙆🏽‍♀️': 5, + '🙆🏽‍♂️': 5, + '🙆🏾‍♀️': 5, + '🙆🏾‍♂️': 5, + '🙆🏿‍♀️': 5, + '🙆🏿‍♂️': 5, + '🙇‍♀️': 3, + '🙇‍♂️': 3, + '🙇🏻‍♀️': 5, + '🙇🏻‍♂️': 5, + '🙇🏼‍♀️': 5, + '🙇🏼‍♂️': 5, + '🙇🏽‍♀️': 5, + '🙇🏽‍♂️': 5, + '🙇🏾‍♀️': 5, + '🙇🏾‍♂️': 5, + '🙇🏿‍♀️': 5, + '🙇🏿‍♂️': 5, + '🙋‍♀️': 3, + '🙋‍♂️': 3, + '🙋🏻‍♀️': 5, + '🙋🏻‍♂️': 5, + '🙋🏼‍♀️': 5, + '🙋🏼‍♂️': 5, + '🙋🏽‍♀️': 5, + '🙋🏽‍♂️': 5, + '🙋🏾‍♀️': 5, + '🙋🏾‍♂️': 5, + '🙋🏿‍♀️': 5, + '🙋🏿‍♂️': 5, + '🙍‍♀️': 3, + '🙍‍♂️': 3, + '🙍🏻‍♀️': 5, + '🙍🏻‍♂️': 5, + '🙍🏼‍♀️': 5, + '🙍🏼‍♂️': 5, + '🙍🏽‍♀️': 5, + '🙍🏽‍♂️': 5, + '🙍🏾‍♀️': 5, + '🙍🏾‍♂️': 5, + '🙍🏿‍♀️': 5, + '🙍🏿‍♂️': 5, + '🙎‍♀️': 3, + '🙎‍♂️': 3, + '🙎🏻‍♀️': 5, + '🙎🏻‍♂️': 5, + '🙎🏼‍♀️': 5, + '🙎🏼‍♂️': 5, + '🙎🏽‍♀️': 5, + '🙎🏽‍♂️': 5, + '🙎🏾‍♀️': 5, + '🙎🏾‍♂️': 5, + '🙎🏿‍♀️': 5, + '🙎🏿‍♂️': 5, + '🚣‍♀️': 3, + '🚣‍♂️': 3, + '🚣🏻‍♀️': 5, + '🚣🏻‍♂️': 5, + '🚣🏼‍♀️': 5, + '🚣🏼‍♂️': 5, + '🚣🏽‍♀️': 5, + '🚣🏽‍♂️': 5, + '🚣🏾‍♀️': 5, + '🚣🏾‍♂️': 5, + '🚣🏿‍♀️': 5, + '🚣🏿‍♂️': 5, + '🚴‍♀️': 3, + '🚴‍♂️': 3, + '🚴🏻‍♀️': 5, + '🚴🏻‍♂️': 5, + '🚴🏼‍♀️': 5, + '🚴🏼‍♂️': 5, + '🚴🏽‍♀️': 5, + '🚴🏽‍♂️': 5, + '🚴🏾‍♀️': 5, + '🚴🏾‍♂️': 5, + '🚴🏿‍♀️': 5, + '🚴🏿‍♂️': 5, + '🚵‍♀️': 3, + '🚵‍♂️': 3, + '🚵🏻‍♀️': 5, + '🚵🏻‍♂️': 5, + '🚵🏼‍♀️': 5, + '🚵🏼‍♂️': 5, + '🚵🏽‍♀️': 5, + '🚵🏽‍♂️': 5, + '🚵🏾‍♀️': 5, + '🚵🏾‍♂️': 5, + '🚵🏿‍♀️': 5, + '🚵🏿‍♂️': 5, + '🚶‍♀️': 3, + '🚶‍♀️‍➡️': 4, + '🚶‍♂️': 3, + '🚶‍♂️‍➡️': 4, + '🚶‍➡️': 3, + '🚶🏻‍♀️': 5, + '🚶🏻‍♀️‍➡️': 6, + '🚶🏻‍♂️': 5, + '🚶🏻‍♂️‍➡️': 6, + '🚶🏻‍➡️': 5, + '🚶🏼‍♀️': 5, + '🚶🏼‍♀️‍➡️': 6, + '🚶🏼‍♂️': 5, + '🚶🏼‍♂️‍➡️': 6, + '🚶🏼‍➡️': 5, + '🚶🏽‍♀️': 5, + '🚶🏽‍♀️‍➡️': 6, + '🚶🏽‍♂️': 5, + '🚶🏽‍♂️‍➡️': 6, + '🚶🏽‍➡️': 5, + '🚶🏾‍♀️': 5, + '🚶🏾‍♀️‍➡️': 6, + '🚶🏾‍♂️': 5, + '🚶🏾‍♂️‍➡️': 6, + '🚶🏾‍➡️': 5, + '🚶🏿‍♀️': 5, + '🚶🏿‍♀️‍➡️': 6, + '🚶🏿‍♂️': 5, + '🚶🏿‍♂️‍➡️': 6, + '🚶🏿‍➡️': 5, + '🤦‍♀️': 3, + '🤦‍♂️': 3, + '🤦🏻‍♀️': 5, + '🤦🏻‍♂️': 5, + '🤦🏼‍♀️': 5, + '🤦🏼‍♂️': 5, + '🤦🏽‍♀️': 5, + '🤦🏽‍♂️': 5, + '🤦🏾‍♀️': 5, + '🤦🏾‍♂️': 5, + '🤦🏿‍♀️': 5, + '🤦🏿‍♂️': 5, + '🤵‍♀️': 3, + '🤵‍♂️': 3, + '🤵🏻‍♀️': 5, + '🤵🏻‍♂️': 5, + '🤵🏼‍♀️': 5, + '🤵🏼‍♂️': 5, + '🤵🏽‍♀️': 5, + '🤵🏽‍♂️': 5, + '🤵🏾‍♀️': 5, + '🤵🏾‍♂️': 5, + '🤵🏿‍♀️': 5, + '🤵🏿‍♂️': 5, + '🤷‍♀️': 3, + '🤷‍♂️': 3, + '🤷🏻‍♀️': 5, + '🤷🏻‍♂️': 5, + '🤷🏼‍♀️': 5, + '🤷🏼‍♂️': 5, + '🤷🏽‍♀️': 5, + '🤷🏽‍♂️': 5, + '🤷🏾‍♀️': 5, + '🤷🏾‍♂️': 5, + '🤷🏿‍♀️': 5, + '🤷🏿‍♂️': 5, + '🤸‍♀️': 3, + '🤸‍♂️': 3, + '🤸🏻‍♀️': 5, + '🤸🏻‍♂️': 5, + '🤸🏼‍♀️': 5, + '🤸🏼‍♂️': 5, + '🤸🏽‍♀️': 5, + '🤸🏽‍♂️': 5, + '🤸🏾‍♀️': 5, + '🤸🏾‍♂️': 5, + '🤸🏿‍♀️': 5, + '🤸🏿‍♂️': 5, + '🤹‍♀️': 3, + '🤹‍♂️': 3, + '🤹🏻‍♀️': 5, + '🤹🏻‍♂️': 5, + '🤹🏼‍♀️': 5, + '🤹🏼‍♂️': 5, + '🤹🏽‍♀️': 5, + '🤹🏽‍♂️': 5, + '🤹🏾‍♀️': 5, + '🤹🏾‍♂️': 5, + '🤹🏿‍♀️': 5, + '🤹🏿‍♂️': 5, + '🤼‍♀️': 3, + '🤼‍♂️': 3, + '🤼🏻‍♀️': 5, + '🤼🏻‍♂️': 5, + '🤼🏼‍♀️': 5, + '🤼🏼‍♂️': 5, + '🤼🏽‍♀️': 5, + '🤼🏽‍♂️': 5, + '🤼🏾‍♀️': 5, + '🤼🏾‍♂️': 5, + '🤼🏿‍♀️': 5, + '🤼🏿‍♂️': 5, + '🤽‍♀️': 3, + '🤽‍♂️': 3, + '🤽🏻‍♀️': 5, + '🤽🏻‍♂️': 5, + '🤽🏼‍♀️': 5, + '🤽🏼‍♂️': 5, + '🤽🏽‍♀️': 5, + '🤽🏽‍♂️': 5, + '🤽🏾‍♀️': 5, + '🤽🏾‍♂️': 5, + '🤽🏿‍♀️': 5, + '🤽🏿‍♂️': 5, + '🤾‍♀️': 3, + '🤾‍♂️': 3, + '🤾🏻‍♀️': 5, + '🤾🏻‍♂️': 5, + '🤾🏼‍♀️': 5, + '🤾🏼‍♂️': 5, + '🤾🏽‍♀️': 5, + '🤾🏽‍♂️': 5, + '🤾🏾‍♀️': 5, + '🤾🏾‍♂️': 5, + '🤾🏿‍♀️': 5, + '🤾🏿‍♂️': 5, + '🦸‍♀️': 3, + '🦸‍♂️': 3, + '🦸🏻‍♀️': 5, + '🦸🏻‍♂️': 5, + '🦸🏼‍♀️': 5, + '🦸🏼‍♂️': 5, + '🦸🏽‍♀️': 5, + '🦸🏽‍♂️': 5, + '🦸🏾‍♀️': 5, + '🦸🏾‍♂️': 5, + '🦸🏿‍♀️': 5, + '🦸🏿‍♂️': 5, + '🦹‍♀️': 3, + '🦹‍♂️': 3, + '🦹🏻‍♀️': 5, + '🦹🏻‍♂️': 5, + '🦹🏼‍♀️': 5, + '🦹🏼‍♂️': 5, + '🦹🏽‍♀️': 5, + '🦹🏽‍♂️': 5, + '🦹🏾‍♀️': 5, + '🦹🏾‍♂️': 5, + '🦹🏿‍♀️': 5, + '🦹🏿‍♂️': 5, + '🧍‍♀️': 3, + '🧍‍♂️': 3, + '🧍🏻‍♀️': 5, + '🧍🏻‍♂️': 5, + '🧍🏼‍♀️': 5, + '🧍🏼‍♂️': 5, + '🧍🏽‍♀️': 5, + '🧍🏽‍♂️': 5, + '🧍🏾‍♀️': 5, + '🧍🏾‍♂️': 5, + '🧍🏿‍♀️': 5, + '🧍🏿‍♂️': 5, + '🧎‍♀️': 3, + '🧎‍♀️‍➡️': 4, + '🧎‍♂️': 3, + '🧎‍♂️‍➡️': 4, + '🧎‍➡️': 3, + '🧎🏻‍♀️': 5, + '🧎🏻‍♀️‍➡️': 6, + '🧎🏻‍♂️': 5, + '🧎🏻‍♂️‍➡️': 6, + '🧎🏻‍➡️': 5, + '🧎🏼‍♀️': 5, + '🧎🏼‍♀️‍➡️': 6, + '🧎🏼‍♂️': 5, + '🧎🏼‍♂️‍➡️': 6, + '🧎🏼‍➡️': 5, + '🧎🏽‍♀️': 5, + '🧎🏽‍♀️‍➡️': 6, + '🧎🏽‍♂️': 5, + '🧎🏽‍♂️‍➡️': 6, + '🧎🏽‍➡️': 5, + '🧎🏾‍♀️': 5, + '🧎🏾‍♀️‍➡️': 6, + '🧎🏾‍♂️': 5, + '🧎🏾‍♂️‍➡️': 6, + '🧎🏾‍➡️': 5, + '🧎🏿‍♀️': 5, + '🧎🏿‍♀️‍➡️': 6, + '🧎🏿‍♂️': 5, + '🧎🏿‍♂️‍➡️': 6, + '🧎🏿‍➡️': 5, + '🧏‍♀️': 3, + '🧏‍♂️': 3, + '🧏🏻‍♀️': 5, + '🧏🏻‍♂️': 5, + '🧏🏼‍♀️': 5, + '🧏🏼‍♂️': 5, + '🧏🏽‍♀️': 5, + '🧏🏽‍♂️': 5, + '🧏🏾‍♀️': 5, + '🧏🏾‍♂️': 5, + '🧏🏿‍♀️': 5, + '🧏🏿‍♂️': 5, + '🧑‍⚕️': 3, + '🧑‍⚖️': 3, + '🧑‍✈️': 3, + '🧑‍🌾': 4, + '🧑‍🍳': 4, + '🧑‍🍼': 4, + '🧑‍🎄': 4, + '🧑‍🎓': 4, + '🧑‍🎤': 4, + '🧑‍🎨': 4, + '🧑‍🏫': 4, + '🧑‍🏭': 4, + '🧑‍💻': 4, + '🧑‍💼': 4, + '🧑‍🔧': 4, + '🧑‍🔬': 4, + '🧑‍🚀': 4, + '🧑‍🚒': 4, + '🧑‍🤝‍🧑': 6, + '🧑‍🦯': 4, + '🧑‍🦯‍➡️': 5, + '🧑‍🦰': 4, + '🧑‍🦱': 4, + '🧑‍🦲': 4, + '🧑‍🦳': 4, + '🧑‍🦼': 4, + '🧑‍🦼‍➡️': 5, + '🧑‍🦽': 4, + '🧑‍🦽‍➡️': 5, + '🧑‍🧑‍🧒': 6, + '🧑‍🧑‍🧒‍🧒': 8, + '🧑‍🧒': 4, + '🧑‍🧒‍🧒': 6, + '🧑‍🩰': 4, + '🧑🏻‍⚕️': 5, + '🧑🏻‍⚖️': 5, + '🧑🏻‍✈️': 5, + '🧑🏻‍❤️‍💋‍🧑🏿': 11, + '🧑🏻‍🌾': 6, + '🧑🏻‍🍳': 6, + '🧑🏻‍🍼': 6, + '🧑🏻‍🎄': 6, + '🧑🏻‍🎓': 6, + '🧑🏻‍🎤': 6, + '🧑🏻‍🎨': 6, + '🧑🏻‍🏫': 6, + '🧑🏻‍🏭': 6, + '🧑🏻‍🐰‍🧑🏽': 10, + '🧑🏻‍🐰‍🧑🏾': 10, + '🧑🏻‍🐰‍🧑🏿': 10, + '🧑🏻‍💻': 6, + '🧑🏻‍💼': 6, + '🧑🏻‍🔧': 6, + '🧑🏻‍🔬': 6, + '🧑🏻‍🚀': 6, + '🧑🏻‍🚒': 6, + '🧑🏻‍🤝‍🧑🏻': 10, + '🧑🏻‍🤝‍🧑🏼': 10, + '🧑🏻‍🤝‍🧑🏽': 10, + '🧑🏻‍🤝‍🧑🏾': 10, + '🧑🏻‍🤝‍🧑🏿': 10, + '🧑🏻‍🦯': 6, + '🧑🏻‍🦯‍➡️': 7, + '🧑🏻‍🦰': 6, + '🧑🏻‍🦱': 6, + '🧑🏻‍🦲': 6, + '🧑🏻‍🦳': 6, + '🧑🏻‍🦼': 6, + '🧑🏻‍🦼‍➡️': 7, + '🧑🏻‍🦽': 6, + '🧑🏻‍🦽‍➡️': 7, + '🧑🏻‍🩰': 6, + '🧑🏻‍🫯‍🧑🏼': 9, + '🧑🏻‍🫯‍🧑🏽': 9, + '🧑🏻‍🫯‍🧑🏾': 9, + '🧑🏻‍🫯‍🧑🏿': 9, + '🧑🏼‍⚕️': 5, + '🧑🏼‍⚖️': 5, + '🧑🏼‍✈️': 5, + '🧑🏼‍🌾': 6, + '🧑🏼‍🍳': 6, + '🧑🏼‍🍼': 6, + '🧑🏼‍🎄': 6, + '🧑🏼‍🎓': 6, + '🧑🏼‍🎤': 6, + '🧑🏼‍🎨': 6, + '🧑🏼‍🏫': 6, + '🧑🏼‍🏭': 6, + '🧑🏼‍🐰‍🧑🏿': 10, + '🧑🏼‍💻': 6, + '🧑🏼‍💼': 6, + '🧑🏼‍🔧': 6, + '🧑🏼‍🔬': 6, + '🧑🏼‍🚀': 6, + '🧑🏼‍🚒': 6, + '🧑🏼‍🤝‍🧑🏻': 10, + '🧑🏼‍🤝‍🧑🏼': 10, + '🧑🏼‍🤝‍🧑🏽': 10, + '🧑🏼‍🤝‍🧑🏿': 10, + '🧑🏼‍🦯': 6, + '🧑🏼‍🦯‍➡️': 7, + '🧑🏼‍🦰': 6, + '🧑🏼‍🦱': 6, + '🧑🏼‍🦲': 6, + '🧑🏼‍🦳': 6, + '🧑🏼‍🦼': 6, + '🧑🏼‍🦽': 6, + '🧑🏼‍🩰': 6, + '🧑🏼‍🫯‍🧑🏻': 9, + '🧑🏼‍🫯‍🧑🏽': 9, + '🧑🏼‍🫯‍🧑🏿': 9, + '🧑🏽‍⚕️': 5, + '🧑🏽‍⚖️': 5, + '🧑🏽‍✈️': 5, + '🧑🏽‍❤️‍💋‍🧑🏿': 11, + '🧑🏽‍🌾': 6, + '🧑🏽‍🍳': 6, + '🧑🏽‍🍼': 6, + '🧑🏽‍🎄': 6, + '🧑🏽‍🎓': 6, + '🧑🏽‍🎤': 6, + '🧑🏽‍🎨': 6, + '🧑🏽‍🏫': 6, + '🧑🏽‍🏭': 6, + '🧑🏽‍🐰‍🧑🏻': 10, + '🧑🏽‍🐰‍🧑🏿': 10, + '🧑🏽‍💻': 6, + '🧑🏽‍💼': 6, + '🧑🏽‍🔧': 6, + '🧑🏽‍🔬': 6, + '🧑🏽‍🚀': 6, + '🧑🏽‍🚒': 6, + '🧑🏽‍🤝‍🧑🏻': 10, + '🧑🏽‍🤝‍🧑🏼': 10, + '🧑🏽‍🤝‍🧑🏽': 10, + '🧑🏽‍🤝‍🧑🏾': 10, + '🧑🏽‍🤝‍🧑🏿': 10, + '🧑🏽‍🦯': 6, + '🧑🏽‍🦯‍➡️': 7, + '🧑🏽‍🦰': 6, + '🧑🏽‍🦱': 6, + '🧑🏽‍🦲': 6, + '🧑🏽‍🦳': 6, + '🧑🏽‍🦼': 6, + '🧑🏽‍🦼‍➡️': 7, + '🧑🏽‍🦽': 6, + '🧑🏽‍🦽‍➡️': 7, + '🧑🏽‍🩰': 6, + '🧑🏽‍🫯‍🧑🏻': 9, + '🧑🏽‍🫯‍🧑🏼': 9, + '🧑🏽‍🫯‍🧑🏾': 9, + '🧑🏽‍🫯‍🧑🏿': 9, + '🧑🏾‍⚕️': 5, + '🧑🏾‍⚖️': 5, + '🧑🏾‍✈️': 5, + '🧑🏾‍🌾': 6, + '🧑🏾‍🍳': 6, + '🧑🏾‍🍼': 6, + '🧑🏾‍🎄': 6, + '🧑🏾‍🎓': 6, + '🧑🏾‍🎤': 6, + '🧑🏾‍🎨': 6, + '🧑🏾‍🏫': 6, + '🧑🏾‍🏭': 6, + '🧑🏾‍🐰‍🧑🏻': 10, + '🧑🏾‍🐰‍🧑🏿': 10, + '🧑🏾‍💻': 6, + '🧑🏾‍💼': 6, + '🧑🏾‍🔧': 6, + '🧑🏾‍🔬': 6, + '🧑🏾‍🚀': 6, + '🧑🏾‍🚒': 6, + '🧑🏾‍🤝‍🧑🏻': 10, + '🧑🏾‍🤝‍🧑🏽': 10, + '🧑🏾‍🤝‍🧑🏾': 10, + '🧑🏾‍🤝‍🧑🏿': 10, + '🧑🏾‍🦯': 6, + '🧑🏾‍🦯‍➡️': 7, + '🧑🏾‍🦰': 6, + '🧑🏾‍🦱': 6, + '🧑🏾‍🦲': 6, + '🧑🏾‍🦳': 6, + '🧑🏾‍🦼': 6, + '🧑🏾‍🦽': 6, + '🧑🏾‍🩰': 6, + '🧑🏾‍🫯‍🧑🏻': 9, + '🧑🏾‍🫯‍🧑🏽': 9, + '🧑🏾‍🫯‍🧑🏿': 9, + '🧑🏿‍⚕️': 5, + '🧑🏿‍⚖️': 5, + '🧑🏿‍✈️': 5, + '🧑🏿‍❤️‍💋‍🧑🏻': 11, + '🧑🏿‍❤️‍💋‍🧑🏽': 11, + '🧑🏿‍🌾': 6, + '🧑🏿‍🍳': 6, + '🧑🏿‍🍼': 6, + '🧑🏿‍🎄': 6, + '🧑🏿‍🎓': 6, + '🧑🏿‍🎤': 6, + '🧑🏿‍🎨': 6, + '🧑🏿‍🏫': 6, + '🧑🏿‍🏭': 6, + '🧑🏿‍🐰‍🧑🏻': 10, + '🧑🏿‍🐰‍🧑🏼': 10, + '🧑🏿‍🐰‍🧑🏽': 10, + '🧑🏿‍🐰‍🧑🏾': 10, + '🧑🏿‍💻': 6, + '🧑🏿‍💼': 6, + '🧑🏿‍🔧': 6, + '🧑🏿‍🔬': 6, + '🧑🏿‍🚀': 6, + '🧑🏿‍🚒': 6, + '🧑🏿‍🤝‍🧑🏻': 10, + '🧑🏿‍🤝‍🧑🏼': 10, + '🧑🏿‍🤝‍🧑🏽': 10, + '🧑🏿‍🤝‍🧑🏾': 10, + '🧑🏿‍🤝‍🧑🏿': 10, + '🧑🏿‍🦯': 6, + '🧑🏿‍🦯‍➡️': 7, + '🧑🏿‍🦰': 6, + '🧑🏿‍🦱': 6, + '🧑🏿‍🦲': 6, + '🧑🏿‍🦳': 6, + '🧑🏿‍🦼': 6, + '🧑🏿‍🦼‍➡️': 7, + '🧑🏿‍🦽': 6, + '🧑🏿‍🦽‍➡️': 7, + '🧑🏿‍🩰': 6, + '🧑🏿‍🫯‍🧑🏻': 9, + '🧑🏿‍🫯‍🧑🏼': 9, + '🧑🏿‍🫯‍🧑🏽': 9, + '🧑🏿‍🫯‍🧑🏾': 9, + '🧔‍♀️': 3, + '🧔‍♂️': 3, + '🧔🏻‍♀️': 5, + '🧔🏻‍♂️': 5, + '🧔🏼‍♀️': 5, + '🧔🏼‍♂️': 5, + '🧔🏽‍♀️': 5, + '🧔🏽‍♂️': 5, + '🧔🏾‍♀️': 5, + '🧔🏾‍♂️': 5, + '🧔🏿‍♀️': 5, + '🧔🏿‍♂️': 5, + '🧖‍♀️': 3, + '🧖‍♂️': 3, + '🧖🏻‍♀️': 5, + '🧖🏻‍♂️': 5, + '🧖🏼‍♀️': 5, + '🧖🏼‍♂️': 5, + '🧖🏽‍♀️': 5, + '🧖🏽‍♂️': 5, + '🧖🏾‍♀️': 5, + '🧖🏾‍♂️': 5, + '🧖🏿‍♀️': 5, + '🧖🏿‍♂️': 5, + '🧗‍♀️': 3, + '🧗‍♂️': 3, + '🧗🏻‍♀️': 5, + '🧗🏻‍♂️': 5, + '🧗🏼‍♀️': 5, + '🧗🏼‍♂️': 5, + '🧗🏽‍♀️': 5, + '🧗🏽‍♂️': 5, + '🧗🏾‍♀️': 5, + '🧗🏾‍♂️': 5, + '🧗🏿‍♀️': 5, + '🧗🏿‍♂️': 5, + '🧘‍♀️': 3, + '🧘‍♂️': 3, + '🧘🏻‍♀️': 5, + '🧘🏻‍♂️': 5, + '🧘🏼‍♀️': 5, + '🧘🏼‍♂️': 5, + '🧘🏽‍♀️': 5, + '🧘🏽‍♂️': 5, + '🧘🏾‍♀️': 5, + '🧘🏾‍♂️': 5, + '🧘🏿‍♀️': 5, + '🧘🏿‍♂️': 5, + '🧙‍♀️': 3, + '🧙‍♂️': 3, + '🧙🏻‍♀️': 5, + '🧙🏻‍♂️': 5, + '🧙🏼‍♀️': 5, + '🧙🏼‍♂️': 5, + '🧙🏽‍♀️': 5, + '🧙🏽‍♂️': 5, + '🧙🏾‍♀️': 5, + '🧙🏾‍♂️': 5, + '🧙🏿‍♀️': 5, + '🧙🏿‍♂️': 5, + '🧚‍♀️': 3, + '🧚‍♂️': 3, + '🧚🏻‍♀️': 5, + '🧚🏻‍♂️': 5, + '🧚🏼‍♀️': 5, + '🧚🏼‍♂️': 5, + '🧚🏽‍♀️': 5, + '🧚🏽‍♂️': 5, + '🧚🏾‍♀️': 5, + '🧚🏾‍♂️': 5, + '🧚🏿‍♀️': 5, + '🧚🏿‍♂️': 5, + '🧛‍♀️': 3, + '🧛‍♂️': 3, + '🧛🏻‍♀️': 5, + '🧛🏻‍♂️': 5, + '🧛🏼‍♀️': 5, + '🧛🏼‍♂️': 5, + '🧛🏽‍♀️': 5, + '🧛🏽‍♂️': 5, + '🧛🏾‍♀️': 5, + '🧛🏾‍♂️': 5, + '🧛🏿‍♀️': 5, + '🧛🏿‍♂️': 5, + '🧜‍♀️': 3, + '🧜‍♂️': 3, + '🧜🏻‍♀️': 5, + '🧜🏻‍♂️': 5, + '🧜🏼‍♀️': 5, + '🧜🏼‍♂️': 5, + '🧜🏽‍♀️': 5, + '🧜🏽‍♂️': 5, + '🧜🏾‍♀️': 5, + '🧜🏾‍♂️': 5, + '🧜🏿‍♀️': 5, + '🧜🏿‍♂️': 5, + '🧝‍♀️': 3, + '🧝‍♂️': 3, + '🧝🏻‍♀️': 5, + '🧝🏻‍♂️': 5, + '🧝🏼‍♀️': 5, + '🧝🏼‍♂️': 5, + '🧝🏽‍♀️': 5, + '🧝🏽‍♂️': 5, + '🧝🏾‍♀️': 5, + '🧝🏾‍♂️': 5, + '🧝🏿‍♀️': 5, + '🧝🏿‍♂️': 5, + '🧞‍♀️': 3, + '🧞‍♂️': 3, + '🧟‍♀️': 3, + '🧟‍♂️': 3, + '🫱🏻‍🫲🏼': 6, + '🫱🏻‍🫲🏽': 6, + '🫱🏻‍🫲🏾': 6, + '🫱🏻‍🫲🏿': 6, + '🫱🏼‍🫲🏻': 6, + '🫱🏼‍🫲🏽': 6, + '🫱🏼‍🫲🏾': 6, + '🫱🏼‍🫲🏿': 6, + '🫱🏽‍🫲🏻': 6, + '🫱🏽‍🫲🏼': 6, + '🫱🏽‍🫲🏾': 6, + '🫱🏽‍🫲🏿': 6, + '🫱🏾‍🫲🏻': 6, + '🫱🏾‍🫲🏼': 6, + '🫱🏾‍🫲🏽': 6, + '🫱🏾‍🫲🏿': 6, + '🫱🏿‍🫲🏻': 6, + '🫱🏿‍🫲🏼': 6, + '🫱🏿‍🫲🏽': 6, + '🫱🏿‍🫲🏾': 6, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_cf02297d.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_cf02297d.py new file mode 100644 index 0000000000000000000000000000000000000000..ff6e2674c3b3610bbda78929fd8cfdec76ae03d1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_cf02297d.py @@ -0,0 +1,1799 @@ +""" +Grapheme overrides for _known_cf02297d. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: foot +""" +# pylint: skip-file +GRAPHEMES = { + '؁۱': 1, + 'का': 1, + 'कां': 1, + 'कि': 1, + 'किं': 1, + 'की': 1, + 'केा': 1, + 'को': 1, + 'कौ': 1, + 'खा': 1, + 'खि': 1, + 'खी': 1, + 'खो': 1, + 'ग़ा': 1, + 'गा': 1, + 'गाँ': 1, + 'गां': 1, + 'गि': 1, + 'गी': 1, + 'गो': 1, + 'गों': 1, + 'गौ': 1, + 'घा': 1, + 'घि': 1, + 'घी': 1, + 'घेि': 1, + 'घो': 1, + 'चा': 1, + 'चां': 1, + 'चि': 1, + 'ची': 1, + 'चो': 1, + 'चौ': 1, + 'छि': 1, + 'छुी': 1, + 'छो': 1, + 'जा': 1, + 'जि': 1, + 'जिं': 1, + 'जी': 1, + 'जो': 1, + 'झा': 1, + 'टा': 1, + 'टां': 1, + 'टि': 1, + 'टी': 1, + 'टों': 1, + 'ठा': 1, + 'ठी': 1, + 'ठैः': 1, + 'ड़ा': 1, + 'डा': 1, + 'डि': 1, + 'डी': 1, + 'डो': 1, + 'ढ़ा': 1, + 'ढ़ि': 1, + 'ढ़ी': 1, + 'ढ़ो': 1, + 'ढा': 1, + 'ढाँ': 1, + 'ढि': 1, + 'णा': 1, + 'णां': 1, + 'णि': 1, + 'णी': 1, + 'णो': 1, + 'णों': 1, + 'तः': 1, + 'ता': 1, + 'तां': 1, + 'ताः': 1, + 'ति': 1, + 'तिं': 1, + 'ती': 1, + 'तो': 1, + 'तों': 1, + 'तौ': 1, + 'था': 1, + 'थि': 1, + 'दः': 1, + 'दा': 1, + 'दां': 1, + 'दि': 1, + 'दी': 1, + 'दो': 1, + 'दौ': 1, + 'धा': 1, + 'धां': 1, + 'धाः': 1, + 'धि': 1, + 'धी': 1, + 'धेः': 1, + 'धो': 1, + 'धों': 1, + 'नः': 1, + 'ना': 1, + 'नां': 1, + 'नाः': 1, + 'ना‌': 1, + 'नि': 1, + 'निँ': 1, + 'निः': 1, + 'नी': 1, + 'नैः': 1, + 'नो': 1, + 'नों': 1, + 'नौ': 1, + 'पा': 1, + 'पाँ': 1, + 'पां': 1, + 'पि': 1, + 'पी': 1, + 'पो': 1, + 'पों': 1, + 'फा': 1, + 'फाँ': 1, + 'फौ': 1, + 'बा': 1, + 'बाँ': 1, + 'बि': 1, + 'बी': 1, + 'बो': 1, + 'भा': 1, + 'भि': 1, + 'भिः': 1, + 'भी': 1, + 'भो': 1, + 'भौ': 1, + 'मा': 1, + 'मां': 1, + 'मि': 1, + 'मी': 1, + 'मो': 1, + 'मों': 1, + 'मौ': 1, + 'यः': 1, + 'या': 1, + 'यां': 1, + 'याः': 1, + 'यि': 1, + 'यी': 1, + 'यैः': 1, + 'यो': 1, + 'यों': 1, + 'रः': 1, + 'रा': 1, + 'रां': 1, + 'राः': 1, + 'रि': 1, + 'रिं': 1, + 'री': 1, + 'रो': 1, + 'रों': 1, + 'रौ': 1, + 'ला': 1, + 'लां': 1, + 'लाः': 1, + 'लि': 1, + 'लिं': 1, + 'ली': 1, + 'लीं': 1, + 'लो': 1, + 'लों': 1, + 'लौ': 1, + 'ळा': 1, + 'ळी': 1, + 'वः': 1, + 'वा': 1, + 'वां': 1, + 'वाः': 1, + 'वि': 1, + 'वी': 1, + 'वो': 1, + 'वों': 1, + 'शः': 1, + 'शा': 1, + 'शां': 1, + 'शाः': 1, + 'शि': 1, + 'शी': 1, + 'शो': 1, + 'शों': 1, + 'षा': 1, + 'षां': 1, + 'षाः': 1, + 'षि': 1, + 'षी': 1, + 'षों': 1, + 'सः': 1, + 'सा': 1, + 'साँ': 1, + 'सां': 1, + 'सि': 1, + 'सी': 1, + 'सो': 1, + 'सौ': 1, + 'हा': 1, + 'हाँ': 1, + 'हां': 1, + 'हि': 1, + 'हिं': 1, + 'ही': 1, + 'हीं': 1, + 'हैः': 1, + 'हो': 1, + 'हों': 1, + 'हौ': 1, + 'क़ा': 1, + 'क़ि': 1, + 'ज़ा': 1, + 'ड़ा': 1, + 'ढ़ा': 1, + 'फ़ा': 1, + 'অং': 1, + 'কা': 1, + 'কা‌': 1, + 'কি': 1, + 'কিং': 1, + 'কে': 1, + 'কে‌': 1, + 'কো': 1, + 'খা': 1, + 'খি': 1, + 'খে': 1, + 'গি': 1, + 'গে': 1, + 'গো': 1, + 'ঘা': 1, + 'ঘে': 1, + 'ঘো': 1, + 'ঘো': 1, + 'চা': 1, + 'চি': 1, + 'চে': 1, + 'চো': 1, + 'চৌ': 1, + 'ছা': 1, + 'ছি': 1, + 'ছে': 1, + 'জা': 1, + 'জি': 1, + 'জী': 1, + 'জে': 1, + 'জে‌': 1, + 'ঝো': 1, + 'টা': 1, + 'টি': 1, + 'ঠি': 1, + 'ড়া': 1, + 'ণা': 1, + 'ণি': 1, + 'ণে': 1, + 'তঃ': 1, + 'তা': 1, + 'তাঁ': 1, + 'তা‌': 1, + 'তি': 1, + 'তি‌': 1, + 'তী': 1, + 'তে': 1, + 'তে‌': 1, + 'থা': 1, + 'থি': 1, + 'থে': 1, + 'দা': 1, + 'দি': 1, + 'দে': 1, + 'দে‌': 1, + 'দৈ': 1, + 'দো': 1, + 'ধা': 1, + 'ধি': 1, + 'ধী': 1, + 'ধে': 1, + 'না': 1, + 'না‌': 1, + 'নি': 1, + 'নী': 1, + 'নে': 1, + 'নৈ': 1, + 'নো': 1, + 'পা': 1, + 'পা‌': 1, + 'পি': 1, + 'পী': 1, + 'পে': 1, + 'পো': 1, + 'ফে': 1, + 'ফৌ': 1, + 'বং': 1, + 'বা': 1, + 'বা‌': 1, + 'বি': 1, + 'বী': 1, + 'বে': 1, + 'বৈ': 1, + 'বো': 1, + 'ভা': 1, + 'ভি': 1, + 'ভে': 1, + 'ভো': 1, + 'ভৌ': 1, + 'মা': 1, + 'মা‌': 1, + 'মি': 1, + 'মে': 1, + 'মৌ': 1, + 'য়া': 1, + 'য়ি': 1, + 'য়ে': 1, + 'য়ো': 1, + 'যা': 1, + 'যে': 1, + 'যো': 1, + 'রা': 1, + 'রাং': 1, + 'রি': 1, + 'রী': 1, + 'রে': 1, + 'রো': 1, + 'লা': 1, + 'লি': 1, + 'লী': 1, + 'লে': 1, + 'লে‌': 1, + 'শং': 1, + 'শা': 1, + 'শি': 1, + 'শী': 1, + 'শৃং': 1, + 'শে': 1, + 'শৈ': 1, + 'ষা': 1, + 'ষি': 1, + 'ষী': 1, + 'ষে': 1, + 'সং': 1, + 'সা': 1, + 'সাং': 1, + 'সি': 1, + 'সী': 1, + 'সে': 1, + 'সে‌': 1, + 'হা': 1, + 'হি': 1, + 'হে': 1, + 'হো': 1, + 'য়ে': 1, + 'ਕਾ': 1, + 'ਕਾਂ': 1, + 'ਕਿ': 1, + 'ਕਿ੍': 1, + 'ਕਿੱ': 1, + 'ਕੀ': 1, + 'ਖਾ': 1, + 'ਖਾਂ': 1, + 'ਖਿ': 1, + 'ਖਿ਼': 1, + 'ਖੀ': 1, + 'ਗਾ': 1, + 'ਗਿ': 1, + 'ਗਿ੍': 1, + 'ਗੀ': 1, + 'ਚਾ': 1, + 'ਚਿ': 1, + 'ਚਿੱ': 1, + 'ਚੀ': 1, + 'ਜਾ': 1, + 'ਜਾਂ': 1, + 'ਜਿ': 1, + 'ਜਿ਼': 1, + 'ਜਿ਼ੰ': 1, + 'ਜੀ': 1, + 'ਝਿ': 1, + 'ਝੀ': 1, + 'ਟਾ': 1, + 'ਟਿ': 1, + 'ਟਿ੍': 1, + 'ਟੀ': 1, + 'ਠੀ': 1, + 'ਡਾ': 1, + 'ਣਾ': 1, + 'ਣਾਂ': 1, + 'ਣੀ': 1, + 'ਤਾ': 1, + 'ਤਾਂ': 1, + 'ਤਿ': 1, + 'ਤੀ': 1, + 'ਦਾ': 1, + 'ਦਾਂ': 1, + 'ਦਿ': 1, + 'ਦਿੱ': 1, + 'ਦੀ': 1, + 'ਧਾ': 1, + 'ਧਾਂ': 1, + 'ਧਿ': 1, + 'ਧੀ': 1, + 'ਨਾ': 1, + 'ਨਾਂ': 1, + 'ਨਿ': 1, + 'ਨੀ': 1, + 'ਨੀਂ': 1, + 'ਪਾ': 1, + 'ਪਿ': 1, + 'ਪੀ': 1, + 'ਫਿ': 1, + 'ਬਾ': 1, + 'ਬਿ': 1, + 'ਬੀ': 1, + 'ਭਾ': 1, + 'ਭਿ': 1, + 'ਮਾ': 1, + 'ਮਾਂ': 1, + 'ਮਿ': 1, + 'ਮੀ': 1, + 'ਯਾ': 1, + 'ਰਾ': 1, + 'ਰਾਂ': 1, + 'ਰਿ': 1, + 'ਰੀ': 1, + 'ਲਾ': 1, + 'ਲਾਂ': 1, + 'ਲਿ': 1, + 'ਲਿੰ': 1, + 'ਲੀ': 1, + 'ਵਾ': 1, + 'ਵਾਂ': 1, + 'ਵਿ': 1, + 'ਵਿੱ': 1, + 'ਵੀ': 1, + 'ਸ਼ਾ': 1, + 'ਸ਼ਾਂ': 1, + 'ਸ਼ਿ': 1, + 'ਸ਼ੀ': 1, + 'ਸਾ': 1, + 'ਸਾਂ': 1, + 'ਸਿ': 1, + 'ਸਿੱ': 1, + 'ਸੀ': 1, + 'ਹਾ': 1, + 'ਹਾਂ': 1, + 'ਹਿ': 1, + 'ਹਿੰ': 1, + 'ਹਿੱ': 1, + 'ਹੀ': 1, + 'ਹੀਂ': 1, + 'ਜ਼ਾ': 1, + 'ਜ਼ੀ': 1, + 'ੜਾ': 1, + 'ੜੀਂ': 1, + 'ਫ਼ਾ': 1, + 'કઃ': 1, + 'કા': 1, + 'કાં': 1, + 'કિ': 1, + 'કી': 1, + 'કો': 1, + 'ખા': 1, + 'ખી': 1, + 'ખો': 1, + 'ગા': 1, + 'ગિ': 1, + 'ગી': 1, + 'ગો': 1, + 'ઘા': 1, + 'ઘો': 1, + 'ચા': 1, + 'ચિ': 1, + 'ચી': 1, + 'છા': 1, + 'છો': 1, + 'જા': 1, + 'જાં': 1, + 'જિ': 1, + 'જી': 1, + 'જો': 1, + 'ટઃ': 1, + 'ડા': 1, + 'ડાં': 1, + 'ડી': 1, + 'ઢા': 1, + 'ઢિ': 1, + 'ણા': 1, + 'ણી': 1, + 'તઃ': 1, + 'તા': 1, + 'તાં': 1, + 'તિ': 1, + 'તી': 1, + 'તો': 1, + 'થા': 1, + 'થી': 1, + 'દા': 1, + 'દી': 1, + 'દો': 1, + 'ધા': 1, + 'ધાં': 1, + 'ધિ': 1, + 'ધી': 1, + 'ધો': 1, + 'નઃ': 1, + 'ના': 1, + 'નાં': 1, + 'નિ': 1, + 'ની': 1, + 'નો': 1, + 'પા': 1, + 'પિ': 1, + 'પી': 1, + 'પો': 1, + 'ફા': 1, + 'ફો': 1, + 'બા': 1, + 'બાં': 1, + 'બી': 1, + 'ભા': 1, + 'ભાં': 1, + 'ભિ': 1, + 'ભો': 1, + 'ભૌ': 1, + 'મઃ': 1, + 'મા': 1, + 'માં': 1, + 'મિ': 1, + 'મી': 1, + 'મો': 1, + 'યા': 1, + 'યિ': 1, + 'યી': 1, + 'યો': 1, + 'રા': 1, + 'રિ': 1, + 'રી': 1, + 'રો': 1, + 'લા': 1, + 'લાં': 1, + 'લિ': 1, + 'લિં': 1, + 'લી': 1, + 'લો': 1, + 'ળા': 1, + 'ળી': 1, + 'વા': 1, + 'વાં': 1, + 'વિ': 1, + 'વી': 1, + 'વો': 1, + 'શા': 1, + 'શાં': 1, + 'શિ': 1, + 'શી': 1, + 'શો': 1, + 'ષા': 1, + 'ષી': 1, + 'ષો': 1, + 'સા': 1, + 'સાં': 1, + 'સિ': 1, + 'સી': 1, + 'સો': 1, + 'હા': 1, + 'હિ': 1, + 'હી': 1, + 'હો': 1, + 'கா': 1, + 'கி': 1, + 'கு': 1, + 'கூ': 1, + 'கெ': 1, + 'கே': 1, + 'கை': 1, + 'கொ': 1, + 'கோ': 1, + 'சா': 1, + 'சி': 1, + 'சு': 1, + 'சூ': 1, + 'செ': 1, + 'சே': 1, + 'சை': 1, + 'சொ': 1, + 'டா': 1, + 'டி': 1, + 'டு': 1, + 'டெ': 1, + 'டை': 1, + 'ணா': 1, + 'ணி': 1, + 'ணு': 1, + 'ணை': 1, + 'தா': 1, + 'தி': 1, + 'து': 1, + 'தூ': 1, + 'தெ': 1, + 'தே': 1, + 'தை': 1, + 'தொ': 1, + 'தோ': 1, + 'நா': 1, + 'நி': 1, + 'நு': 1, + 'நெ': 1, + 'நே': 1, + 'நோ': 1, + 'னா': 1, + 'னி': 1, + 'னு': 1, + 'னே': 1, + 'னை': 1, + 'னொ': 1, + 'பா': 1, + 'பி': 1, + 'பு': 1, + 'பெ': 1, + 'பே': 1, + 'பை': 1, + 'பொ': 1, + 'போ': 1, + 'மா': 1, + 'மி': 1, + 'மு': 1, + 'மூ': 1, + 'மெ': 1, + 'மே': 1, + 'மை': 1, + 'மொ': 1, + 'மோ': 1, + 'யா': 1, + 'யி': 1, + 'யு': 1, + 'யே': 1, + 'யை': 1, + 'யோ': 1, + 'ரா': 1, + 'ரி': 1, + 'ரு': 1, + 'ரெ': 1, + 'ரை': 1, + 'றா': 1, + 'றி': 1, + 'று': 1, + 'றே': 1, + 'றை': 1, + 'றொ': 1, + 'றோ': 1, + 'லா': 1, + 'லி': 1, + 'லு': 1, + 'லெ': 1, + 'லே': 1, + 'லை': 1, + 'லோ': 1, + 'ளா': 1, + 'ளி': 1, + 'ளு': 1, + 'ளெ': 1, + 'ளை': 1, + 'ழி': 1, + 'ழு': 1, + 'ழை': 1, + 'வா': 1, + 'வி': 1, + 'வு': 1, + 'வூ': 1, + 'வெ': 1, + 'வே': 1, + 'வை': 1, + 'வொ': 1, + 'வோ': 1, + 'అం': 1, + 'ఆం': 1, + 'ఒం': 1, + 'కం': 1, + 'కాం': 1, + 'కు': 1, + 'కుం': 1, + 'కూ': 1, + 'కృ': 1, + 'కెం': 1, + 'గిం': 1, + 'గు': 1, + 'గూ': 1, + 'గృ': 1, + 'చు': 1, + 'చెం': 1, + 'టం': 1, + 'టిం': 1, + 'టు': 1, + 'టుం': 1, + 'డు': 1, + 'ణిం': 1, + 'తం': 1, + 'తః': 1, + 'తు': 1, + 'తృ': 1, + 'దం': 1, + 'దిం': 1, + 'దు': 1, + 'దుం': 1, + 'దృ': 1, + 'ధిం': 1, + 'ధు': 1, + 'నం': 1, + 'నః': 1, + 'నాం': 1, + 'నిం': 1, + 'ను': 1, + 'నుం': 1, + 'నొం': 1, + 'పం': 1, + 'పిం': 1, + 'పు': 1, + 'పూ': 1, + 'పెం': 1, + 'పొం': 1, + 'బం': 1, + 'భం': 1, + 'భు': 1, + 'మిం': 1, + 'ము': 1, + 'మూ': 1, + 'యం': 1, + 'యః': 1, + 'యిం': 1, + 'యు': 1, + 'యుం': 1, + 'రం': 1, + 'రిం': 1, + 'రు': 1, + 'రూ': 1, + 'ఱు': 1, + 'లం': 1, + 'లిం': 1, + 'లు': 1, + 'విం': 1, + 'వు': 1, + 'వృ': 1, + 'శాం': 1, + 'శిం': 1, + 'శు': 1, + 'షిం': 1, + 'షు': 1, + 'సం': 1, + 'సాం': 1, + 'సు': 1, + 'సూ': 1, + 'హిం': 1, + 'ಅಂ': 1, + 'ಇಂ': 1, + 'ಉಂ': 1, + 'ಎಂ': 1, + 'ಒಂ': 1, + 'ಕಾ': 1, + 'ಕಾಂ': 1, + 'ಕಿಂ': 1, + 'ಕೀ': 1, + 'ಕು': 1, + 'ಕುಂ': 1, + 'ಕೂ': 1, + 'ಕೃ': 1, + 'ಕೆಂ': 1, + 'ಕೇ': 1, + 'ಕೈ': 1, + 'ಕೊ': 1, + 'ಕೊಂ': 1, + 'ಖಾಂ': 1, + 'ಗಾ': 1, + 'ಗಾಂ': 1, + 'ಗೀ': 1, + 'ಗು': 1, + 'ಗೂ': 1, + 'ಗೈ': 1, + 'ಗೊ': 1, + 'ಗೊಂ': 1, + 'ಗೋ': 1, + 'ಚಾ': 1, + 'ಚೀ': 1, + 'ಚು': 1, + 'ಛಾ': 1, + 'ಜಾ': 1, + 'ಜೀ': 1, + 'ಟು': 1, + 'ಟುಂ': 1, + 'ಟೇ': 1, + 'ಠಾ': 1, + 'ಡಾ': 1, + 'ಡು': 1, + 'ಡೂ': 1, + 'ಢೀ': 1, + 'ಣಂ': 1, + 'ಣಾ': 1, + 'ಣು': 1, + 'ಣೈ': 1, + 'ತಂ': 1, + 'ತಃ': 1, + 'ತಾ': 1, + 'ತೀ': 1, + 'ತು': 1, + 'ತೃ': 1, + 'ತೊ': 1, + 'ತೋ': 1, + 'ಥಾ': 1, + 'ದಂ': 1, + 'ದಾ': 1, + 'ದಿಂ': 1, + 'ದು': 1, + 'ದೂ': 1, + 'ದೃ': 1, + 'ದೇ': 1, + 'ದೊ': 1, + 'ದೋ': 1, + 'ಧಾ': 1, + 'ಧೀ': 1, + 'ಧೂ': 1, + 'ನಃ': 1, + 'ನಾ': 1, + 'ನಾಂ': 1, + 'ನಿಂ': 1, + 'ನು': 1, + 'ನೂ': 1, + 'ನೇ': 1, + 'ನೈ': 1, + 'ನೊ': 1, + 'ಪಂ': 1, + 'ಪಾ': 1, + 'ಪು': 1, + 'ಪೂ': 1, + 'ಪೇ': 1, + 'ಬಂ': 1, + 'ಬಾ': 1, + 'ಬು': 1, + 'ಬೇ': 1, + 'ಬೋ': 1, + 'ಭಾ': 1, + 'ಭೀ': 1, + 'ಭು': 1, + 'ಭೇ': 1, + 'ಭೋ': 1, + 'ಮಾ': 1, + 'ಮೀ': 1, + 'ಮು': 1, + 'ಮೂ': 1, + 'ಮೇ': 1, + 'ಮೈ': 1, + 'ಯಂ': 1, + 'ಯಾ': 1, + 'ಯಿಂ': 1, + 'ಯು': 1, + 'ಯುಂ': 1, + 'ಯೂ': 1, + 'ಯೆಂ': 1, + 'ಯೇ': 1, + 'ಯೊ': 1, + 'ಯೋ': 1, + 'ರಂ': 1, + 'ರಾ': 1, + 'ರಾಂ': 1, + 'ರಿಂ': 1, + 'ರೀ': 1, + 'ರು': 1, + 'ರೂ': 1, + 'ರೆಂ': 1, + 'ರೊ': 1, + 'ರೋ': 1, + 'ಲಂ': 1, + 'ಲಾ': 1, + 'ಲೀ': 1, + 'ಲು': 1, + 'ಲೂ': 1, + 'ಲೆಂ': 1, + 'ಲೇ': 1, + 'ಲೋ': 1, + 'ಳಾ': 1, + 'ಳಿಂ': 1, + 'ಳು': 1, + 'ಳೂ': 1, + 'ವಾ': 1, + 'ವೀ': 1, + 'ವು': 1, + 'ವುಂ': 1, + 'ವೂ': 1, + 'ವೃ': 1, + 'ವೆಂ': 1, + 'ವೇ': 1, + 'ವೈ': 1, + 'ವೋ': 1, + 'ಶಾ': 1, + 'ಶಾಂ': 1, + 'ಶೀ': 1, + 'ಶೇ': 1, + 'ಷಾ': 1, + 'ಷೇ': 1, + 'ಸಂ': 1, + 'ಸಾ': 1, + 'ಸಾಂ': 1, + 'ಸು': 1, + 'ಸೂ': 1, + 'ಸೇ': 1, + 'ಹಾ': 1, + 'ಹು': 1, + 'ಹೇ': 1, + 'ಹೊ': 1, + 'ಹೊಂ': 1, + 'ಹೋ': 1, + 'അം': 1, + 'കാ': 1, + 'കി': 1, + 'കെ': 1, + 'കേ': 1, + 'കൈ': 1, + 'കൊ': 1, + 'കോ': 1, + 'ഗം': 1, + 'ഗി': 1, + 'ഗീ': 1, + 'ഘി': 1, + 'ചാ': 1, + 'ചി': 1, + 'ചെ': 1, + 'ചേ': 1, + 'ചോ': 1, + 'ജാ': 1, + 'ജി': 1, + 'ജീ': 1, + 'ടാ': 1, + 'ടി': 1, + 'ടും': 1, + 'ടെ': 1, + 'ടേ': 1, + 'ഠി': 1, + 'ണം': 1, + 'ണാ': 1, + 'ണി': 1, + 'ണെ': 1, + 'തം': 1, + 'താ': 1, + 'തി': 1, + 'തീ': 1, + 'തും': 1, + 'തെ': 1, + 'തേ': 1, + 'തൊ': 1, + 'തോ': 1, + 'ദം': 1, + 'ദാ': 1, + 'ദി': 1, + 'ദേ': 1, + 'ധാ': 1, + 'ധി': 1, + 'നം': 1, + 'നാ': 1, + 'നി': 1, + 'നീ': 1, + 'നും': 1, + 'നെ': 1, + 'നേ': 1, + 'പാ': 1, + 'പി': 1, + 'പീ': 1, + 'പെ': 1, + 'പൈ': 1, + 'പൊ': 1, + 'പോ': 1, + 'പൌ': 1, + 'ബം': 1, + 'ബാ': 1, + 'ബോ': 1, + 'ഭാ': 1, + 'ഭി': 1, + 'ഭേ': 1, + 'ഭൌ': 1, + 'മം': 1, + 'മാ': 1, + 'മി': 1, + 'മെ': 1, + 'മേ': 1, + 'മൊ': 1, + 'മോ': 1, + 'മൌ': 1, + 'യം': 1, + 'യാ': 1, + 'യി': 1, + 'യും': 1, + 'യെ': 1, + 'യേ': 1, + 'യോ': 1, + 'രം': 1, + 'രാ': 1, + 'രി': 1, + 'രീ': 1, + 'രും': 1, + 'രെ': 1, + 'രേ': 1, + 'രോ': 1, + 'റം': 1, + 'റി': 1, + 'റെ': 1, + 'ലം': 1, + 'ലാ': 1, + 'ലി': 1, + 'ലും': 1, + 'ലെ': 1, + 'ലേ': 1, + 'ലോ': 1, + 'ളം': 1, + 'ളാ': 1, + 'ളി': 1, + 'ളും': 1, + 'ളെ': 1, + 'ളേ': 1, + 'ളോ': 1, + 'ഴി': 1, + 'വാ': 1, + 'വി': 1, + 'വും': 1, + 'വെ': 1, + 'വേ': 1, + 'വൈ': 1, + 'വോ': 1, + 'ശാ': 1, + 'ശി': 1, + 'ശീ': 1, + 'ശേ': 1, + 'ഷം': 1, + 'ഷി': 1, + 'സം': 1, + 'സാ': 1, + 'സാം': 1, + 'സി': 1, + 'സൌ': 1, + 'ഹം': 1, + 'ഹാ': 1, + 'ഹി': 1, + 'ഹിം': 1, + 'කා': 1, + 'කැ': 1, + 'කෘ': 1, + 'කෙ': 1, + 'කො': 1, + 'කෝ': 1, + 'කෲ': 1, + 'ගා': 1, + 'ගැ': 1, + 'ගෙ': 1, + 'ගේ': 1, + 'චා': 1, + 'චැ': 1, + 'චෝ': 1, + 'ජා': 1, + 'ඥා': 1, + 'ටා': 1, + 'ටේ': 1, + 'ඨා': 1, + 'ඩං': 1, + 'ඩා': 1, + 'තා': 1, + 'තැ': 1, + 'තෘ': 1, + 'තෙ': 1, + 'තේ': 1, + 'තො': 1, + 'තෝ': 1, + 'ථා': 1, + 'දා': 1, + 'දැ': 1, + 'දිං': 1, + 'දෙ': 1, + 'දේ': 1, + 'දෝ': 1, + 'ධා': 1, + 'නා': 1, + 'නැ': 1, + 'නෑ': 1, + 'නෙ': 1, + 'නේ': 1, + 'නො': 1, + 'ඳා': 1, + 'පා': 1, + 'පැ': 1, + 'පෑ': 1, + 'පෙ': 1, + 'පේ': 1, + 'පො': 1, + 'පෞ': 1, + 'බා': 1, + 'බැ': 1, + 'බෙ': 1, + 'බේ': 1, + 'බෝ': 1, + 'භා': 1, + 'භෞ': 1, + 'මා': 1, + 'මැ': 1, + 'මෙ': 1, + 'මේ': 1, + 'යා': 1, + 'යෙ': 1, + 'යේ': 1, + 'යො': 1, + 'යෝ': 1, + 'රා': 1, + 'රැ': 1, + 'රෙ': 1, + 'රේ': 1, + 'රෝ': 1, + 'ලං': 1, + 'ලා': 1, + 'ලැ': 1, + 'ලෙ': 1, + 'ලේ': 1, + 'ලෝ': 1, + 'වං': 1, + 'වා': 1, + 'වැ': 1, + 'වෘ': 1, + 'වෙ': 1, + 'වේ': 1, + 'වෝ': 1, + 'ශේ': 1, + 'ෂා': 1, + 'සං': 1, + 'සා': 1, + 'සැ': 1, + 'සෑ': 1, + 'සෙ': 1, + 'සේ': 1, + 'සෞ': 1, + 'හා': 1, + 'හැ': 1, + 'හිං': 1, + 'හෘ': 1, + 'හෙ': 1, + 'හො': 1, + 'හෝ': 1, + 'ළැ': 1, + 'ကေ': 1, + 'ကေု': 1, + 'က်ျ': 1, + 'ကျ': 1, + 'ကျို': 1, + 'ကျူ': 1, + 'ကျေ': 1, + 'ကျွ': 1, + 'ကြ': 1, + 'ကြို': 1, + 'ကြီ': 1, + 'ကြု': 1, + 'ကြေ': 1, + 'ကြံ': 1, + 'ကြွေ': 1, + 'ကၠေ': 1, + 'ကၠေံ': 1, + 'ခေ': 1, + 'ချ': 1, + 'ချိ': 1, + 'ချို': 1, + 'ချို့': 1, + 'ချီ': 1, + 'ချု': 1, + 'ချေ': 1, + 'ချဳ': 1, + 'ခြ': 1, + 'ခြုံ': 1, + 'ခြေ': 1, + 'ဂျို': 1, + 'ဂၠေ': 1, + 'ငြ': 1, + 'ငြိ': 1, + 'ငွေ': 1, + 'ငႄ': 1, + 'စေ': 1, + 'စှ်ေ': 1, + 'စၞေ': 1, + 'စၠေ': 1, + 'ဆေ': 1, + 'ဇြ': 1, + 'ဇြေ': 1, + 'ဇြဳ': 1, + 'ဇၞေ': 1, + 'ညေ': 1, + 'တေ': 1, + 'တေံ': 1, + 'တြ': 1, + 'တြုံ': 1, + 'တွေ': 1, + 'တှ်ေ': 1, + 'တၟေ': 1, + 'ထေ': 1, + 'ထွေ': 1, + 'ဒေ': 1, + 'ဒေံ': 1, + 'ဒြ': 1, + 'နေ': 1, + 'နေ့': 1, + 'နှေ': 1, + 'ပေ': 1, + 'ပေဲ': 1, + 'ပျ': 1, + 'ပျေ': 1, + 'ပျဲ': 1, + 'ပြ': 1, + 'ပြီ': 1, + 'ပြု': 1, + 'ပြေ': 1, + 'ပြဳ': 1, + 'ပြံ': 1, + 'ဖေ': 1, + 'ဖျ': 1, + 'ဖျု': 1, + 'ဖျေံ': 1, + 'ဖြ': 1, + 'ဖြို': 1, + 'ဗျဵု': 1, + 'ဗြေ': 1, + 'ဗြဴ': 1, + 'ဗၠေ': 1, + 'ဘေ': 1, + 'မေ': 1, + 'မျ': 1, + 'မျို': 1, + 'မျီု': 1, + 'မျှ': 1, + 'မြ': 1, + 'မြေ': 1, + 'မြှ': 1, + 'မွေ': 1, + 'မွေ့': 1, + 'မှေ': 1, + 'မၠေ': 1, + 'မႄ': 1, + 'ယေ': 1, + 'ယျ': 1, + 'ယျဵု': 1, + 'ယြဴ': 1, + 'ရေ': 1, + 'ရေံ': 1, + 'ရွေ': 1, + 'ရွှေ့': 1, + 'ရှေ': 1, + 'ရှေ့': 1, + 'ရှ်ေ': 1, + 'လေ': 1, + 'လျ': 1, + 'လျို': 1, + 'လျေ': 1, + 'လျှ': 1, + 'လျှို့': 1, + 'လျှေ': 1, + 'လၟေ': 1, + 'လႄ': 1, + 'ဝေ': 1, + 'သေ': 1, + 'သြ': 1, + 'သြို': 1, + 'သှ်ေ': 1, + 'သၞေ': 1, + 'ဟေ': 1, + 'အေ': 1, + 'ၜေ': 1, + 'ၵေ': 1, + 'ၵႄ': 1, + 'ၶေ': 1, + 'ၼေ': 1, + 'ၼႄ': 1, + 'ၽႄ': 1, + 'ႁေ': 1, + 'ႁႄ': 1, + 'កា': 1, + 'កើ': 1, + 'កេ': 1, + 'កោ': 1, + 'ខា': 1, + 'ខែ': 1, + 'គា': 1, + 'គាំ': 1, + 'គេ': 1, + 'គោ': 1, + 'ឃា': 1, + 'ឃើ': 1, + 'ឃោ': 1, + 'ឃៅ': 1, + 'ងា': 1, + 'ចា': 1, + 'ចាំ': 1, + 'ចេ': 1, + 'ចែ': 1, + 'ចោ': 1, + 'ឆាំ': 1, + 'ជា': 1, + 'ជៀ': 1, + 'ឈា': 1, + 'ញុះ': 1, + 'ដា': 1, + 'ដើ': 1, + 'ដែ': 1, + 'ដៃ': 1, + 'ដោ': 1, + 'ដៅ': 1, + 'ឋា': 1, + 'ណា': 1, + 'ណើ': 1, + 'ណែ': 1, + 'ណោ': 1, + 'ណោះ': 1, + 'ណៈ': 1, + 'តា': 1, + 'តេ': 1, + 'តែ': 1, + 'ថា': 1, + 'ថែ': 1, + 'ទា': 1, + 'ទាំ': 1, + 'ទៀ': 1, + 'ទេ': 1, + 'ទៃ': 1, + 'ទោ': 1, + 'ទោះ': 1, + 'ទៅ': 1, + 'ធា': 1, + 'នា': 1, + 'នាំ': 1, + 'នឿ': 1, + 'នេះ': 1, + 'នៃ': 1, + 'នោះ': 1, + 'នៅ': 1, + 'នៈ': 1, + 'បា': 1, + 'បើ': 1, + 'បៀ': 1, + 'បែ': 1, + 'បោ': 1, + 'បោះ': 1, + 'បះ': 1, + 'ប៉ះ': 1, + 'ពា': 1, + 'ពើ': 1, + 'ពេ': 1, + 'ពោះ': 1, + 'ភា': 1, + 'ភេ': 1, + 'មា': 1, + 'មើ': 1, + 'មេ': 1, + 'មែ': 1, + 'ម៉ា': 1, + 'ម៉ោ': 1, + 'យា': 1, + 'យោ': 1, + 'យៈ': 1, + 'យ៉ា': 1, + 'រា': 1, + 'រាំ': 1, + 'រើ': 1, + 'រឿ': 1, + 'រៀ': 1, + 'រះ': 1, + 'រៈ': 1, + 'លា': 1, + 'លុះ': 1, + 'លើ': 1, + 'លេ': 1, + 'លោ': 1, + 'លៈ': 1, + 'វា': 1, + 'វេ': 1, + 'វៈ': 1, + 'សា': 1, + 'សើ': 1, + 'សេ': 1, + 'សៈ': 1, + 'ហា': 1, + 'ហើ': 1, + 'ហេ': 1, + 'ហែ': 1, + 'ហោ': 1, + 'ឡា': 1, + 'ឡើ': 1, + 'អា': 1, + 'អើ': 1, + 'អៀ': 1, + 'ᨠᩮ᩠': 1, + 'ᨠᩮᩢ᩵': 1, + 'ᨠᩮ᩵': 1, + 'ᨠᩯ᩠': 1, + 'ᨠᩯ᩵': 1, + 'ᨡᩮ᩠': 1, + 'ᨡᩮᩢ': 1, + 'ᨡᩮᩢᩢ': 1, + 'ᨡᩯ᩠': 1, + 'ᨡᩱᩢ': 1, + 'ᨣᩕ': 1, + 'ᨣᩕ᩠': 1, + 'ᨣᩕᩮ᩠': 1, + 'ᨣᩭ': 1, + 'ᨣᩮᩢᩢ': 1, + 'ᨣᩯ᩠': 1, + 'ᨤᩮᩢ': 1, + 'ᨤᩱ᩵': 1, + 'ᨧᩮ': 1, + 'ᨧᩮ᩠': 1, + 'ᨧᩮᩢᩢ': 1, + 'ᨧᩱ': 1, + 'ᨧᩱ᩠': 1, + 'ᨩᩭ᩵': 1, + 'ᨩᩮ᩠': 1, + 'ᨩᩱᩢ': 1, + 'ᨩ᩵ᩭ': 1, + 'ᨪᩮᩢ': 1, + 'ᨯᩪᩯ': 1, + 'ᨯᩯ᩠': 1, + 'ᨯᩰ᩠': 1, + 'ᨯᩱ': 1, + 'ᨯᩱᩢ': 1, + 'ᨲᩕ': 1, + 'ᨲᩕᩦ': 1, + 'ᨲᩕ᩼': 1, + 'ᨲᩮ᩠': 1, + 'ᨲᩯ᩠': 1, + 'ᨲᩯ᩵': 1, + 'ᨲᩱ': 1, + 'ᨲᩱ᩠': 1, + 'ᨲᩱᩢ': 1, + 'ᨳᩮ᩠': 1, + 'ᨳᩮᩢᩢ': 1, + 'ᨳᩯ᩠': 1, + 'ᨴᩮ᩠': 1, + 'ᨴᩮᩢᩢ': 1, + 'ᨴᩮᩢ᩵': 1, + 'ᨴᩯ᩠': 1, + 'ᨴᩯᩢ': 1, + 'ᨴᩰ᩠': 1, + 'ᨶᩮ': 1, + 'ᨶᩯ᩠': 1, + 'ᨶᩱ': 1, + 'ᨷᩕ': 1, + 'ᨷᩮ᩠': 1, + 'ᨸᩮ᩠': 1, + 'ᨸᩮᩢ᩵': 1, + 'ᨹᩪᩢᩱ': 1, + 'ᨹᩮᩨ᩠': 1, + 'ᨻᩕ᩠': 1, + 'ᨻᩮ᩠': 1, + 'ᨻᩱ': 1, + 'ᨽᩱ᩠': 1, + 'ᨾᩮ᩠': 1, + 'ᨾᩯ᩵': 1, + 'ᨾᩱ': 1, + 'ᨿᩮ᩠': 1, + 'ᨿᩰ': 1, + 'ᩁᩢᩭ': 1, + 'ᩁᩮ᩠': 1, + 'ᩁᩮᩨ᩠': 1, + 'ᩁᩯ᩠': 1, + 'ᩃᩮ᩠': 1, + 'ᩃᩯ': 1, + 'ᩃᩰ᩠': 1, + 'ᩅᩮ': 1, + 'ᩅᩮ᩠': 1, + 'ᩅᩱᩢ': 1, + 'ᩈᩮ': 1, + 'ᩈᩮ᩠': 1, + 'ᩈᩯ᩠': 1, + 'ᩈᩱ': 1, + 'ᩈᩱ᩠': 1, + 'ᩉᩕᩨ': 1, + 'ᩉᩮᩖᩨ': 1, + 'ᩉᩮ᩠': 1, + 'ᩉᩯ᩠': 1, + 'ᩉᩯ᩵': 1, + 'ᩉᩱ᩠': 1, + 'ꦏꦃ': 1, + 'ꦏꦺ': 1, + 'ꦏꦺꦴ': 1, + 'ꦏꦿ': 1, + 'ꦏꦿꦁ': 1, + 'ꦏꦿꦂ': 1, + 'ꦒꦸꦃ': 1, + 'ꦒꦺꦴ': 1, + 'ꦒꦿ': 1, + 'ꦒꦿꦺ': 1, + 'ꦔꦃ': 1, + 'ꦔꦺ': 1, + 'ꦔꦺꦴ': 1, + 'ꦔꦿ': 1, + 'ꦕꦃ': 1, + 'ꦕꦺꦴ': 1, + 'ꦗꦃ': 1, + 'ꦗꦺ': 1, + 'ꦗꦿꦺꦴ': 1, + 'ꦝꦃ': 1, + 'ꦝꦺ': 1, + 'ꦝꦺꦴ': 1, + 'ꦝꦺꦴꦂ': 1, + 'ꦠꦸꦃ': 1, + 'ꦠꦺ': 1, + 'ꦠꦺꦃ': 1, + 'ꦠꦺꦴ': 1, + 'ꦠꦾ': 1, + 'ꦠꦿ': 1, + 'ꦠꦿꦶ': 1, + 'ꦢꦃ': 1, + 'ꦢꦺ': 1, + 'ꦢꦺꦴ': 1, + 'ꦢꦾ': 1, + 'ꦢꦿ': 1, + 'ꦤꦺ': 1, + 'ꦤꦺꦃ': 1, + 'ꦤꦺꦴ': 1, + 'ꦥꦃ': 1, + 'ꦥꦺ': 1, + 'ꦥꦺꦴ': 1, + 'ꦥꦿ': 1, + 'ꦥꦿꦃ': 1, + 'ꦥꦿꦶ': 1, + 'ꦥꦿꦺꦴ': 1, + 'ꦧꦺ': 1, + 'ꦧꦺꦃ': 1, + 'ꦧꦺꦴ': 1, + 'ꦧꦿ': 1, + 'ꦩꦃ': 1, + 'ꦩꦺ': 1, + 'ꦩꦺꦃ': 1, + 'ꦩꦺꦴ': 1, + 'ꦩꦿ': 1, + 'ꦩꦿꦃ': 1, + 'ꦩꦿꦶꦃ': 1, + 'ꦪꦃ': 1, + 'ꦪꦸꦃ': 1, + 'ꦪꦺꦴ': 1, + 'ꦫꦶꦃ': 1, + 'ꦫꦺ': 1, + 'ꦫꦺꦴ': 1, + 'ꦫꦾ': 1, + 'ꦭꦃ': 1, + 'ꦭꦶꦃ': 1, + 'ꦭꦺ': 1, + 'ꦭꦺꦃ': 1, + 'ꦭꦺꦴ': 1, + 'ꦭꦺꦴꦁ': 1, + 'ꦮꦃ': 1, + 'ꦮꦶꦃ': 1, + 'ꦮꦸꦃ': 1, + 'ꦮꦺ': 1, + 'ꦮꦺꦴ': 1, + 'ꦮꦺꦴꦁ': 1, + 'ꦮꦺꦴꦃ': 1, + 'ꦮꦿꦸꦃ': 1, + 'ꦱꦶꦃ': 1, + 'ꦱꦺ': 1, + 'ꦱꦺꦴ': 1, + 'ꦱꦾ': 1, + 'ꦱꦿ': 1, + 'ꦱꦿꦃ': 1, + 'ꦲꦺ': 1, + 'ꦲꦺꦴ': 1, + '𑄃𑄬': 1, + '𑄃𑄬𑄭': 1, + '𑄇𑄬': 1, + '𑄈𑄬': 1, + '𑄉𑄬': 1, + '𑄉𑄬𑄭': 1, + '𑄊𑄬': 1, + '𑄌𑄬': 1, + '𑄎𑄬': 1, + '𑄎𑄬𑄭': 1, + '𑄏𑄬': 1, + '𑄑𑄬': 1, + '𑄖𑄬': 1, + '𑄗𑄬': 1, + '𑄘𑄬': 1, + '𑄙𑄬': 1, + '𑄚𑄬': 1, + '𑄚𑄬𑄭': 1, + '𑄛𑄬': 1, + '𑄜𑄬': 1, + '𑄝𑄬': 1, + '𑄞𑄬': 1, + '𑄞𑄬𑄭': 1, + '𑄟𑄬': 1, + '𑄠𑄬': 1, + '𑄠𑄬𑄭': 1, + '𑄡𑄬': 1, + '𑄡𑄬𑄭': 1, + '𑄢𑄬': 1, + '𑄢𑄬𑄭': 1, + '𑄣𑄬': 1, + '𑄣𑄬𑄭': 1, + '𑄥𑄬': 1, + '𑄦𑄬': 1, + '𑌅𑌂': 1, + '𑌕𑌂': 1, + '𑌕𑌾': 1, + '𑌕𑌾𑌂': 1, + '𑌕𑌾𑌃': 1, + '𑌕𑌿': 1, + '𑌕𑍂': 1, + '𑌕𑍃': 1, + '𑌕𑍇': 1, + '𑌕𑍋': 1, + '𑌗𑌾': 1, + '𑌗𑌿': 1, + '𑌗𑍁': 1, + '𑌗𑍃': 1, + '𑌗𑍇': 1, + '𑌗𑍌': 1, + '𑌘𑌾': 1, + '𑌘𑍇': 1, + '𑌘𑍋': 1, + '𑌚𑌾': 1, + '𑌚𑌿': 1, + '𑌚𑍇': 1, + '𑌚𑍈': 1, + '𑌛𑌾': 1, + '𑌛𑍁': 1, + '𑌛𑍇': 1, + '𑌜𑌾': 1, + '𑌜𑌿': 1, + '𑌜𑍇': 1, + '𑌞𑌾': 1, + '𑌟𑌃': 1, + '𑌟𑌾': 1, + '𑌟𑌾𑌂': 1, + '𑌟𑌾𑌃': 1, + '𑌠𑌾': 1, + '𑌠𑍇': 1, + '𑌠𑍈𑌃': 1, + '𑌡𑌂': 1, + '𑌡𑌃': 1, + '𑌡𑌿': 1, + '𑌣𑌂': 1, + '𑌣𑌾': 1, + '𑌣𑌾𑌂': 1, + '𑌣𑌿': 1, + '𑌣𑍁': 1, + '𑌣𑍇': 1, + '𑌤𑌂': 1, + '𑌤𑌃': 1, + '𑌤𑌾': 1, + '𑌤𑌾𑌂': 1, + '𑌤𑌾𑌃': 1, + '𑌤𑌿': 1, + '𑌤𑌿𑌂': 1, + '𑌤𑌿𑌃': 1, + '𑌤𑍁': 1, + '𑌤𑍁𑌂': 1, + '𑌤𑍃': 1, + '𑌤𑍇': 1, + '𑌤𑍇𑌃': 1, + '𑌤𑍈': 1, + '𑌤𑍋': 1, + '𑌤𑍌': 1, + '𑌥𑌂': 1, + '𑌥𑌾': 1, + '𑌥𑌾𑌂': 1, + '𑌥𑌿': 1, + '𑌦𑌂': 1, + '𑌦𑌃': 1, + '𑌦𑌾': 1, + '𑌦𑌿': 1, + '𑌦𑍁': 1, + '𑌦𑍃': 1, + '𑌦𑍇': 1, + '𑌦𑍋': 1, + '𑌧𑌃': 1, + '𑌧𑌾': 1, + '𑌧𑌾𑌃': 1, + '𑌧𑌿': 1, + '𑌧𑌿𑌂': 1, + '𑌧𑍁': 1, + '𑌧𑍃': 1, + '𑌧𑍇': 1, + '𑌧𑍇𑌃': 1, + '𑌧𑍈𑌃': 1, + '𑌨𑌂': 1, + '𑌨𑌃': 1, + '𑌨𑌾': 1, + '𑌨𑌾𑌂': 1, + '𑌨𑌾𑌃': 1, + '𑌨𑌿': 1, + '𑌨𑌿𑌃': 1, + '𑌨𑍁': 1, + '𑌨𑍂': 1, + '𑌨𑍇': 1, + '𑌨𑍈': 1, + '𑌨𑍈𑌃': 1, + '𑌨𑍋': 1, + '𑌪𑌂': 1, + '𑌪𑌾': 1, + '𑌪𑌿': 1, + '𑌪𑍁': 1, + '𑌪𑍂': 1, + '𑌪𑍇': 1, + '𑌪𑍋': 1, + '𑌬𑌾': 1, + '𑌬𑍃': 1, + '𑌭𑌾': 1, + '𑌭𑌿': 1, + '𑌭𑌿𑌃': 1, + '𑌭𑍁': 1, + '𑌭𑍂': 1, + '𑌭𑍇': 1, + '𑌮𑌂': 1, + '𑌮𑌾': 1, + '𑌮𑌿': 1, + '𑌮𑌿𑌂': 1, + '𑌮𑍁': 1, + '𑌮𑍂': 1, + '𑌮𑍇': 1, + '𑌮𑍈': 1, + '𑌮𑍋': 1, + '𑌮𑍌': 1, + '𑌯𑌂': 1, + '𑌯𑌃': 1, + '𑌯𑌾': 1, + '𑌯𑌾𑌂': 1, + '𑌯𑌾𑌃': 1, + '𑌯𑌿': 1, + '𑌯𑍁': 1, + '𑌯𑍁𑌃': 1, + '𑌯𑍇': 1, + '𑌯𑍈': 1, + '𑌯𑍈𑌃': 1, + '𑌯𑍋': 1, + '𑌯𑍋𑌃': 1, + '𑌰𑌂': 1, + '𑌰𑌃': 1, + '𑌰𑌾': 1, + '𑌰𑌾𑌃': 1, + '𑌰𑌿': 1, + '𑌰𑌿𑌂': 1, + '𑌰𑍁': 1, + '𑌰𑍂': 1, + '𑌰𑍇': 1, + '𑌰𑍋': 1, + '𑌰𑍌': 1, + '𑌲𑌂': 1, + '𑌲𑌾': 1, + '𑌲𑌾𑌃': 1, + '𑌲𑌿': 1, + '𑌲𑌿𑌂': 1, + '𑌲𑍇': 1, + '𑌲𑍈': 1, + '𑌲𑍋': 1, + '𑌵𑌂': 1, + '𑌵𑌃': 1, + '𑌵𑌾': 1, + '𑌵𑌾𑌂': 1, + '𑌵𑌾𑌃': 1, + '𑌵𑌿': 1, + '𑌵𑍃': 1, + '𑌵𑍇': 1, + '𑌵𑍈': 1, + '𑌵𑍋': 1, + '𑌶𑌂': 1, + '𑌶𑌃': 1, + '𑌶𑌾': 1, + '𑌶𑌾𑌃': 1, + '𑌶𑌿': 1, + '𑌶𑍁': 1, + '𑌶𑍂': 1, + '𑌶𑍇': 1, + '𑌶𑍋': 1, + '𑌷𑌂': 1, + '𑌷𑌾': 1, + '𑌷𑌾𑌂': 1, + '𑌷𑌾𑌃': 1, + '𑌷𑌿': 1, + '𑌷𑍁': 1, + '𑌷𑍇': 1, + '𑌷𑍈': 1, + '𑌷𑍋': 1, + '𑌸𑌂': 1, + '𑌸𑌃': 1, + '𑌸𑌾': 1, + '𑌸𑌾𑌂': 1, + '𑌸𑌿': 1, + '𑌸𑍁': 1, + '𑌸𑍂': 1, + '𑌸𑍇': 1, + '𑌸𑍋': 1, + '𑌸𑍌': 1, + '𑌹𑌾': 1, + '𑌹𑌾𑌃': 1, + '𑌹𑌿': 1, + '𑌹𑍇': 1, + '𑌹𑍋': 1, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_e18ac6a7.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_e18ac6a7.py new file mode 100644 index 0000000000000000000000000000000000000000..473228e8049ea2625292e5d35a72d49b974632f2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_e18ac6a7.py @@ -0,0 +1,6674 @@ +""" +Grapheme overrides for _known_e18ac6a7. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: extraterm +""" +# pylint: skip-file +GRAPHEMES = { + ' ̃': 2, + ' ̣': 2, + ' ̱́': 3, + ' ོ': 2, + '-́': 2, + '.̃': 2, + 'à': 2, + 'À': 2, + 'á': 2, + 'â': 2, + 'ã': 2, + 'Ā': 2, + 'ā': 2, + 'ä': 2, + 'ả': 2, + 'ǎ': 2, + 'ạ': 2, + 'a̱': 2, + 'A̱': 2, + 'A̸': 2, + 'b̃': 2, + 'c̈': 2, + 'ç': 2, + 'Ç': 2, + 'c̱': 2, + 'ḍ': 2, + 'ḏ': 2, + 'è': 2, + 'È': 2, + 'É': 2, + 'é': 2, + 'Ê': 2, + 'ê': 2, + 'ẽ': 2, + 'ē': 2, + 'ẻ': 2, + 'e̊': 2, + 'ě': 2, + 'ẹ': 2, + 'e̱': 2, + 'E̱': 2, + 'ğ': 2, + 'ḥ': 2, + 'Ḥ': 2, + 'ì': 2, + 'í': 2, + 'Í': 2, + 'î': 2, + 'ĩ': 2, + 'ī': 2, + 'İ': 2, + 'ï': 2, + 'ỉ': 2, + 'ǐ': 2, + 'ị': 2, + 'I̱': 2, + 'i̱': 2, + 'k̀': 2, + 'm̃': 2, + 'ǹ': 2, + 'ñ': 2, + 'n̄': 2, + 'ṅ': 2, + 'ṉ': 2, + 'ò': 2, + 'ó': 2, + 'ô': 2, + 'õ': 2, + 'ō': 2, + 'Ö': 2, + 'ö': 2, + 'ỏ': 2, + 'ǒ': 2, + 'ọ': 2, + 'O̱': 2, + 'o̱': 2, + 'p̃': 2, + 'p̱': 2, + 'p̱̱': 3, + 'r̃': 2, + 'ṛ': 2, + 'S̈': 2, + 's̈': 2, + 'Ṣ': 2, + 'ṣ': 2, + 'Ş': 2, + 'ş': 2, + 'T̃': 2, + 't̃': 2, + 'ṭ': 2, + 'ṯ': 2, + 'ù': 2, + 'Ú': 2, + 'ú': 2, + 'û': 2, + 'ũ': 2, + 'ū': 2, + 'Ü': 2, + 'ü': 2, + 'ủ': 2, + 'ụ': 2, + 'u̱': 2, + 'U̱': 2, + 'ỳ': 2, + 'Ý': 2, + 'ý': 2, + 'ỹ': 2, + 'ỷ': 2, + 'ỵ': 2, + 'ẓ': 2, + 'á̱': 2, + 'ầ': 2, + 'ấ': 2, + 'ẫ': 2, + 'ẩ': 2, + 'ậ': 2, + 'â̱': 2, + 'ã̱': 2, + 'ä́': 2, + 'ä̱': 2, + 'ề': 2, + 'ế': 2, + 'ễ': 2, + 'ể': 2, + 'ệ': 2, + 'ë́': 2, + 'ë̱': 2, + 'í̱': 2, + 'ï̱': 2, + 'ó̱': 2, + 'ồ': 2, + 'ố': 2, + 'ỗ': 2, + 'ổ': 2, + 'ộ': 2, + 'ö́': 2, + 'ö̱': 2, + 'Ü̃': 2, + 'ü̃': 2, + 'ü̃́': 3, + 'ü̱̃': 3, + 'ü̱': 2, + 'ằ': 2, + 'ắ': 2, + 'ẳ': 2, + 'ặ': 2, + 'ą́': 2, + 'ę́': 2, + 'į́': 2, + 'ờ': 2, + 'ớ': 2, + 'ỡ': 2, + 'ở': 2, + 'ợ': 2, + 'ừ': 2, + 'ứ': 2, + 'ữ': 2, + 'ử': 2, + 'ự': 2, + 'ǎ̱': 2, + 'ǫ́': 2, + 'ɔ̀': 2, + 'ɔ́': 2, + 'Ɔ́': 2, + 'ɔ̂': 2, + 'ɔ̃': 2, + 'ɔ̈': 2, + 'ɔ̌': 2, + 'ə̀': 2, + 'ə́': 2, + 'ɛ̀': 2, + 'ɛ́': 2, + 'ɛ̂': 2, + 'ɛ̃': 2, + 'ɛ̈': 2, + 'ɛ̌': 2, + 'Ɨ́': 2, + 'ɨ́': 2, + 'ɨ̂': 2, + 'ɨ̈': 2, + 'ɨ̌': 2, + 'ɨ̱': 2, + 'ɨ̱́': 3, + 'ɨ̱̈': 3, + 'ɩ́': 2, + 'ʉ́': 2, + 'ʉ̌': 2, + 'ʊ́': 2, + 'а̄': 2, + 'е̄': 2, + 'ё': 2, + 'ӣ': 2, + 'ӣ̄': 3, + 'й': 2, + 'о̄': 2, + 'о̄̄': 3, + 'Р̌': 2, + 'р̌': 2, + 'ӯ': 2, + 'ы̄': 2, + 'ы̄̄': 3, + 'э̄': 2, + 'э̄̄': 3, + 'ю̄': 2, + 'я̄': 2, + 'ө̄': 2, + 'אַ': 2, + 'אָ': 2, + 'בֿ': 2, + 'וּ': 2, + 'יִ': 2, + 'כּ': 2, + 'פּ': 2, + 'פֿ': 2, + 'תּ': 2, + 'ײַ': 2, + 'اً': 2, + 'اُ': 2, + 'اّ': 2, + 'أ': 2, + 'إ': 2, + 'بَ': 2, + 'تُ': 2, + 'ت‌': 2, + 'ثّ': 2, + 'جُ': 2, + 'دّ': 2, + 'رً': 2, + 'رِ': 2, + 'رّ': 2, + 'صّ': 2, + 'ضً': 2, + 'فّ': 2, + 'قِ': 2, + 'لِ': 2, + 'مً': 2, + 'مِ': 2, + 'مّ': 2, + 'نِ': 2, + 'نّ': 2, + 'ن‌': 2, + 'هٔ': 2, + 'ه‌': 2, + 'وَ': 2, + 'وّ': 2, + 'ؤ': 2, + 'يُ': 2, + 'پُ': 2, + 'چّ': 2, + 'کُ': 2, + 'کِ': 2, + 'ھُ': 2, + 'ھٔ': 2, + 'ہِ': 2, + 'ہٰ': 2, + 'یِ': 2, + 'یّ': 2, + 'یٔ': 2, + 'یٰ': 2, + 'ی‌': 2, + 'ے‌': 2, + 'ܒ݂': 2, + 'ܓ̰': 2, + 'ܓ݂': 2, + 'ܝܼ': 2, + 'ܟ̰': 2, + 'ܟ݂': 2, + 'ܡܹ': 2, + 'ܬܵ': 2, + 'ހަ': 2, + 'ހާ': 2, + 'ހި': 2, + 'ހީ': 2, + 'ހު': 2, + 'ހެ': 2, + 'ހޭ': 2, + 'ހޮ': 2, + 'ހޯ': 2, + 'ށަ': 2, + 'ށާ': 2, + 'ށި': 2, + 'ށު': 2, + 'ށެ': 2, + 'ށޭ': 2, + 'ށް': 2, + 'ނަ': 2, + 'ނާ': 2, + 'ނި': 2, + 'ނީ': 2, + 'ނު': 2, + 'ނޫ': 2, + 'ނެ': 2, + 'ނޭ': 2, + 'ން': 2, + 'ރަ': 2, + 'ރާ': 2, + 'ރި': 2, + 'ރީ': 2, + 'ރު': 2, + 'ރޫ': 2, + 'ރެ': 2, + 'ރޭ': 2, + 'ރޮ': 2, + 'ބަ': 2, + 'ބާ': 2, + 'ބި': 2, + 'ބީ': 2, + 'ބު': 2, + 'ބޫ': 2, + 'ބެ': 2, + 'ބޭ': 2, + 'ބޮ': 2, + 'ބް': 2, + 'ޅަ': 2, + 'ޅާ': 2, + 'ޅި': 2, + 'ޅު': 2, + 'ޅެ': 2, + 'ޅޭ': 2, + 'ކަ': 2, + 'ކާ': 2, + 'ކި': 2, + 'ކީ': 2, + 'ކު': 2, + 'ކެ': 2, + 'ކޮ': 2, + 'ކް': 2, + 'އަ': 2, + 'އާ': 2, + 'އި': 2, + 'އީ': 2, + 'އު': 2, + 'އޫ': 2, + 'އެ': 2, + 'އޭ': 2, + 'އޮ': 2, + 'އޯ': 2, + 'އް': 2, + 'ވަ': 2, + 'ވާ': 2, + 'ވި': 2, + 'ވީ': 2, + 'ވު': 2, + 'ވެ': 2, + 'ވޭ': 2, + 'ވޮ': 2, + 'ވޯ': 2, + 'މަ': 2, + 'މާ': 2, + 'މި': 2, + 'މީ': 2, + 'މު': 2, + 'މުި': 3, + 'މެ': 2, + 'މޭ': 2, + 'މް': 2, + 'ފަ': 2, + 'ފާ': 2, + 'ފި': 2, + 'ފީ': 2, + 'ފު': 2, + 'ފޫ': 2, + 'ފެ': 2, + 'ފޯ': 2, + 'ފް': 2, + 'ދަ': 2, + 'ދާ': 2, + 'ދި': 2, + 'ދީ': 2, + 'ދު': 2, + 'ދޫ': 2, + 'ދެ': 2, + 'ދޭ': 2, + 'ދޮ': 2, + 'ތަ': 2, + 'ތާ': 2, + 'ތި': 2, + 'ތީ': 2, + 'ތު': 2, + 'ތެ': 2, + 'ތް': 2, + 'ލަ': 2, + 'ލާ': 2, + 'ލި': 2, + 'ލީ': 2, + 'ލު': 2, + 'ލޫ': 2, + 'ލެ': 2, + 'ލޭ': 2, + 'ލް': 2, + 'ގަ': 2, + 'ގާ': 2, + 'ގި': 2, + 'ގު': 2, + 'ގެ': 2, + 'ގޮ': 2, + 'ޏަ': 2, + 'ޏެ': 2, + 'ސަ': 2, + 'ސާ': 2, + 'ސި': 2, + 'ސީ': 2, + 'ސު': 2, + 'ސޫ': 2, + 'ސެ': 2, + 'ސް': 2, + 'ޑަ': 2, + 'ޑާ': 2, + 'ޑި': 2, + 'ޑު': 2, + 'ޑެ': 2, + 'ޒަ': 2, + 'ޒާ': 2, + 'ޒި': 2, + 'ޒީ': 2, + 'ޒު': 2, + 'ޒެ': 2, + 'ޓަ': 2, + 'ޓި': 2, + 'ޓީ': 2, + 'ޓު': 2, + 'ޓެ': 2, + 'ޔަ': 2, + 'ޔާ': 2, + 'ޔި': 2, + 'ޔު': 2, + 'ޔެ': 2, + 'ޔޭ': 2, + 'ޔޮ': 2, + 'ޕް': 2, + 'ޖަ': 2, + 'ޖާ': 2, + 'ޖި': 2, + 'ޖު': 2, + 'ޖޫ': 2, + 'ޖެ': 2, + 'ޖޭ': 2, + 'ޖް': 2, + 'ޗަ': 2, + 'ޗު': 2, + 'ޗެ': 2, + 'ޘަ': 2, + 'ޙަ': 2, + 'ޙާ': 2, + 'ޙި': 2, + 'ޙީ': 2, + 'ޙު': 2, + 'ޙެ': 2, + 'ޙް': 2, + 'ޚާ': 2, + 'ޚި': 2, + 'ޚު': 2, + 'ޚް': 2, + 'ޛަ': 2, + 'ޝަ': 2, + 'ޞަ': 2, + 'ޞާ': 2, + 'ޞި': 2, + 'ޞު': 2, + 'ޞޫ': 2, + 'ޞް': 2, + 'ޟު': 2, + 'ޠަ': 2, + 'ޠީ': 2, + 'ޢަ': 2, + 'ޢާ': 2, + 'ޢީ': 2, + 'ޢު': 2, + 'ޢެ': 2, + 'ޢް': 2, + 'ޣާ': 2, + 'ޤަ': 2, + 'ޤާ': 2, + 'ޤި': 2, + 'ޤީ': 2, + 'ޤު': 2, + 'ޤެ': 2, + 'ޤް': 2, + 'अं': 2, + 'आं': 2, + 'इँ': 2, + 'इं': 2, + 'ऊं': 2, + 'एं': 2, + 'ओं': 2, + 'कं': 2, + 'कां': 3, + 'किं': 3, + 'कु': 2, + 'कू': 2, + 'कृ': 2, + 'के': 2, + 'केँ': 3, + 'कें': 3, + 'केा': 3, + 'कै': 2, + 'क्': 2, + 'क्क': 3, + 'क्का': 4, + 'क्कां': 5, + 'क्को': 4, + 'क्घ्घि्': 7, + 'क्छ': 3, + 'क्त': 3, + 'क्ता': 4, + 'क्ति': 4, + 'क्ती': 4, + 'क्तीं': 5, + 'क्तुं': 5, + 'क्तेः': 5, + 'क्त्योः': 7, + 'क्ना': 4, + 'क्नि': 4, + 'क्य': 3, + 'क्या': 4, + 'क्र': 3, + 'क्रा': 4, + 'क्रि': 4, + 'क्रू': 4, + 'क्ष': 3, + 'क्षं': 4, + 'क्षा': 4, + 'क्षां': 5, + 'क्षाः': 5, + 'क्षि': 4, + 'क्षे': 4, + 'क्षै': 4, + 'क्षो': 4, + 'क्ष्ण': 5, + 'क्ष्य': 5, + 'क्ष्या': 6, + 'क्सा': 4, + 'खु': 2, + 'खे': 2, + 'खै': 2, + 'ख्त': 3, + 'ख्ने': 4, + 'ख्य': 3, + 'ख्यः': 4, + 'ख्या': 4, + 'ख्‍ने': 5, + 'गं': 2, + 'ग़': 2, + 'ग़ा': 3, + 'ग़ु': 3, + 'गाँ': 3, + 'गां': 3, + 'गु': 2, + 'गू': 2, + 'गृ': 2, + 'गे': 2, + 'गै': 2, + 'गों': 3, + 'ग्ण': 3, + 'ग्न': 3, + 'ग्ने': 4, + 'ग्भे': 4, + 'ग्य': 3, + 'ग्या': 4, + 'ग्ये': 4, + 'ग्यैः': 5, + 'ग्र': 3, + 'ग्रे': 4, + 'ग्र्य': 5, + 'घं': 2, + 'घू': 2, + 'घृ': 2, + 'घे': 2, + 'घेि': 3, + 'घ्': 2, + 'घ्ंत': 4, + 'घ्का': 4, + 'घ्त': 3, + 'घ्र': 3, + 'घ्र्व्य': 7, + 'घ्लि': 4, + 'घ्व': 3, + 'घ्श्य': 5, + 'घ्स्ट': 5, + 'ङ्ग': 3, + 'ङ्घ': 3, + 'चां': 3, + 'चु': 2, + 'चूं': 3, + 'चे': 2, + 'चै': 2, + 'च्च': 3, + 'च्चा': 4, + 'च्चे': 4, + 'च्चों': 5, + 'च्छ': 3, + 'च्छं': 4, + 'च्छा': 4, + 'च्छि': 4, + 'च्छु': 4, + 'च्छे': 4, + 'च्या': 4, + 'च्यां': 5, + 'च्यो': 4, + 'छु': 2, + 'छुी': 3, + 'छै': 2, + 'जँ': 2, + 'जिं': 3, + 'जु': 2, + 'जे': 2, + 'जेँ': 3, + 'ज्ज': 3, + 'ज्ञा': 4, + 'ज्ञे': 4, + 'ज्ने': 4, + 'ज्य': 3, + 'ज्या': 4, + 'ज्या‌': 5, + 'ज्रा': 4, + 'झे': 2, + 'ञ्च': 3, + 'ञ्चा': 4, + 'ञ्चि': 4, + 'टां': 3, + 'टुँ': 3, + 'टुं': 3, + 'टू': 2, + 'टे': 2, + 'टै': 2, + 'टों': 3, + 'ट्ज़': 4, + 'ट्टि': 4, + 'ट्टी': 4, + 'ट्या': 4, + 'ट्र': 3, + 'ट्रा': 4, + 'ट्रे': 4, + 'ठे': 2, + 'ठैः': 3, + 'ड़': 2, + 'ड़ा': 3, + 'ड़े': 3, + 'डू': 2, + 'डे़': 3, + 'ढं': 2, + 'ढ़': 2, + 'ढ़ा': 3, + 'ढ़ि': 3, + 'ढ़ी': 3, + 'ढ़ो': 3, + 'ढाँ': 3, + 'ढे': 2, + 'णं': 2, + 'णां': 3, + 'णु': 2, + 'णू': 2, + 'णे': 2, + 'णेँ': 3, + 'णों': 3, + 'ण्ड': 3, + 'ण्डं': 4, + 'ण्डः': 4, + 'ण्डि': 4, + 'ण्य': 3, + 'ण्या': 4, + 'ण्यां': 5, + 'तँ': 2, + 'तं': 2, + 'तां': 3, + 'ताः': 3, + 'तिं': 3, + 'तु': 2, + 'तुं': 3, + 'तू': 2, + 'तृ': 2, + 'ते': 2, + 'तेँ': 3, + 'तै': 2, + 'तों': 3, + 'त्': 2, + 'त्का': 4, + 'त्त': 3, + 'त्ता': 4, + 'त्ति': 4, + 'त्ते': 4, + 'त्त्थि': 6, + 'त्त्व': 5, + 'त्त्वा': 6, + 'त्त्वे': 6, + 'त्न': 3, + 'त्नी': 4, + 'त्नों': 5, + 'त्प': 3, + 'त्पा': 4, + 'त्पी': 4, + 'त्पू': 4, + 'त्म': 3, + 'त्मा': 4, + 'त्य': 3, + 'त्यं': 4, + 'त्या': 4, + 'त्यां': 5, + 'त्यि': 4, + 'त्ये': 4, + 'त्यै': 4, + 'त्र': 3, + 'त्रा': 4, + 'त्राा': 5, + 'त्राि': 5, + 'त्रि': 4, + 'त्री': 4, + 'त्रे': 4, + 'त्र्त': 5, + 'त्र्य': 5, + 'त्र्या': 6, + 'त्र्ये': 6, + 'त्व': 3, + 'त्वं': 4, + 'त्वा': 4, + 'त्वां': 5, + 'त्वे': 4, + 'त्सं': 4, + 'त्सा': 4, + 'त्सो': 4, + 'त्स्वा': 6, + 'थु': 2, + 'थे': 2, + 'थै': 2, + 'थ्य': 3, + 'दं': 2, + 'दां': 3, + 'दु': 2, + 'दू': 2, + 'दृ': 2, + 'दे': 2, + 'दै': 2, + 'द्घ': 3, + 'द्घि': 4, + 'द्घो': 4, + 'द्द': 3, + 'द्दा': 4, + 'द्दि': 4, + 'द्दी': 4, + 'द्दे': 4, + 'द्ध': 3, + 'द्धः': 4, + 'द्धा': 4, + 'द्धां': 5, + 'द्धि': 4, + 'द्धिं': 5, + 'द्धी': 4, + 'द्धीं': 5, + 'द्धैः': 5, + 'द्भ': 3, + 'द्भा': 4, + 'द्य': 3, + 'द्या': 4, + 'द्र': 3, + 'द्रो': 4, + 'द्व': 3, + 'द्वा': 4, + 'द्वि': 4, + 'द्वे': 4, + 'द्स': 3, + 'द्‌': 3, + 'धां': 3, + 'धाः': 3, + 'धु': 2, + 'धृ': 2, + 'धे': 2, + 'धेः': 3, + 'धों': 3, + 'ध्य': 3, + 'ध्या': 4, + 'ध्ये': 4, + 'ध्व': 3, + 'नं': 2, + 'नां': 3, + 'नाः': 3, + 'ना‌': 3, + 'निँ': 3, + 'निः': 3, + 'नु': 2, + 'नू': 2, + 'नृ': 2, + 'ने': 2, + 'नै': 2, + 'नैः': 3, + 'नों': 3, + 'न्': 2, + 'न्का': 4, + 'न्चि': 4, + 'न्छे': 4, + 'न्जे': 4, + 'न्ञ्या': 6, + 'न्त': 3, + 'न्तं': 4, + 'न्तः': 4, + 'न्ता': 4, + 'न्ति': 4, + 'न्तु': 4, + 'न्तुं': 5, + 'न्ते': 4, + 'न्तो': 4, + 'न्तों': 5, + 'न्त्र': 5, + 'न्त्रा': 6, + 'न्त्राः': 7, + 'न्त्रि': 6, + 'न्त्री': 6, + 'न्त्र्य': 7, + 'न्त्र्यं': 8, + 'न्त्र्या': 8, + 'न्त्र्ये': 8, + 'न्द': 3, + 'न्दा': 4, + 'न्दी': 4, + 'न्दो': 4, + 'न्ध': 3, + 'न्धा': 4, + 'न्धि': 4, + 'न्धी': 4, + 'न्धु': 4, + 'न्धों': 5, + 'न्न': 3, + 'न्ना': 4, + 'न्नाः': 5, + 'न्नि': 4, + 'न्ने': 4, + 'न्म': 3, + 'न्मा': 4, + 'न्मु': 4, + 'न्मे': 4, + 'न्य': 3, + 'न्या': 4, + 'न्ये': 4, + 'न्यै': 4, + 'न्यो': 4, + 'न्व': 3, + 'न्वे': 4, + 'न्स': 3, + 'न्हा': 4, + 'न्हें': 5, + 'न्ह्यां': 7, + 'पं': 2, + 'पाँ': 3, + 'पां': 3, + 'पु': 2, + 'पू': 2, + 'पृ': 2, + 'पे': 2, + 'पेँ': 3, + 'पै': 2, + 'पों': 3, + 'प्त': 3, + 'प्तं': 4, + 'प्ति': 4, + 'प्तुं': 5, + 'प्तौ': 4, + 'प्य': 3, + 'प्यं': 4, + 'प्या': 4, + 'प्र': 3, + 'प्रा': 4, + 'फ़': 2, + 'फाँ': 3, + 'फु': 2, + 'फे': 2, + 'फ्त': 3, + 'फ्ता': 4, + 'फ्ना': 4, + 'फ्नो': 4, + 'फ्रां': 5, + 'बँ': 2, + 'बं': 2, + 'बाँ': 3, + 'बु': 2, + 'बू': 2, + 'बृ': 2, + 'बे': 2, + 'बै': 2, + 'ब्द': 3, + 'ब्ध': 3, + 'ब्धि': 4, + 'ब्यू': 4, + 'भं': 2, + 'भिः': 3, + 'भु': 2, + 'भू': 2, + 'भे': 2, + 'भै': 2, + 'भ्य': 3, + 'भ्यः': 4, + 'भ्या': 4, + 'भ्यां': 5, + 'भ्यु': 4, + 'भ्यो': 4, + 'भ्र': 3, + 'मं': 2, + 'मां': 3, + 'मु': 2, + 'मू': 2, + 'मे': 2, + 'मेँ': 3, + 'में': 3, + 'मै': 2, + 'मों': 3, + 'म्': 2, + 'म्ति': 4, + 'म्न': 3, + 'म्नि': 4, + 'म्प': 3, + 'म्पा': 4, + 'म्प्र': 5, + 'म्ब': 3, + 'म्बु': 4, + 'म्भि': 4, + 'म्म': 3, + 'म्मा': 4, + 'म्मि': 4, + 'म्मे': 4, + 'म्या': 4, + 'म्से': 4, + 'म्ह': 3, + 'म्ही': 4, + 'म्हो': 4, + 'यं': 2, + 'यां': 3, + 'याः': 3, + 'यु': 2, + 'यू': 2, + 'ये': 2, + 'यै': 2, + 'यैः': 3, + 'यों': 3, + 'य्य': 3, + 'य्यो': 4, + 'रं': 2, + 'रां': 3, + 'राः': 3, + 'रिं': 3, + 'रु': 2, + 'रू': 2, + 'रे': 2, + 'रें': 3, + 'रै': 2, + 'रों': 3, + 'र्क': 3, + 'र्कि': 4, + 'र्ग': 3, + 'र्गी': 4, + 'र्गे': 4, + 'र्चि': 4, + 'र्छ': 3, + 'र्ज': 3, + 'र्जा': 4, + 'र्जि': 4, + 'र्जी': 4, + 'र्ट': 3, + 'र्ढ': 3, + 'र्ण': 3, + 'र्णं': 4, + 'र्णां': 5, + 'र्णी': 4, + 'र्त': 3, + 'र्ता': 4, + 'र्ति': 4, + 'र्तिः': 5, + 'र्ती': 4, + 'र्तुं': 5, + 'र्त्त': 5, + 'र्त्ति': 6, + 'र्थ': 3, + 'र्थं': 4, + 'र्थि': 4, + 'र्थी': 4, + 'र्द': 3, + 'र्दा': 4, + 'र्दि': 4, + 'र्दु': 4, + 'र्दे': 4, + 'र्दै': 4, + 'र्दो': 4, + 'र्द्ध': 5, + 'र्ध': 3, + 'र्धा': 4, + 'र्धि': 4, + 'र्न': 3, + 'र्नि': 4, + 'र्नु': 4, + 'र्नू': 4, + 'र्ने': 4, + 'र्फ': 3, + 'र्ब': 3, + 'र्बं': 4, + 'र्बा': 4, + 'र्भ': 3, + 'र्भा': 4, + 'र्म': 3, + 'र्मं': 4, + 'र्मा': 4, + 'र्मि': 4, + 'र्य': 3, + 'र्यं': 4, + 'र्या': 4, + 'र्यां': 5, + 'र्ये': 4, + 'र्यों': 5, + 'र्रा': 4, + 'र्व': 3, + 'र्वा': 4, + 'र्वां': 5, + 'र्वृ': 4, + 'र्वे': 4, + 'र्वो': 4, + 'र्श': 3, + 'र्ष': 3, + 'र्षे': 4, + 'र्स': 3, + 'र्सा': 4, + 'र्ह': 3, + 'र्हाः': 5, + 'र्हि': 4, + 'र्हो': 4, + 'र्‍या': 5, + 'लां': 3, + 'लाः': 3, + 'लिं': 3, + 'लीं': 3, + 'लु': 2, + 'लू': 2, + 'ले': 2, + 'लै': 2, + 'लों': 3, + 'ल्क': 3, + 'ल्का': 4, + 'ल्ने': 4, + 'ल्प': 3, + 'ल्पि': 4, + 'ल्म': 3, + 'ल्य': 3, + 'ल्यं': 4, + 'ल्या': 4, + 'ल्यां': 5, + 'ल्याः': 5, + 'ल्ये': 4, + 'ल्ल': 3, + 'ल्लं': 4, + 'ल्ला': 4, + 'ल्लि': 4, + 'ल्ले': 4, + 'ल्ह': 3, + 'ळे': 2, + 'वं': 2, + 'वां': 3, + 'वाः': 3, + 'वू': 2, + 'वृ': 2, + 'वे': 2, + 'वै': 2, + 'वों': 3, + 'व्य': 3, + 'व्या': 4, + 'व्ये': 4, + 'व्यों': 5, + 'शं': 2, + 'शां': 3, + 'शाः': 3, + 'शु': 2, + 'शू': 2, + 'शे': 2, + 'शों': 3, + 'श्च': 3, + 'श्चि': 4, + 'श्य': 3, + 'श्या': 4, + 'श्यि': 4, + 'श्यों': 5, + 'श्र': 3, + 'श्रा': 4, + 'श्रां': 5, + 'श्रु': 4, + 'श्व': 3, + 'श्वा': 4, + 'श्वि': 4, + 'षां': 3, + 'षाः': 3, + 'षु': 2, + 'षे': 2, + 'षों': 3, + 'ष्का': 4, + 'ष्ट': 3, + 'ष्टः': 4, + 'ष्टा': 4, + 'ष्टां': 5, + 'ष्टाः': 5, + 'ष्टि': 4, + 'ष्टी': 4, + 'ष्टीं': 5, + 'ष्ट्र': 5, + 'ष्ट्रा': 6, + 'ष्ट्रां': 7, + 'ष्ट्रि': 6, + 'ष्ट्री': 6, + 'ष्ट्रे': 6, + 'ष्ट्रो': 6, + 'ष्ट्रों': 7, + 'ष्ठा': 4, + 'ष्ठे': 4, + 'ष्ठों': 5, + 'ष्णु': 4, + 'ष्प': 3, + 'ष्प्र': 5, + 'ष्य': 3, + 'ष्यः': 4, + 'ष्यों': 5, + 'सँ': 2, + 'सं': 2, + 'साँ': 3, + 'सां': 3, + 'सु': 2, + 'सू': 2, + 'सृ': 2, + 'से': 2, + 'सै': 2, + 'स्क': 3, + 'स्का': 4, + 'स्काः': 5, + 'स्कु': 4, + 'स्कू': 4, + 'स्कृ': 4, + 'स्ट': 3, + 'स्ट्या': 6, + 'स्त': 3, + 'स्ता': 4, + 'स्ति': 4, + 'स्ती': 4, + 'स्तु': 4, + 'स्तुं': 5, + 'स्तै': 4, + 'स्तो': 4, + 'स्त्र': 5, + 'स्त्रा': 6, + 'स्त्रि': 6, + 'स्त्री': 6, + 'स्थ': 3, + 'स्था': 4, + 'स्थां': 5, + 'स्थि': 4, + 'स्थी': 4, + 'स्थे': 4, + 'स्थ्य': 5, + 'स्धी': 4, + 'स्प': 3, + 'स्पे': 4, + 'स्म': 3, + 'स्मि': 4, + 'स्मिं': 5, + 'स्मै': 4, + 'स्य': 3, + 'स्या': 4, + 'स्यां': 5, + 'स्याः': 5, + 'स्युः': 5, + 'स्यों': 5, + 'स्रो': 4, + 'स्ल': 3, + 'स्व': 3, + 'स्वं': 4, + 'स्वा': 4, + 'स्वी': 4, + 'स्वे': 4, + 'स्स': 3, + 'स्सा': 4, + 'हाँ': 3, + 'हां': 3, + 'हिं': 3, + 'हीं': 3, + 'हु': 2, + 'हुँ': 3, + 'हू': 2, + 'हे': 2, + 'है': 2, + 'हैं': 3, + 'हैः': 3, + 'हों': 3, + 'ह्या': 4, + 'ह्रा': 4, + 'फ़्ता': 4, + 'আ‌': 2, + 'ই‌': 2, + 'এ‌': 2, + 'কা‌': 3, + 'কিং': 3, + 'কু': 2, + 'কূ': 2, + 'কৃ': 2, + 'কে‌': 3, + 'ক্ত': 3, + 'ক্তি': 4, + 'ক্য': 3, + 'ক্র': 3, + 'ক্রী': 4, + 'ক্ষ': 3, + 'ক্ষা': 4, + 'ক্ষি': 4, + 'ক্ষে': 4, + 'ক্ষ্য': 5, + 'ক্ষ্যে': 6, + 'খু': 2, + 'খ্যা': 4, + 'গু': 2, + 'গৃ': 2, + 'গ্য': 3, + 'গ্র': 3, + 'গ্রা': 4, + 'গ্রে': 4, + 'ঘৃ': 2, + 'ঘো': 3, + 'ঙ্খা': 4, + 'ঙ্গ': 3, + 'ঙ্গী': 4, + 'ঙ্গে': 4, + 'ঙ্ঘ': 3, + 'চ্চ': 3, + 'চ্ছ': 3, + 'চ্ছা': 4, + 'চ্ছা‌': 5, + 'চ্ছু': 4, + 'চ্ছে': 4, + 'ছু': 2, + 'জে‌': 3, + 'জ্ঞ': 3, + 'জ্ঞা': 4, + 'জ্য': 3, + 'ঞ্চি': 4, + 'ঞ্ছি': 4, + 'ট্রে': 4, + 'ড়': 2, + 'ড়া': 3, + 'ঢ়': 2, + 'ণ্ড': 3, + 'ণ্ডে': 4, + 'ণ্য': 3, + 'তাঁ': 3, + 'তা‌': 3, + 'তি‌': 3, + 'তু': 2, + 'তৃ': 2, + 'তে‌': 3, + 'ত্ত': 3, + 'ত্তা': 4, + 'ত্তি': 4, + 'ত্ন': 3, + 'ত্ব': 3, + 'ত্বে': 4, + 'ত্ম': 3, + 'ত্য': 3, + 'ত্যা': 4, + 'ত্যি': 4, + 'ত্যে': 4, + 'ত্র': 3, + 'ত্রা': 4, + 'ত্রে': 4, + 'ত্‍': 3, + 'ত্‍প': 4, + 'ত্‍পী': 5, + 'ত্‍সা': 5, + 'থ্য': 3, + 'দৃ': 2, + 'দে‌': 3, + 'দ্দি': 4, + 'দ্দে': 4, + 'দ্ধ': 3, + 'দ্ধা': 4, + 'দ্ধি': 4, + 'দ্ধে': 4, + 'দ্বা': 4, + 'দ্ভ': 3, + 'দ্ভূ': 4, + 'দ্য': 3, + 'দ্রো': 4, + 'ধ্য': 3, + 'ধ্যে': 4, + 'না‌': 3, + 'নু': 2, + 'ন্ড': 3, + 'ন্ত': 3, + 'ন্তা': 4, + 'ন্তি': 4, + 'ন্তে': 4, + 'ন্ত্রি': 6, + 'ন্ত্রে': 6, + 'ন্থী': 4, + 'ন্ধ': 3, + 'ন্ধা': 4, + 'ন্ধু': 4, + 'ন্ন': 3, + 'ন্ম': 3, + 'ন্মা': 4, + 'ন্মু': 4, + 'ন্য': 3, + 'ন্যা': 4, + 'ন্যে': 4, + 'ন‌': 2, + 'পা‌': 3, + 'পু': 2, + 'পূ': 2, + 'পৃ': 2, + 'প্ত': 3, + 'প্তা': 4, + 'প্র': 3, + 'প্রা': 4, + 'বা‌': 3, + 'বু': 2, + 'বৃ': 2, + 'ব্ধি': 4, + 'ব্য': 3, + 'ব্যা': 4, + 'ব্র': 3, + 'ভূ': 2, + 'ভ্য': 3, + 'ভ্রা': 4, + 'মা‌': 3, + 'মু': 2, + 'মূ': 2, + 'ম্প': 3, + 'ম্পা': 4, + 'ম্ব': 3, + 'ম্ভ': 3, + 'ম্ম': 3, + 'ম্মা': 4, + 'ম্য': 3, + 'য়': 2, + 'য়া': 3, + 'য়ি': 3, + 'য়ে': 3, + 'য়ো': 3, + 'যু': 2, + 'য্য': 3, + 'রাং': 3, + 'রু': 2, + 'রূ': 2, + 'র্ক': 3, + 'র্জ': 3, + 'র্জা': 4, + 'র্ণ': 3, + 'র্ত': 3, + 'র্থ': 3, + 'র্থে': 4, + 'র্দো': 4, + 'র্ধ': 3, + 'র্ধা': 4, + 'র্নী': 4, + 'র্ব': 3, + 'র্বা': 4, + 'র্বি': 4, + 'র্বো': 4, + 'র্ব্য': 5, + 'র্ভূ': 4, + 'র্ম': 3, + 'র্মে': 4, + 'র্য': 3, + 'র্যা': 4, + 'র‌': 2, + 'লে‌': 3, + 'ল্প': 3, + 'ল্য': 3, + 'ল্যা': 4, + 'ল্যে': 4, + 'ল্লে': 4, + 'শু': 2, + 'শৃং': 3, + 'শ্চ': 3, + 'শ্চি': 4, + 'শ্বা': 4, + 'শ্বে': 4, + 'শ্য': 3, + 'শ্যে': 4, + 'শ্র': 3, + 'শ্রা': 4, + 'ষ্ট': 3, + 'ষ্টা': 4, + 'ষ্টি': 4, + 'ষ্ট্র': 5, + 'ষ্ট্রী': 6, + 'ষ্ট্রে': 6, + 'ষ্ঠা': 4, + 'ষ্ঠি': 4, + 'ষ্ঠী': 4, + 'ষ্ঠু': 4, + 'ষ্ণু': 4, + 'সাং': 3, + 'সু': 2, + 'সৃ': 2, + 'সে‌': 3, + 'স্ক': 3, + 'স্কৃ': 4, + 'স্ত': 3, + 'স্তি': 4, + 'স্তি‌': 5, + 'স্ত্র': 5, + 'স্থ': 3, + 'স্থা': 4, + 'স্থ্য': 5, + 'স্ব': 3, + 'স্বা': 4, + 'স্বী': 4, + 'স্য': 3, + 'স্যা': 4, + 'স্যে': 4, + 'হ্য': 3, + 'হ‌': 2, + 'ਅੰ': 2, + 'ਅੱ': 2, + 'ਆਂ': 2, + 'ਇੰ': 2, + 'ਉਂ': 2, + 'ਉੱ': 2, + 'ਕਾਂ': 3, + 'ਕਿ੍': 3, + 'ਕਿੱ': 3, + 'ਕੁ': 2, + 'ਕੂ': 2, + 'ਕੇ': 2, + 'ਕੋ': 2, + 'ਕੌ': 2, + 'ਕੰ': 2, + 'ਕੱ': 2, + 'ਖਾਂ': 3, + 'ਖਿ਼': 3, + 'ਖੁ': 2, + 'ਖੁੱ': 3, + 'ਖੇ': 2, + 'ਖੋ': 2, + 'ਖੋਂ': 3, + 'ਗਿ੍': 3, + 'ਗੁ': 2, + 'ਗੇ': 2, + 'ਗੈ': 2, + 'ਗੱ': 2, + 'ਘੁੰ': 3, + 'ਘੰ': 2, + 'ਚਿੱ': 3, + 'ਚੁ': 2, + 'ਚੇ': 2, + 'ਚੋ': 2, + 'ਚੋਂ': 3, + 'ਚੰ': 2, + 'ਛੁ': 2, + 'ਛੋਂ': 3, + 'ਜਾਂ': 3, + 'ਜਿ਼': 3, + 'ਜਿ਼ੰ': 4, + 'ਜੁ': 2, + 'ਜੇ': 2, + 'ਜੋ': 2, + 'ਜੋਂ': 3, + 'ਜੰ': 2, + 'ਜੱ': 2, + 'ਝੰ': 2, + 'ਟਿ੍': 3, + 'ਟੇ': 2, + 'ਢੇ': 2, + 'ਢੰ': 2, + 'ਣਾਂ': 3, + 'ਣੇ': 2, + 'ਤਾਂ': 3, + 'ਤੇ': 2, + 'ਤੋਂ': 3, + 'ਤੰ': 2, + 'ਤੱ': 2, + 'ਥੇ': 2, + 'ਥੋਂ': 3, + 'ਦਾਂ': 3, + 'ਦਿੱ': 3, + 'ਦੁ': 2, + 'ਦੂ': 2, + 'ਦੇ': 2, + 'ਦੋ': 2, + 'ਦੋਂ': 3, + 'ਦੰ': 2, + 'ਧਾਂ': 3, + 'ਧੁ': 2, + 'ਧੇ': 2, + 'ਧੱ': 2, + 'ਨਾਂ': 3, + 'ਨੀਂ': 3, + 'ਨੁ': 2, + 'ਨੁੱ': 3, + 'ਨੂੰ': 3, + 'ਨੇ': 2, + 'ਨੋ': 2, + 'ਨੌ': 2, + 'ਨ੍': 2, + 'ਨੰ': 2, + 'ਪੁ': 2, + 'ਪੂ': 2, + 'ਪੈ': 2, + 'ਪ੍': 2, + 'ਪੰ': 2, + 'ਪੱ': 2, + 'ਫੌ': 2, + 'ਬੁ': 2, + 'ਬੂ': 2, + 'ਬੇ': 2, + 'ਬੋ': 2, + 'ਬੰ': 2, + 'ਬੱ': 2, + 'ਭੂ': 2, + 'ਭੇ': 2, + 'ਮਾਂ': 3, + 'ਮੁ': 2, + 'ਮੁੱ': 3, + 'ਮੂ': 2, + 'ਮੇ': 2, + 'ਮੇਂ': 3, + 'ਮੈਂ': 3, + 'ਮੌ': 2, + 'ਮੰ': 2, + 'ਯੁ': 2, + 'ਯੂ': 2, + 'ਯੋ': 2, + 'ਰਾਂ': 3, + 'ਰੁ': 2, + 'ਰੁੱ': 3, + 'ਰੂ': 2, + 'ਰੇ': 2, + 'ਰੋ': 2, + 'ਰ੍': 2, + 'ਰੰ': 2, + 'ਰੱ': 2, + 'ਲਾਂ': 3, + 'ਲਿੰ': 3, + 'ਲੇ': 2, + 'ਲੈ': 2, + 'ਲੋ': 2, + 'ਲ੍': 2, + 'ਲੰ': 2, + 'ਵਾਂ': 3, + 'ਵਿੱ': 3, + 'ਵੇ': 2, + 'ਵੇਂ': 3, + 'ਵੈ': 2, + 'ਵੰ': 2, + 'ਵੱ': 2, + 'ਸ਼ਾਂ': 3, + 'ਸ਼ੇ': 2, + 'ਸ਼ੋ': 2, + 'ਸ਼ੌ': 2, + 'ਸਾਂ': 3, + 'ਸਿੱ': 3, + 'ਸੁ': 2, + 'ਸੁੰ': 3, + 'ਸੂ': 2, + 'ਸੇ': 2, + 'ਸੇੇ': 3, + 'ਸੈਂ': 3, + 'ਸੌ': 2, + 'ਸੰ': 2, + 'ਸੱ': 2, + 'ਹਾਂ': 3, + 'ਹਿੰ': 3, + 'ਹਿੱ': 3, + 'ਹੀਂ': 3, + 'ਹੁ': 2, + 'ਹੁੰ': 3, + 'ਹੂ': 2, + 'ਹੇ': 2, + 'ਹੈ': 2, + 'ਹੋ': 2, + 'ਹੋਂ': 3, + 'ਹੱ': 2, + 'ਜ਼ੁ': 2, + 'ੜੀਂ': 3, + 'ੜੇ': 2, + 'ੜ੍': 2, + 'ਫ਼ੁ': 2, + 'અં': 2, + 'આં': 2, + 'ઊં': 2, + 'કાં': 3, + 'કુ': 2, + 'કૃ': 2, + 'કે': 2, + 'ક્ક': 3, + 'ક્કા': 4, + 'ક્કો': 4, + 'ક્તિ': 4, + 'ક્ર': 3, + 'ક્ષ': 3, + 'ક્ષા': 4, + 'ખુ': 2, + 'ખૂ': 2, + 'ખ્ત': 3, + 'ગુ': 2, + 'ગે': 2, + 'ગ્ન': 3, + 'ગ્ય': 3, + 'ચૂં': 3, + 'ચ્ચ': 3, + 'ચ્ચા': 4, + 'ચ્ચે': 4, + 'ચ્છા': 4, + 'ચ્છે': 4, + 'છું': 3, + 'છૂ': 2, + 'છે': 2, + 'જં': 2, + 'જાં': 3, + 'જુ': 2, + 'જૂ': 2, + 'જે': 2, + 'જ્ઞા': 4, + 'જ્ય': 3, + 'જ્યો': 4, + 'ઝૂં': 3, + 'ટું': 3, + 'ટે': 2, + 'ટ્ર': 3, + 'ટ્રે': 4, + 'ડાં': 3, + 'ડે': 2, + 'ણુ': 2, + 'ણે': 2, + 'તં': 2, + 'તાં': 3, + 'તુ': 2, + 'તૃ': 2, + 'તે': 2, + 'ત્તા': 4, + 'ત્તિ': 4, + 'ત્ત્વ': 5, + 'ત્ત્વા': 6, + 'ત્ન': 3, + 'ત્મ': 3, + 'ત્ય': 3, + 'ત્યા': 4, + 'ત્યાં': 5, + 'ત્યિ': 4, + 'ત્યે': 4, + 'ત્યો': 4, + 'ત્ર': 3, + 'ત્રી': 4, + 'ત્ર્ય': 5, + 'ત્વ': 3, + 'થે': 2, + 'દુ': 2, + 'દૃ': 2, + 'દે': 2, + 'દ્ધ': 3, + 'દ્ધા': 4, + 'દ્ધાં': 5, + 'દ્ધિ': 4, + 'દ્ભ': 3, + 'દ્વા': 4, + 'ધાં': 3, + 'ધુ': 2, + 'ધ્ય': 3, + 'ધ્યા': 4, + 'નં': 2, + 'નાં': 3, + 'નુ': 2, + 'નું': 3, + 'ને': 2, + 'નૈ': 2, + 'ન્ત': 3, + 'ન્તો': 4, + 'ન્મ': 3, + 'ન્મા': 4, + 'ન્મે': 4, + 'ન્ય': 3, + 'ન્યા': 4, + 'ન્યૂં': 5, + 'પુ': 2, + 'પૂ': 2, + 'પે': 2, + 'પ્ત': 3, + 'પ્ર': 3, + 'પ્રા': 4, + 'ફે': 2, + 'બં': 2, + 'બાં': 3, + 'બે': 2, + 'બ્ધ': 3, + 'ભં': 2, + 'ભાં': 3, + 'ભૂ': 2, + 'ભે': 2, + 'ભ્ય': 3, + 'મં': 2, + 'માં': 3, + 'મુ': 2, + 'મૂ': 2, + 'મૃ': 2, + 'મે': 2, + 'મૈ': 2, + 'મ્ય': 3, + 'મ્યાં': 5, + 'યુ': 2, + 'રં': 2, + 'રુ': 2, + 'રૂ': 2, + 'રે': 2, + 'ર્જ': 3, + 'ર્ણ': 3, + 'ર્ત': 3, + 'ર્તા': 4, + 'ર્થ': 3, + 'ર્થિ': 4, + 'ર્દો': 4, + 'ર્મ': 3, + 'ર્મિ': 4, + 'ર્મે': 4, + 'ર્ય': 3, + 'ર્યા': 4, + 'ર્યો': 4, + 'ર્વ': 3, + 'લાં': 3, + 'લિં': 3, + 'લે': 2, + 'લ્મ': 3, + 'લ્ય': 3, + 'ળે': 2, + 'વં': 2, + 'વાં': 3, + 'વું': 3, + 'વૃ': 2, + 'વે': 2, + 'વૈ': 2, + 'વ્ય': 3, + 'વ્યા': 4, + 'વ્યો': 4, + 'શાં': 3, + 'શુ': 2, + 'શે': 2, + 'શ્કે': 4, + 'શ્ચ': 3, + 'શ્ય': 3, + 'શ્ર': 3, + 'શ્વ': 3, + 'ષ્ટિ': 4, + 'ષ્ટ્ર': 5, + 'ષ્ટ્રી': 6, + 'ષ્ટ્રો': 6, + 'ષ્ઠા': 4, + 'ષ્ણુ': 4, + 'ષ્પ': 3, + 'સં': 2, + 'સાં': 3, + 'સુ': 2, + 'સું': 3, + 'સૂ': 2, + 'સે': 2, + 'સ્કૃ': 4, + 'સ્ટ': 3, + 'સ્તિ': 4, + 'સ્તી': 4, + 'સ્ત્રી': 6, + 'સ્થા': 4, + 'સ્થિ': 4, + 'સ્પ': 3, + 'સ્રી': 4, + 'સ્વ': 3, + 'સ્વા': 4, + 'સ્વી': 4, + 'સ્સા': 4, + 'હુ': 2, + 'હે': 2, + 'கீ': 2, + 'க்': 2, + 'ங்': 2, + 'சீ': 2, + 'ச்': 2, + 'ஞ்': 2, + 'ட்': 2, + 'ண்': 2, + 'தீ': 2, + 'த்': 2, + 'நீ': 2, + 'ந்': 2, + 'ன்': 2, + 'ப்': 2, + 'மீ': 2, + 'ம்': 2, + 'யீ': 2, + 'ய்': 2, + 'ர்': 2, + 'ற்': 2, + 'ல்': 2, + 'ள்': 2, + 'ழ்': 2, + 'வீ': 2, + 'வ்': 2, + 'ஸ்': 2, + 'కా': 2, + 'కాం': 3, + 'కి': 2, + 'కీ': 2, + 'కుం': 3, + 'కె': 2, + 'కెం': 3, + 'కై': 2, + 'కొ': 2, + 'క్క': 3, + 'క్కు': 4, + 'క్త': 3, + 'క్తి': 4, + 'క్తీ': 4, + 'క్తు': 4, + 'క్య': 3, + 'క్ర': 3, + 'క్రాం': 5, + 'క్రి': 4, + 'క్రూ': 4, + 'క్ష': 3, + 'క్షా': 4, + 'క్షి': 4, + 'క్షిం': 5, + 'క్షే': 4, + 'క్షో': 4, + 'క్స్వా': 6, + 'ఖా': 2, + 'ఖ్య': 3, + 'ఖ్యా': 4, + 'గా': 2, + 'గి': 2, + 'గిం': 3, + 'గీ': 2, + 'గౌ': 2, + 'గ్భా': 4, + 'గ్మ': 3, + 'గ్య': 3, + 'గ్ర': 3, + 'గ్రి': 4, + 'ఘి': 2, + 'ఘో': 2, + 'చా': 2, + 'చి': 2, + 'చెం': 3, + 'చే': 2, + 'చో': 2, + 'చ్చు': 4, + 'చ్ఛ': 3, + 'చ్ఛా': 4, + 'చ్ఛే': 4, + 'ఛ్ఛా': 4, + 'జా': 2, + 'జి': 2, + 'జీ': 2, + 'జే': 2, + 'జో': 2, + 'జ్ఞ': 3, + 'జ్ఞా': 4, + 'జ్య': 3, + 'టి': 2, + 'టిం': 3, + 'టుం': 3, + 'టే': 2, + 'ట్టి': 4, + 'ట్లు': 4, + 'డి': 2, + 'డ్డ': 3, + 'డ్రు': 4, + 'ణా': 2, + 'ణిం': 3, + 'ణీ': 2, + 'తా': 2, + 'తి': 2, + 'తీ': 2, + 'తె': 2, + 'తొ': 2, + 'తో': 2, + 'త్కా': 4, + 'త్త': 3, + 'త్తి': 4, + 'త్తు': 4, + 'త్న': 3, + 'త్నిం': 5, + 'త్ప': 3, + 'త్ఫ': 3, + 'త్య': 3, + 'త్యం': 4, + 'త్యా': 4, + 'త్ర': 3, + 'త్రు': 4, + 'త్ర్య': 5, + 'త్వ': 3, + 'త్వా': 4, + 'త్స': 3, + 'థా': 2, + 'దా': 2, + 'ది': 2, + 'దిం': 3, + 'దుం': 3, + 'దే': 2, + 'దై': 2, + 'దో': 2, + 'ద్ఘో': 4, + 'ద్ది': 4, + 'ద్దు': 4, + 'ద్దే': 4, + 'ద్ధ': 3, + 'ద్ధి': 4, + 'ద్ధిం': 5, + 'ద్య': 3, + 'ద్యా': 4, + 'ద్యో': 4, + 'ద్ర్య': 5, + 'ద్వా': 4, + 'ధా': 2, + 'ధి': 2, + 'ధిం': 3, + 'ధీ': 2, + 'ధ్య': 3, + 'నా': 2, + 'నాం': 3, + 'ని': 2, + 'నిం': 3, + 'నీ': 2, + 'నుం': 3, + 'నె': 2, + 'నే': 2, + 'నై': 2, + 'నొ': 2, + 'నొం': 3, + 'న్ధ': 3, + 'న్న': 3, + 'న్నా': 4, + 'న్ని': 4, + 'న్ను': 4, + 'న్మ': 3, + 'న్య': 3, + 'న్యా': 4, + 'న్వే': 4, + 'పా': 2, + 'పిం': 3, + 'పీ': 2, + 'పె': 2, + 'పెం': 3, + 'పే': 2, + 'పై': 2, + 'పొం': 3, + 'ప్త': 3, + 'ప్ర': 3, + 'ప్రా': 4, + 'ప్రే': 4, + 'బా': 2, + 'బి': 2, + 'బో': 2, + 'బ్ర': 3, + 'భా': 2, + 'భి': 2, + 'భే': 2, + 'భ్య': 3, + 'భ్యు': 4, + 'భ్ర': 3, + 'భ్రా': 4, + 'మా': 2, + 'మి': 2, + 'మిం': 3, + 'మే': 2, + 'మై': 2, + 'మో': 2, + 'మ్య': 3, + 'యా': 2, + 'యి': 2, + 'యిం': 3, + 'యుం': 3, + 'యె': 2, + 'యే': 2, + 'యొ': 2, + 'యో': 2, + 'రా': 2, + 'రి': 2, + 'రిం': 3, + 'రై': 2, + 'రో': 2, + 'ర్': 2, + 'ర్గ': 3, + 'ర్చి': 4, + 'ర్చు': 4, + 'ర్ణ': 3, + 'ర్ణాం': 5, + 'ర్ణు': 4, + 'ర్త': 3, + 'ర్తి': 4, + 'ర్తిం': 5, + 'ర్తృ': 4, + 'ర్థ': 3, + 'ర్థి': 4, + 'ర్థిం': 5, + 'ర్ద': 3, + 'ర్దో': 4, + 'ర్ధ': 3, + 'ర్ప': 3, + 'ర్బం': 4, + 'ర్భ': 3, + 'ర్భా': 4, + 'ర్య': 3, + 'ర్యా': 4, + 'ర్రా': 4, + 'ర్వ': 3, + 'ర్వా': 4, + 'ర్హ': 3, + 'ర్హాం': 5, + 'ర్హు': 4, + 'లా': 2, + 'లి': 2, + 'లిం': 3, + 'లీ': 2, + 'లె': 2, + 'లే': 2, + 'లో': 2, + 'లౌ': 2, + 'ల్క': 3, + 'ల్గొ': 4, + 'ల్ప': 3, + 'ల్ల': 3, + 'ల్లి': 4, + 'ళా': 2, + 'వా': 2, + 'వి': 2, + 'విం': 3, + 'వీ': 2, + 'వే': 2, + 'వై': 2, + 'వ్య': 3, + 'వ్యా': 4, + 'వ్వ': 3, + 'శా': 2, + 'శాం': 3, + 'శి': 2, + 'శిం': 3, + 'శై': 2, + 'శ్చ': 3, + 'శ్చి': 4, + 'శ్య': 3, + 'శ్ర': 3, + 'శ్రాం': 5, + 'శ్లే': 4, + 'శ్వా': 4, + 'షా': 2, + 'షి': 2, + 'షిం': 3, + 'షే': 2, + 'ష్ట': 3, + 'ష్టు': 4, + 'ష్ట్ర': 5, + 'ష్ట్రీ': 6, + 'ష్ఠ': 3, + 'ష్ఠా': 4, + 'ష్ఠు': 4, + 'ష్థ': 3, + 'ష్ప': 3, + 'సా': 2, + 'సాం': 3, + 'సి': 2, + 'సీ': 2, + 'సె': 2, + 'సే': 2, + 'సౌ': 2, + 'స్కృ': 4, + 'స్తా': 4, + 'స్తి': 4, + 'స్త్ర': 5, + 'స్త్రీ': 6, + 'స్థ': 3, + 'స్థా': 4, + 'స్థి': 4, + 'స్థ్య': 5, + 'స్ప': 3, + 'స్య': 3, + 'స్వ': 3, + 'స్వా': 4, + 'స్వీ': 4, + 'స్వే': 4, + 'హా': 2, + 'హి': 2, + 'హిం': 3, + 'హో': 2, + 'ಕಾಂ': 3, + 'ಕಿಂ': 3, + 'ಕುಂ': 3, + 'ಕೆ': 2, + 'ಕೆಂ': 3, + 'ಕೊಂ': 3, + 'ಕೌ': 2, + 'ಕ್': 2, + 'ಕ್‌': 3, + 'ಖಾಂ': 3, + 'ಖ್': 2, + 'ಗಾಂ': 3, + 'ಗಿ': 2, + 'ಗೆ': 2, + 'ಗೊಂ': 3, + 'ಗೌ': 2, + 'ಗ್': 2, + 'ಘಿ': 2, + 'ಚಿ': 2, + 'ಚ್': 2, + 'ಛಿ': 2, + 'ಛೆ': 2, + 'ಜಿ': 2, + 'ಜೆ': 2, + 'ಜ್': 2, + 'ಞೆ': 2, + 'ಞೌ': 2, + 'ಟಿ': 2, + 'ಟುಂ': 3, + 'ಟ್': 2, + 'ಠಿ': 2, + 'ಡಿ': 2, + 'ಡೆ': 2, + 'ಡ್': 2, + 'ಢಿ': 2, + 'ಣಿ': 2, + 'ಣೆ': 2, + 'ತಿ': 2, + 'ತೆ': 2, + 'ತ್': 2, + 'ಥಿ': 2, + 'ಥೆ': 2, + 'ದಿ': 2, + 'ದಿಂ': 3, + 'ದೆ': 2, + 'ದೌ': 2, + 'ದ್': 2, + 'ಧಿ': 2, + 'ಧೆ': 2, + 'ಧ್': 2, + 'ನಾಂ': 3, + 'ನಿ': 2, + 'ನಿಂ': 3, + 'ನೆ': 2, + 'ನೌ': 2, + 'ನ್': 2, + 'ಪಿ': 2, + 'ಪ್': 2, + 'ಬೆ': 2, + 'ಬ್': 2, + 'ಭಿ': 2, + 'ಭೆ': 2, + 'ಭೌ': 2, + 'ಮಿ': 2, + 'ಮೆ': 2, + 'ಮ್': 2, + 'ಯಿ': 2, + 'ಯಿಂ': 3, + 'ಯುಂ': 3, + 'ಯೆ': 2, + 'ಯೆಂ': 3, + 'ಯ್': 2, + 'ರಾಂ': 3, + 'ರಿ': 2, + 'ರಿಂ': 3, + 'ರೆ': 2, + 'ರೆಂ': 3, + 'ರ್': 2, + 'ಲಿ': 2, + 'ಲೆ': 2, + 'ಲೆಂ': 3, + 'ಲ್': 2, + 'ಳಿ': 2, + 'ಳಿಂ': 3, + 'ಳೆ': 2, + 'ಳ್': 2, + 'ವಿ': 2, + 'ವುಂ': 3, + 'ವೆ': 2, + 'ವೆಂ': 3, + 'ವ್': 2, + 'ಶಾಂ': 3, + 'ಶಿ': 2, + 'ಶ್': 2, + 'ಷಿ': 2, + 'ಷೆ': 2, + 'ಷ್': 2, + 'ಸಾಂ': 3, + 'ಸಿ': 2, + 'ಸೆ': 2, + 'ಸ್': 2, + 'ಹಿ': 2, + 'ಹೆ': 2, + 'ಹೊಂ': 3, + 'കു': 2, + 'കൂ': 2, + 'കൃ': 2, + 'ക്ക': 3, + 'ക്കാ': 4, + 'ക്കി': 4, + 'ക്കു': 4, + 'ക്കും': 5, + 'ക്കെ': 4, + 'ക്കേ': 4, + 'ക്കൊ': 4, + 'ക്കോ': 4, + 'ക്ക്‌': 5, + 'ക്തി': 4, + 'ക്യ': 3, + 'ക്യം': 4, + 'ക്ര': 3, + 'ക്രൂ': 4, + 'ക്ഷ': 3, + 'ക്ഷാ': 4, + 'ക്ഷി': 4, + 'ക്ഷേ': 4, + 'ഖ്യാ': 4, + 'ഗു': 2, + 'ഗ്ഗം': 4, + 'ഗ്ദാ': 4, + 'ഗ്യ': 3, + 'ഗ്യം': 4, + 'ഗ്ര': 3, + 'ങ്കി': 4, + 'ങ്കെ': 4, + 'ങ്കേ': 4, + 'ങ്ങ': 3, + 'ങ്ങി': 4, + 'ച്ച': 3, + 'ച്ചി': 4, + 'ച്ചു': 4, + 'ച്ചും': 5, + 'ച്ചെ': 4, + 'ച്ചേ': 4, + 'ജ്യ': 3, + 'ജ്യാ': 4, + 'ഞ്ച': 3, + 'ഞ്ഞ': 3, + 'ഞ്ഞി': 4, + 'ഞ്ഞെ': 4, + 'ടു': 2, + 'ടും': 3, + 'ട്ട': 3, + 'ട്ടാ': 4, + 'ട്ടി': 4, + 'ട്ടു': 4, + 'ട്ടോ': 4, + 'ട്‌': 3, + 'ണ്ട': 3, + 'ണ്ടാ': 4, + 'ണ്ടി': 4, + 'ണ്ടു': 4, + 'ണ്ടും': 5, + 'ണ്ടെ': 4, + 'ണ്ട്‌': 5, + 'ണ്ഡ': 3, + 'ണ്ണ': 3, + 'ണ്‌': 3, + 'തു': 2, + 'തും': 3, + 'തൃ': 2, + 'ത്ത': 3, + 'ത്താ': 4, + 'ത്തി': 4, + 'ത്തു': 4, + 'ത്തും': 5, + 'ത്തെ': 4, + 'ത്തേ': 4, + 'ത്തോ': 4, + 'ത്ത്‌': 5, + 'ത്ന': 3, + 'ത്നം': 4, + 'ത്നി': 4, + 'ത്യ': 3, + 'ത്യാ': 4, + 'ത്യേ': 4, + 'ത്ര': 3, + 'ത്വ': 3, + 'ത്വം': 4, + 'ത്‌': 3, + 'ദൃ': 2, + 'ദ്ദ': 3, + 'ദ്ധ': 3, + 'ദ്ധി': 4, + 'ദ്യ': 3, + 'ദ്യാ': 4, + 'ദ്ര': 3, + 'ധൂ': 2, + 'ധ്യ': 3, + 'നു': 2, + 'നും': 3, + 'ന്ത': 3, + 'ന്തം': 4, + 'ന്തെ': 4, + 'ന്ത്ര': 5, + 'ന്ത്ര്യ': 7, + 'ന്ത്ര്യം': 8, + 'ന്ഥ': 3, + 'ന്ദ': 3, + 'ന്ധ': 3, + 'ന്ധി': 4, + 'ന്ന': 3, + 'ന്നാ': 4, + 'ന്നി': 4, + 'ന്നീ': 4, + 'ന്നു': 4, + 'ന്നും': 5, + 'ന്നെ': 4, + 'ന്നേ': 4, + 'ന്നോ': 4, + 'ന്ന്': 4, + 'ന്മ': 3, + 'ന്മാ': 4, + 'ന്മു': 4, + 'ന്മൂ': 4, + 'ന്യ': 3, + 'ന്യം': 4, + 'ന്യാ': 4, + 'ന്യേ': 4, + 'ന്യോ': 4, + 'ന്റെ': 4, + 'ന്‌': 3, + 'ന്‍': 3, + 'ന്‍കൂ': 5, + 'ന്‍പി': 5, + 'പു': 2, + 'പൂ': 2, + 'പ്പ': 3, + 'പ്പി': 4, + 'പ്പു': 4, + 'പ്പെ': 4, + 'പ്പോ': 4, + 'പ്പ്‌': 5, + 'പ്ര': 3, + 'പ്രാ': 4, + 'ബു': 2, + 'ബ്ലി': 4, + 'ഭ്യാ': 4, + 'ഭ്രാ': 4, + 'മു': 2, + 'മൃ': 2, + 'മ്പ': 3, + 'മ്പാ': 4, + 'മ്പ്ര': 5, + 'മ്മ': 3, + 'മ്മി': 4, + 'യു': 2, + 'യും': 3, + 'യ്ക്കു': 6, + 'യ്തി': 4, + 'യ്തു': 4, + 'യ്മ': 3, + 'യ്യാ': 4, + 'യ്യി': 4, + 'രു': 2, + 'രും': 3, + 'രൂ': 2, + 'ര്യ': 3, + 'ര്യം': 4, + 'ര്‍ക്കു': 7, + 'ര്‍ക്കും': 8, + 'ര്‍ക്ക്‌': 8, + 'ര്‍ഗ്ഗം': 7, + 'ര്‍ച്ച': 6, + 'ര്‍ണ്ണ': 6, + 'ര്‍ത്ത': 6, + 'ര്‍ത്തി': 7, + 'ര്‍ത്തു': 7, + 'ര്‍ത്തേ': 7, + 'ര്‍ദേ': 5, + 'ര്‍ദ്ദ': 6, + 'ര്‍പ്പെ': 7, + 'ര്‍ബ': 4, + 'ര്‍ഭ': 4, + 'ര്‍മ്മി': 7, + 'ര്‍രാ': 5, + 'ര്‍വ്വ': 6, + 'ര്‍ഹ': 4, + 'ര്‍ഹി': 5, + 'റു': 2, + 'റ്റ': 3, + 'റ്റം': 4, + 'റ്റു': 4, + 'റ്റേ': 4, + 'ലു': 2, + 'ലും': 3, + 'ല്യ': 3, + 'ല്യാ': 4, + 'ല്ല': 3, + 'ല്ലാ': 4, + 'ല്ലാം': 5, + 'ല്ലെ': 4, + 'ല്‍': 3, + 'ല്‍കി': 5, + 'ല്‍കു': 5, + 'ല്‍കേ': 5, + 'ല്‍ത': 4, + 'ല്‍നി': 5, + 'ല്‍പ്പ': 6, + 'ളു': 2, + 'ളും': 3, + 'ള്ള': 3, + 'ള്ളാ': 4, + 'ള്ളി': 4, + 'ള്ളൂ': 4, + 'ള്‍': 3, + 'ള്‍കൊ': 5, + 'ള്‍ക്ക': 6, + 'ള്‍ക്കി': 7, + 'ള്‍ക്കു': 7, + 'ള്‍ക്കും': 8, + 'ള്‍ക്കെ': 7, + 'ള്‍ക്ക്‌': 8, + 'ഴു': 2, + 'വു': 2, + 'വും': 3, + 'വൃ': 2, + 'വ്യ': 3, + 'വ്യം': 4, + 'വ്യാ': 4, + 'വ്വ': 3, + 'ശു': 2, + 'ശ്യ': 3, + 'ശ്ര': 3, + 'ശ്വാ': 4, + 'ഷ്ട': 3, + 'ഷ്ട്യാ': 6, + 'ഷ്ട്ര': 5, + 'ഷ്ട്രീ': 6, + 'ഷ്ണു': 4, + 'ഷ്യ': 3, + 'ഷ്യാ': 4, + 'സാം': 3, + 'സു': 2, + 'സൃ': 2, + 'സ്കാ': 4, + 'സ്തു': 4, + 'സ്ത്രം': 6, + 'സ്ത്രീ': 6, + 'സ്ഥ': 3, + 'സ്ഥാ': 4, + 'സ്ഥി': 4, + 'സ്യ': 3, + 'സ്റ്റ്‌': 7, + 'സ്വ': 3, + 'സ്വാ': 4, + 'സ്വീ': 4, + 'സ്സ': 3, + 'സ്സാ': 4, + 'സ്സി': 4, + 'സ്സും': 5, + 'സ്സോ': 4, + 'ഹിം': 3, + 'ഹു': 2, + 'ഹൃ': 2, + 'ൻ്റെ': 4, + 'ක්': 2, + 'ක්‍': 3, + 'කි': 2, + 'කී': 2, + 'කු': 2, + 'කූ': 2, + 'ඛ්‍': 3, + 'ගි': 2, + 'ගී': 2, + 'ගු': 2, + 'ඟි': 2, + 'ඟී': 2, + 'ච්': 2, + 'චි': 2, + 'ජ්‍': 3, + 'ජි': 2, + 'ජී': 2, + 'ටි': 2, + 'ටී': 2, + 'ටු': 2, + 'ඩි': 2, + 'ඩු': 2, + 'ණ්': 2, + 'ණි': 2, + 'ණී': 2, + 'ණු': 2, + 'ඬු': 2, + 'ත්': 2, + 'ත්‍': 3, + 'ති': 2, + 'තී': 2, + 'තු': 2, + 'ථි': 2, + 'ද්': 2, + 'ද්‍': 3, + 'දි': 2, + 'දිං': 3, + 'දී': 2, + 'දු': 2, + 'ධ්‍': 3, + 'ධි': 2, + 'ධී': 2, + 'න්': 2, + 'න්‍': 3, + 'නි': 2, + 'නී': 2, + 'නු': 2, + 'ඳි': 2, + 'ඳී': 2, + 'ඳු': 2, + 'ප්': 2, + 'ප්‍': 3, + 'පි': 2, + 'පී': 2, + 'පු': 2, + 'පූ': 2, + 'බි': 2, + 'බී': 2, + 'භු': 2, + 'ම්': 2, + 'මි': 2, + 'මී': 2, + 'මු': 2, + 'මූ': 2, + 'ඹී': 2, + 'ඹු': 2, + 'යි': 2, + 'යු': 2, + 'ර්': 2, + 'රි': 2, + 'රී': 2, + 'රු': 2, + 'රූ': 2, + 'ල්': 2, + 'ලි': 2, + 'ලී': 2, + 'ලු': 2, + 'ව්': 2, + 'ව්‍': 3, + 'වි': 2, + 'වී': 2, + 'වු': 2, + 'වූ': 2, + 'ශ්': 2, + 'ශ්‍': 3, + 'ශී': 2, + 'ෂ්': 2, + 'ෂ්‍': 3, + 'ෂි': 2, + 'ස්': 2, + 'සි': 2, + 'සී': 2, + 'සු': 2, + 'හි': 2, + 'හිං': 3, + 'හී': 2, + 'හු': 2, + 'ළි': 2, + 'ළු': 2, + 'กั': 2, + 'กิ': 2, + 'กี': 2, + 'กุ': 2, + 'ก็': 2, + 'ก่': 2, + 'ก้': 2, + 'ขั': 2, + 'ขั้': 3, + 'ขี่': 3, + 'ขึ้': 3, + 'ขื': 2, + 'ข็': 2, + 'ข่': 2, + 'ข้': 2, + 'คั': 2, + 'คิ': 2, + 'คุ': 2, + 'คุ้': 3, + 'คู่': 3, + 'ค่': 2, + 'ค้': 2, + 'ค์': 2, + 'งิ': 2, + 'งื่': 3, + 'จั': 2, + 'จิ': 2, + 'จึ': 2, + 'จุ': 2, + 'จ็': 2, + 'จ่': 2, + 'จ้': 2, + 'ฉั': 2, + 'ชั้': 3, + 'ชิ': 2, + 'ชี': 2, + 'ชื่': 3, + 'ชื้': 3, + 'ชุ': 2, + 'ช่': 2, + 'ช้': 2, + 'ซี่': 3, + 'ซึ่': 3, + 'ญิ': 2, + 'ฎิ': 2, + 'ฏิ': 2, + 'ฒิ': 2, + 'ณิ': 2, + 'ณี': 2, + 'ณ์': 2, + 'ดั': 2, + 'ดั่': 3, + 'ดิ': 2, + 'ดิ์': 3, + 'ดี': 2, + 'ดู': 2, + 'ด็': 2, + 'ด้': 2, + 'ตั': 2, + 'ตั้': 3, + 'ติ': 2, + 'ตี': 2, + 'ตุ': 2, + 'ต็': 2, + 'ต่': 2, + 'ต่ำ': 3, + 'ต้': 2, + 'ถิ่': 3, + 'ถี': 2, + 'ถึ': 2, + 'ถื': 2, + 'ถื่': 3, + 'ถุ': 2, + 'ถู': 2, + 'ถ้': 2, + 'ทั': 2, + 'ทั่': 3, + 'ทั้': 3, + 'ทิ': 2, + 'ที': 2, + 'ที่': 3, + 'ทุ': 2, + 'ท่': 2, + 'ท้': 2, + 'ธั': 2, + 'ธิ': 2, + 'ธิ์': 3, + 'ธี': 2, + 'ธุ์': 3, + 'ธ์': 2, + 'นั': 2, + 'นั้': 3, + 'นิ': 2, + 'นี้': 3, + 'นึ': 2, + 'นึ่': 3, + 'นื': 2, + 'นื่': 3, + 'นุ': 2, + 'นุ่': 3, + 'นู': 2, + 'น่': 2, + 'น้': 2, + 'น์': 2, + 'บั': 2, + 'บั่': 3, + 'บิ': 2, + 'บี': 2, + 'บื้': 3, + 'บุ': 2, + 'บู': 2, + 'บ่': 2, + 'ปั': 2, + 'ปิ': 2, + 'ป็': 2, + 'ป่': 2, + 'ผิ': 2, + 'ผู้': 3, + 'ผ่': 2, + 'พั': 2, + 'พิ': 2, + 'พิ่': 3, + 'พี': 2, + 'พื่': 3, + 'พื้': 3, + 'พู': 2, + 'พ้': 2, + 'ภั': 2, + 'มั': 2, + 'มั่': 3, + 'มิ': 2, + 'มิ่': 3, + 'มี': 2, + 'มื': 2, + 'มุ่': 3, + 'มู': 2, + 'มู่': 3, + 'ม่': 2, + 'ม้': 2, + 'ยั': 2, + 'ยิ': 2, + 'ยิ่': 3, + 'ยี': 2, + 'ยึ': 2, + 'ยื': 2, + 'ยุ': 2, + 'ยู่': 3, + 'ย่': 2, + 'ย่ำ': 3, + 'ย้': 2, + 'ย์': 2, + 'รั': 2, + 'รั้': 3, + 'ริ': 2, + 'รี': 2, + 'รื': 2, + 'รื่': 3, + 'รุ': 2, + 'รู': 2, + 'ร็': 2, + 'ร่': 2, + 'ร้': 2, + 'ร์': 2, + 'ลั': 2, + 'ลิ': 2, + 'ลี่': 3, + 'ลี้': 3, + 'ลึ': 2, + 'ลื': 2, + 'ลื่': 3, + 'ลุ': 2, + 'ลุ่': 3, + 'ลู่': 3, + 'ล่': 2, + 'ล้': 2, + 'วั': 2, + 'วิ': 2, + 'วุ': 2, + 'ว่': 2, + 'ว้': 2, + 'ศั': 2, + 'ศิ': 2, + 'ศี': 2, + 'ศึ': 2, + 'ษ์': 2, + 'สั': 2, + 'สิ': 2, + 'สิ่': 3, + 'สิ้': 3, + 'สี': 2, + 'สื': 2, + 'สื่': 3, + 'สุ': 2, + 'สู': 2, + 'สู่': 3, + 'สู้': 3, + 'ส่': 2, + 'หั': 2, + 'ห็': 2, + 'ห่': 2, + 'ห้': 2, + 'อั': 2, + 'อิ': 2, + 'อี': 2, + 'อื่': 3, + 'อื้': 3, + 'อ้': 2, + 'ກັ': 2, + 'ກິ': 2, + 'ກີ': 2, + 'ກຸ': 2, + 'ກຸ່': 3, + 'ກົ': 2, + 'ກ່': 2, + 'ກ້': 2, + 'ກໍ': 2, + 'ກໍ່': 3, + 'ຂັ': 2, + 'ຂັ້': 3, + 'ຂີ່': 3, + 'ຂື້': 3, + 'ຂົ': 2, + 'ຂົ່': 3, + 'ຂົ້': 3, + 'ຂ່': 2, + 'ຂ້': 2, + 'ຂໍ': 2, + 'ຂໍ້': 3, + 'ຄັ': 2, + 'ຄິ': 2, + 'ຄື': 2, + 'ຄື່': 3, + 'ຄຸ': 2, + 'ຄຸ້': 3, + 'ຄູ່': 3, + 'ຄົ': 2, + 'ຄົ້': 3, + 'ຄ່': 2, + 'ຄ້': 2, + 'ງົ': 2, + 'ຈັ': 2, + 'ຈັ້': 3, + 'ຈິ': 2, + 'ຈື່': 3, + 'ຈຸ': 2, + 'ຈົ': 2, + 'ຈົ່': 3, + 'ຈົ້': 3, + 'ຈ່': 2, + 'ຈ້': 2, + 'ຊັ': 2, + 'ຊັ່': 3, + 'ຊັ້': 3, + 'ຊິ': 2, + 'ຊີ': 2, + 'ຊີ້': 3, + 'ຊື່': 3, + 'ຊື້': 3, + 'ຊຸ': 2, + 'ຊູ': 2, + 'ຊົ': 2, + 'ຊົ່': 3, + 'ຊ່': 2, + 'ຊ້': 2, + 'ຍິ': 2, + 'ຍີ່': 3, + 'ຍຸ': 2, + 'ຍົ': 2, + 'ຍ່': 2, + 'ຍ້': 2, + 'ດັ': 2, + 'ດັ່': 3, + 'ດິ': 2, + 'ດີ': 2, + 'ດົ': 2, + 'ດ້': 2, + 'ຕັ': 2, + 'ຕັ້': 3, + 'ຕິ': 2, + 'ຕີ': 2, + 'ຕົ': 2, + 'ຕົ້': 3, + 'ຕ່': 2, + 'ຕ້': 2, + 'ຕໍ່': 3, + 'ຖິ': 2, + 'ຖື': 2, + 'ຖື່': 3, + 'ຖຸ': 2, + 'ຖົ້': 3, + 'ຖ້': 2, + 'ທັ': 2, + 'ທິ': 2, + 'ທີ': 2, + 'ທີ່': 3, + 'ທຸ': 2, + 'ທົ່': 3, + 'ທ່': 2, + 'ທ້': 2, + 'ທໍ': 2, + 'ນັ': 2, + 'ນັ້': 3, + 'ນິ': 2, + 'ນີ': 2, + 'ນີ້': 3, + 'ນື': 2, + 'ນື່': 3, + 'ນື້': 3, + 'ນຸ': 2, + 'ນຸ່': 3, + 'ນູ': 2, + 'ນົ': 2, + 'ນ້': 2, + 'ບັ': 2, + 'ບີ': 2, + 'ບຸ': 2, + 'ບູ': 2, + 'ບົ': 2, + 'ບ່': 2, + 'ບໍ': 2, + 'ບໍ່': 3, + 'ປັ': 2, + 'ປີ': 2, + 'ປົ': 2, + 'ປ່': 2, + 'ປ້': 2, + 'ຜັ': 2, + 'ຜິ': 2, + 'ຜີ': 2, + 'ຜູ້': 3, + 'ຜົ': 2, + 'ຜ່': 2, + 'ພັ': 2, + 'ພິ': 2, + 'ພີ': 2, + 'ພີ່': 3, + 'ພຶ': 2, + 'ພື່': 3, + 'ພູ': 2, + 'ພົ': 2, + 'ພົ້': 3, + 'ພ້': 2, + 'ພໍ': 2, + 'ພໍ່': 3, + 'ຟັ': 2, + 'ຟ້': 2, + 'ມັ': 2, + 'ມິ': 2, + 'ມີ': 2, + 'ມື': 2, + 'ມື່': 3, + 'ມຸ້': 3, + 'ມູ': 2, + 'ມົ': 2, + 'ມ່': 2, + 'ຢັ': 2, + 'ຢື': 2, + 'ຢູ່': 3, + 'ຢູ້': 3, + 'ຢ່': 2, + 'ຢ້': 2, + 'ລັ': 2, + 'ລິ': 2, + 'ລີ': 2, + 'ລື': 2, + 'ລຸ': 2, + 'ລຸ້': 3, + 'ລູ': 2, + 'ລົ': 2, + 'ລ້': 2, + 'ວັ': 2, + 'ວັ່': 3, + 'ວິ': 2, + 'ວຸ': 2, + 'ວົ': 2, + 'ວົ້': 3, + 'ວ່': 2, + 'ວ້': 2, + 'ສັ': 2, + 'ສິ': 2, + 'ສີ່': 3, + 'ສີ້': 3, + 'ສຶ': 2, + 'ສື': 2, + 'ສຸ': 2, + 'ສູ້': 3, + 'ສົ': 2, + 'ສ່': 2, + 'ສ້': 2, + 'ຫັ': 2, + 'ຫຼ': 2, + 'ຫຼັ': 3, + 'ຫຼິ': 3, + 'ຫຼື': 3, + 'ຫຼົ': 3, + 'ຫຼົ່': 4, + 'ຫ່': 2, + 'ຫ້': 2, + 'ອັ': 2, + 'ອິ': 2, + 'ອີ': 2, + 'ອື່': 3, + 'ອຸ': 2, + 'ອົ': 2, + 'ອ່': 2, + 'ອ້': 2, + 'ຮັ': 2, + 'ຮີ': 2, + 'ຮູ້': 3, + 'ຮົ': 2, + 'ຮົ່': 3, + 'ຮ່': 2, + 'ຮ້': 2, + 'ໜັ': 2, + 'ໜີ່': 3, + 'ໜື່': 3, + 'ໜູ': 2, + 'ໜ່': 2, + 'ໜ້': 2, + 'ໝັ້': 3, + 'ໝີ': 2, + 'ໝູ່': 3, + 'ໝ່': 2, + 'ໝ້': 2, + 'ཀུ': 2, + 'ཀོ': 2, + 'ཀྱ': 2, + 'ཀྱི': 3, + 'ཀླ': 2, + 'ཀློ': 3, + 'ཁུ': 2, + 'ཁེ': 2, + 'ཁོ': 2, + 'ཁྱ': 2, + 'ཁྱི': 3, + 'ཁྲི': 3, + 'ཁྲོ': 3, + 'གི': 2, + 'གུ': 2, + 'གེ': 2, + 'གོ': 2, + 'གྱ': 2, + 'གྱི': 3, + 'གྱུ': 3, + 'གྱོ': 3, + 'གྲ': 2, + 'གྲི': 3, + 'གྲུ': 3, + 'གྲེ': 3, + 'གྲོ': 3, + 'གླ': 2, + 'གླི': 3, + 'གླེ': 3, + 'ངུ': 2, + 'ངེ': 2, + 'ངོ': 2, + 'ཅི': 2, + 'ཅུ': 2, + 'ཅོ': 2, + 'ཆུ': 2, + 'ཆེ': 2, + 'ཆོ': 2, + 'ཇི': 2, + 'ཇུ': 2, + 'ཇོ': 2, + 'ཉི': 2, + 'ཉེ': 2, + 'ཉོ': 2, + 'ཏུ': 2, + 'ཏེ': 2, + 'ཏོ': 2, + 'ཐི': 2, + 'ཐུ': 2, + 'ཐེ': 2, + 'ཐོ': 2, + 'དི': 2, + 'དུ': 2, + 'དེ': 2, + 'དོ': 2, + 'དྲ': 2, + 'དྲི': 3, + 'དྲུ': 3, + 'དྲོ': 3, + 'ནི': 2, + 'ནུ': 2, + 'ནོ': 2, + 'པེ': 2, + 'པོ': 2, + 'པྱ': 2, + 'པྱོ': 3, + 'ཕེ': 2, + 'ཕོ': 2, + 'ཕྱི': 3, + 'ཕྱེ': 3, + 'ཕྱོ': 3, + 'ཕྲུ': 3, + 'ཕྲོ': 3, + 'བུ': 2, + 'བེ': 2, + 'བོ': 2, + 'བྱ': 2, + 'བྱི': 3, + 'བྱུ': 3, + 'བྱེ': 3, + 'བྱོ': 3, + 'བྲ': 2, + 'བྲེ': 3, + 'བླ': 2, + 'བློ': 3, + 'མི': 2, + 'མེ': 2, + 'མོ': 2, + 'མྱོ': 3, + 'ཙུ': 2, + 'ཙོ': 2, + 'ཚུ': 2, + 'ཚེ': 2, + 'ཚོ': 2, + 'ཛི': 2, + 'ཛུ': 2, + 'ཛོ': 2, + 'ཞི': 2, + 'ཞུ': 2, + 'ཟི': 2, + 'ཟུ': 2, + 'ཟེ': 2, + 'ཟོ': 2, + 'ཟླ': 2, + 'ཟློ': 3, + 'འི': 2, + 'འུ': 2, + 'འོ': 2, + 'ཡི': 2, + 'ཡུ': 2, + 'ཡོ': 2, + 'རི': 2, + 'རུ': 2, + 'རེ': 2, + 'རོ': 2, + 'རྐྱ': 3, + 'རྐྱེ': 4, + 'རྒ': 2, + 'རྒོ': 3, + 'རྒྱ': 3, + 'རྒྱུ': 4, + 'རྗེ': 3, + 'རྗོ': 3, + 'རྟ': 2, + 'རྟེ': 3, + 'རྟོ': 3, + 'རྡ': 2, + 'རྣ': 2, + 'རྩ': 2, + 'རྩི': 3, + 'རྩུ': 3, + 'རྩོ': 3, + 'རྫ': 2, + 'ལཱ': 2, + 'ལུ': 2, + 'ལེ': 2, + 'ལོ': 2, + 'ལྔ': 2, + 'ལྕི': 3, + 'ལྕོ': 3, + 'ལྟ': 2, + 'ལྟེ': 3, + 'ལྡ': 2, + 'ལྡེ': 3, + 'ལྷ': 2, + 'ལྷུ': 3, + 'ལྷོ': 3, + 'ཤི': 2, + 'ཤུ': 2, + 'ཤེ': 2, + 'ཤོ': 2, + 'སུ': 2, + 'སེ': 2, + 'སོ': 2, + 'སྐ': 2, + 'སྐི': 3, + 'སྐུ': 3, + 'སྐོ': 3, + 'སྐྱ': 3, + 'སྐྱི': 4, + 'སྐྱུ': 4, + 'སྐྱེ': 4, + 'སྐྱོ': 4, + 'སྒེ': 3, + 'སྒོ': 3, + 'སྒྱུ': 4, + 'སྒྲ': 3, + 'སྒྲི': 4, + 'སྒྲུ': 4, + 'སྔ': 2, + 'སྔོ': 3, + 'སྙི': 3, + 'སྟ': 2, + 'སྟུ': 3, + 'སྟེ': 3, + 'སྟོ': 3, + 'སྡ': 2, + 'སྡི': 3, + 'སྡུ': 3, + 'སྡེ': 3, + 'སྡོ': 3, + 'སྣ': 2, + 'སྣོ': 3, + 'སྤུ': 3, + 'སྤེ': 3, + 'སྤྱ': 3, + 'སྤྱི': 4, + 'སྤྱོ': 4, + 'སྤྲ': 3, + 'སྤྲོ': 4, + 'སྦེ': 3, + 'སྦྱ': 3, + 'སྦྱི': 4, + 'སྦྱོ': 4, + 'སྦྲེ': 4, + 'སྨ': 2, + 'སྨྲ': 3, + 'སྲ': 2, + 'སྲི': 3, + 'སྲུ': 3, + 'སྲོ': 3, + 'སླ': 2, + 'སློ': 3, + 'ཧྲི': 3, + 'ཧྲེ': 3, + 'ཨི': 2, + 'ཨུ': 2, + 'ကိ': 2, + 'ကို': 3, + 'ကီု': 3, + 'ကု': 2, + 'ကူ': 2, + 'ကေု': 3, + 'ကဲ့': 3, + 'ကဵု': 3, + 'ကံ': 2, + 'က္က': 3, + 'က္ခ': 3, + 'က္ဍ': 3, + 'က္ဍို': 5, + 'က်': 2, + 'က်ျ': 3, + 'ကျို': 4, + 'ကျူ': 3, + 'ကျေ': 3, + 'ကျွ': 3, + 'ကြို': 4, + 'ကြီ': 3, + 'ကြု': 3, + 'ကြေ': 3, + 'ကြံ': 3, + 'ကြွေ': 4, + 'ကွ': 2, + 'ကၟ': 2, + 'ကၟိ': 3, + 'ကၟို': 4, + 'ကၟဲ': 3, + 'ကၠ': 2, + 'ကၠို': 4, + 'ကၠီု': 4, + 'ကၠု': 3, + 'ကၠေ': 3, + 'ကၠေံ': 4, + 'ကၠဳ': 3, + 'ခိ': 2, + 'ခို': 3, + 'ခု': 2, + 'ခဲ့': 3, + 'ခဳ': 2, + 'ခံ': 2, + 'ချိ': 3, + 'ချို': 4, + 'ချို့': 5, + 'ချီ': 3, + 'ချု': 3, + 'ချေ': 3, + 'ချဳ': 3, + 'ခြုံ': 4, + 'ခြေ': 3, + 'ခွ': 2, + 'ခွဲ': 3, + 'ခၞံ': 3, + 'ခၠ': 2, + 'ဂိ': 2, + 'ဂို': 3, + 'ဂီု': 3, + 'ဂု': 2, + 'ဂဵု': 3, + 'ဂ္ဂ': 3, + 'ဂ္ဂို': 5, + 'ဂျို': 4, + 'ဂွံ': 3, + 'ဂှ်': 3, + 'ဂၞ': 2, + 'ဂၞဴ': 3, + 'ဂၟံ': 3, + 'ဂၠ': 2, + 'ဂၠိ': 3, + 'ဂၠို': 4, + 'ဂၠေ': 3, + 'ဂၠံ': 3, + 'ငိ': 2, + 'ငို': 3, + 'ငဲ့': 3, + 'ငံ': 2, + 'င့်': 3, + 'င်': 2, + 'င်္ဂ': 4, + 'ငြိ': 3, + 'ငွေ': 3, + 'ငှ': 2, + 'စိ': 2, + 'စို': 3, + 'စီ': 2, + 'စု': 2, + 'စုံ': 3, + 'စဳ': 2, + 'စဴ': 2, + 'စဵု': 3, + 'စံ': 2, + 'စ္စ': 3, + 'စ်': 2, + 'စွ': 2, + 'စွဲ': 3, + 'စွံ': 3, + 'စှ်': 3, + 'စှ်ေ': 4, + 'စၞ': 2, + 'စၞေ': 3, + 'စၟ': 2, + 'စၠေ': 3, + 'ဆို': 3, + 'ဆီ': 2, + 'ဆုဲ': 3, + 'ဆုံ': 3, + 'ဆံ': 2, + 'ဆွဲ': 3, + 'ဇို': 3, + 'ဇူ': 2, + 'ဇြေ': 3, + 'ဇြဳ': 3, + 'ဇၞ': 2, + 'ဇၞေ': 3, + 'ဇၟ': 2, + 'ဉ်': 2, + 'ညိ': 2, + 'ညီ': 2, + 'ညဳ': 2, + 'ညံ': 2, + 'ည်': 2, + 'ည့်': 3, + 'ညှ': 2, + 'ဋိ': 2, + 'ဋ္ဌ': 3, + 'ဍိ': 2, + 'ဍို': 3, + 'ဍု': 2, + 'ဍဵု': 3, + 'ဏီ': 2, + 'ဏံ': 2, + 'ဏ်': 2, + 'ဏှ': 2, + 'တိ': 2, + 'တို': 3, + 'တို့': 4, + 'တိူ': 3, + 'တီ': 2, + 'တု': 2, + 'တုဲ': 3, + 'တူ': 2, + 'တေံ': 3, + 'တဲ': 2, + 'တဴ': 2, + 'တဵ': 2, + 'တံ': 2, + 'တံ့': 3, + 'တ္တ': 3, + 'တ္ၚဲ': 4, + 'တ်': 2, + 'တ်ို': 4, + 'တြုံ': 4, + 'တွ': 2, + 'တွေ': 3, + 'တွဵု': 4, + 'တှ်ေ': 4, + 'တၞ': 2, + 'တၟ': 2, + 'တၟိ': 3, + 'တၟို': 4, + 'တၟေ': 3, + 'တၟံ': 3, + 'တၠု': 3, + 'တႂ်': 3, + 'တႅ': 2, + 'ထိ': 2, + 'ထို': 3, + 'ထို့': 4, + 'ထီ': 2, + 'ထု': 2, + 'ထုဲ': 3, + 'ထူ': 2, + 'ထဵ': 2, + 'ထံ': 2, + 'ထ္ၜ': 3, + 'ထွ': 2, + 'ထွေ': 3, + 'ဒို': 3, + 'ဒီ': 2, + 'ဒီု': 3, + 'ဒု': 2, + 'ဒေံ': 3, + 'ဒဳ': 2, + 'ဒဵု': 3, + 'ဒ္ဂေ': 4, + 'ဒ်': 2, + 'ဒှ်': 3, + 'ဒၞ': 2, + 'ဒၟံ': 3, + 'ဓိ': 2, + 'ဓု': 2, + 'နိ': 2, + 'နို': 3, + 'နု': 2, + 'နူ': 2, + 'နေ့': 3, + 'န္ဒ': 3, + 'န္နိ': 4, + 'န်': 2, + 'န့်': 3, + 'နွ': 2, + 'နွံ': 3, + 'နှ': 2, + 'နှိ': 3, + 'နှီ': 3, + 'နှေ': 3, + 'ပိ': 2, + 'ပို': 3, + 'ပိုဲ': 4, + 'ပိူ': 3, + 'ပီ': 2, + 'ပု': 2, + 'ပုံ': 3, + 'ပူ': 2, + 'ပေဲ': 3, + 'ပဲ': 2, + 'ပဵ': 2, + 'ပံ': 2, + 'ပံ့': 3, + 'ပ္ဍဲ': 4, + 'ပ္တံ': 4, + 'ပ္ပ': 3, + 'ပ္ပံ': 4, + 'ပ်': 2, + 'ပျေ': 3, + 'ပျဲ': 3, + 'ပြီ': 3, + 'ပြု': 3, + 'ပြေ': 3, + 'ပြဳ': 3, + 'ပြံ': 3, + 'ပွ': 2, + 'ပွဲ': 3, + 'ပွႆ': 3, + 'ပၟိ': 3, + 'ပၠ': 2, + 'ပႂ်': 3, + 'ပႅ': 2, + 'ပႆ': 2, + 'ဖိ': 2, + 'ဖီ': 2, + 'ဖဵု': 3, + 'ဖံ': 2, + 'ဖျု': 3, + 'ဖျေံ': 4, + 'ဖြို': 4, + 'ဖွ': 2, + 'ဖွဲ့': 4, + 'ဖွံ့': 4, + 'ဗီု': 3, + 'ဗု': 2, + 'ဗ္တေ': 4, + 'ဗ္ၜေ': 4, + 'ဗျဵု': 4, + 'ဗြေ': 3, + 'ဗြဴ': 3, + 'ဗွို': 4, + 'ဗွဲ': 3, + 'ဗၠ': 2, + 'ဗၠေ': 3, + 'ဘူ': 2, + 'ဘဲ': 2, + 'ဘဴ': 2, + 'မိ': 2, + 'မို': 3, + 'မိူ': 3, + 'မီ': 2, + 'မု': 2, + 'မူ': 2, + 'မဲ': 2, + 'မဲ့': 3, + 'မဳ': 2, + 'မဵု': 3, + 'မံ': 2, + 'မ္ဂ': 3, + 'မ္တီ': 4, + 'မ္ဘ': 3, + 'မ္မ': 3, + 'မ္ၚဵု': 5, + 'မ်': 2, + 'မ့်': 3, + 'မျို': 4, + 'မျီု': 4, + 'မျှ': 3, + 'မြေ': 3, + 'မြှ': 3, + 'မွ': 2, + 'မွေ': 3, + 'မွေ့': 4, + 'မွဲ': 3, + 'မှ': 2, + 'မှီ': 3, + 'မှု': 3, + 'မှေ': 3, + 'မၞိ': 3, + 'မၞု': 3, + 'မၞုံ': 4, + 'မၠို': 4, + 'မၠေ': 3, + 'မႂ်': 3, + 'မႅ': 2, + 'မႆ': 2, + 'ယိ': 2, + 'ယို': 3, + 'ယိူ': 3, + 'ယု': 2, + 'ယုံ': 3, + 'ယူ': 2, + 'ယဲ': 2, + 'ယဵ': 2, + 'ယံ': 2, + 'ယ်': 2, + 'ယျဵု': 4, + 'ယြဴ': 3, + 'ယွ': 2, + 'ယှ': 2, + 'ယႂ်': 3, + 'ယႅ': 2, + 'ရို': 3, + 'ရီု': 3, + 'ရု': 2, + 'ရုဲ': 3, + 'ရုံ': 3, + 'ရူ': 2, + 'ရေံ': 3, + 'ရဲ': 2, + 'ရဴ': 2, + 'ရံ': 2, + 'ရ်': 2, + 'ရွ': 2, + 'ရွေ': 3, + 'ရွံ့': 4, + 'ရွှေ့': 5, + 'ရှ': 2, + 'ရှိ': 3, + 'ရှေ': 3, + 'ရှေ့': 4, + 'ရှ်ေ': 4, + 'လိ': 2, + 'လို': 3, + 'လို့': 4, + 'လိူ': 3, + 'လီ': 2, + 'လီု': 3, + 'လု': 2, + 'လုံ': 3, + 'လူ': 2, + 'လူ့': 3, + 'လဲ': 2, + 'လဵ': 2, + 'လဵု': 3, + 'လံ': 2, + 'လ္ပ': 3, + 'လ္ၚ': 3, + 'လ်': 2, + 'လျို': 4, + 'လျေ': 3, + 'လျှ': 3, + 'လျှို့': 6, + 'လျှေ': 4, + 'လွ': 2, + 'လွဳ': 3, + 'လွှ': 3, + 'လွှဲ': 4, + 'လှ': 2, + 'လှုံ': 4, + 'လၟေ': 3, + 'လႂ်': 3, + 'လႅ': 2, + 'လႆ': 2, + 'ဝူ': 2, + 'ဝဲ': 2, + 'ဝဳ': 2, + 'ဝဵု': 3, + 'ဝ်': 2, + 'ဝွံ': 3, + 'ဝှ': 2, + 'ဝႆ': 2, + 'သိ': 2, + 'သို': 3, + 'သို့': 4, + 'သိူ': 3, + 'သီ': 2, + 'သီု': 3, + 'သု': 2, + 'သုံ': 3, + 'သူ': 2, + 'သူ့': 3, + 'သဳ': 2, + 'သဵ': 2, + 'သဵု': 3, + 'သ္က': 3, + 'သ္ကံ': 4, + 'သ္ဂု': 4, + 'သ္ဂေ': 4, + 'သ္ဇို': 5, + 'သ္ဒ': 3, + 'သ္ပ': 3, + 'သ္ၚိ': 4, + 'သ်': 2, + 'သြို': 4, + 'သွ': 2, + 'သွံ': 3, + 'သှ်': 3, + 'သှ်ေ': 4, + 'သၞ': 2, + 'သၞေ': 3, + 'သၟ': 2, + 'သၠ': 2, + 'သၠု': 3, + 'သႂ်': 3, + 'သႅ': 2, + 'ဟို': 3, + 'ဟီု': 3, + 'ဟု': 2, + 'ဟူ': 2, + 'ဟ်': 2, + 'ဟွံ': 3, + 'အိ': 2, + 'အို': 3, + 'အု': 2, + 'အံ': 2, + 'အ်': 2, + 'ဢိ': 2, + 'ဢို': 3, + 'ဢွ': 2, + 'ဿီု': 3, + 'ၚု': 2, + 'ၚ်': 2, + 'ၜို': 3, + 'ၵိ': 2, + 'ၵို': 3, + 'ၵိူ': 3, + 'ၵု': 2, + 'ၵူ': 2, + 'ၵဵ': 2, + 'ၵ်': 2, + 'ၵွ': 2, + 'ၵႂ': 2, + 'ၵႅ': 2, + 'ၶိ': 2, + 'ၶို': 3, + 'ၶိူ': 3, + 'ၶီ': 2, + 'ၶု': 2, + 'ၶူ': 2, + 'ၶွ': 2, + 'ၶႂ': 2, + 'ၶႅ': 2, + 'ၶႆ': 2, + 'ၸိ': 2, + 'ၸို': 3, + 'ၸိူ': 3, + 'ၸု': 2, + 'ၸူ': 2, + 'ၸဵ': 2, + 'ၸွ': 2, + 'ၸွႆ': 3, + 'ၸႂ်': 3, + 'ၸႅ': 2, + 'ၺ်': 2, + 'ၺွ': 2, + 'ၼို': 3, + 'ၼိူ': 3, + 'ၼု': 2, + 'ၼဵ': 2, + 'ၼ်': 2, + 'ၼွ': 2, + 'ၼႂ်': 3, + 'ၼႆ': 2, + 'ၽိ': 2, + 'ၽို': 3, + 'ၽု': 2, + 'ၽူ': 2, + 'ၽဵ': 2, + 'ၽွ': 2, + 'ၽႂ်': 3, + 'ၾိ': 2, + 'ႁို': 3, + 'ႁိူ': 3, + 'ႁု': 2, + 'ႁူ': 2, + 'ႁဵ': 2, + 'ႁွ': 2, + 'ႁႂ်': 3, + 'ႁႅ': 2, + 'ᜄ᜔': 2, + 'ᜆᜒ': 2, + 'ᜆ᜔': 2, + 'ᜇᜒ': 2, + 'ᜇᜓ': 2, + 'ᜇ᜔': 2, + 'ᜈᜒ': 2, + 'ᜈ᜔': 2, + 'ᜉᜒ': 2, + 'ᜊᜓ': 2, + 'ᜋ᜔': 2, + 'ᜌ᜔': 2, + 'ᜎᜓ': 2, + 'ᜏᜒ': 2, + 'ᜐᜒ': 2, + 'ᜑᜒ': 2, + 'កិ': 2, + 'កុ': 2, + 'កុំ': 3, + 'កំ': 2, + 'ក់': 2, + 'ក៏': 2, + 'ក្ខ': 3, + 'ក្ដិ': 4, + 'ក្ដី': 4, + 'ក្ដៅ': 4, + 'ក្នុ': 4, + 'ក្រ': 3, + 'ក្រុ': 4, + 'ក្រោ': 4, + 'ក្ស': 3, + 'ក្សា': 4, + 'ខិ': 2, + 'ខុ': 2, + 'ខំ': 2, + 'ខ្ជា': 4, + 'ខ្ព': 3, + 'ខ្លា': 4, + 'ខ្លួ': 4, + 'គាំ': 3, + 'គិ': 2, + 'គឺ': 2, + 'គំ': 2, + 'គ៌': 2, + 'គ្គ': 3, + 'គ្នា': 4, + 'គ្មា': 4, + 'គ្រ': 3, + 'គ្រា': 4, + 'គ្រឹះ': 5, + 'គ្រួ': 4, + 'ឃុំ': 3, + 'ឃ្ន': 3, + 'ងឺ': 2, + 'ង់': 2, + 'ង្ក': 3, + 'ង្កើ': 4, + 'ង្ខិ': 4, + 'ង្ខំ': 4, + 'ង្គ': 3, + 'ង្រី': 4, + 'ង្រឹ': 4, + 'ង្រៀ': 4, + 'ង្ហា': 4, + 'ង្អ': 3, + 'ចាំ': 3, + 'ចិ': 2, + 'ចុ': 2, + 'ចូ': 2, + 'ចំ': 2, + 'ច់': 2, + 'ច្ច': 3, + 'ច្ចេ': 4, + 'ច្បា': 4, + 'ឆាំ': 3, + 'ឆ្នាំ': 5, + 'ឆ្នោ': 4, + 'ឆ្ល': 3, + 'ឆ្លើ': 4, + 'ជិ': 2, + 'ជី': 2, + 'ជុំ': 3, + 'ជំ': 2, + 'ជ្ជ': 3, + 'ជ្ជា': 4, + 'ជ្ញា': 4, + 'ជ្យ': 3, + 'ជ្រ': 3, + 'ជ្រើ': 4, + 'ជ្រៀ': 4, + 'ជ្រែ': 4, + 'ឈ្មោះ': 5, + 'ញុះ': 3, + 'ញ្ចូ': 4, + 'ញ្ជា': 4, + 'ញ្ញ': 3, + 'ញ្ញា': 4, + 'ញ្ញៈ': 4, + 'ដី': 2, + 'ដឹ': 2, + 'ដូ': 2, + 'ដំ': 2, + 'ដ៏': 2, + 'ដ្ឋ': 3, + 'ដ្ឋា': 4, + 'ឌ្ឍ': 3, + 'ណិ': 2, + 'ណី': 2, + 'ណោះ': 3, + 'ណ៌': 2, + 'ណ៍': 2, + 'ណ្ដា': 4, + 'ណ្ដុះ': 5, + 'ណ្ឌ': 3, + 'ណ្ណោះ': 5, + 'តិ': 2, + 'តី': 2, + 'តុ': 2, + 'តំ': 2, + 'ត់': 2, + 'ត់់': 3, + 'ត៌': 2, + 'ត្ដ': 3, + 'ត្ដិ': 4, + 'ត្ថ': 3, + 'ត្ថិ': 4, + 'ត្យ': 3, + 'ត្រ': 3, + 'ត្រា': 4, + 'ត្រឹ': 4, + 'ត្រូ': 4, + 'ត្ស': 3, + 'ថ្ងៃ': 4, + 'ថ្នា': 4, + 'ថ្នូ': 4, + 'ថ្មី': 4, + 'ថ្លៃ': 4, + 'ទាំ': 3, + 'ទិ': 2, + 'ទិ៍': 3, + 'ទី': 2, + 'ទឹ': 2, + 'ទុ': 2, + 'ទូ': 2, + 'ទួ': 2, + 'ទោះ': 3, + 'ទំ': 2, + 'ទ្ធ': 3, + 'ទ្ធិ': 4, + 'ទ្យា': 4, + 'ទ្រ': 3, + 'ធិ': 2, + 'ធី': 2, + 'ធ្ង': 3, + 'ធ្នា': 4, + 'ធ្នូ': 4, + 'ធ្យា': 4, + 'ធ្យោ': 4, + 'ធ្វើ': 4, + 'នាំ': 3, + 'និ': 2, + 'នី': 2, + 'នឹ': 2, + 'នុ': 2, + 'នូ': 2, + 'នួ': 2, + 'នេះ': 3, + 'នោះ': 3, + 'ន់': 2, + 'ន៍': 2, + 'ន្ដ': 3, + 'ន្ដិ': 4, + 'ន្ថែ': 4, + 'ន្ថោ': 4, + 'ន្ទា': 4, + 'ន្ទៈ': 4, + 'ន្ធ': 3, + 'ន្និ': 4, + 'ន្ម': 3, + 'ន្យា': 4, + 'ន្លែ': 4, + 'បិ': 2, + 'បី': 2, + 'បុ': 2, + 'បូ': 2, + 'បោះ': 3, + 'បំ': 2, + 'ប៉ុ': 3, + 'ប៉ះ': 3, + 'ប់': 2, + 'ប្ដី': 4, + 'ប្ដូ': 4, + 'ប្ដេ': 4, + 'ប្ប': 3, + 'ប្បី': 4, + 'ប្រ': 3, + 'ប្រា': 4, + 'ប្រឹ': 4, + 'ប្រុ': 4, + 'ប្រើ': 4, + 'ប្រែ': 4, + 'ប្អូ': 4, + 'ផុ': 2, + 'ផ្ដ': 3, + 'ផ្ដា': 4, + 'ផ្ទា': 4, + 'ផ្ទុ': 4, + 'ផ្ទេ': 4, + 'ផ្នែ': 4, + 'ផ្លា': 4, + 'ផ្លិ': 4, + 'ផ្ស': 3, + 'ផ្សា': 4, + 'ផ្សេ': 4, + 'ផ្សៃ': 4, + 'ពិ': 2, + 'ពី': 2, + 'ពុ': 2, + 'ពូ': 2, + 'ពោះ': 3, + 'ព័': 2, + 'ព្យ': 3, + 'ព្យា': 4, + 'ព្រ': 3, + 'ព្រឹ': 4, + 'ព្រៀ': 4, + 'ព្រៃ': 4, + 'ព្រំ': 4, + 'ព្វ': 3, + 'ភិ': 2, + 'ភ័': 2, + 'មិ': 2, + 'មុ': 2, + 'មូ': 2, + 'មួ': 2, + 'ម៉ា': 3, + 'ម៉ោ': 3, + 'ម៌': 2, + 'ម័': 2, + 'ម្ងា': 4, + 'ម្ចា': 4, + 'ម្ដា': 4, + 'ម្ដែ': 4, + 'ម្នា': 4, + 'ម្នេ': 4, + 'ម្ប': 3, + 'ម្បី': 4, + 'ម្បុ': 4, + 'ម្ភា': 4, + 'ម្ម': 3, + 'ម្រ': 3, + 'ម្រា': 4, + 'ម្រិ': 4, + 'ម្រូ': 4, + 'ម្រើ': 4, + 'ម្រេ': 4, + 'ម្លៀ': 4, + 'ម្លៃ': 4, + 'យុ': 2, + 'យ៉ា': 3, + 'យ្យ': 3, + 'រាំ': 3, + 'រិ': 2, + 'រី': 2, + 'រុ': 2, + 'រូ': 2, + 'រួ': 2, + 'រំ': 2, + 'រ្ដិ៍': 5, + 'លិ': 2, + 'លុះ': 3, + 'លូ': 2, + 'លំ': 2, + 'ល់': 2, + 'ល្បៈ': 4, + 'ល្មើ': 4, + 'វិ': 2, + 'សិ': 2, + 'សី': 2, + 'សុ': 2, + 'សុំ': 3, + 'សំ': 2, + 'ស់': 2, + 'ស័': 2, + 'ស្គា': 4, + 'ស្ដី': 4, + 'ស្ដ្រី': 6, + 'ស្ត្រ': 5, + 'ស្ថា': 4, + 'ស្ថិ': 4, + 'ស្ទួ': 4, + 'ស្នា': 4, + 'ស្មា': 4, + 'ស្មើ': 4, + 'ស្រ': 3, + 'ស្រា': 4, + 'ស្រី': 4, + 'ស្រ័': 4, + 'ស្លា': 4, + 'ស្វែ': 4, + 'ស្វ័': 4, + 'ស្ស': 3, + 'ហូ': 2, + 'ហ៍': 2, + 'ហ្ម': 3, + 'ឡុ': 2, + 'អំ': 2, + 'អ្ន': 3, + 'អ្វី': 4, + 'ឱ្យ': 3, + 'ᨠ᩠ᨠ': 3, + 'ᨠ᩠ᨦᩢᩢ': 5, + 'ᨠ᩠ᨦᩨ᩵': 5, + 'ᨠ᩠ᨭᩫ': 4, + 'ᨠ᩠ᨯᩢ': 4, + 'ᨠ᩠ᨶᩢ': 4, + 'ᨠ᩠ᨶᩥ': 4, + 'ᨠ᩠ᩅ': 3, + 'ᨠ᩠ᩅᩢ': 4, + 'ᨠ᩠ᩅᩫ': 4, + 'ᨠ᩠ᩋ᩵': 4, + 'ᨠᩢ': 2, + 'ᨠᩢ᩠ᨷ': 4, + 'ᨠᩥ': 2, + 'ᨠᩩ': 2, + 'ᨠᩮ᩠ᨯᩨ': 5, + 'ᨠᩮᩢ᩵': 4, + 'ᨠᩮ᩵': 3, + 'ᨠᩯ᩠ᨯ': 4, + 'ᨠᩯ᩠ᨶ᩵': 5, + 'ᨠᩯ᩵': 3, + 'ᨠᩳ᩵': 3, + 'ᨠ᩵': 2, + 'ᨠ᩵ᩴ': 3, + 'ᨡ᩠ᨦᩢ': 4, + 'ᨡ᩠ᨯᩢ': 4, + 'ᨡ᩠ᨶ': 3, + 'ᨡ᩠ᨶᩢ': 4, + 'ᨡ᩠ᨶᩨ᩶': 5, + 'ᨡ᩠ᩅ': 3, + 'ᨡ᩠ᩋ': 3, + 'ᨡᩢ': 2, + 'ᨡᩮ᩠ᨲ': 4, + 'ᨡᩮᩢ': 3, + 'ᨡᩮᩢᩢ': 4, + 'ᨡᩯ᩠ᨠ': 4, + 'ᨡᩯ᩠ᨦ': 4, + 'ᨡᩱᩢ': 3, + 'ᨡᩳ᩶': 3, + 'ᨡ᩵': 2, + 'ᨣᩕ᩠ᩋ': 4, + 'ᨣᩕᩮ᩠ᨦᩨ᩵': 7, + 'ᨣ᩠ᨣ': 3, + 'ᨣ᩠ᨯᩧ': 4, + 'ᨣ᩠ᨶᩢ': 4, + 'ᨣ᩠ᨾᩫ': 4, + 'ᨣ᩠ᩅ': 3, + 'ᨣ᩠ᩋᩢ': 4, + 'ᨣᩢ': 2, + 'ᨣᩢ᩠ᨷ': 4, + 'ᨣᩢᩴ': 3, + 'ᨣᩩ': 2, + 'ᨣᩩᩢ': 3, + 'ᨣᩮᩢᩢ': 4, + 'ᨣᩯ᩠ᨶᩢ': 5, + 'ᨣᩯ᩠ᩅ': 4, + 'ᨣᩳ᩶': 3, + 'ᨣᩴ': 2, + 'ᨤ᩠ᨯᩥ': 4, + 'ᨤ᩠ᨶᩨ': 4, + 'ᨤ᩠ᨶᩫ': 4, + 'ᨤ᩠ᩅᩫ': 4, + 'ᨤ᩠ᩋ': 3, + 'ᨤᩢ᩠ᨬ': 4, + 'ᨤᩮᩢ': 3, + 'ᨤᩱ᩵': 3, + 'ᨥᩢ': 2, + 'ᨧ᩠ᨦᩥ᩵': 5, + 'ᨧ᩠ᨯᩢ': 4, + 'ᨧᩢ': 2, + 'ᨧᩮ᩠ᨷ': 4, + 'ᨧᩮᩢᩢ': 4, + 'ᨧᩱ᩠ᨿ': 4, + 'ᨧᩴ': 2, + 'ᨧ᩵ᩴ': 3, + 'ᨨ᩠ᨶᩢ': 4, + 'ᨩ᩠ᨶᩢᩢ': 5, + 'ᨩ᩠ᨶ᩼': 4, + 'ᨩᩢ': 2, + 'ᨩᩦ': 2, + 'ᨩᩨ᩵': 3, + 'ᨩᩩ': 2, + 'ᨩᩭ᩵': 3, + 'ᨩᩮ᩠ᩋᩨ': 5, + 'ᨩᩮ᩠ᩋᩨ᩵': 6, + 'ᨩᩮ᩠ᩋᩨ᩶': 6, + 'ᨩᩱᩢ': 3, + 'ᨩ᩵ᩭ': 3, + 'ᨪ᩠ᨦᩨ᩵': 5, + 'ᨪᩨ᩵': 3, + 'ᨪᩩ': 2, + 'ᨪᩮᩢ': 3, + 'ᨬ᩠ᨬ': 3, + 'ᨭᩛ': 2, + 'ᨭᩥ': 2, + 'ᨯ᩠ᨦᩢ᩵': 5, + 'ᨯ᩠ᨰ': 3, + 'ᨯ᩠ᨶᩥ': 4, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 6, + 'ᨯᩢ': 2, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 6, + 'ᨯᩦ': 2, + 'ᨯᩪ': 2, + 'ᨯᩪᩯ': 3, + 'ᨯᩯ᩠ᨦ': 4, + 'ᨯᩯ᩠ᨶ': 4, + 'ᨯᩰ᩠ᨿ': 4, + 'ᨯᩱᩢ': 3, + 'ᨯᩴ᩠ᨿ': 4, + 'ᨱ᩠ᨱ': 3, + 'ᨲᩕᩦ': 3, + 'ᨲᩕ᩼': 3, + 'ᨲ᩠ᨠᩫ': 4, + 'ᨲ᩠ᨦᩢᩢ': 5, + 'ᨲ᩠ᨯᩢ': 4, + 'ᨲ᩠ᨲᩥ': 4, + 'ᨲ᩠ᨳᩩ': 4, + 'ᨲ᩠ᨶᩫ': 4, + 'ᨲ᩠ᨶᩫᩢ': 5, + 'ᨲ᩠ᩅᩫ': 4, + 'ᨲ᩠ᩋᩢ': 4, + 'ᨲᩥ': 2, + 'ᨲᩮ᩠ᨠ': 4, + 'ᨲᩮ᩠ᨦ': 4, + 'ᨲᩮ᩠ᨾ': 4, + 'ᨲᩮ᩠ᨾᩨ᩵': 6, + 'ᨲᩯ᩠ᨠ': 4, + 'ᨲᩯ᩠ᨦ᩵': 5, + 'ᨲᩯ᩠ᨾᩢ': 5, + 'ᨲᩯ᩵': 3, + 'ᨲᩱ᩠ᨿ': 4, + 'ᨲᩱᩢ': 3, + 'ᨲᩳ᩵': 3, + 'ᨲ᩵': 2, + 'ᨲ᩵ᩴ': 3, + 'ᨳ᩠ᨦᩨ': 4, + 'ᨳ᩠ᩅᩢ': 4, + 'ᨳᩨ': 2, + 'ᨳᩪ': 2, + 'ᨳᩫ᩠ᨷ': 4, + 'ᨳᩮ᩠ᨶᩨ᩵': 6, + 'ᨳᩮᩢᩢ': 4, + 'ᨳᩯ᩠ᨦᩢ': 5, + 'ᨳᩯ᩠ᨾ': 4, + 'ᨴ᩠ᨦᩢ': 4, + 'ᨴ᩠ᨦᩨ': 4, + 'ᨴ᩠ᨵᩥ': 4, + 'ᨴ᩠ᨿ': 3, + 'ᨴ᩠ᨿ᩵': 4, + 'ᨴ᩠ᩅᩢ': 4, + 'ᨴ᩠ᩅᩫ᩵': 5, + 'ᨴᩦ᩵': 3, + 'ᨴᩩ': 2, + 'ᨴᩮ᩠ᩈ': 4, + 'ᨴᩮ᩠ᩈᩱ': 5, + 'ᨴᩮᩢᩢ': 4, + 'ᨴᩮᩢ᩵': 4, + 'ᨴᩯ᩠ᨶ': 4, + 'ᨴᩯᩢ': 3, + 'ᨴᩰ᩠ᩈ': 4, + 'ᨵᩥ': 2, + 'ᨵᩦ': 2, + 'ᨶ᩠ᨲᩥ': 4, + 'ᨶ᩠ᨶᩢᩢ': 5, + 'ᨶ᩠ᨶᩥ': 4, + 'ᨶ᩠ᩋ': 3, + 'ᨶ᩠ᩋᩢ': 4, + 'ᨶᩢ᩠ᨷ': 4, + 'ᨶᩦ᩶': 3, + 'ᨶᩩ': 2, + 'ᨶᩩ᩵': 3, + 'ᨶᩯ᩠ᨶ': 4, + 'ᨷ᩠ᨦᩢ': 4, + 'ᨷ᩠ᨯᩢ': 4, + 'ᨷ᩠ᨲᩢ': 4, + 'ᨷ᩠ᨲᩥ': 4, + 'ᨷ᩠ᨴᩫ': 4, + 'ᨷ᩠ᨿ': 3, + 'ᨷ᩠ᩅᩫ': 4, + 'ᨷ᩠ᩋ': 3, + 'ᨷᩢ': 2, + 'ᨷᩥ': 2, + 'ᨷᩩ': 2, + 'ᨷᩪ': 2, + 'ᨷᩮ᩠ᨦᩨ᩶': 6, + 'ᨸ᩠ᨠᩫ': 4, + 'ᨸ᩠ᨯᩨ': 4, + 'ᨸ᩠ᨶᩢ': 4, + 'ᨸ᩠ᩋ': 3, + 'ᨸᩮ᩠ᨦᩨ': 5, + 'ᨸᩮ᩠ᨶ': 4, + 'ᨸᩮᩢ᩵': 4, + 'ᨸ᩵': 2, + 'ᨸ᩠᩵ᨿ': 4, + 'ᨹ᩠ᨯᩥ': 4, + 'ᨹ᩠ᨿ᩵': 4, + 'ᨹ᩠ᩅᩥ': 4, + 'ᨹᩪᩢ': 3, + 'ᨹᩪᩢᩱ': 4, + 'ᨹᩫ᩠ᩃ': 4, + 'ᨹᩮᩨ᩠ᨿ': 5, + 'ᨹ᩵': 2, + 'ᨻᩕ᩠ᩋᩢ': 5, + 'ᨻ᩠ᨦ': 3, + 'ᨻ᩠ᨶᩨ᩶': 5, + 'ᨻ᩠ᨶᩫ᩶': 5, + 'ᨻ᩠ᨿ': 3, + 'ᨻ᩠ᩋ': 3, + 'ᨻᩥ': 2, + 'ᨻᩦ᩵': 3, + 'ᨻᩮ᩠ᩋᩨ᩵': 6, + 'ᨻᩳ': 2, + 'ᨽᩱ᩠ᨿ': 4, + 'ᨾ᩠ᨲᩥ': 4, + 'ᨾ᩠ᨾ': 3, + 'ᨾ᩠ᨾ᩼': 4, + 'ᨾ᩠ᩅ': 3, + 'ᨾ᩠ᩅ᩵': 4, + 'ᨾᩢ': 2, + 'ᨾᩦ': 2, + 'ᨾᩨ': 2, + 'ᨾᩩ': 2, + 'ᨾᩪ': 2, + 'ᨾᩮ᩠ᨠᩨ': 5, + 'ᨾᩮ᩠ᨦᩨ': 5, + 'ᨾᩮ᩠ᩋᩨ᩵': 6, + 'ᨾᩯ᩵': 3, + 'ᨿ᩠ᨦᩢ': 4, + 'ᨿ᩠ᨦᩢᩢ': 5, + 'ᨿ᩠ᨦᩥ': 4, + 'ᨿ᩠ᨦᩥ᩵': 5, + 'ᨿ᩠ᩋ': 3, + 'ᨿᩢ᩠ᨷ': 4, + 'ᨿᩩ': 2, + 'ᨿᩫ᩠ᩈ': 4, + 'ᨿᩮ᩠ᨶ': 4, + 'ᨿᩮ᩠ᨾᩨ': 5, + 'ᩀᩪ᩵': 3, + 'ᩀ᩵': 2, + 'ᩁ᩠ᨠᩢ': 4, + 'ᩁ᩠ᨮᩢ': 4, + 'ᩁ᩠ᨾᩫ': 4, + 'ᩁ᩠ᨿ': 3, + 'ᩁ᩠ᩅ': 3, + 'ᩁ᩠ᩅ᩵': 4, + 'ᩁ᩠ᩋ': 3, + 'ᩁᩢ': 2, + 'ᩁᩢ᩠ᨷ': 4, + 'ᩁᩢᩭ': 3, + 'ᩁᩥ': 2, + 'ᩁᩦ': 2, + 'ᩁᩪᩢ': 3, + 'ᩁᩫ᩠ᨷ': 4, + 'ᩁᩮ᩠ᨦᩨ᩵': 6, + 'ᩁᩮ᩠ᨧ': 4, + 'ᩁᩮ᩠ᨶᩨ': 5, + 'ᩁᩮᩨ᩠ᨬ': 5, + 'ᩁᩯ᩠ᨦ': 4, + 'ᩃ᩠ᨦᩫ': 4, + 'ᩃ᩠ᩅ᩵': 4, + 'ᩃᩢ᩠ᨿ': 4, + 'ᩃᩢᩴ': 3, + 'ᩃᩥ': 2, + 'ᩃᩨ᩠ᨷ': 4, + 'ᩃᩩ': 2, + 'ᩃᩪ': 2, + 'ᩃᩮ᩠ᨠᩨ': 5, + 'ᩃᩮ᩠ᨦᩨ': 5, + 'ᩃᩰ᩠ᨠ': 4, + 'ᩅ᩠ᨲᩥ': 4, + 'ᩅ᩠ᨶᩢ': 4, + 'ᩅ᩠ᨿ': 3, + 'ᩅ᩠ᩅ᩵': 4, + 'ᩅᩢ': 2, + 'ᩅᩥ': 2, + 'ᩅᩮ᩠ᨶ': 4, + 'ᩅᩮ᩠ᨶᩢ': 5, + 'ᩅᩱᩢ': 3, + 'ᩈ᩠ᨠᩢ': 4, + 'ᩈ᩠ᨠᩧ': 4, + 'ᩈ᩠ᨦᩢ': 4, + 'ᩈ᩠ᨦᩥ᩵': 5, + 'ᩈ᩠ᨦᩫ': 4, + 'ᩈ᩠ᨶᩫ': 4, + 'ᩈ᩠ᨾᩫ': 4, + 'ᩈ᩠ᨿ': 3, + 'ᩈ᩠ᩅ᩵': 4, + 'ᩈ᩠ᩋ': 3, + 'ᩈᩢ': 2, + 'ᩈᩢ᩠ᨿ': 4, + 'ᩈᩥ': 2, + 'ᩈᩦ': 2, + 'ᩈᩨ᩵': 3, + 'ᩈᩩ': 2, + 'ᩈᩪ': 2, + 'ᩈᩪᩢ': 3, + 'ᩈᩫ᩠ᨾ': 4, + 'ᩈᩮ᩠ᩈ': 4, + 'ᩈᩯ᩠ᩅ': 4, + 'ᩈᩱ᩠ᨿ': 4, + 'ᩈᩳ᩵': 3, + 'ᩈ᩵ᩴ': 3, + 'ᩉᩕᩨ': 3, + 'ᩉᩖ': 2, + 'ᩉᩖᩢ': 3, + 'ᩉ᩠ᨶᩢ': 4, + 'ᩉ᩠ᨶᩦ': 4, + 'ᩉ᩠ᨶᩧ': 4, + 'ᩉ᩠ᨶᩧ᩵': 5, + 'ᩉ᩠ᨶᩫ': 4, + 'ᩉ᩠ᨾ': 3, + 'ᩉ᩠ᨾᩢ': 4, + 'ᩉ᩠ᨾᩢᩢ': 5, + 'ᩉ᩠ᨾᩪ᩵': 5, + 'ᩉ᩠ᨾᩳ': 4, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 6, + 'ᩉ᩠ᨿᩩ': 4, + 'ᩉ᩠ᩅᩫ': 4, + 'ᩉ᩠ᩅ᩵': 4, + 'ᩉᩢ': 2, + 'ᩉᩨᩢ': 3, + 'ᩉᩨ᩶': 3, + 'ᩉᩮᩖᩨ': 4, + 'ᩉᩮ᩠ᨦᩢᩢ': 6, + 'ᩉᩮ᩠ᨯ': 4, + 'ᩉᩮ᩠ᨲᩩ': 5, + 'ᩉᩮ᩠ᨶᩨ': 5, + 'ᩉᩮ᩠ᨾᩨ': 5, + 'ᩉᩮ᩠ᨾᩨᩨ': 6, + 'ᩉᩯ᩠ᨦ᩵': 5, + 'ᩉᩯ᩠ᨶᩢ': 5, + 'ᩉᩯ᩠ᨾ': 4, + 'ᩉᩯ᩵': 3, + 'ᩉᩱ᩠ᨾ᩵': 5, + 'ᩉᩱ᩠ᨿ᩵': 5, + 'ᩉᩳ': 2, + 'ᩋ᩠ᨶᩢ': 4, + 'ᩋ᩠ᨶᩨ᩵': 5, + 'ᩋ᩠ᩋ': 3, + 'ᩋᩢ': 2, + 'ᩋᩪᩢ': 3, + 'ᩋᩴ': 2, + 'ᩐᩢ': 2, + 'ᩓ᩠ᩅᩢ': 4, + 'ᩓᩢ': 2, + 'ᩔ᩼': 2, + 'ᩣ᩠ᨠ': 3, + 'ᩣ᩠ᨦ': 3, + 'ᩣ᩠ᨧ': 3, + 'ᩣ᩠ᨩ': 3, + 'ᩣ᩠ᨯ': 3, + 'ᩣ᩠ᨲ': 3, + 'ᩣ᩠ᨲᩱ': 4, + 'ᩣ᩠ᨶ': 3, + 'ᩣ᩠ᨷ': 3, + 'ᩣ᩠ᨾ': 3, + 'ᩣ᩠ᨿ': 3, + 'ᩣ᩠ᩁ': 3, + 'ᩣ᩠ᩃ': 3, + 'ᩣ᩠ᩅ': 3, + 'ᩣ᩠ᩈ': 3, + 'ᩤ᩠ᨦ': 3, + 'ᩤ᩠ᨶᩢ': 4, + 'ᵾ́': 2, + 'Ẹ̀': 2, + 'ẹ̀': 2, + 'ẹ́': 2, + 'ẽ́': 2, + 'ẽ̱': 2, + 'Ọ̀': 2, + 'ọ̀': 2, + 'Ọ́': 2, + 'ọ́': 2, + '⛓️‍💥': 5, + '⛹️‍♀️': 5, + '⛹️‍♂️': 5, + '⛹🏻‍♀️': 6, + '⛹🏻‍♂️': 6, + '⛹🏼‍♀️': 6, + '⛹🏼‍♂️': 6, + '⛹🏽‍♀️': 6, + '⛹🏽‍♂️': 6, + '⛹🏾‍♀️': 6, + '⛹🏾‍♂️': 6, + '⛹🏿‍♀️': 6, + '⛹🏿‍♂️': 6, + '❤️‍🔥': 5, + '❤️‍🩹': 5, + 'ꦉꦁ': 2, + 'ꦏꦁ': 2, + 'ꦏꦂ': 2, + 'ꦏꦶ': 2, + 'ꦏꦶꦂ': 3, + 'ꦏꦸ': 2, + 'ꦏꦸꦂ': 3, + 'ꦏꦺꦴ': 3, + 'ꦏꦼ': 2, + 'ꦏꦿꦁ': 3, + 'ꦏꦿꦂ': 3, + 'ꦏ꧀': 2, + 'ꦏ꧀ꦏ': 3, + 'ꦏ꧀ꦏꦁ': 4, + 'ꦏ꧀ꦏꦺ': 4, + 'ꦏ꧀ꦏꦼ': 4, + 'ꦏ꧀ꦔ': 3, + 'ꦏ꧀ꦔꦸ': 4, + 'ꦏ꧀ꦔꦿ': 4, + 'ꦏ꧀ꦕ': 3, + 'ꦏ꧀ꦠ': 3, + 'ꦏ꧀ꦠꦶ': 4, + 'ꦏ꧀ꦠꦸ': 4, + 'ꦏ꧀ꦠꦺ': 4, + 'ꦏ꧀ꦢ': 3, + 'ꦏ꧀ꦢꦂ': 4, + 'ꦏ꧀ꦢꦶ': 4, + 'ꦏ꧀ꦤ': 3, + 'ꦏ꧀ꦤꦶꦁ': 5, + 'ꦏ꧀ꦥ': 3, + 'ꦏ꧀ꦥꦶ': 4, + 'ꦏ꧀ꦥꦿꦶ': 5, + 'ꦏ꧀ꦧ': 3, + 'ꦏ꧀ꦧꦶ': 4, + 'ꦏ꧀ꦧꦺ': 4, + 'ꦏ꧀ꦩ': 3, + 'ꦏ꧀ꦩꦸ': 4, + 'ꦏ꧀ꦪ': 3, + 'ꦏ꧀ꦭ': 3, + 'ꦏ꧀ꦮ': 3, + 'ꦏ꧀ꦱ': 3, + 'ꦏ꧀ꦱꦂ': 4, + 'ꦏ꧀ꦱꦶ': 4, + 'ꦏ꧀ꦱꦸ': 4, + 'ꦏ꧀ꦱꦺ': 4, + 'ꦏ꧀ꦲ': 3, + 'ꦏ꧀ꦲꦁ': 4, + 'ꦏ꧀ꦲꦶꦁ': 5, + 'ꦏ꧀ꦲꦸ': 4, + 'ꦏ꧀ꦲꦺ': 4, + 'ꦏ꧀ꦲꦺꦴ': 5, + 'ꦒꦁ': 2, + 'ꦒꦂ': 2, + 'ꦒꦸ': 2, + 'ꦒꦸꦁ': 3, + 'ꦒꦸꦂ': 3, + 'ꦒꦸꦃ': 3, + 'ꦒꦺꦴ': 3, + 'ꦒꦼ': 2, + 'ꦒꦼꦂ': 3, + 'ꦒꦿꦺ': 3, + 'ꦒ꧀ꦒ': 3, + 'ꦔꦁ': 2, + 'ꦔꦶ': 2, + 'ꦔꦶꦁ': 3, + 'ꦔꦸ': 2, + 'ꦔꦺꦴ': 3, + 'ꦔꦼ': 2, + 'ꦔꦼꦂ': 3, + 'ꦔꦽ': 2, + 'ꦔ꧀ꦒꦼ': 4, + 'ꦔ꧀ꦒꦿꦼꦁ': 6, + 'ꦔ꧀ꦭ': 3, + 'ꦔ꧀ꦭꦁ': 4, + 'ꦔ꧀ꦭꦸ': 4, + 'ꦔ꧀ꦭꦼ': 4, + 'ꦕꦶ': 2, + 'ꦕꦶꦁ': 3, + 'ꦕꦸ': 2, + 'ꦕꦺꦴ': 3, + 'ꦗꦶ': 2, + 'ꦗꦸ': 2, + 'ꦗꦼ': 2, + 'ꦗꦿꦺꦴ': 4, + 'ꦚꦁ': 2, + 'ꦚꦶꦁ': 3, + 'ꦚ꧀ꦕ': 3, + 'ꦚ꧀ꦕꦶ': 4, + 'ꦚ꧀ꦗ': 3, + 'ꦚ꧀ꦗꦶ': 4, + 'ꦚ꧀ꦗꦸꦁ': 5, + 'ꦚ꧀ꦗꦸꦂ': 5, + 'ꦝꦁ': 2, + 'ꦝꦂ': 2, + 'ꦝꦶ': 2, + 'ꦝꦺꦴ': 3, + 'ꦝꦺꦴꦂ': 4, + 'ꦝꦼ': 2, + 'ꦝꦼꦁ': 3, + 'ꦠꦁ': 2, + 'ꦠꦶ': 2, + 'ꦠꦸ': 2, + 'ꦠꦸꦁ': 3, + 'ꦠꦸꦂ': 3, + 'ꦠꦸꦃ': 3, + 'ꦠꦺꦃ': 3, + 'ꦠꦺꦴ': 3, + 'ꦠꦼ': 2, + 'ꦠꦼꦂ': 3, + 'ꦠꦽ': 2, + 'ꦠꦿꦶ': 3, + 'ꦠ꧀': 2, + 'ꦠ꧀ꦏꦁ': 4, + 'ꦠ꧀ꦏꦸ': 4, + 'ꦠ꧀ꦒ': 3, + 'ꦠ꧀ꦔꦸ': 4, + 'ꦠ꧀ꦚ': 3, + 'ꦠ꧀ꦠ': 3, + 'ꦠ꧀ꦠꦶ': 4, + 'ꦠ꧀ꦠꦶꦁ': 5, + 'ꦠ꧀ꦠꦸ': 4, + 'ꦠ꧀ꦠꦺ': 4, + 'ꦠ꧀ꦤ': 3, + 'ꦠ꧀ꦤꦶ': 4, + 'ꦠ꧀ꦩ': 3, + 'ꦠ꧀ꦩꦼ': 4, + 'ꦠ꧀ꦭ': 3, + 'ꦠ꧀ꦭꦺ': 4, + 'ꦠ꧀ꦱ': 3, + 'ꦠ꧀ꦱꦶꦁ': 5, + 'ꦠ꧀ꦱꦶꦃ': 5, + 'ꦠ꧀ꦱꦾ': 4, + 'ꦠ꧀ꦱ꧀ꦮ': 5, + 'ꦠ꧀ꦲ': 3, + 'ꦠ꧀ꦲꦶꦁ': 5, + 'ꦠ꧀ꦲꦺꦴ': 5, + 'ꦢꦂ': 2, + 'ꦢꦶ': 2, + 'ꦢꦸ': 2, + 'ꦢꦸꦂ': 3, + 'ꦢꦺꦴ': 3, + 'ꦢꦼ': 2, + 'ꦢ꧀': 2, + 'ꦢ꧀ꦏ': 3, + 'ꦢ꧀ꦠ': 3, + 'ꦢ꧀ꦠꦶꦁ': 5, + 'ꦢ꧀ꦢ': 3, + 'ꦢ꧀ꦥ': 3, + 'ꦢ꧀ꦩꦺꦴ': 5, + 'ꦢ꧀ꦲ': 3, + 'ꦤꦁ': 2, + 'ꦤꦂ': 2, + 'ꦤꦶ': 2, + 'ꦤꦶꦁ': 3, + 'ꦤꦸ': 2, + 'ꦤꦸꦁ': 3, + 'ꦤꦺꦃ': 3, + 'ꦤꦺꦴ': 3, + 'ꦤꦼ': 2, + 'ꦤꦼꦁ': 3, + 'ꦤꦼꦂ': 3, + 'ꦤ꧀': 2, + 'ꦤ꧀ꦏ': 3, + 'ꦤ꧀ꦏꦁ': 4, + 'ꦤ꧀ꦏꦸ': 4, + 'ꦤ꧀ꦏꦼ': 4, + 'ꦤ꧀ꦒ': 3, + 'ꦤ꧀ꦔ': 3, + 'ꦤ꧀ꦔꦁ': 4, + 'ꦤ꧀ꦔꦶ': 4, + 'ꦤ꧀ꦔꦸ': 4, + 'ꦤ꧀ꦔꦸꦂ': 5, + 'ꦤ꧀ꦔꦺ': 4, + 'ꦤ꧀ꦔꦼ': 4, + 'ꦤ꧀ꦔꦿꦸ': 5, + 'ꦤ꧀ꦗ': 3, + 'ꦤ꧀ꦗꦸ': 4, + 'ꦤ꧀ꦗꦼ': 4, + 'ꦤ꧀ꦚꦶ': 4, + 'ꦤ꧀ꦛꦃ': 4, + 'ꦤ꧀ꦛꦶ': 4, + 'ꦤ꧀ꦝ': 3, + 'ꦤ꧀ꦝꦁ': 4, + 'ꦤ꧀ꦝꦶ': 4, + 'ꦤ꧀ꦝꦸ': 4, + 'ꦤ꧀ꦝꦸꦁ': 5, + 'ꦤ꧀ꦝꦺꦁ': 5, + 'ꦤ꧀ꦝꦺꦴꦁ': 6, + 'ꦤ꧀ꦝꦼ': 4, + 'ꦤ꧀ꦠ': 3, + 'ꦤ꧀ꦠꦂ': 4, + 'ꦤ꧀ꦠꦃ': 4, + 'ꦤ꧀ꦠꦶ': 4, + 'ꦤ꧀ꦠꦸ': 4, + 'ꦤ꧀ꦠꦸꦁ': 5, + 'ꦤ꧀ꦠꦺ': 4, + 'ꦤ꧀ꦠꦼ': 4, + 'ꦤ꧀ꦠꦼꦂ': 5, + 'ꦤ꧀ꦠꦽ': 4, + 'ꦤ꧀ꦢ': 3, + 'ꦤ꧀ꦢꦁ': 4, + 'ꦤ꧀ꦢꦂ': 4, + 'ꦤ꧀ꦢꦶ': 4, + 'ꦤ꧀ꦢꦸ': 4, + 'ꦤ꧀ꦢꦺ': 4, + 'ꦤ꧀ꦢꦼ': 4, + 'ꦤ꧀ꦤ': 3, + 'ꦤ꧀ꦤꦶ': 4, + 'ꦤ꧀ꦤꦶꦁ': 5, + 'ꦤ꧀ꦤꦺ': 4, + 'ꦤ꧀ꦤꦼ': 4, + 'ꦤ꧀ꦥ': 3, + 'ꦤ꧀ꦥꦁ': 4, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 7, + 'ꦤ꧀ꦥꦶ': 4, + 'ꦤ꧀ꦥꦸ': 4, + 'ꦤ꧀ꦥꦼ': 4, + 'ꦤ꧀ꦥꦿ': 4, + 'ꦤ꧀ꦥꦿꦶ': 5, + 'ꦤ꧀ꦧ': 3, + 'ꦤ꧀ꦧꦁ': 4, + 'ꦤ꧀ꦧꦶ': 4, + 'ꦤ꧀ꦧꦸ': 4, + 'ꦤ꧀ꦧꦺ': 4, + 'ꦤ꧀ꦧꦺꦴ': 5, + 'ꦤ꧀ꦧꦼ': 4, + 'ꦤ꧀ꦩ': 3, + 'ꦤ꧀ꦩꦂ': 4, + 'ꦤ꧀ꦩꦶ': 4, + 'ꦤ꧀ꦩꦸꦂ': 5, + 'ꦤ꧀ꦩꦼ': 4, + 'ꦤ꧀ꦭ': 3, + 'ꦤ꧀ꦭꦶ': 4, + 'ꦤ꧀ꦭꦸ': 4, + 'ꦤ꧀ꦮ': 3, + 'ꦤ꧀ꦮꦂ': 4, + 'ꦤ꧀ꦮꦶ': 4, + 'ꦤ꧀ꦮꦸ': 4, + 'ꦤ꧀ꦮꦼ': 4, + 'ꦤ꧀ꦱ': 3, + 'ꦤ꧀ꦱꦂ': 4, + 'ꦤ꧀ꦱꦃ': 4, + 'ꦤ꧀ꦱꦶ': 4, + 'ꦤ꧀ꦱꦶꦁ': 5, + 'ꦤ꧀ꦱꦸ': 4, + 'ꦤ꧀ꦱꦺꦴ': 5, + 'ꦤ꧀ꦱꦼ': 4, + 'ꦤ꧀ꦲ': 3, + 'ꦤ꧀ꦲꦁ': 4, + 'ꦤ꧀ꦲꦶ': 4, + 'ꦤ꧀ꦲꦶꦁ': 5, + 'ꦤ꧀ꦲꦸ': 4, + 'ꦤ꧀ꦲꦺꦴ': 5, + 'ꦥꦁ': 2, + 'ꦥ꦳ꦼ': 3, + 'ꦥ꦳꧀': 3, + 'ꦥꦶ': 2, + 'ꦥꦸ': 2, + 'ꦥꦸꦁ': 3, + 'ꦥꦺꦴ': 3, + 'ꦥꦼ': 2, + 'ꦥꦼꦂ': 3, + 'ꦥꦿꦃ': 3, + 'ꦥꦿꦶ': 3, + 'ꦥꦿꦺꦴ': 4, + 'ꦥ꧀': 2, + 'ꦥ꧀ꦏ': 3, + 'ꦥ꧀ꦏꦁ': 4, + 'ꦥ꧀ꦠ': 3, + 'ꦥ꧀ꦠꦶ': 4, + 'ꦥ꧀ꦢꦸ': 4, + 'ꦥ꧀ꦤ': 3, + 'ꦥ꧀ꦤꦶ': 4, + 'ꦥ꧀ꦥ': 3, + 'ꦥ꧀ꦥꦶ': 4, + 'ꦥ꧀ꦥꦺ': 4, + 'ꦥ꧀ꦧꦺ': 4, + 'ꦥ꧀ꦩ': 3, + 'ꦥ꧀ꦩꦂ': 4, + 'ꦥ꧀ꦫꦺ': 4, + 'ꦥ꧀ꦭ': 3, + 'ꦥ꧀ꦭꦸ': 4, + 'ꦥ꧀ꦱ': 3, + 'ꦥ꧀ꦱꦶꦂ': 5, + 'ꦥ꧀ꦱꦼ': 4, + 'ꦥ꧀ꦲ': 3, + 'ꦧꦁ': 2, + 'ꦧꦶ': 2, + 'ꦧꦸ': 2, + 'ꦧꦸꦂ': 3, + 'ꦧꦺꦃ': 3, + 'ꦧꦺꦴ': 3, + 'ꦧꦼ': 2, + 'ꦧ꧀': 2, + 'ꦧ꧀ꦏ': 3, + 'ꦧ꧀ꦠꦸ': 4, + 'ꦧ꧀ꦥ': 3, + 'ꦧ꧀ꦧ': 3, + 'ꦧ꧀ꦧꦺ': 4, + 'ꦧ꧀ꦲ': 3, + 'ꦧ꧀ꦲꦶ': 4, + 'ꦩꦁ': 2, + 'ꦩꦂ': 2, + 'ꦩꦶ': 2, + 'ꦩꦸ': 2, + 'ꦩꦸꦁ': 3, + 'ꦩꦸꦂ': 3, + 'ꦩꦺꦃ': 3, + 'ꦩꦺꦴ': 3, + 'ꦩꦼ': 2, + 'ꦩꦼꦂ': 3, + 'ꦩꦿꦃ': 3, + 'ꦩꦿꦶꦃ': 4, + 'ꦩ꧀': 2, + 'ꦩ꧀ꦏꦁ': 4, + 'ꦩ꧀ꦔꦼ': 4, + 'ꦩ꧀ꦠꦸ': 4, + 'ꦩ꧀ꦠꦺꦴ': 5, + 'ꦩ꧀ꦤꦶꦁ': 5, + 'ꦩ꧀ꦥ': 3, + 'ꦩ꧀ꦥꦶ': 4, + 'ꦩ꧀ꦥꦸ': 4, + 'ꦩ꧀ꦥꦼ': 4, + 'ꦩ꧀ꦧ': 3, + 'ꦩ꧀ꦧꦁ': 4, + 'ꦩ꧀ꦧꦂ': 4, + 'ꦩ꧀ꦧꦃ': 4, + 'ꦩ꧀ꦧꦶ': 4, + 'ꦩ꧀ꦧꦸ': 4, + 'ꦩ꧀ꦧꦸꦁ': 5, + 'ꦩ꧀ꦧꦺ': 4, + 'ꦩ꧀ꦧꦺꦂ': 5, + 'ꦩ꧀ꦧꦼꦂ': 5, + 'ꦩ꧀ꦧꦾꦸꦂ': 6, + 'ꦩ꧀ꦩ': 3, + 'ꦩ꧀ꦩꦶ': 4, + 'ꦩ꧀ꦫ': 3, + 'ꦩ꧀ꦫꦃ': 4, + 'ꦩ꧀ꦭ': 3, + 'ꦩ꧀ꦲꦶ': 4, + 'ꦪꦁ': 2, + 'ꦪꦶ': 2, + 'ꦪꦸ': 2, + 'ꦪꦸꦁ': 3, + 'ꦪꦸꦃ': 3, + 'ꦪꦺꦴ': 3, + 'ꦫꦁ': 2, + 'ꦫꦶ': 2, + 'ꦫꦶꦁ': 3, + 'ꦫꦶꦃ': 3, + 'ꦫꦸ': 2, + 'ꦫꦸꦁ': 3, + 'ꦫꦺꦴ': 3, + 'ꦭꦁ': 2, + 'ꦭꦂ': 2, + 'ꦭꦶ': 2, + 'ꦭꦶꦁ': 3, + 'ꦭꦶꦃ': 3, + 'ꦭꦸ': 2, + 'ꦭꦸꦁ': 3, + 'ꦭꦸꦂ': 3, + 'ꦭꦺꦃ': 3, + 'ꦭꦺꦴ': 3, + 'ꦭꦺꦴꦁ': 4, + 'ꦭ꧀': 2, + 'ꦭ꧀ꦏꦁ': 4, + 'ꦭ꧀ꦚꦼꦁ': 5, + 'ꦭ꧀ꦠꦸ': 4, + 'ꦭ꧀ꦧꦸ': 4, + 'ꦭ꧀ꦩꦸ': 4, + 'ꦭ꧀ꦭ': 3, + 'ꦭ꧀ꦭꦶ': 4, + 'ꦭ꧀ꦭꦶꦁ': 5, + 'ꦭ꧀ꦭꦺ': 4, + 'ꦭ꧀ꦮ': 3, + 'ꦭ꧀ꦱ': 3, + 'ꦭ꧀ꦱꦂ': 4, + 'ꦭ꧀ꦱꦶꦁ': 5, + 'ꦭ꧀ꦱꦸ': 4, + 'ꦭ꧀ꦲ': 3, + 'ꦭ꧀ꦲꦁ': 4, + 'ꦭ꧀ꦲꦶꦁ': 5, + 'ꦭ꧀ꦲꦸ': 4, + 'ꦮꦂ': 2, + 'ꦮ꦳ꦼꦂ': 4, + 'ꦮꦶ': 2, + 'ꦮꦶꦃ': 3, + 'ꦮꦸ': 2, + 'ꦮꦸꦁ': 3, + 'ꦮꦸꦃ': 3, + 'ꦮꦺꦴ': 3, + 'ꦮꦺꦴꦁ': 4, + 'ꦮꦺꦴꦃ': 4, + 'ꦮꦼ': 2, + 'ꦮꦼꦁ': 3, + 'ꦮꦼꦂ': 3, + 'ꦮꦿꦸꦃ': 4, + 'ꦱꦂ': 2, + 'ꦱꦶ': 2, + 'ꦱꦶꦁ': 3, + 'ꦱꦶꦂ': 3, + 'ꦱꦶꦃ': 3, + 'ꦱꦸ': 2, + 'ꦱꦸꦁ': 3, + 'ꦱꦺꦴ': 3, + 'ꦱꦼ': 2, + 'ꦱꦼꦁ': 3, + 'ꦱꦿꦃ': 3, + 'ꦱ꧀': 2, + 'ꦱ꧀ꦏ': 3, + 'ꦱ꧀ꦏꦁ': 4, + 'ꦱ꧀ꦏꦿꦶ': 5, + 'ꦱ꧀ꦒ': 3, + 'ꦱ꧀ꦔꦸ': 4, + 'ꦱ꧀ꦔꦿ': 4, + 'ꦱ꧀ꦛꦶ': 4, + 'ꦱ꧀ꦠ': 3, + 'ꦱ꧀ꦠꦿ': 4, + 'ꦱ꧀ꦢꦂ': 4, + 'ꦱ꧀ꦢꦶ': 4, + 'ꦱ꧀ꦢꦸ': 4, + 'ꦱ꧀ꦥ': 3, + 'ꦱ꧀ꦧ': 3, + 'ꦱ꧀ꦧꦁ': 4, + 'ꦱ꧀ꦩ': 3, + 'ꦱ꧀ꦩꦶ': 4, + 'ꦱ꧀ꦩꦼ': 4, + 'ꦱ꧀ꦩꦿ': 4, + 'ꦱ꧀ꦭ': 3, + 'ꦱ꧀ꦮ': 3, + 'ꦱ꧀ꦱ': 3, + 'ꦱ꧀ꦱꦂ': 4, + 'ꦱ꧀ꦱꦶ': 4, + 'ꦱ꧀ꦱꦶꦁ': 5, + 'ꦱ꧀ꦱꦸ': 4, + 'ꦱ꧀ꦱꦺ': 4, + 'ꦱ꧀ꦲ': 3, + 'ꦱ꧀ꦲꦁ': 4, + 'ꦱ꧀ꦲꦶ': 4, + 'ꦱ꧀ꦲꦶꦁ': 5, + 'ꦱ꧀ꦲꦸ': 4, + 'ꦲꦁ': 2, + 'ꦲꦶ': 2, + 'ꦲꦶꦁ': 3, + 'ꦲꦶꦂ': 3, + 'ꦲꦸ': 2, + 'ꦲꦸꦂ': 3, + 'ꦲꦺꦴ': 3, + 'ꦲꦼ': 2, + 'ꪀꪰ': 2, + 'ꪀꪲ': 2, + 'ꪀꪳ': 2, + 'ꪀꪴ': 2, + 'ꪀꪷ': 2, + 'ꪀꪾ': 2, + 'ꪁꪴ': 2, + 'ꪁꪷ': 2, + 'ꪁꪸ': 2, + 'ꪁꪾ': 2, + 'ꪄꪰ': 2, + 'ꪄꪲ': 2, + 'ꪄꪳ': 2, + 'ꪄꪴ': 2, + 'ꪄꪷ': 2, + 'ꪅꪰ': 2, + 'ꪈꪲ': 2, + 'ꪈꪸ': 2, + 'ꪈꪾ': 2, + 'ꪉꪷ': 2, + 'ꪉꪸ': 2, + 'ꪊꪰ': 2, + 'ꪊꪲ': 2, + 'ꪊꪴ': 2, + 'ꪊꪸ': 2, + 'ꪋꪲ': 2, + 'ꪋꪳ': 2, + 'ꪋꪴ': 2, + 'ꪋꪷ': 2, + 'ꪋꪸ': 2, + 'ꪎꪰ': 2, + 'ꪎꪲ': 2, + 'ꪎꪳ': 2, + 'ꪎꪴ': 2, + 'ꪎꪷ': 2, + 'ꪎꪸ': 2, + 'ꪏꪴ': 2, + 'ꪏꪷ': 2, + 'ꪏꪸ': 2, + 'ꪑꪰ': 2, + 'ꪑꪲ': 2, + 'ꪑꪷ': 2, + 'ꪒꪰ': 2, + 'ꪒꪲ': 2, + 'ꪒꪴ': 2, + 'ꪒꪷ': 2, + 'ꪒꪸ': 2, + 'ꪔꪰ': 2, + 'ꪔꪲ': 2, + 'ꪔꪳ': 2, + 'ꪔꪷ': 2, + 'ꪔꪸ': 2, + 'ꪔꪾ': 2, + 'ꪕꪰ': 2, + 'ꪕꪲ': 2, + 'ꪕꪳ': 2, + 'ꪕꪴ': 2, + 'ꪕꪷ': 2, + 'ꪕꪸ': 2, + 'ꪕꪾ': 2, + 'ꪖꪸ': 2, + 'ꪘꪰ': 2, + 'ꪘꪳ': 2, + 'ꪙꪲ': 2, + 'ꪙꪴ': 2, + 'ꪙꪾ': 2, + 'ꪚꪰ': 2, + 'ꪚꪴ': 2, + 'ꪚꪷ': 2, + 'ꪜꪰ': 2, + 'ꪜꪲ': 2, + 'ꪜꪴ': 2, + 'ꪜꪸ': 2, + 'ꪝꪰ': 2, + 'ꪝꪲ': 2, + 'ꪝꪳ': 2, + 'ꪝꪷ': 2, + 'ꪝꪸ': 2, + 'ꪠꪲ': 2, + 'ꪠꪴ': 2, + 'ꪠꪸ': 2, + 'ꪢꪲ': 2, + 'ꪢꪴ': 2, + 'ꪢꪸ': 2, + 'ꪣꪰ': 2, + 'ꪣꪲ': 2, + 'ꪣꪳ': 2, + 'ꪣꪷ': 2, + 'ꪣꪸ': 2, + 'ꪤꪰ': 2, + 'ꪤꪴ': 2, + 'ꪤꪷ': 2, + 'ꪤꪸ': 2, + 'ꪤꪾ': 2, + 'ꪥꪰ': 2, + 'ꪥꪴ': 2, + 'ꪥꪸ': 2, + 'ꪨꪰ': 2, + 'ꪨꪷ': 2, + 'ꪨꪸ': 2, + 'ꪩꪰ': 2, + 'ꪩꪳ': 2, + 'ꪩꪴ': 2, + 'ꪩꪷ': 2, + 'ꪩꪾ': 2, + 'ꪪꪴ': 2, + 'ꪫꪸ': 2, + 'ꪬꪷ': 2, + 'ꪬꪸ': 2, + 'ꪭꪰ': 2, + 'ꪭꪲ': 2, + 'ꪭꪳ': 2, + 'ꪭꪴ': 2, + 'ꪭꪷ': 2, + 'ꪭꪸ': 2, + 'ꪮꪲ': 2, + 'ꪮꪳ': 2, + 'ꪮꪴ': 2, + 'ꪮꪸ': 2, + 'ꪯꪸ': 2, + '𑄃𑄧': 2, + '𑄃𑄧𑄁': 3, + '𑄃𑄨': 2, + '𑄃𑄪': 2, + '𑄃𑄬𑄭': 3, + '𑄃𑄮': 2, + '𑄃𑄰': 2, + '𑄃𑄳𑄃': 3, + '𑄃𑄳𑄦𑄧': 4, + '𑄃𑄳𑄦𑄨': 4, + '𑄅𑄪': 2, + '𑄅𑄫': 2, + '𑄇𑄧': 2, + '𑄇𑄧𑄧': 3, + '𑄇𑄧𑄧𑄱': 4, + '𑄇𑄨': 2, + '𑄇𑄨𑄁': 3, + '𑄇𑄪': 2, + '𑄇𑄭𑄭': 3, + '𑄇𑄳𑄠': 3, + '𑄇𑄳𑄠𑄬': 4, + '𑄇𑄳𑄠𑄴': 4, + '𑄇𑄳𑄢𑄨': 4, + '𑄇𑄳𑄦𑄧': 4, + '𑄇𑄳𑄦𑄴': 4, + '𑄇𑄴': 2, + '𑄈𑄧': 2, + '𑄈𑄪': 2, + '𑄈𑄳𑄠': 3, + '𑄈𑄳𑄠𑄬': 4, + '𑄉𑄧': 2, + '𑄉𑄨': 2, + '𑄉𑄩': 2, + '𑄉𑄪': 2, + '𑄉𑄬𑄭': 3, + '𑄉𑄭': 2, + '𑄉𑄮': 2, + '𑄉𑄳𑄠': 3, + '𑄉𑄳𑄢𑄧': 4, + '𑄊𑄧': 2, + '𑄊𑄨': 2, + '𑄋𑄧': 2, + '𑄋𑄨': 2, + '𑄌𑄧': 2, + '𑄌𑄨': 2, + '𑄌𑄮': 2, + '𑄌𑄯': 2, + '𑄌𑄳𑄠𑄬': 4, + '𑄌𑄳𑄠𑄴': 4, + '𑄌𑄴': 2, + '𑄍𑄨': 2, + '𑄍𑄪': 2, + '𑄎𑄧': 2, + '𑄎𑄨': 2, + '𑄎𑄨𑄁': 3, + '𑄎𑄩': 2, + '𑄎𑄩𑄁': 3, + '𑄎𑄪': 2, + '𑄎𑄪𑄁': 3, + '𑄎𑄬𑄭': 3, + '𑄎𑄮': 2, + '𑄎𑄳𑄠𑄧': 4, + '𑄎𑄳𑄠𑄬': 4, + '𑄏𑄨': 2, + '𑄏𑄮': 2, + '𑄑𑄨': 2, + '𑄑𑄳𑄢𑄬': 4, + '𑄒𑄨': 2, + '𑄓𑄧': 2, + '𑄓𑄨': 2, + '𑄓𑄮': 2, + '𑄕𑄧': 2, + '𑄖𑄧': 2, + '𑄖𑄧𑄧': 3, + '𑄖𑄧𑄧𑄱': 4, + '𑄖𑄨': 2, + '𑄖𑄨𑄨': 3, + '𑄖𑄨𑄨𑄪': 4, + '𑄖𑄩': 2, + '𑄖𑄪': 2, + '𑄖𑄳𑄠𑄧': 4, + '𑄖𑄳𑄠𑄬': 4, + '𑄖𑄳𑄠𑄴': 4, + '𑄖𑄳𑄢𑄨': 4, + '𑄖𑄳𑄢𑄬': 4, + '𑄖𑄳𑄦𑄴': 4, + '𑄖𑄴': 2, + '𑄗𑄧': 2, + '𑄗𑄪': 2, + '𑄗𑄭': 2, + '𑄘𑄁': 2, + '𑄘𑄧': 2, + '𑄘𑄨': 2, + '𑄘𑄪': 2, + '𑄘𑄮': 2, + '𑄘𑄳𑄠𑄧': 4, + '𑄘𑄳𑄠𑄬': 4, + '𑄙𑄧': 2, + '𑄙𑄨': 2, + '𑄙𑄩': 2, + '𑄙𑄪': 2, + '𑄙𑄮': 2, + '𑄙𑄳𑄠': 3, + '𑄙𑄳𑄠𑄧': 4, + '𑄚𑄧': 2, + '𑄚𑄧𑄧𑄱': 4, + '𑄚𑄨': 2, + '𑄚𑄩': 2, + '𑄚𑄪': 2, + '𑄚𑄬𑄭': 3, + '𑄚𑄮': 2, + '𑄚𑄳𑄠𑄧': 4, + '𑄚𑄳𑄠𑄬': 4, + '𑄚𑄳𑄠𑄴': 4, + '𑄚𑄳𑄢𑄧𑄧': 5, + '𑄚𑄳𑄦𑄧': 4, + '𑄚𑄳𑄦𑄨': 4, + '𑄚𑄳𑄦𑄴': 4, + '𑄚𑄴': 2, + '𑄛𑄧': 2, + '𑄛𑄨': 2, + '𑄛𑄪': 2, + '𑄛𑄭': 2, + '𑄛𑄮': 2, + '𑄛𑄱': 2, + '𑄛𑄳𑄢': 3, + '𑄛𑄳𑄢𑄧': 4, + '𑄛𑄳𑄦': 3, + '𑄛𑄴': 2, + '𑄜𑄧': 2, + '𑄜𑄨': 2, + '𑄜𑄪': 2, + '𑄜𑄯': 2, + '𑄝𑄧': 2, + '𑄝𑄧𑄧': 3, + '𑄝𑄨': 2, + '𑄝𑄪': 2, + '𑄝𑄮': 2, + '𑄝𑄰': 2, + '𑄝𑄳𑄠': 3, + '𑄝𑄳𑄢𑄨': 4, + '𑄝𑄳𑄢𑄬': 4, + '𑄞𑄧': 2, + '𑄞𑄨': 2, + '𑄞𑄩': 2, + '𑄞𑄪': 2, + '𑄞𑄬𑄭': 3, + '𑄞𑄮': 2, + '𑄞𑄯': 2, + '𑄟𑄧': 2, + '𑄟𑄨': 2, + '𑄟𑄪': 2, + '𑄟𑄫': 2, + '𑄟𑄮': 2, + '𑄟𑄱': 2, + '𑄟𑄳𑄠𑄬': 4, + '𑄟𑄴': 2, + '𑄠𑄧': 2, + '𑄠𑄨': 2, + '𑄠𑄬𑄭': 3, + '𑄠𑄮': 2, + '𑄠𑄴': 2, + '𑄡𑄧': 2, + '𑄡𑄨': 2, + '𑄡𑄪': 2, + '𑄡𑄬𑄭': 3, + '𑄡𑄳𑄠𑄬': 4, + '𑄢𑄁': 2, + '𑄢𑄧': 2, + '𑄢𑄨': 2, + '𑄢𑄩': 2, + '𑄢𑄪': 2, + '𑄢𑄬𑄭': 3, + '𑄢𑄮': 2, + '𑄢𑄳𑄦𑄧𑄱𑄱': 6, + '𑄢𑄴': 2, + '𑄣𑄧': 2, + '𑄣𑄨': 2, + '𑄣𑄩': 2, + '𑄣𑄪': 2, + '𑄣𑄬𑄭': 3, + '𑄣𑄮': 2, + '𑄣𑄰𑄱': 3, + '𑄣𑄳𑄦𑄬': 4, + '𑄣𑄳𑄦𑄴': 4, + '𑄣𑄴': 2, + '𑄥𑄁': 2, + '𑄥𑄧': 2, + '𑄥𑄧𑄁': 3, + '𑄥𑄨': 2, + '𑄥𑄩': 2, + '𑄥𑄪': 2, + '𑄥𑄳𑄠': 3, + '𑄥𑄳𑄠𑄧': 4, + '𑄥𑄳𑄢𑄧': 4, + '𑄥𑄳𑄢𑄨𑄁': 5, + '𑄦𑄧': 2, + '𑄦𑄨': 2, + '𑄦𑄮': 2, + '𑄦𑄰': 2, + '𑌕𑌾𑌂': 3, + '𑌕𑌾𑌃': 3, + '𑌕𑍀': 2, + '𑌕𑍍': 2, + '𑌗𑍀': 2, + '𑌗𑍍': 2, + '𑌚𑍍': 2, + '𑌜𑌼': 2, + '𑌜𑍀': 2, + '𑌜𑍍': 2, + '𑌞𑍍': 2, + '𑌟𑌾𑌂': 3, + '𑌟𑌾𑌃': 3, + '𑌟𑍍': 2, + '𑌠𑍈𑌃': 3, + '𑌢𑌼𑍀': 3, + '𑌣𑌾𑌂': 3, + '𑌣𑍀': 2, + '𑌣𑍍': 2, + '𑌤𑌾𑌂': 3, + '𑌤𑌾𑌃': 3, + '𑌤𑌿𑌂': 3, + '𑌤𑌿𑌃': 3, + '𑌤𑍀': 2, + '𑌤𑍁𑌂': 3, + '𑌤𑍇𑌃': 3, + '𑌤𑍍': 2, + '𑌥𑌾𑌂': 3, + '𑌦𑍀': 2, + '𑌦𑍍': 2, + '𑌧𑌾𑌃': 3, + '𑌧𑌿𑌂': 3, + '𑌧𑍀': 2, + '𑌧𑍇𑌃': 3, + '𑌧𑍈𑌃': 3, + '𑌧𑍍': 2, + '𑌨𑌾𑌂': 3, + '𑌨𑌾𑌃': 3, + '𑌨𑌿𑌃': 3, + '𑌨𑍀': 2, + '𑌨𑍈𑌃': 3, + '𑌨𑍍': 2, + '𑌪𑍀': 2, + '𑌪𑍍': 2, + '𑌬𑍍': 2, + '𑌭𑌿𑌃': 3, + '𑌭𑍍': 2, + '𑌮𑌿𑌂': 3, + '𑌮𑍀': 2, + '𑌮𑍍': 2, + '𑌯𑌾𑌂': 3, + '𑌯𑌾𑌃': 3, + '𑌯𑍀': 2, + '𑌯𑍁𑌃': 3, + '𑌯𑍈𑌃': 3, + '𑌯𑍋𑌃': 3, + '𑌯𑍍': 2, + '𑌰𑌾𑌃': 3, + '𑌰𑌿𑌂': 3, + '𑌰𑍀': 2, + '𑌰𑍍': 2, + '𑌲𑌾𑌃': 3, + '𑌲𑌿𑌂': 3, + '𑌲𑍍': 2, + '𑌵𑌾𑌂': 3, + '𑌵𑌾𑌃': 3, + '𑌵𑍀': 2, + '𑌵𑍍': 2, + '𑌶𑌾𑌃': 3, + '𑌶𑍀': 2, + '𑌶𑍍': 2, + '𑌷𑌾𑌂': 3, + '𑌷𑌾𑌃': 3, + '𑌷𑍍': 2, + '𑌸𑌾𑌂': 3, + '𑌸𑍀': 2, + '𑌸𑍍': 2, + '𑌹𑌾𑌃': 3, + '𑌹𑍀': 2, + '𞤀𞥄': 2, + '𞤢𞥄': 2, + '𞤣𞥆': 2, + '𞤂𞥆': 2, + '𞤤𞥆': 2, + '𞤥𞥆': 2, + '𞤦𞥆': 2, + '𞤨𞥆': 2, + '𞤩𞥆': 2, + '𞤫𞥅': 2, + '𞤭𞥅': 2, + '𞤌𞥅': 2, + '𞤮𞥅': 2, + '𞤍𞥆': 2, + '𞤯𞥆': 2, + '𞤰𞥆': 2, + '𞤲𞥆': 2, + '𞤳𞥆': 2, + '𞤵𞥅': 2, + '𞤔𞥆': 2, + '𞤶𞥆': 2, + '𞤷𞥆': 2, + '𞤺𞥆': 2, + '𞤼𞥆': 2, + '🍄‍🟫': 5, + '🍋‍🟩': 5, + '🏃‍♀️': 5, + '🏃‍♀️‍➡️': 8, + '🏃‍♂️': 5, + '🏃‍♂️‍➡️': 8, + '🏃‍➡️': 5, + '🏃🏻‍♀️': 7, + '🏃🏻‍♀️‍➡️': 10, + '🏃🏻‍♂️': 7, + '🏃🏻‍♂️‍➡️': 10, + '🏃🏻‍➡️': 7, + '🏃🏼‍♀️': 7, + '🏃🏼‍♀️‍➡️': 10, + '🏃🏼‍♂️': 7, + '🏃🏼‍♂️‍➡️': 10, + '🏃🏼‍➡️': 7, + '🏃🏽‍♀️': 7, + '🏃🏽‍♀️‍➡️': 10, + '🏃🏽‍♂️': 7, + '🏃🏽‍♂️‍➡️': 10, + '🏃🏽‍➡️': 7, + '🏃🏾‍♀️': 7, + '🏃🏾‍♀️‍➡️': 10, + '🏃🏾‍♂️': 7, + '🏃🏾‍♂️‍➡️': 10, + '🏃🏾‍➡️': 7, + '🏃🏿‍♀️': 7, + '🏃🏿‍♀️‍➡️': 10, + '🏃🏿‍♂️': 7, + '🏃🏿‍♂️‍➡️': 10, + '🏃🏿‍➡️': 7, + '🏄‍♀️': 5, + '🏄‍♂️': 5, + '🏄🏻‍♀️': 7, + '🏄🏻‍♂️': 7, + '🏄🏼‍♀️': 7, + '🏄🏼‍♂️': 7, + '🏄🏽‍♀️': 7, + '🏄🏽‍♂️': 7, + '🏄🏾‍♀️': 7, + '🏄🏾‍♂️': 7, + '🏄🏿‍♀️': 7, + '🏄🏿‍♂️': 7, + '🏊‍♀️': 5, + '🏊‍♂️': 5, + '🏊🏻‍♀️': 7, + '🏊🏻‍♂️': 7, + '🏊🏼‍♀️': 7, + '🏊🏼‍♂️': 7, + '🏊🏽‍♀️': 7, + '🏊🏽‍♂️': 7, + '🏊🏾‍♀️': 7, + '🏊🏾‍♂️': 7, + '🏊🏿‍♀️': 7, + '🏊🏿‍♂️': 7, + '🏋️‍♀️': 5, + '🏋️‍♂️': 5, + '🏋🏻‍♀️': 6, + '🏋🏻‍♂️': 6, + '🏋🏼‍♀️': 6, + '🏋🏼‍♂️': 6, + '🏋🏽‍♀️': 6, + '🏋🏽‍♂️': 6, + '🏋🏾‍♀️': 6, + '🏋🏾‍♂️': 6, + '🏋🏿‍♀️': 6, + '🏋🏿‍♂️': 6, + '🏌️‍♀️': 5, + '🏌️‍♂️': 5, + '🏌🏻‍♀️': 6, + '🏌🏻‍♂️': 6, + '🏌🏼‍♀️': 6, + '🏌🏼‍♂️': 6, + '🏌🏽‍♀️': 6, + '🏌🏽‍♂️': 6, + '🏌🏾‍♀️': 6, + '🏌🏾‍♂️': 6, + '🏌🏿‍♀️': 6, + '🏌🏿‍♂️': 6, + '🏳️‍⚧️': 5, + '🏳️‍🌈': 5, + '🏴‍☠️': 5, + '🏴󠁧󠁢󠁥󠁮󠁧󠁿': 8, + '🏴󠁧󠁢󠁳󠁣󠁴󠁿': 8, + '🏴󠁧󠁢󠁷󠁬󠁳󠁿': 8, + '🐈‍⬛': 5, + '🐕‍🦺': 5, + '🐦‍⬛': 5, + '🐦‍🔥': 5, + '🐻‍❄️': 5, + '👁️‍🗨️': 5, + '👨‍⚕️': 5, + '👨‍⚖️': 5, + '👨‍✈️': 5, + '👨‍❤️‍👨': 8, + '👨‍❤️‍💋‍👨': 11, + '👨‍🌾': 5, + '👨‍🍳': 5, + '👨‍🍼': 5, + '👨‍🎓': 5, + '👨‍🎤': 5, + '👨‍🎨': 5, + '👨‍🏫': 5, + '👨‍🏭': 5, + '👨‍👦': 5, + '👨‍👦‍👦': 8, + '👨‍👧': 5, + '👨‍👧‍👦': 8, + '👨‍👧‍👧': 8, + '👨‍👨‍👦': 8, + '👨‍👨‍👦‍👦': 11, + '👨‍👨‍👧': 8, + '👨‍👨‍👧‍👦': 11, + '👨‍👨‍👧‍👧': 11, + '👨‍👩‍👦': 8, + '👨‍👩‍👦‍👦': 11, + '👨‍👩‍👧': 8, + '👨‍👩‍👧‍👦': 11, + '👨‍👩‍👧‍👧': 11, + '👨‍💻': 5, + '👨‍💼': 5, + '👨‍🔧': 5, + '👨‍🔬': 5, + '👨‍🚀': 5, + '👨‍🚒': 5, + '👨‍🦯': 5, + '👨‍🦯‍➡️': 8, + '👨‍🦰': 5, + '👨‍🦱': 5, + '👨‍🦲': 5, + '👨‍🦳': 5, + '👨‍🦼': 5, + '👨‍🦼‍➡️': 8, + '👨‍🦽': 5, + '👨‍🦽‍➡️': 8, + '👨🏻‍⚕️': 7, + '👨🏻‍⚖️': 7, + '👨🏻‍✈️': 7, + '👨🏻‍❤️‍👨🏻': 12, + '👨🏻‍❤️‍👨🏽': 12, + '👨🏻‍❤️‍👨🏿': 12, + '👨🏻‍❤️‍💋‍👨🏻': 15, + '👨🏻‍❤️‍💋‍👨🏽': 15, + '👨🏻‍❤️‍💋‍👨🏾': 15, + '👨🏻‍❤️‍💋‍👨🏿': 15, + '👨🏻‍🌾': 7, + '👨🏻‍🍳': 7, + '👨🏻‍🍼': 7, + '👨🏻‍🎓': 7, + '👨🏻‍🎤': 7, + '👨🏻‍🎨': 7, + '👨🏻‍🏫': 7, + '👨🏻‍🏭': 7, + '👨🏻‍🐰‍👨🏼': 12, + '👨🏻‍🐰‍👨🏽': 12, + '👨🏻‍🐰‍👨🏾': 12, + '👨🏻‍🐰‍👨🏿': 12, + '👨🏻‍💻': 7, + '👨🏻‍💼': 7, + '👨🏻‍🔧': 7, + '👨🏻‍🔬': 7, + '👨🏻‍🚀': 7, + '👨🏻‍🚒': 7, + '👨🏻‍🤝‍👨🏼': 12, + '👨🏻‍🤝‍👨🏽': 12, + '👨🏻‍🤝‍👨🏾': 12, + '👨🏻‍🤝‍👨🏿': 12, + '👨🏻‍🦯': 7, + '👨🏻‍🦯‍➡️': 10, + '👨🏻‍🦰': 7, + '👨🏻‍🦱': 7, + '👨🏻‍🦲': 7, + '👨🏻‍🦳': 7, + '👨🏻‍🦼': 7, + '👨🏻‍🦼‍➡️': 10, + '👨🏻‍🦽': 7, + '👨🏻‍🦽‍➡️': 10, + '👨🏻‍🫯‍👨🏼': 11, + '👨🏻‍🫯‍👨🏽': 11, + '👨🏻‍🫯‍👨🏾': 11, + '👨🏻‍🫯‍👨🏿': 11, + '👨🏼‍⚕️': 7, + '👨🏼‍⚖️': 7, + '👨🏼‍✈️': 7, + '👨🏼‍❤️‍👨🏼': 12, + '👨🏼‍❤️‍💋‍👨🏼': 15, + '👨🏼‍❤️‍💋‍👨🏿': 15, + '👨🏼‍🌾': 7, + '👨🏼‍🍳': 7, + '👨🏼‍🍼': 7, + '👨🏼‍🎓': 7, + '👨🏼‍🎤': 7, + '👨🏼‍🎨': 7, + '👨🏼‍🏫': 7, + '👨🏼‍🏭': 7, + '👨🏼‍🐰‍👨🏻': 12, + '👨🏼‍🐰‍👨🏽': 12, + '👨🏼‍🐰‍👨🏿': 12, + '👨🏼‍💻': 7, + '👨🏼‍💼': 7, + '👨🏼‍🔧': 7, + '👨🏼‍🔬': 7, + '👨🏼‍🚀': 7, + '👨🏼‍🚒': 7, + '👨🏼‍🤝‍👨🏻': 12, + '👨🏼‍🤝‍👨🏽': 12, + '👨🏼‍🤝‍👨🏿': 12, + '👨🏼‍🦯': 7, + '👨🏼‍🦯‍➡️': 10, + '👨🏼‍🦰': 7, + '👨🏼‍🦱': 7, + '👨🏼‍🦲': 7, + '👨🏼‍🦳': 7, + '👨🏼‍🦼': 7, + '👨🏼‍🦽': 7, + '👨🏼‍🦽‍➡️': 10, + '👨🏼‍🫯‍👨🏻': 11, + '👨🏼‍🫯‍👨🏽': 11, + '👨🏼‍🫯‍👨🏾': 11, + '👨🏼‍🫯‍👨🏿': 11, + '👨🏽‍⚕️': 7, + '👨🏽‍⚖️': 7, + '👨🏽‍✈️': 7, + '👨🏽‍❤️‍👨🏻': 12, + '👨🏽‍❤️‍👨🏽': 12, + '👨🏽‍❤️‍👨🏿': 12, + '👨🏽‍❤️‍💋‍👨🏻': 15, + '👨🏽‍❤️‍💋‍👨🏽': 15, + '👨🏽‍❤️‍💋‍👨🏿': 15, + '👨🏽‍🌾': 7, + '👨🏽‍🍳': 7, + '👨🏽‍🍼': 7, + '👨🏽‍🎓': 7, + '👨🏽‍🎤': 7, + '👨🏽‍🎨': 7, + '👨🏽‍🏫': 7, + '👨🏽‍🏭': 7, + '👨🏽‍🐰‍👨🏻': 12, + '👨🏽‍🐰‍👨🏼': 12, + '👨🏽‍🐰‍👨🏾': 12, + '👨🏽‍🐰‍👨🏿': 12, + '👨🏽‍💻': 7, + '👨🏽‍💼': 7, + '👨🏽‍🔧': 7, + '👨🏽‍🔬': 7, + '👨🏽‍🚀': 7, + '👨🏽‍🚒': 7, + '👨🏽‍🤝‍👨🏻': 12, + '👨🏽‍🤝‍👨🏼': 12, + '👨🏽‍🤝‍👨🏾': 12, + '👨🏽‍🤝‍👨🏿': 12, + '👨🏽‍🦯': 7, + '👨🏽‍🦯‍➡️': 10, + '👨🏽‍🦰': 7, + '👨🏽‍🦱': 7, + '👨🏽‍🦲': 7, + '👨🏽‍🦳': 7, + '👨🏽‍🦼': 7, + '👨🏽‍🦼‍➡️': 10, + '👨🏽‍🦽': 7, + '👨🏽‍🦽‍➡️': 10, + '👨🏽‍🫯‍👨🏻': 11, + '👨🏽‍🫯‍👨🏼': 11, + '👨🏽‍🫯‍👨🏾': 11, + '👨🏽‍🫯‍👨🏿': 11, + '👨🏾‍⚕️': 7, + '👨🏾‍⚖️': 7, + '👨🏾‍✈️': 7, + '👨🏾‍❤️‍👨🏾': 12, + '👨🏾‍❤️‍💋‍👨🏻': 15, + '👨🏾‍❤️‍💋‍👨🏾': 15, + '👨🏾‍❤️‍💋‍👨🏿': 15, + '👨🏾‍🌾': 7, + '👨🏾‍🍳': 7, + '👨🏾‍🍼': 7, + '👨🏾‍🎓': 7, + '👨🏾‍🎤': 7, + '👨🏾‍🎨': 7, + '👨🏾‍🏫': 7, + '👨🏾‍🏭': 7, + '👨🏾‍🐰‍👨🏻': 12, + '👨🏾‍🐰‍👨🏽': 12, + '👨🏾‍🐰‍👨🏿': 12, + '👨🏾‍💻': 7, + '👨🏾‍💼': 7, + '👨🏾‍🔧': 7, + '👨🏾‍🔬': 7, + '👨🏾‍🚀': 7, + '👨🏾‍🚒': 7, + '👨🏾‍🤝‍👨🏻': 12, + '👨🏾‍🤝‍👨🏽': 12, + '👨🏾‍🤝‍👨🏿': 12, + '👨🏾‍🦯': 7, + '👨🏾‍🦯‍➡️': 10, + '👨🏾‍🦰': 7, + '👨🏾‍🦱': 7, + '👨🏾‍🦲': 7, + '👨🏾‍🦳': 7, + '👨🏾‍🦼': 7, + '👨🏾‍🦽': 7, + '👨🏾‍🦽‍➡️': 10, + '👨🏾‍🫯‍👨🏻': 11, + '👨🏾‍🫯‍👨🏼': 11, + '👨🏾‍🫯‍👨🏽': 11, + '👨🏾‍🫯‍👨🏿': 11, + '👨🏿‍⚕️': 7, + '👨🏿‍⚖️': 7, + '👨🏿‍✈️': 7, + '👨🏿‍❤️‍👨🏻': 12, + '👨🏿‍❤️‍👨🏽': 12, + '👨🏿‍❤️‍👨🏿': 12, + '👨🏿‍❤️‍💋‍👨🏻': 15, + '👨🏿‍❤️‍💋‍👨🏼': 15, + '👨🏿‍❤️‍💋‍👨🏽': 15, + '👨🏿‍❤️‍💋‍👨🏾': 15, + '👨🏿‍❤️‍💋‍👨🏿': 15, + '👨🏿‍🌾': 7, + '👨🏿‍🍳': 7, + '👨🏿‍🍼': 7, + '👨🏿‍🎓': 7, + '👨🏿‍🎤': 7, + '👨🏿‍🎨': 7, + '👨🏿‍🏫': 7, + '👨🏿‍🏭': 7, + '👨🏿‍🐰‍👨🏻': 12, + '👨🏿‍🐰‍👨🏼': 12, + '👨🏿‍🐰‍👨🏽': 12, + '👨🏿‍🐰‍👨🏾': 12, + '👨🏿‍💻': 7, + '👨🏿‍💼': 7, + '👨🏿‍🔧': 7, + '👨🏿‍🔬': 7, + '👨🏿‍🚀': 7, + '👨🏿‍🚒': 7, + '👨🏿‍🤝‍👨🏻': 12, + '👨🏿‍🤝‍👨🏼': 12, + '👨🏿‍🤝‍👨🏽': 12, + '👨🏿‍🤝‍👨🏾': 12, + '👨🏿‍🦯': 7, + '👨🏿‍🦯‍➡️': 10, + '👨🏿‍🦰': 7, + '👨🏿‍🦱': 7, + '👨🏿‍🦲': 7, + '👨🏿‍🦳': 7, + '👨🏿‍🦼': 7, + '👨🏿‍🦼‍➡️': 10, + '👨🏿‍🦽': 7, + '👨🏿‍🦽‍➡️': 10, + '👨🏿‍🫯‍👨🏻': 11, + '👨🏿‍🫯‍👨🏼': 11, + '👨🏿‍🫯‍👨🏽': 11, + '👨🏿‍🫯‍👨🏾': 11, + '👩‍⚕️': 5, + '👩‍⚖️': 5, + '👩‍✈️': 5, + '👩‍❤️‍👨': 8, + '👩‍❤️‍👩': 8, + '👩‍❤️‍💋‍👨': 11, + '👩‍❤️‍💋‍👩': 11, + '👩‍🌾': 5, + '👩‍🍳': 5, + '👩‍🍼': 5, + '👩‍🎓': 5, + '👩‍🎤': 5, + '👩‍🎨': 5, + '👩‍🏫': 5, + '👩‍🏭': 5, + '👩‍👦': 5, + '👩‍👦‍👦': 8, + '👩‍👧': 5, + '👩‍👧‍👦': 8, + '👩‍👧‍👧': 8, + '👩‍👩‍👦': 8, + '👩‍👩‍👦‍👦': 11, + '👩‍👩‍👧': 8, + '👩‍👩‍👧‍👦': 11, + '👩‍👩‍👧‍👧': 11, + '👩‍💻': 5, + '👩‍💼': 5, + '👩‍🔧': 5, + '👩‍🔬': 5, + '👩‍🚀': 5, + '👩‍🚒': 5, + '👩‍🦯': 5, + '👩‍🦯‍➡️': 8, + '👩‍🦰': 5, + '👩‍🦱': 5, + '👩‍🦲': 5, + '👩‍🦳': 5, + '👩‍🦼': 5, + '👩‍🦼‍➡️': 8, + '👩‍🦽': 5, + '👩‍🦽‍➡️': 8, + '👩🏻‍⚕️': 7, + '👩🏻‍⚖️': 7, + '👩🏻‍✈️': 7, + '👩🏻‍❤️‍👨🏻': 12, + '👩🏻‍❤️‍👨🏿': 12, + '👩🏻‍❤️‍👩🏻': 12, + '👩🏻‍❤️‍💋‍👨🏻': 15, + '👩🏻‍❤️‍💋‍👨🏽': 15, + '👩🏻‍❤️‍💋‍👨🏿': 15, + '👩🏻‍❤️‍💋‍👩🏻': 15, + '👩🏻‍❤️‍💋‍👩🏽': 15, + '👩🏻‍❤️‍💋‍👩🏿': 15, + '👩🏻‍🌾': 7, + '👩🏻‍🍳': 7, + '👩🏻‍🍼': 7, + '👩🏻‍🎓': 7, + '👩🏻‍🎤': 7, + '👩🏻‍🎨': 7, + '👩🏻‍🏫': 7, + '👩🏻‍🏭': 7, + '👩🏻‍🐰‍👩🏼': 12, + '👩🏻‍🐰‍👩🏽': 12, + '👩🏻‍🐰‍👩🏾': 12, + '👩🏻‍🐰‍👩🏿': 12, + '👩🏻‍💻': 7, + '👩🏻‍💼': 7, + '👩🏻‍🔧': 7, + '👩🏻‍🔬': 7, + '👩🏻‍🚀': 7, + '👩🏻‍🚒': 7, + '👩🏻‍🤝‍👨🏽': 12, + '👩🏻‍🤝‍👨🏿': 12, + '👩🏻‍🤝‍👩🏼': 12, + '👩🏻‍🤝‍👩🏽': 12, + '👩🏻‍🤝‍👩🏾': 12, + '👩🏻‍🤝‍👩🏿': 12, + '👩🏻‍🦯': 7, + '👩🏻‍🦯‍➡️': 10, + '👩🏻‍🦰': 7, + '👩🏻‍🦱': 7, + '👩🏻‍🦲': 7, + '👩🏻‍🦳': 7, + '👩🏻‍🦼': 7, + '👩🏻‍🦼‍➡️': 10, + '👩🏻‍🦽': 7, + '👩🏻‍🦽‍➡️': 10, + '👩🏻‍🫯‍👩🏼': 11, + '👩🏻‍🫯‍👩🏽': 11, + '👩🏻‍🫯‍👩🏾': 11, + '👩🏻‍🫯‍👩🏿': 11, + '👩🏼‍⚕️': 7, + '👩🏼‍⚖️': 7, + '👩🏼‍✈️': 7, + '👩🏼‍❤️‍👨🏼': 12, + '👩🏼‍❤️‍👩🏼': 12, + '👩🏼‍❤️‍💋‍👨🏼': 15, + '👩🏼‍❤️‍💋‍👩🏼': 15, + '👩🏼‍🌾': 7, + '👩🏼‍🍳': 7, + '👩🏼‍🍼': 7, + '👩🏼‍🎓': 7, + '👩🏼‍🎤': 7, + '👩🏼‍🎨': 7, + '👩🏼‍🏫': 7, + '👩🏼‍🏭': 7, + '👩🏼‍🐰‍👩🏻': 12, + '👩🏼‍🐰‍👩🏿': 12, + '👩🏼‍💻': 7, + '👩🏼‍💼': 7, + '👩🏼‍🔧': 7, + '👩🏼‍🔬': 7, + '👩🏼‍🚀': 7, + '👩🏼‍🚒': 7, + '👩🏼‍🤝‍👩🏻': 12, + '👩🏼‍🤝‍👩🏽': 12, + '👩🏼‍🤝‍👩🏿': 12, + '👩🏼‍🦯': 7, + '👩🏼‍🦯‍➡️': 10, + '👩🏼‍🦰': 7, + '👩🏼‍🦱': 7, + '👩🏼‍🦲': 7, + '👩🏼‍🦳': 7, + '👩🏼‍🦼': 7, + '👩🏼‍🦽': 7, + '👩🏼‍🫯‍👩🏻': 11, + '👩🏼‍🫯‍👩🏽': 11, + '👩🏼‍🫯‍👩🏾': 11, + '👩🏼‍🫯‍👩🏿': 11, + '👩🏽‍⚕️': 7, + '👩🏽‍⚖️': 7, + '👩🏽‍✈️': 7, + '👩🏽‍❤️‍👨🏽': 12, + '👩🏽‍❤️‍👩🏽': 12, + '👩🏽‍❤️‍💋‍👨🏻': 15, + '👩🏽‍❤️‍💋‍👨🏽': 15, + '👩🏽‍❤️‍💋‍👨🏿': 15, + '👩🏽‍❤️‍💋‍👩🏻': 15, + '👩🏽‍❤️‍💋‍👩🏽': 15, + '👩🏽‍❤️‍💋‍👩🏿': 15, + '👩🏽‍🌾': 7, + '👩🏽‍🍳': 7, + '👩🏽‍🍼': 7, + '👩🏽‍🎓': 7, + '👩🏽‍🎤': 7, + '👩🏽‍🎨': 7, + '👩🏽‍🏫': 7, + '👩🏽‍🏭': 7, + '👩🏽‍🐰‍👩🏻': 12, + '👩🏽‍🐰‍👩🏾': 12, + '👩🏽‍🐰‍👩🏿': 12, + '👩🏽‍💻': 7, + '👩🏽‍💼': 7, + '👩🏽‍🔧': 7, + '👩🏽‍🔬': 7, + '👩🏽‍🚀': 7, + '👩🏽‍🚒': 7, + '👩🏽‍🤝‍👨🏻': 12, + '👩🏽‍🤝‍👨🏿': 12, + '👩🏽‍🤝‍👩🏻': 12, + '👩🏽‍🤝‍👩🏼': 12, + '👩🏽‍🤝‍👩🏾': 12, + '👩🏽‍🤝‍👩🏿': 12, + '👩🏽‍🦯': 7, + '👩🏽‍🦯‍➡️': 10, + '👩🏽‍🦰': 7, + '👩🏽‍🦱': 7, + '👩🏽‍🦲': 7, + '👩🏽‍🦳': 7, + '👩🏽‍🦼': 7, + '👩🏽‍🦼‍➡️': 10, + '👩🏽‍🦽': 7, + '👩🏽‍🦽‍➡️': 10, + '👩🏽‍🫯‍👩🏻': 11, + '👩🏽‍🫯‍👩🏼': 11, + '👩🏽‍🫯‍👩🏾': 11, + '👩🏽‍🫯‍👩🏿': 11, + '👩🏾‍⚕️': 7, + '👩🏾‍⚖️': 7, + '👩🏾‍✈️': 7, + '👩🏾‍❤️‍👨🏾': 12, + '👩🏾‍❤️‍👩🏾': 12, + '👩🏾‍❤️‍💋‍👨🏾': 15, + '👩🏾‍❤️‍💋‍👩🏾': 15, + '👩🏾‍🌾': 7, + '👩🏾‍🍳': 7, + '👩🏾‍🍼': 7, + '👩🏾‍🎓': 7, + '👩🏾‍🎤': 7, + '👩🏾‍🎨': 7, + '👩🏾‍🏫': 7, + '👩🏾‍🏭': 7, + '👩🏾‍🐰‍👩🏻': 12, + '👩🏾‍🐰‍👩🏽': 12, + '👩🏾‍🐰‍👩🏿': 12, + '👩🏾‍💻': 7, + '👩🏾‍💼': 7, + '👩🏾‍🔧': 7, + '👩🏾‍🔬': 7, + '👩🏾‍🚀': 7, + '👩🏾‍🚒': 7, + '👩🏾‍🤝‍👩🏻': 12, + '👩🏾‍🤝‍👩🏽': 12, + '👩🏾‍🤝‍👩🏿': 12, + '👩🏾‍🦯': 7, + '👩🏾‍🦯‍➡️': 10, + '👩🏾‍🦰': 7, + '👩🏾‍🦱': 7, + '👩🏾‍🦲': 7, + '👩🏾‍🦳': 7, + '👩🏾‍🦼': 7, + '👩🏾‍🦽': 7, + '👩🏾‍🦽‍➡️': 10, + '👩🏾‍🫯‍👩🏻': 11, + '👩🏾‍🫯‍👩🏼': 11, + '👩🏾‍🫯‍👩🏽': 11, + '👩🏾‍🫯‍👩🏿': 11, + '👩🏿‍⚕️': 7, + '👩🏿‍⚖️': 7, + '👩🏿‍✈️': 7, + '👩🏿‍❤️‍👨🏻': 12, + '👩🏿‍❤️‍👨🏿': 12, + '👩🏿‍❤️‍👩🏿': 12, + '👩🏿‍❤️‍💋‍👨🏻': 15, + '👩🏿‍❤️‍💋‍👨🏽': 15, + '👩🏿‍❤️‍💋‍👨🏿': 15, + '👩🏿‍❤️‍💋‍👩🏻': 15, + '👩🏿‍❤️‍💋‍👩🏽': 15, + '👩🏿‍❤️‍💋‍👩🏿': 15, + '👩🏿‍🌾': 7, + '👩🏿‍🍳': 7, + '👩🏿‍🍼': 7, + '👩🏿‍🎓': 7, + '👩🏿‍🎤': 7, + '👩🏿‍🎨': 7, + '👩🏿‍🏫': 7, + '👩🏿‍🏭': 7, + '👩🏿‍🐰‍👩🏻': 12, + '👩🏿‍🐰‍👩🏼': 12, + '👩🏿‍🐰‍👩🏽': 12, + '👩🏿‍🐰‍👩🏾': 12, + '👩🏿‍💻': 7, + '👩🏿‍💼': 7, + '👩🏿‍🔧': 7, + '👩🏿‍🔬': 7, + '👩🏿‍🚀': 7, + '👩🏿‍🚒': 7, + '👩🏿‍🤝‍👨🏻': 12, + '👩🏿‍🤝‍👨🏽': 12, + '👩🏿‍🤝‍👩🏻': 12, + '👩🏿‍🤝‍👩🏼': 12, + '👩🏿‍🤝‍👩🏽': 12, + '👩🏿‍🤝‍👩🏾': 12, + '👩🏿‍🦯': 7, + '👩🏿‍🦯‍➡️': 10, + '👩🏿‍🦰': 7, + '👩🏿‍🦱': 7, + '👩🏿‍🦲': 7, + '👩🏿‍🦳': 7, + '👩🏿‍🦼': 7, + '👩🏿‍🦼‍➡️': 10, + '👩🏿‍🦽': 7, + '👩🏿‍🦽‍➡️': 10, + '👩🏿‍🫯‍👩🏻': 11, + '👩🏿‍🫯‍👩🏼': 11, + '👩🏿‍🫯‍👩🏽': 11, + '👩🏿‍🫯‍👩🏾': 11, + '👮‍♀️': 5, + '👮‍♂️': 5, + '👮🏻‍♀️': 7, + '👮🏻‍♂️': 7, + '👮🏼‍♀️': 7, + '👮🏼‍♂️': 7, + '👮🏽‍♀️': 7, + '👮🏽‍♂️': 7, + '👮🏾‍♀️': 7, + '👮🏾‍♂️': 7, + '👮🏿‍♀️': 7, + '👮🏿‍♂️': 7, + '👯‍♀️': 5, + '👯‍♂️': 5, + '👯🏻‍♀️': 7, + '👯🏻‍♂️': 7, + '👯🏼‍♀️': 7, + '👯🏼‍♂️': 7, + '👯🏽‍♀️': 7, + '👯🏽‍♂️': 7, + '👯🏾‍♀️': 7, + '👯🏾‍♂️': 7, + '👯🏿‍♀️': 7, + '👯🏿‍♂️': 7, + '👰‍♀️': 5, + '👰‍♂️': 5, + '👰🏻‍♀️': 7, + '👰🏻‍♂️': 7, + '👰🏼‍♀️': 7, + '👰🏼‍♂️': 7, + '👰🏽‍♀️': 7, + '👰🏽‍♂️': 7, + '👰🏾‍♀️': 7, + '👰🏾‍♂️': 7, + '👰🏿‍♀️': 7, + '👰🏿‍♂️': 7, + '👱‍♀️': 5, + '👱‍♂️': 5, + '👱🏻‍♀️': 7, + '👱🏻‍♂️': 7, + '👱🏼‍♀️': 7, + '👱🏼‍♂️': 7, + '👱🏽‍♀️': 7, + '👱🏽‍♂️': 7, + '👱🏾‍♀️': 7, + '👱🏾‍♂️': 7, + '👱🏿‍♀️': 7, + '👱🏿‍♂️': 7, + '👳‍♀️': 5, + '👳‍♂️': 5, + '👳🏻‍♀️': 7, + '👳🏻‍♂️': 7, + '👳🏼‍♀️': 7, + '👳🏼‍♂️': 7, + '👳🏽‍♀️': 7, + '👳🏽‍♂️': 7, + '👳🏾‍♀️': 7, + '👳🏾‍♂️': 7, + '👳🏿‍♀️': 7, + '👳🏿‍♂️': 7, + '👷‍♀️': 5, + '👷‍♂️': 5, + '👷🏻‍♀️': 7, + '👷🏻‍♂️': 7, + '👷🏼‍♀️': 7, + '👷🏼‍♂️': 7, + '👷🏽‍♀️': 7, + '👷🏽‍♂️': 7, + '👷🏾‍♀️': 7, + '👷🏾‍♂️': 7, + '👷🏿‍♀️': 7, + '👷🏿‍♂️': 7, + '💁‍♀️': 5, + '💁‍♂️': 5, + '💁🏻‍♀️': 7, + '💁🏻‍♂️': 7, + '💁🏼‍♀️': 7, + '💁🏼‍♂️': 7, + '💁🏽‍♀️': 7, + '💁🏽‍♂️': 7, + '💁🏾‍♀️': 7, + '💁🏾‍♂️': 7, + '💁🏿‍♀️': 7, + '💁🏿‍♂️': 7, + '💂‍♀️': 5, + '💂‍♂️': 5, + '💂🏻‍♀️': 7, + '💂🏻‍♂️': 7, + '💂🏼‍♀️': 7, + '💂🏼‍♂️': 7, + '💂🏽‍♀️': 7, + '💂🏽‍♂️': 7, + '💂🏾‍♀️': 7, + '💂🏾‍♂️': 7, + '💂🏿‍♀️': 7, + '💂🏿‍♂️': 7, + '💆‍♀️': 5, + '💆‍♂️': 5, + '💆🏻‍♀️': 7, + '💆🏻‍♂️': 7, + '💆🏼‍♀️': 7, + '💆🏼‍♂️': 7, + '💆🏽‍♀️': 7, + '💆🏽‍♂️': 7, + '💆🏾‍♀️': 7, + '💆🏾‍♂️': 7, + '💆🏿‍♀️': 7, + '💆🏿‍♂️': 7, + '💇‍♀️': 5, + '💇‍♂️': 5, + '💇🏻‍♀️': 7, + '💇🏻‍♂️': 7, + '💇🏼‍♀️': 7, + '💇🏼‍♂️': 7, + '💇🏽‍♀️': 7, + '💇🏽‍♂️': 7, + '💇🏾‍♀️': 7, + '💇🏾‍♂️': 7, + '💇🏿‍♀️': 7, + '💇🏿‍♂️': 7, + '🕵️‍♀️': 5, + '🕵️‍♂️': 5, + '🕵🏻‍♀️': 6, + '🕵🏻‍♂️': 6, + '🕵🏼‍♀️': 6, + '🕵🏼‍♂️': 6, + '🕵🏽‍♀️': 6, + '🕵🏽‍♂️': 6, + '🕵🏾‍♀️': 6, + '🕵🏾‍♂️': 6, + '🕵🏿‍♀️': 6, + '🕵🏿‍♂️': 6, + '😮‍💨': 5, + '😵‍💫': 5, + '😶‍🌫️': 5, + '🙂‍↔️': 5, + '🙂‍↕️': 5, + '🙅‍♀️': 5, + '🙅‍♂️': 5, + '🙅🏻‍♀️': 7, + '🙅🏻‍♂️': 7, + '🙅🏼‍♀️': 7, + '🙅🏼‍♂️': 7, + '🙅🏽‍♀️': 7, + '🙅🏽‍♂️': 7, + '🙅🏾‍♀️': 7, + '🙅🏾‍♂️': 7, + '🙅🏿‍♀️': 7, + '🙅🏿‍♂️': 7, + '🙆‍♀️': 5, + '🙆‍♂️': 5, + '🙆🏻‍♀️': 7, + '🙆🏻‍♂️': 7, + '🙆🏼‍♀️': 7, + '🙆🏼‍♂️': 7, + '🙆🏽‍♀️': 7, + '🙆🏽‍♂️': 7, + '🙆🏾‍♀️': 7, + '🙆🏾‍♂️': 7, + '🙆🏿‍♀️': 7, + '🙆🏿‍♂️': 7, + '🙇‍♀️': 5, + '🙇‍♂️': 5, + '🙇🏻‍♀️': 7, + '🙇🏻‍♂️': 7, + '🙇🏼‍♀️': 7, + '🙇🏼‍♂️': 7, + '🙇🏽‍♀️': 7, + '🙇🏽‍♂️': 7, + '🙇🏾‍♀️': 7, + '🙇🏾‍♂️': 7, + '🙇🏿‍♀️': 7, + '🙇🏿‍♂️': 7, + '🙋‍♀️': 5, + '🙋‍♂️': 5, + '🙋🏻‍♀️': 7, + '🙋🏻‍♂️': 7, + '🙋🏼‍♀️': 7, + '🙋🏼‍♂️': 7, + '🙋🏽‍♀️': 7, + '🙋🏽‍♂️': 7, + '🙋🏾‍♀️': 7, + '🙋🏾‍♂️': 7, + '🙋🏿‍♀️': 7, + '🙋🏿‍♂️': 7, + '🙍‍♀️': 5, + '🙍‍♂️': 5, + '🙍🏻‍♀️': 7, + '🙍🏻‍♂️': 7, + '🙍🏼‍♀️': 7, + '🙍🏼‍♂️': 7, + '🙍🏽‍♀️': 7, + '🙍🏽‍♂️': 7, + '🙍🏾‍♀️': 7, + '🙍🏾‍♂️': 7, + '🙍🏿‍♀️': 7, + '🙍🏿‍♂️': 7, + '🙎‍♀️': 5, + '🙎‍♂️': 5, + '🙎🏻‍♀️': 7, + '🙎🏻‍♂️': 7, + '🙎🏼‍♀️': 7, + '🙎🏼‍♂️': 7, + '🙎🏽‍♀️': 7, + '🙎🏽‍♂️': 7, + '🙎🏾‍♀️': 7, + '🙎🏾‍♂️': 7, + '🙎🏿‍♀️': 7, + '🙎🏿‍♂️': 7, + '🚣‍♀️': 5, + '🚣‍♂️': 5, + '🚣🏻‍♀️': 7, + '🚣🏻‍♂️': 7, + '🚣🏼‍♀️': 7, + '🚣🏼‍♂️': 7, + '🚣🏽‍♀️': 7, + '🚣🏽‍♂️': 7, + '🚣🏾‍♀️': 7, + '🚣🏾‍♂️': 7, + '🚣🏿‍♀️': 7, + '🚣🏿‍♂️': 7, + '🚴‍♀️': 5, + '🚴‍♂️': 5, + '🚴🏻‍♀️': 7, + '🚴🏻‍♂️': 7, + '🚴🏼‍♀️': 7, + '🚴🏼‍♂️': 7, + '🚴🏽‍♀️': 7, + '🚴🏽‍♂️': 7, + '🚴🏾‍♀️': 7, + '🚴🏾‍♂️': 7, + '🚴🏿‍♀️': 7, + '🚴🏿‍♂️': 7, + '🚵‍♀️': 5, + '🚵‍♂️': 5, + '🚵🏻‍♀️': 7, + '🚵🏻‍♂️': 7, + '🚵🏼‍♀️': 7, + '🚵🏼‍♂️': 7, + '🚵🏽‍♀️': 7, + '🚵🏽‍♂️': 7, + '🚵🏾‍♀️': 7, + '🚵🏾‍♂️': 7, + '🚵🏿‍♀️': 7, + '🚵🏿‍♂️': 7, + '🚶‍♀️': 5, + '🚶‍♀️‍➡️': 8, + '🚶‍♂️': 5, + '🚶‍♂️‍➡️': 8, + '🚶‍➡️': 5, + '🚶🏻‍♀️': 7, + '🚶🏻‍♀️‍➡️': 10, + '🚶🏻‍♂️': 7, + '🚶🏻‍♂️‍➡️': 10, + '🚶🏻‍➡️': 7, + '🚶🏼‍♀️': 7, + '🚶🏼‍♀️‍➡️': 10, + '🚶🏼‍♂️': 7, + '🚶🏼‍♂️‍➡️': 10, + '🚶🏼‍➡️': 7, + '🚶🏽‍♀️': 7, + '🚶🏽‍♀️‍➡️': 10, + '🚶🏽‍♂️': 7, + '🚶🏽‍♂️‍➡️': 10, + '🚶🏽‍➡️': 7, + '🚶🏾‍♀️': 7, + '🚶🏾‍♀️‍➡️': 10, + '🚶🏾‍♂️': 7, + '🚶🏾‍♂️‍➡️': 10, + '🚶🏾‍➡️': 7, + '🚶🏿‍♀️': 7, + '🚶🏿‍♀️‍➡️': 10, + '🚶🏿‍♂️': 7, + '🚶🏿‍♂️‍➡️': 10, + '🚶🏿‍➡️': 7, + '🤦‍♀️': 5, + '🤦‍♂️': 5, + '🤦🏻‍♀️': 7, + '🤦🏻‍♂️': 7, + '🤦🏼‍♀️': 7, + '🤦🏼‍♂️': 7, + '🤦🏽‍♀️': 7, + '🤦🏽‍♂️': 7, + '🤦🏾‍♀️': 7, + '🤦🏾‍♂️': 7, + '🤦🏿‍♀️': 7, + '🤦🏿‍♂️': 7, + '🤵‍♀️': 5, + '🤵‍♂️': 5, + '🤵🏻‍♀️': 7, + '🤵🏻‍♂️': 7, + '🤵🏼‍♀️': 7, + '🤵🏼‍♂️': 7, + '🤵🏽‍♀️': 7, + '🤵🏽‍♂️': 7, + '🤵🏾‍♀️': 7, + '🤵🏾‍♂️': 7, + '🤵🏿‍♀️': 7, + '🤵🏿‍♂️': 7, + '🤷‍♀️': 5, + '🤷‍♂️': 5, + '🤷🏻‍♀️': 7, + '🤷🏻‍♂️': 7, + '🤷🏼‍♀️': 7, + '🤷🏼‍♂️': 7, + '🤷🏽‍♀️': 7, + '🤷🏽‍♂️': 7, + '🤷🏾‍♀️': 7, + '🤷🏾‍♂️': 7, + '🤷🏿‍♀️': 7, + '🤷🏿‍♂️': 7, + '🤸‍♀️': 5, + '🤸‍♂️': 5, + '🤸🏻‍♀️': 7, + '🤸🏻‍♂️': 7, + '🤸🏼‍♀️': 7, + '🤸🏼‍♂️': 7, + '🤸🏽‍♀️': 7, + '🤸🏽‍♂️': 7, + '🤸🏾‍♀️': 7, + '🤸🏾‍♂️': 7, + '🤸🏿‍♀️': 7, + '🤸🏿‍♂️': 7, + '🤹‍♀️': 5, + '🤹‍♂️': 5, + '🤹🏻‍♀️': 7, + '🤹🏻‍♂️': 7, + '🤹🏼‍♀️': 7, + '🤹🏼‍♂️': 7, + '🤹🏽‍♀️': 7, + '🤹🏽‍♂️': 7, + '🤹🏾‍♀️': 7, + '🤹🏾‍♂️': 7, + '🤹🏿‍♀️': 7, + '🤹🏿‍♂️': 7, + '🤼‍♀️': 5, + '🤼‍♂️': 5, + '🤼🏻‍♀️': 7, + '🤼🏻‍♂️': 7, + '🤼🏼‍♀️': 7, + '🤼🏼‍♂️': 7, + '🤼🏽‍♀️': 7, + '🤼🏽‍♂️': 7, + '🤼🏾‍♀️': 7, + '🤼🏾‍♂️': 7, + '🤼🏿‍♀️': 7, + '🤼🏿‍♂️': 7, + '🤽‍♀️': 5, + '🤽‍♂️': 5, + '🤽🏻‍♀️': 7, + '🤽🏻‍♂️': 7, + '🤽🏼‍♀️': 7, + '🤽🏼‍♂️': 7, + '🤽🏽‍♀️': 7, + '🤽🏽‍♂️': 7, + '🤽🏾‍♀️': 7, + '🤽🏾‍♂️': 7, + '🤽🏿‍♀️': 7, + '🤽🏿‍♂️': 7, + '🤾‍♀️': 5, + '🤾‍♂️': 5, + '🤾🏻‍♀️': 7, + '🤾🏻‍♂️': 7, + '🤾🏼‍♀️': 7, + '🤾🏼‍♂️': 7, + '🤾🏽‍♀️': 7, + '🤾🏽‍♂️': 7, + '🤾🏾‍♀️': 7, + '🤾🏾‍♂️': 7, + '🤾🏿‍♀️': 7, + '🤾🏿‍♂️': 7, + '🦸‍♀️': 5, + '🦸‍♂️': 5, + '🦸🏻‍♀️': 7, + '🦸🏻‍♂️': 7, + '🦸🏼‍♀️': 7, + '🦸🏼‍♂️': 7, + '🦸🏽‍♀️': 7, + '🦸🏽‍♂️': 7, + '🦸🏾‍♀️': 7, + '🦸🏾‍♂️': 7, + '🦸🏿‍♀️': 7, + '🦸🏿‍♂️': 7, + '🦹‍♀️': 5, + '🦹‍♂️': 5, + '🦹🏻‍♀️': 7, + '🦹🏻‍♂️': 7, + '🦹🏼‍♀️': 7, + '🦹🏼‍♂️': 7, + '🦹🏽‍♀️': 7, + '🦹🏽‍♂️': 7, + '🦹🏾‍♀️': 7, + '🦹🏾‍♂️': 7, + '🦹🏿‍♀️': 7, + '🦹🏿‍♂️': 7, + '🧍‍♀️': 5, + '🧍‍♂️': 5, + '🧍🏻‍♀️': 7, + '🧍🏻‍♂️': 7, + '🧍🏼‍♀️': 7, + '🧍🏼‍♂️': 7, + '🧍🏽‍♀️': 7, + '🧍🏽‍♂️': 7, + '🧍🏾‍♀️': 7, + '🧍🏾‍♂️': 7, + '🧍🏿‍♀️': 7, + '🧍🏿‍♂️': 7, + '🧎‍♀️': 5, + '🧎‍♀️‍➡️': 8, + '🧎‍♂️': 5, + '🧎‍♂️‍➡️': 8, + '🧎‍➡️': 5, + '🧎🏻‍♀️': 7, + '🧎🏻‍♀️‍➡️': 10, + '🧎🏻‍♂️': 7, + '🧎🏻‍♂️‍➡️': 10, + '🧎🏻‍➡️': 7, + '🧎🏼‍♀️': 7, + '🧎🏼‍♀️‍➡️': 10, + '🧎🏼‍♂️': 7, + '🧎🏼‍♂️‍➡️': 10, + '🧎🏼‍➡️': 7, + '🧎🏽‍♀️': 7, + '🧎🏽‍♀️‍➡️': 10, + '🧎🏽‍♂️': 7, + '🧎🏽‍♂️‍➡️': 10, + '🧎🏽‍➡️': 7, + '🧎🏾‍♀️': 7, + '🧎🏾‍♀️‍➡️': 10, + '🧎🏾‍♂️': 7, + '🧎🏾‍♂️‍➡️': 10, + '🧎🏾‍➡️': 7, + '🧎🏿‍♀️': 7, + '🧎🏿‍♀️‍➡️': 10, + '🧎🏿‍♂️': 7, + '🧎🏿‍♂️‍➡️': 10, + '🧎🏿‍➡️': 7, + '🧏‍♀️': 5, + '🧏‍♂️': 5, + '🧏🏻‍♀️': 7, + '🧏🏻‍♂️': 7, + '🧏🏼‍♀️': 7, + '🧏🏼‍♂️': 7, + '🧏🏽‍♀️': 7, + '🧏🏽‍♂️': 7, + '🧏🏾‍♀️': 7, + '🧏🏾‍♂️': 7, + '🧏🏿‍♀️': 7, + '🧏🏿‍♂️': 7, + '🧑‍⚕️': 5, + '🧑‍⚖️': 5, + '🧑‍✈️': 5, + '🧑‍🌾': 5, + '🧑‍🍳': 5, + '🧑‍🍼': 5, + '🧑‍🎄': 5, + '🧑‍🎓': 5, + '🧑‍🎤': 5, + '🧑‍🎨': 5, + '🧑‍🏫': 5, + '🧑‍🏭': 5, + '🧑‍💻': 5, + '🧑‍💼': 5, + '🧑‍🔧': 5, + '🧑‍🔬': 5, + '🧑‍🚀': 5, + '🧑‍🚒': 5, + '🧑‍🤝‍🧑': 8, + '🧑‍🦯': 5, + '🧑‍🦯‍➡️': 8, + '🧑‍🦰': 5, + '🧑‍🦱': 5, + '🧑‍🦲': 5, + '🧑‍🦳': 5, + '🧑‍🦼': 5, + '🧑‍🦼‍➡️': 8, + '🧑‍🦽': 5, + '🧑‍🦽‍➡️': 8, + '🧑‍🧑‍🧒': 8, + '🧑‍🧑‍🧒‍🧒': 11, + '🧑‍🧒': 5, + '🧑‍🧒‍🧒': 8, + '🧑‍🩰': 5, + '🧑🏻‍⚕️': 7, + '🧑🏻‍⚖️': 7, + '🧑🏻‍✈️': 7, + '🧑🏻‍❤️‍💋‍🧑🏿': 15, + '🧑🏻‍🌾': 7, + '🧑🏻‍🍳': 7, + '🧑🏻‍🍼': 7, + '🧑🏻‍🎄': 7, + '🧑🏻‍🎓': 7, + '🧑🏻‍🎤': 7, + '🧑🏻‍🎨': 7, + '🧑🏻‍🏫': 7, + '🧑🏻‍🏭': 7, + '🧑🏻‍🐰‍🧑🏽': 12, + '🧑🏻‍🐰‍🧑🏾': 12, + '🧑🏻‍🐰‍🧑🏿': 12, + '🧑🏻‍💻': 7, + '🧑🏻‍💼': 7, + '🧑🏻‍🔧': 7, + '🧑🏻‍🔬': 7, + '🧑🏻‍🚀': 7, + '🧑🏻‍🚒': 7, + '🧑🏻‍🤝‍🧑🏻': 12, + '🧑🏻‍🤝‍🧑🏼': 12, + '🧑🏻‍🤝‍🧑🏽': 12, + '🧑🏻‍🤝‍🧑🏾': 12, + '🧑🏻‍🤝‍🧑🏿': 12, + '🧑🏻‍🦯': 7, + '🧑🏻‍🦯‍➡️': 10, + '🧑🏻‍🦰': 7, + '🧑🏻‍🦱': 7, + '🧑🏻‍🦲': 7, + '🧑🏻‍🦳': 7, + '🧑🏻‍🦼': 7, + '🧑🏻‍🦼‍➡️': 10, + '🧑🏻‍🦽': 7, + '🧑🏻‍🦽‍➡️': 10, + '🧑🏻‍🩰': 7, + '🧑🏻‍🫯‍🧑🏼': 11, + '🧑🏻‍🫯‍🧑🏽': 11, + '🧑🏻‍🫯‍🧑🏾': 11, + '🧑🏻‍🫯‍🧑🏿': 11, + '🧑🏼‍⚕️': 7, + '🧑🏼‍⚖️': 7, + '🧑🏼‍✈️': 7, + '🧑🏼‍🌾': 7, + '🧑🏼‍🍳': 7, + '🧑🏼‍🍼': 7, + '🧑🏼‍🎄': 7, + '🧑🏼‍🎓': 7, + '🧑🏼‍🎤': 7, + '🧑🏼‍🎨': 7, + '🧑🏼‍🏫': 7, + '🧑🏼‍🏭': 7, + '🧑🏼‍🐰‍🧑🏿': 12, + '🧑🏼‍💻': 7, + '🧑🏼‍💼': 7, + '🧑🏼‍🔧': 7, + '🧑🏼‍🔬': 7, + '🧑🏼‍🚀': 7, + '🧑🏼‍🚒': 7, + '🧑🏼‍🤝‍🧑🏻': 12, + '🧑🏼‍🤝‍🧑🏼': 12, + '🧑🏼‍🤝‍🧑🏽': 12, + '🧑🏼‍🤝‍🧑🏿': 12, + '🧑🏼‍🦯': 7, + '🧑🏼‍🦯‍➡️': 10, + '🧑🏼‍🦰': 7, + '🧑🏼‍🦱': 7, + '🧑🏼‍🦲': 7, + '🧑🏼‍🦳': 7, + '🧑🏼‍🦼': 7, + '🧑🏼‍🦽': 7, + '🧑🏼‍🩰': 7, + '🧑🏼‍🫯‍🧑🏻': 11, + '🧑🏼‍🫯‍🧑🏽': 11, + '🧑🏼‍🫯‍🧑🏿': 11, + '🧑🏽‍⚕️': 7, + '🧑🏽‍⚖️': 7, + '🧑🏽‍✈️': 7, + '🧑🏽‍❤️‍💋‍🧑🏿': 15, + '🧑🏽‍🌾': 7, + '🧑🏽‍🍳': 7, + '🧑🏽‍🍼': 7, + '🧑🏽‍🎄': 7, + '🧑🏽‍🎓': 7, + '🧑🏽‍🎤': 7, + '🧑🏽‍🎨': 7, + '🧑🏽‍🏫': 7, + '🧑🏽‍🏭': 7, + '🧑🏽‍🐰‍🧑🏻': 12, + '🧑🏽‍🐰‍🧑🏿': 12, + '🧑🏽‍💻': 7, + '🧑🏽‍💼': 7, + '🧑🏽‍🔧': 7, + '🧑🏽‍🔬': 7, + '🧑🏽‍🚀': 7, + '🧑🏽‍🚒': 7, + '🧑🏽‍🤝‍🧑🏻': 12, + '🧑🏽‍🤝‍🧑🏼': 12, + '🧑🏽‍🤝‍🧑🏽': 12, + '🧑🏽‍🤝‍🧑🏾': 12, + '🧑🏽‍🤝‍🧑🏿': 12, + '🧑🏽‍🦯': 7, + '🧑🏽‍🦯‍➡️': 10, + '🧑🏽‍🦰': 7, + '🧑🏽‍🦱': 7, + '🧑🏽‍🦲': 7, + '🧑🏽‍🦳': 7, + '🧑🏽‍🦼': 7, + '🧑🏽‍🦼‍➡️': 10, + '🧑🏽‍🦽': 7, + '🧑🏽‍🦽‍➡️': 10, + '🧑🏽‍🩰': 7, + '🧑🏽‍🫯‍🧑🏻': 11, + '🧑🏽‍🫯‍🧑🏼': 11, + '🧑🏽‍🫯‍🧑🏾': 11, + '🧑🏽‍🫯‍🧑🏿': 11, + '🧑🏾‍⚕️': 7, + '🧑🏾‍⚖️': 7, + '🧑🏾‍✈️': 7, + '🧑🏾‍🌾': 7, + '🧑🏾‍🍳': 7, + '🧑🏾‍🍼': 7, + '🧑🏾‍🎄': 7, + '🧑🏾‍🎓': 7, + '🧑🏾‍🎤': 7, + '🧑🏾‍🎨': 7, + '🧑🏾‍🏫': 7, + '🧑🏾‍🏭': 7, + '🧑🏾‍🐰‍🧑🏻': 12, + '🧑🏾‍🐰‍🧑🏿': 12, + '🧑🏾‍💻': 7, + '🧑🏾‍💼': 7, + '🧑🏾‍🔧': 7, + '🧑🏾‍🔬': 7, + '🧑🏾‍🚀': 7, + '🧑🏾‍🚒': 7, + '🧑🏾‍🤝‍🧑🏻': 12, + '🧑🏾‍🤝‍🧑🏽': 12, + '🧑🏾‍🤝‍🧑🏾': 12, + '🧑🏾‍🤝‍🧑🏿': 12, + '🧑🏾‍🦯': 7, + '🧑🏾‍🦯‍➡️': 10, + '🧑🏾‍🦰': 7, + '🧑🏾‍🦱': 7, + '🧑🏾‍🦲': 7, + '🧑🏾‍🦳': 7, + '🧑🏾‍🦼': 7, + '🧑🏾‍🦽': 7, + '🧑🏾‍🩰': 7, + '🧑🏾‍🫯‍🧑🏻': 11, + '🧑🏾‍🫯‍🧑🏽': 11, + '🧑🏾‍🫯‍🧑🏿': 11, + '🧑🏿‍⚕️': 7, + '🧑🏿‍⚖️': 7, + '🧑🏿‍✈️': 7, + '🧑🏿‍❤️‍💋‍🧑🏻': 15, + '🧑🏿‍❤️‍💋‍🧑🏽': 15, + '🧑🏿‍🌾': 7, + '🧑🏿‍🍳': 7, + '🧑🏿‍🍼': 7, + '🧑🏿‍🎄': 7, + '🧑🏿‍🎓': 7, + '🧑🏿‍🎤': 7, + '🧑🏿‍🎨': 7, + '🧑🏿‍🏫': 7, + '🧑🏿‍🏭': 7, + '🧑🏿‍🐰‍🧑🏻': 12, + '🧑🏿‍🐰‍🧑🏼': 12, + '🧑🏿‍🐰‍🧑🏽': 12, + '🧑🏿‍🐰‍🧑🏾': 12, + '🧑🏿‍💻': 7, + '🧑🏿‍💼': 7, + '🧑🏿‍🔧': 7, + '🧑🏿‍🔬': 7, + '🧑🏿‍🚀': 7, + '🧑🏿‍🚒': 7, + '🧑🏿‍🤝‍🧑🏻': 12, + '🧑🏿‍🤝‍🧑🏼': 12, + '🧑🏿‍🤝‍🧑🏽': 12, + '🧑🏿‍🤝‍🧑🏾': 12, + '🧑🏿‍🤝‍🧑🏿': 12, + '🧑🏿‍🦯': 7, + '🧑🏿‍🦯‍➡️': 10, + '🧑🏿‍🦰': 7, + '🧑🏿‍🦱': 7, + '🧑🏿‍🦲': 7, + '🧑🏿‍🦳': 7, + '🧑🏿‍🦼': 7, + '🧑🏿‍🦼‍➡️': 10, + '🧑🏿‍🦽': 7, + '🧑🏿‍🦽‍➡️': 10, + '🧑🏿‍🩰': 7, + '🧑🏿‍🫯‍🧑🏻': 11, + '🧑🏿‍🫯‍🧑🏼': 11, + '🧑🏿‍🫯‍🧑🏽': 11, + '🧑🏿‍🫯‍🧑🏾': 11, + '🧔‍♀️': 5, + '🧔‍♂️': 5, + '🧔🏻‍♀️': 7, + '🧔🏻‍♂️': 7, + '🧔🏼‍♀️': 7, + '🧔🏼‍♂️': 7, + '🧔🏽‍♀️': 7, + '🧔🏽‍♂️': 7, + '🧔🏾‍♀️': 7, + '🧔🏾‍♂️': 7, + '🧔🏿‍♀️': 7, + '🧔🏿‍♂️': 7, + '🧖‍♀️': 5, + '🧖‍♂️': 5, + '🧖🏻‍♀️': 7, + '🧖🏻‍♂️': 7, + '🧖🏼‍♀️': 7, + '🧖🏼‍♂️': 7, + '🧖🏽‍♀️': 7, + '🧖🏽‍♂️': 7, + '🧖🏾‍♀️': 7, + '🧖🏾‍♂️': 7, + '🧖🏿‍♀️': 7, + '🧖🏿‍♂️': 7, + '🧗‍♀️': 5, + '🧗‍♂️': 5, + '🧗🏻‍♀️': 7, + '🧗🏻‍♂️': 7, + '🧗🏼‍♀️': 7, + '🧗🏼‍♂️': 7, + '🧗🏽‍♀️': 7, + '🧗🏽‍♂️': 7, + '🧗🏾‍♀️': 7, + '🧗🏾‍♂️': 7, + '🧗🏿‍♀️': 7, + '🧗🏿‍♂️': 7, + '🧘‍♀️': 5, + '🧘‍♂️': 5, + '🧘🏻‍♀️': 7, + '🧘🏻‍♂️': 7, + '🧘🏼‍♀️': 7, + '🧘🏼‍♂️': 7, + '🧘🏽‍♀️': 7, + '🧘🏽‍♂️': 7, + '🧘🏾‍♀️': 7, + '🧘🏾‍♂️': 7, + '🧘🏿‍♀️': 7, + '🧘🏿‍♂️': 7, + '🧙‍♀️': 5, + '🧙‍♂️': 5, + '🧙🏻‍♀️': 7, + '🧙🏻‍♂️': 7, + '🧙🏼‍♀️': 7, + '🧙🏼‍♂️': 7, + '🧙🏽‍♀️': 7, + '🧙🏽‍♂️': 7, + '🧙🏾‍♀️': 7, + '🧙🏾‍♂️': 7, + '🧙🏿‍♀️': 7, + '🧙🏿‍♂️': 7, + '🧚‍♀️': 5, + '🧚‍♂️': 5, + '🧚🏻‍♀️': 7, + '🧚🏻‍♂️': 7, + '🧚🏼‍♀️': 7, + '🧚🏼‍♂️': 7, + '🧚🏽‍♀️': 7, + '🧚🏽‍♂️': 7, + '🧚🏾‍♀️': 7, + '🧚🏾‍♂️': 7, + '🧚🏿‍♀️': 7, + '🧚🏿‍♂️': 7, + '🧛‍♀️': 5, + '🧛‍♂️': 5, + '🧛🏻‍♀️': 7, + '🧛🏻‍♂️': 7, + '🧛🏼‍♀️': 7, + '🧛🏼‍♂️': 7, + '🧛🏽‍♀️': 7, + '🧛🏽‍♂️': 7, + '🧛🏾‍♀️': 7, + '🧛🏾‍♂️': 7, + '🧛🏿‍♀️': 7, + '🧛🏿‍♂️': 7, + '🧜‍♀️': 5, + '🧜‍♂️': 5, + '🧜🏻‍♀️': 7, + '🧜🏻‍♂️': 7, + '🧜🏼‍♀️': 7, + '🧜🏼‍♂️': 7, + '🧜🏽‍♀️': 7, + '🧜🏽‍♂️': 7, + '🧜🏾‍♀️': 7, + '🧜🏾‍♂️': 7, + '🧜🏿‍♀️': 7, + '🧜🏿‍♂️': 7, + '🧝‍♀️': 5, + '🧝‍♂️': 5, + '🧝🏻‍♀️': 7, + '🧝🏻‍♂️': 7, + '🧝🏼‍♀️': 7, + '🧝🏼‍♂️': 7, + '🧝🏽‍♀️': 7, + '🧝🏽‍♂️': 7, + '🧝🏾‍♀️': 7, + '🧝🏾‍♂️': 7, + '🧝🏿‍♀️': 7, + '🧝🏿‍♂️': 7, + '🧞‍♀️': 5, + '🧞‍♂️': 5, + '🧟‍♀️': 5, + '🧟‍♂️': 5, + '🫱🏻‍🫲🏼': 9, + '🫱🏻‍🫲🏽': 9, + '🫱🏻‍🫲🏾': 9, + '🫱🏻‍🫲🏿': 9, + '🫱🏼‍🫲🏻': 9, + '🫱🏼‍🫲🏽': 9, + '🫱🏼‍🫲🏾': 9, + '🫱🏼‍🫲🏿': 9, + '🫱🏽‍🫲🏻': 9, + '🫱🏽‍🫲🏼': 9, + '🫱🏽‍🫲🏾': 9, + '🫱🏽‍🫲🏿': 9, + '🫱🏾‍🫲🏻': 9, + '🫱🏾‍🫲🏼': 9, + '🫱🏾‍🫲🏽': 9, + '🫱🏾‍🫲🏿': 9, + '🫱🏿‍🫲🏻': 9, + '🫱🏿‍🫲🏼': 9, + '🫱🏿‍🫲🏽': 9, + '🫱🏿‍🫲🏾': 9, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_e2b75ee3.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_e2b75ee3.py new file mode 100644 index 0000000000000000000000000000000000000000..17a8bd2d0e3c94bf4e82e3de0be7705e5c45079f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_e2b75ee3.py @@ -0,0 +1,42 @@ +""" +Grapheme overrides for _known_e2b75ee3. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: ghostty +""" +# pylint: skip-file +GRAPHEMES = { + 'ꦏ꧀': 2, + 'ꦠ꧀': 2, + 'ꦢ꧀': 2, + 'ꦤ꧀': 2, + 'ꦥ꦳꧀': 2, + 'ꦥ꧀': 2, + 'ꦧ꧀': 2, + 'ꦩ꧀': 2, + 'ꦭ꧀': 2, + 'ꦱ꧀': 2, + '𑌕𑍍': 2, + '𑌗𑍍': 2, + '𑌚𑍍': 2, + '𑌜𑍍': 2, + '𑌞𑍍': 2, + '𑌟𑍍': 2, + '𑌣𑍍': 2, + '𑌤𑍍': 2, + '𑌦𑍍': 2, + '𑌧𑍍': 2, + '𑌨𑍍': 2, + '𑌪𑍍': 2, + '𑌬𑍍': 2, + '𑌭𑍍': 2, + '𑌮𑍍': 2, + '𑌯𑍍': 2, + '𑌰𑍍': 2, + '𑌲𑍍': 2, + '𑌵𑍍': 2, + '𑌶𑍍': 2, + '𑌷𑍍': 2, + '𑌸𑍍': 2, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_fb5fd79b.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_fb5fd79b.py new file mode 100644 index 0000000000000000000000000000000000000000..4cb0497a80d1141d1906540c1b161dc76df6ee10 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_fb5fd79b.py @@ -0,0 +1,2952 @@ +""" +Grapheme overrides for _known_fb5fd79b. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: bobcat +""" +# pylint: skip-file +GRAPHEMES = { + 'क्का': 3, + 'क्कां': 3, + 'क्को': 3, + 'क्घ्घि्': 4, + 'क्ता': 3, + 'क्ति': 3, + 'क्ती': 3, + 'क्तीं': 3, + 'क्तेः': 3, + 'क्त्योः': 5, + 'क्ना': 3, + 'क्नि': 3, + 'क्या': 3, + 'क्रा': 3, + 'क्रि': 3, + 'क्षा': 3, + 'क्षां': 3, + 'क्षाः': 4, + 'क्षि': 3, + 'क्षो': 3, + 'क्ष्ण': 3, + 'क्ष्य': 3, + 'क्ष्या': 4, + 'क्सा': 3, + 'ख्यः': 3, + 'ख्या': 3, + 'ग्या': 3, + 'ग्यैः': 3, + 'ग्र्य': 3, + 'घ्का': 3, + 'घ्र्व्य': 4, + 'घ्लि': 3, + 'घ्श्य': 3, + 'घ्स्ट': 3, + 'च्चा': 3, + 'च्चों': 3, + 'च्छा': 3, + 'च्छि': 3, + 'च्या': 3, + 'च्यां': 3, + 'च्यो': 3, + 'ज्ञा': 3, + 'ज्या': 3, + 'ज्या‌': 3, + 'ज्रा': 3, + 'ञ्चा': 3, + 'ञ्चि': 3, + 'ट्टि': 3, + 'ट्टी': 3, + 'ट्या': 3, + 'ट्रा': 3, + 'ण्डः': 3, + 'ण्डि': 3, + 'ण्या': 3, + 'ण्यां': 3, + 'ताः': 3, + 'त्का': 3, + 'त्ता': 3, + 'त्ति': 3, + 'त्त्थि': 4, + 'त्त्व': 3, + 'त्त्वा': 4, + 'त्त्वे': 3, + 'त्नी': 3, + 'त्नों': 3, + 'त्पा': 3, + 'त्पी': 3, + 'त्मा': 3, + 'त्या': 3, + 'त्यां': 3, + 'त्यि': 3, + 'त्रा': 3, + 'त्राा': 4, + 'त्राि': 4, + 'त्रि': 3, + 'त्री': 3, + 'त्र्त': 3, + 'त्र्य': 3, + 'त्र्या': 4, + 'त्र्ये': 3, + 'त्वा': 3, + 'त्वां': 3, + 'त्सा': 3, + 'त्सो': 3, + 'त्स्वा': 4, + 'द्घि': 3, + 'द्घो': 3, + 'द्दा': 3, + 'द्दि': 3, + 'द्दी': 3, + 'द्धः': 3, + 'द्धा': 3, + 'द्धां': 3, + 'द्धि': 3, + 'द्धिं': 3, + 'द्धी': 3, + 'द्धीं': 3, + 'द्धैः': 3, + 'द्भा': 3, + 'द्या': 3, + 'द्रो': 3, + 'द्वा': 3, + 'द्वि': 3, + 'धाः': 3, + 'ध्या': 3, + 'नाः': 3, + 'निः': 3, + 'न्का': 3, + 'न्चि': 3, + 'न्ञ्या': 4, + 'न्तः': 3, + 'न्ता': 3, + 'न्ति': 3, + 'न्तो': 3, + 'न्तों': 3, + 'न्त्र': 3, + 'न्त्रा': 4, + 'न्त्राः': 5, + 'न्त्रि': 4, + 'न्त्री': 4, + 'न्त्र्य': 4, + 'न्त्र्यं': 4, + 'न्त्र्या': 5, + 'न्त्र्ये': 4, + 'न्दा': 3, + 'न्दी': 3, + 'न्दो': 3, + 'न्धा': 3, + 'न्धि': 3, + 'न्धी': 3, + 'न्धों': 3, + 'न्ना': 3, + 'न्नाः': 4, + 'न्नि': 3, + 'न्मा': 3, + 'न्या': 3, + 'न्यो': 3, + 'न्हा': 3, + 'न्ह्यां': 4, + 'प्ति': 3, + 'प्तौ': 3, + 'प्या': 3, + 'प्रा': 3, + 'फ्ता': 3, + 'फ्ना': 3, + 'फ्नो': 3, + 'फ्रां': 3, + 'ब्धि': 3, + 'भिः': 3, + 'भ्यः': 3, + 'भ्या': 3, + 'भ्यां': 3, + 'भ्यो': 3, + 'म्ति': 3, + 'म्नि': 3, + 'म्पा': 3, + 'म्प्र': 3, + 'म्भि': 3, + 'म्मा': 3, + 'म्मि': 3, + 'म्या': 3, + 'म्ही': 3, + 'म्हो': 3, + 'याः': 3, + 'य्यो': 3, + 'राः': 3, + 'र्कि': 3, + 'र्गी': 3, + 'र्चि': 3, + 'र्जा': 3, + 'र्जि': 3, + 'र्जी': 3, + 'र्णां': 3, + 'र्णी': 3, + 'र्ता': 3, + 'र्ति': 3, + 'र्तिः': 4, + 'र्ती': 3, + 'र्त्त': 3, + 'र्त्ति': 4, + 'र्थि': 3, + 'र्थी': 3, + 'र्दा': 3, + 'र्दि': 3, + 'र्दो': 3, + 'र्द्ध': 3, + 'र्धा': 3, + 'र्धि': 3, + 'र्नि': 3, + 'र्बा': 3, + 'र्भा': 3, + 'र्मा': 3, + 'र्मि': 3, + 'र्या': 3, + 'र्यां': 3, + 'र्यों': 3, + 'र्रा': 3, + 'र्वा': 3, + 'र्वां': 3, + 'र्वो': 3, + 'र्सा': 3, + 'र्हाः': 4, + 'र्हि': 3, + 'र्हो': 3, + 'र्‍या': 3, + 'लाः': 3, + 'ल्का': 3, + 'ल्पि': 3, + 'ल्या': 3, + 'ल्यां': 3, + 'ल्याः': 4, + 'ल्ला': 3, + 'ल्लि': 3, + 'वाः': 3, + 'व्या': 3, + 'व्यों': 3, + 'शाः': 3, + 'श्चि': 3, + 'श्या': 3, + 'श्यि': 3, + 'श्यों': 3, + 'श्रा': 3, + 'श्रां': 3, + 'श्वा': 3, + 'श्वि': 3, + 'षाः': 3, + 'ष्का': 3, + 'ष्टः': 3, + 'ष्टा': 3, + 'ष्टां': 3, + 'ष्टाः': 4, + 'ष्टि': 3, + 'ष्टी': 3, + 'ष्टीं': 3, + 'ष्ट्र': 3, + 'ष्ट्रा': 4, + 'ष्ट्रां': 4, + 'ष्ट्रि': 4, + 'ष्ट्री': 4, + 'ष्ट्रे': 3, + 'ष्ट्रो': 4, + 'ष्ट्रों': 4, + 'ष्ठा': 3, + 'ष्ठों': 3, + 'ष्प्र': 3, + 'ष्यः': 3, + 'ष्यों': 3, + 'स्का': 3, + 'स्काः': 4, + 'स्ट्या': 4, + 'स्ता': 3, + 'स्ति': 3, + 'स्ती': 3, + 'स्तो': 3, + 'स्त्र': 3, + 'स्त्रा': 4, + 'स्त्रि': 4, + 'स्त्री': 4, + 'स्था': 3, + 'स्थां': 3, + 'स्थि': 3, + 'स्थी': 3, + 'स्थ्य': 3, + 'स्धी': 3, + 'स्मि': 3, + 'स्मिं': 3, + 'स्या': 3, + 'स्यां': 3, + 'स्याः': 4, + 'स्युः': 3, + 'स्यों': 3, + 'स्रो': 3, + 'स्वा': 3, + 'स्वी': 3, + 'स्सा': 3, + 'ह्या': 3, + 'ह्रा': 3, + 'फ़्ता': 3, + 'কিং': 3, + 'ক্তি': 3, + 'ক্রী': 3, + 'ক্ষা': 3, + 'ক্ষি': 3, + 'ক্ষে': 3, + 'ক্ষ্য': 3, + 'ক্ষ্যে': 4, + 'খ্যা': 3, + 'গ্রা': 3, + 'গ্রে': 3, + 'ঘো': 3, + 'ঙ্খা': 3, + 'ঙ্গী': 3, + 'ঙ্গে': 3, + 'চ্ছা': 3, + 'চ্ছা‌': 3, + 'চ্ছে': 3, + 'জ্ঞা': 3, + 'ঞ্চি': 3, + 'ঞ্ছি': 3, + 'ট্রে': 3, + 'ণ্ডে': 3, + 'ত্তা': 3, + 'ত্তি': 3, + 'ত্বে': 3, + 'ত্যা': 3, + 'ত্যি': 3, + 'ত্যে': 3, + 'ত্রা': 3, + 'ত্রে': 3, + 'ত্‍পী': 3, + 'ত্‍সা': 3, + 'দ্দি': 3, + 'দ্দে': 3, + 'দ্ধা': 3, + 'দ্ধি': 3, + 'দ্ধে': 3, + 'দ্বা': 3, + 'দ্রো': 3, + 'ধ্যে': 3, + 'ন্তা': 3, + 'ন্তি': 3, + 'ন্তে': 3, + 'ন্ত্রি': 4, + 'ন্ত্রে': 4, + 'ন্থী': 3, + 'ন্ধা': 3, + 'ন্মা': 3, + 'ন্যা': 3, + 'ন্যে': 3, + 'প্তা': 3, + 'প্রা': 3, + 'ব্ধি': 3, + 'ব্যা': 3, + 'ভ্রা': 3, + 'ম্পা': 3, + 'ম্মা': 3, + 'রাং': 3, + 'র্জা': 3, + 'র্থে': 3, + 'র্দো': 3, + 'র্ধা': 3, + 'র্নী': 3, + 'র্বা': 3, + 'র্বি': 3, + 'র্বো': 3, + 'র্ব্য': 3, + 'র্মে': 3, + 'র্যা': 3, + 'ল্যা': 3, + 'ল্যে': 3, + 'ল্লে': 3, + 'শ্চি': 3, + 'শ্বা': 3, + 'শ্বে': 3, + 'শ্যে': 3, + 'শ্রা': 3, + 'ষ্টা': 3, + 'ষ্টি': 3, + 'ষ্ট্র': 3, + 'ষ্ট্রী': 4, + 'ষ্ট্রে': 4, + 'ষ্ঠা': 3, + 'ষ্ঠি': 3, + 'ষ্ঠী': 3, + 'সাং': 3, + 'স্তি': 3, + 'স্তি‌': 3, + 'স্ত্র': 3, + 'স্থা': 3, + 'স্থ্য': 3, + 'স্বা': 3, + 'স্বী': 3, + 'স্যা': 3, + 'স্যে': 3, + 'ક્કા': 3, + 'ક્કો': 3, + 'ક્તિ': 3, + 'ક્ષા': 3, + 'ચ્ચા': 3, + 'ચ્છા': 3, + 'જ્ઞા': 3, + 'જ્યો': 3, + 'ત્તા': 3, + 'ત્તિ': 3, + 'ત્ત્વ': 3, + 'ત્ત્વા': 4, + 'ત્યા': 3, + 'ત્યાં': 3, + 'ત્યિ': 3, + 'ત્યો': 3, + 'ત્રી': 3, + 'ત્ર્ય': 3, + 'દ્ધા': 3, + 'દ્ધાં': 3, + 'દ્ધિ': 3, + 'દ્વા': 3, + 'ધ્યા': 3, + 'ન્તો': 3, + 'ન્મા': 3, + 'ન્યા': 3, + 'પ્રા': 3, + 'મ્યાં': 3, + 'ર્તા': 3, + 'ર્થિ': 3, + 'ર્દો': 3, + 'ર્મિ': 3, + 'ર્યા': 3, + 'ર્યો': 3, + 'વ્યા': 3, + 'વ્યો': 3, + 'ષ્ટિ': 3, + 'ષ્ટ્ર': 3, + 'ષ્ટ્રી': 4, + 'ષ્ટ્રો': 4, + 'ષ્ઠા': 3, + 'સ્તિ': 3, + 'સ્તી': 3, + 'સ્ત્રી': 4, + 'સ્થા': 3, + 'સ્થિ': 3, + 'સ્રી': 3, + 'સ્વા': 3, + 'સ્વી': 3, + 'સ્સા': 3, + 'కుం': 3, + 'క్కు': 3, + 'క్తు': 3, + 'క్రాం': 3, + 'క్రూ': 3, + 'క్షిం': 3, + 'క్స్వా': 3, + 'చ్చు': 3, + 'టుం': 3, + 'ట్లు': 3, + 'డ్రు': 3, + 'త్తు': 3, + 'త్నిం': 3, + 'త్యం': 3, + 'త్రు': 3, + 'త్ర్య': 3, + 'దుం': 3, + 'ద్దు': 3, + 'ద్ధిం': 3, + 'ద్ర్య': 3, + 'నుం': 3, + 'న్ను': 3, + 'భ్యు': 3, + 'యుం': 3, + 'ర్చు': 3, + 'ర్ణాం': 3, + 'ర్ణు': 3, + 'ర్తిం': 3, + 'ర్తృ': 3, + 'ర్థిం': 3, + 'ర్బం': 3, + 'ర్హాం': 3, + 'ర్హు': 3, + 'శ్రాం': 3, + 'ష్టు': 3, + 'ష్ట్ర': 3, + 'ష్ట్రీ': 3, + 'ష్ఠు': 3, + 'స్కృ': 3, + 'స్త్ర': 3, + 'స్త్రీ': 3, + 'స్థ్య': 3, + 'ಕಾಂ': 3, + 'ಕುಂ': 3, + 'ಕೊಂ': 3, + 'ಖಾಂ': 3, + 'ಗಾಂ': 3, + 'ಗೊಂ': 3, + 'ಟುಂ': 3, + 'ನಾಂ': 3, + 'ಯುಂ': 3, + 'ರಾಂ': 3, + 'ವುಂ': 3, + 'ಶಾಂ': 3, + 'ಸಾಂ': 3, + 'ಹೊಂ': 3, + 'ക്കാ': 3, + 'ക്കി': 3, + 'ക്കും': 3, + 'ക്കെ': 3, + 'ക്കേ': 3, + 'ക്കൊ': 3, + 'ക്കോ': 3, + 'ക്തി': 3, + 'ക്യം': 3, + 'ക്ഷാ': 3, + 'ക്ഷി': 3, + 'ക്ഷേ': 3, + 'ഖ്യാ': 3, + 'ഗ്ഗം': 3, + 'ഗ്ദാ': 3, + 'ഗ്യം': 3, + 'ങ്കി': 3, + 'ങ്കെ': 3, + 'ങ്കേ': 3, + 'ങ്ങി': 3, + 'ച്ചി': 3, + 'ച്ചും': 3, + 'ച്ചെ': 3, + 'ച്ചേ': 3, + 'ജ്യാ': 3, + 'ഞ്ഞി': 3, + 'ഞ്ഞെ': 3, + 'ട്ടാ': 3, + 'ട്ടി': 3, + 'ട്ടോ': 3, + 'ണ്ടാ': 3, + 'ണ്ടി': 3, + 'ണ്ടും': 3, + 'ണ്ടെ': 3, + 'ത്താ': 3, + 'ത്തി': 3, + 'ത്തും': 3, + 'ത്തെ': 3, + 'ത്തേ': 3, + 'ത്തോ': 3, + 'ത്നം': 3, + 'ത്നി': 3, + 'ത്യാ': 3, + 'ത്യേ': 3, + 'ത്വം': 3, + 'ദ്ധി': 3, + 'ദ്യാ': 3, + 'ന്തം': 3, + 'ന്തെ': 3, + 'ന്ത്ര': 3, + 'ന്ത്ര്യ': 4, + 'ന്ത്ര്യം': 5, + 'ന്ധി': 3, + 'ന്നാ': 3, + 'ന്നി': 3, + 'ന്നീ': 3, + 'ന്നും': 3, + 'ന്നെ': 3, + 'ന്നേ': 3, + 'ന്നോ': 3, + 'ന്മാ': 3, + 'ന്യം': 3, + 'ന്യാ': 3, + 'ന്യേ': 3, + 'ന്യോ': 3, + 'ന്റെ': 3, + 'ന്‍പി': 3, + 'പ്പി': 3, + 'പ്പെ': 3, + 'പ്പോ': 3, + 'പ്രാ': 3, + 'ബ്ലി': 3, + 'ഭ്യാ': 3, + 'ഭ്രാ': 3, + 'മ്പാ': 3, + 'മ്പ്ര': 3, + 'മ്മി': 3, + 'യ്ക്കു': 3, + 'യ്തി': 3, + 'യ്യാ': 3, + 'യ്യി': 3, + 'ര്യം': 3, + 'ര്‍ക്കു': 3, + 'ര്‍ക്കും': 4, + 'ര്‍ക്ക്‌': 3, + 'ര്‍ഗ്ഗം': 4, + 'ര്‍ച്ച': 3, + 'ര്‍ണ്ണ': 3, + 'ര്‍ത്ത': 3, + 'ര്‍ത്തി': 4, + 'ര്‍ത്തു': 3, + 'ര്‍ത്തേ': 4, + 'ര്‍ദേ': 3, + 'ര്‍ദ്ദ': 3, + 'ര്‍പ്പെ': 4, + 'ര്‍മ്മി': 4, + 'ര്‍രാ': 3, + 'ര്‍വ്വ': 3, + 'ര്‍ഹി': 3, + 'റ്റം': 3, + 'റ്റേ': 3, + 'ല്യാ': 3, + 'ല്ലാ': 3, + 'ല്ലാം': 4, + 'ല്ലെ': 3, + 'ല്‍കി': 3, + 'ല്‍കേ': 3, + 'ല്‍നി': 3, + 'ല്‍പ്പ': 3, + 'ള്ളാ': 3, + 'ള്ളി': 3, + 'ള്‍കൊ': 3, + 'ള്‍ക്ക': 3, + 'ള്‍ക്കി': 4, + 'ള്‍ക്കു': 3, + 'ള്‍ക്കും': 4, + 'ള്‍ക്കെ': 4, + 'ള്‍ക്ക്‌': 3, + 'വ്യം': 3, + 'വ്യാ': 3, + 'ശ്വാ': 3, + 'ഷ്ട്യാ': 4, + 'ഷ്ട്ര': 3, + 'ഷ്ട്രീ': 4, + 'ഷ്യാ': 3, + 'സാം': 3, + 'സ്കാ': 3, + 'സ്ത്രം': 4, + 'സ്ത്രീ': 4, + 'സ്ഥാ': 3, + 'സ്ഥി': 3, + 'സ്റ്റ്‌': 3, + 'സ്വാ': 3, + 'സ്വീ': 3, + 'സ്സാ': 3, + 'സ്സി': 3, + 'സ്സും': 3, + 'സ്സോ': 3, + 'ഹിം': 3, + 'ൻ്റെ': 3, + 'က်ျ': 1, + 'ကျ': 1, + 'ကျို': 1, + 'ကျူ': 1, + 'ကျွ': 1, + 'ကြ': 1, + 'ကြို': 1, + 'ကြီ': 1, + 'ကြု': 1, + 'ကြံ': 1, + 'ချ': 1, + 'ချိ': 1, + 'ချို': 1, + 'ချို့': 1, + 'ချီ': 1, + 'ချု': 1, + 'ချဳ': 1, + 'ခြ': 1, + 'ခြုံ': 1, + 'ဂျို': 1, + 'ငြ': 1, + 'ငြိ': 1, + 'ဇြ': 1, + 'ဇြဳ': 1, + 'တြ': 1, + 'တြုံ': 1, + 'ဒ္ဂေ': 3, + 'ဒြ': 1, + 'ပျ': 1, + 'ပျဲ': 1, + 'ပြ': 1, + 'ပြီ': 1, + 'ပြု': 1, + 'ပြဳ': 1, + 'ပြံ': 1, + 'ဖျ': 1, + 'ဖျု': 1, + 'ဖြ': 1, + 'ဖြို': 1, + 'ဗ္တေ': 3, + 'ဗ္ၜေ': 3, + 'ဗျဵု': 1, + 'ဗြဴ': 1, + 'မျ': 1, + 'မျို': 1, + 'မျီု': 1, + 'မျှ': 1, + 'မြ': 1, + 'မြှ': 1, + 'ယျ': 1, + 'ယျဵု': 1, + 'ယြဴ': 1, + 'လျ': 1, + 'လျို': 1, + 'လျှ': 1, + 'လျှို့': 1, + 'သ္ဂေ': 3, + 'သြ': 1, + 'သြို': 1, + 'ក្ដៅ': 3, + 'ក្រោ': 3, + 'ក្សា': 3, + 'ខ្ជា': 3, + 'ខ្លា': 3, + 'គ្នា': 3, + 'គ្មា': 3, + 'គ្រា': 3, + 'គ្រឹះ': 3, + 'ង្កើ': 3, + 'ង្រៀ': 3, + 'ង្ហា': 3, + 'ច្ចេ': 3, + 'ច្បា': 3, + 'ឆ្នាំ': 3, + 'ឆ្នោ': 3, + 'ឆ្លើ': 3, + 'ជ្ជា': 3, + 'ជ្ញា': 3, + 'ជ្រើ': 3, + 'ជ្រៀ': 3, + 'ជ្រែ': 3, + 'ឈ្មោះ': 4, + 'ញ្ជា': 3, + 'ញ្ញា': 3, + 'ញ្ញៈ': 3, + 'ដ្ឋា': 3, + 'ណោះ': 3, + 'ណ្ដា': 3, + 'ណ្ដុះ': 3, + 'ណ្ណោះ': 4, + 'ត្រា': 3, + 'ថ្ងៃ': 3, + 'ថ្នា': 3, + 'ថ្លៃ': 3, + 'ទោះ': 3, + 'ទ្យា': 3, + 'ធ្នា': 3, + 'ធ្យា': 3, + 'ធ្យោ': 3, + 'ធ្វើ': 3, + 'នេះ': 3, + 'នោះ': 3, + 'ន្ថែ': 3, + 'ន្ថោ': 3, + 'ន្ទា': 3, + 'ន្ទៈ': 3, + 'ន្យា': 3, + 'ន្លែ': 3, + 'បោះ': 3, + 'ប្ដេ': 3, + 'ប្រា': 3, + 'ប្រើ': 3, + 'ប្រែ': 3, + 'ផ្ដា': 3, + 'ផ្ទា': 3, + 'ផ្ទេ': 3, + 'ផ្នែ': 3, + 'ផ្លា': 3, + 'ផ្សា': 3, + 'ផ្សេ': 3, + 'ផ្សៃ': 3, + 'ពោះ': 3, + 'ព្យា': 3, + 'ព្រៀ': 3, + 'ព្រៃ': 3, + 'ម្ងា': 3, + 'ម្ចា': 3, + 'ម្ដា': 3, + 'ម្ដែ': 3, + 'ម្នា': 3, + 'ម្នេ': 3, + 'ម្ភា': 3, + 'ម្រា': 3, + 'ម្រើ': 3, + 'ម្រេ': 3, + 'ម្លៀ': 3, + 'ម្លៃ': 3, + 'ល្បៈ': 3, + 'ល្មើ': 3, + 'ស្គា': 3, + 'ស្ដ្រី': 3, + 'ស្ត្រ': 3, + 'ស្ថា': 3, + 'ស្នា': 3, + 'ស្មា': 3, + 'ស្មើ': 3, + 'ស្រា': 3, + 'ស្លា': 3, + 'ស្វែ': 3, + 'ᨠᩮ᩠ᨯᩨ': 3, + 'ᨠᩯ᩠ᨯ': 3, + 'ᨠᩯ᩠ᨶ᩵': 3, + 'ᨡᩮ᩠ᨲ': 3, + 'ᨡᩯ᩠ᨠ': 3, + 'ᨡᩯ᩠ᨦ': 3, + 'ᨣᩕ᩠ᩋ': 3, + 'ᨣᩕᩮ᩠ᨦᩨ᩵': 4, + 'ᨣᩯ᩠ᨶᩢ': 3, + 'ᨣᩯ᩠ᩅ': 3, + 'ᨧᩮ᩠ᨷ': 3, + 'ᨧᩱ᩠ᨿ': 3, + 'ᨩᩮ᩠ᩋᩨ': 3, + 'ᨩᩮ᩠ᩋᩨ᩵': 3, + 'ᨩᩮ᩠ᩋᩨ᩶': 3, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 3, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 3, + 'ᨯᩯ᩠ᨦ': 3, + 'ᨯᩯ᩠ᨶ': 3, + 'ᨯᩰ᩠ᨿ': 3, + 'ᨲᩮ᩠ᨠ': 3, + 'ᨲᩮ᩠ᨦ': 3, + 'ᨲᩮ᩠ᨾ': 3, + 'ᨲᩮ᩠ᨾᩨ᩵': 3, + 'ᨲᩯ᩠ᨠ': 3, + 'ᨲᩯ᩠ᨦ᩵': 3, + 'ᨲᩯ᩠ᨾᩢ': 3, + 'ᨲᩱ᩠ᨿ': 3, + 'ᨳᩮ᩠ᨶᩨ᩵': 3, + 'ᨳᩯ᩠ᨦᩢ': 3, + 'ᨳᩯ᩠ᨾ': 3, + 'ᨴᩮ᩠ᩈ': 3, + 'ᨴᩮ᩠ᩈᩱ': 4, + 'ᨴᩯ᩠ᨶ': 3, + 'ᨴᩰ᩠ᩈ': 3, + 'ᨶᩯ᩠ᨶ': 3, + 'ᨷᩮ᩠ᨦᩨ᩶': 3, + 'ᨸᩮ᩠ᨦᩨ': 3, + 'ᨸᩮ᩠ᨶ': 3, + 'ᨹᩮᩨ᩠ᨿ': 3, + 'ᨻᩕ᩠ᩋᩢ': 3, + 'ᨻᩮ᩠ᩋᩨ᩵': 3, + 'ᨽᩱ᩠ᨿ': 3, + 'ᨾᩮ᩠ᨠᩨ': 3, + 'ᨾᩮ᩠ᨦᩨ': 3, + 'ᨾᩮ᩠ᩋᩨ᩵': 3, + 'ᨿᩮ᩠ᨶ': 3, + 'ᨿᩮ᩠ᨾᩨ': 3, + 'ᩁᩮ᩠ᨦᩨ᩵': 3, + 'ᩁᩮ᩠ᨧ': 3, + 'ᩁᩮ᩠ᨶᩨ': 3, + 'ᩁᩮᩨ᩠ᨬ': 3, + 'ᩁᩯ᩠ᨦ': 3, + 'ᩃᩮ᩠ᨠᩨ': 3, + 'ᩃᩮ᩠ᨦᩨ': 3, + 'ᩃᩰ᩠ᨠ': 3, + 'ᩅᩮ᩠ᨶ': 3, + 'ᩅᩮ᩠ᨶᩢ': 3, + 'ᩈᩮ᩠ᩈ': 3, + 'ᩈᩯ᩠ᩅ': 3, + 'ᩈᩱ᩠ᨿ': 3, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 3, + 'ᩉᩮ᩠ᨦᩢᩢ': 3, + 'ᩉᩮ᩠ᨯ': 3, + 'ᩉᩮ᩠ᨲᩩ': 3, + 'ᩉᩮ᩠ᨶᩨ': 3, + 'ᩉᩮ᩠ᨾᩨ': 3, + 'ᩉᩮ᩠ᨾᩨᩨ': 3, + 'ᩉᩯ᩠ᨦ᩵': 3, + 'ᩉᩯ᩠ᨶᩢ': 3, + 'ᩉᩯ᩠ᨾ': 3, + 'ᩉᩱ᩠ᨾ᩵': 3, + 'ᩉᩱ᩠ᨿ᩵': 3, + 'ᩣ᩠ᨲᩱ': 3, + '⛓️‍💥': 4, + '⛹️‍♀️': 4, + '⛹️‍♂️': 4, + '⛹🏻‍♀️': 3, + '⛹🏻‍♂️': 3, + '⛹🏼‍♀️': 3, + '⛹🏼‍♂️': 3, + '⛹🏽‍♀️': 3, + '⛹🏽‍♂️': 3, + '⛹🏾‍♀️': 3, + '⛹🏾‍♂️': 3, + '⛹🏿‍♀️': 3, + '⛹🏿‍♂️': 3, + '❤️‍🔥': 4, + '❤️‍🩹': 4, + 'ꦏꦺꦴ': 3, + 'ꦏ꧀': 2, + 'ꦏ꧀ꦏ': 3, + 'ꦏ꧀ꦏꦁ': 3, + 'ꦏ꧀ꦏꦺ': 4, + 'ꦏ꧀ꦏꦼ': 3, + 'ꦏ꧀ꦔ': 3, + 'ꦏ꧀ꦔꦸ': 3, + 'ꦏ꧀ꦔꦿ': 4, + 'ꦏ꧀ꦕ': 3, + 'ꦏ꧀ꦠ': 3, + 'ꦏ꧀ꦠꦶ': 3, + 'ꦏ꧀ꦠꦸ': 3, + 'ꦏ꧀ꦠꦺ': 4, + 'ꦏ꧀ꦢ': 3, + 'ꦏ꧀ꦢꦂ': 3, + 'ꦏ꧀ꦢꦶ': 3, + 'ꦏ꧀ꦤ': 3, + 'ꦏ꧀ꦤꦶꦁ': 3, + 'ꦏ꧀ꦥ': 3, + 'ꦏ꧀ꦥꦶ': 3, + 'ꦏ꧀ꦥꦿꦶ': 4, + 'ꦏ꧀ꦧ': 3, + 'ꦏ꧀ꦧꦶ': 3, + 'ꦏ꧀ꦧꦺ': 4, + 'ꦏ꧀ꦩ': 3, + 'ꦏ꧀ꦩꦸ': 3, + 'ꦏ꧀ꦪ': 3, + 'ꦏ꧀ꦭ': 3, + 'ꦏ꧀ꦮ': 3, + 'ꦏ꧀ꦱ': 3, + 'ꦏ꧀ꦱꦂ': 3, + 'ꦏ꧀ꦱꦶ': 3, + 'ꦏ꧀ꦱꦸ': 3, + 'ꦏ꧀ꦱꦺ': 4, + 'ꦏ꧀ꦲ': 3, + 'ꦏ꧀ꦲꦁ': 3, + 'ꦏ꧀ꦲꦶꦁ': 3, + 'ꦏ꧀ꦲꦸ': 3, + 'ꦏ꧀ꦲꦺ': 4, + 'ꦏ꧀ꦲꦺꦴ': 5, + 'ꦒꦺꦴ': 3, + 'ꦒꦿꦺ': 3, + 'ꦒ꧀ꦒ': 3, + 'ꦔꦺꦴ': 3, + 'ꦔ꧀ꦒꦼ': 3, + 'ꦔ꧀ꦒꦿꦼꦁ': 4, + 'ꦔ꧀ꦭ': 3, + 'ꦔ꧀ꦭꦁ': 3, + 'ꦔ꧀ꦭꦸ': 3, + 'ꦔ꧀ꦭꦼ': 3, + 'ꦕꦺꦴ': 3, + 'ꦗꦿꦺꦴ': 4, + 'ꦚ꧀ꦕ': 3, + 'ꦚ꧀ꦕꦶ': 3, + 'ꦚ꧀ꦗ': 3, + 'ꦚ꧀ꦗꦶ': 3, + 'ꦚ꧀ꦗꦸꦁ': 3, + 'ꦚ꧀ꦗꦸꦂ': 3, + 'ꦝꦺꦴ': 3, + 'ꦝꦺꦴꦂ': 3, + 'ꦠꦺꦃ': 3, + 'ꦠꦺꦴ': 3, + 'ꦠ꧀': 2, + 'ꦠ꧀ꦏꦁ': 3, + 'ꦠ꧀ꦏꦸ': 3, + 'ꦠ꧀ꦒ': 3, + 'ꦠ꧀ꦔꦸ': 3, + 'ꦠ꧀ꦚ': 3, + 'ꦠ꧀ꦠ': 3, + 'ꦠ꧀ꦠꦶ': 3, + 'ꦠ꧀ꦠꦶꦁ': 3, + 'ꦠ꧀ꦠꦸ': 3, + 'ꦠ꧀ꦠꦺ': 4, + 'ꦠ꧀ꦤ': 3, + 'ꦠ꧀ꦤꦶ': 3, + 'ꦠ꧀ꦩ': 3, + 'ꦠ꧀ꦩꦼ': 3, + 'ꦠ꧀ꦭ': 3, + 'ꦠ꧀ꦭꦺ': 4, + 'ꦠ꧀ꦱ': 3, + 'ꦠ꧀ꦱꦶꦁ': 3, + 'ꦠ꧀ꦱꦶꦃ': 4, + 'ꦠ꧀ꦱꦾ': 4, + 'ꦠ꧀ꦱ꧀ꦮ': 5, + 'ꦠ꧀ꦲ': 3, + 'ꦠ꧀ꦲꦶꦁ': 3, + 'ꦠ꧀ꦲꦺꦴ': 5, + 'ꦢꦺꦴ': 3, + 'ꦢ꧀': 2, + 'ꦢ꧀ꦏ': 3, + 'ꦢ꧀ꦠ': 3, + 'ꦢ꧀ꦠꦶꦁ': 3, + 'ꦢ꧀ꦢ': 3, + 'ꦢ꧀ꦥ': 3, + 'ꦢ꧀ꦩꦺꦴ': 5, + 'ꦢ꧀ꦲ': 3, + 'ꦤꦺꦃ': 3, + 'ꦤꦺꦴ': 3, + 'ꦤ꧀': 2, + 'ꦤ꧀ꦏ': 3, + 'ꦤ꧀ꦏꦁ': 3, + 'ꦤ꧀ꦏꦸ': 3, + 'ꦤ꧀ꦏꦼ': 3, + 'ꦤ꧀ꦒ': 3, + 'ꦤ꧀ꦔ': 3, + 'ꦤ꧀ꦔꦁ': 3, + 'ꦤ꧀ꦔꦶ': 3, + 'ꦤ꧀ꦔꦸ': 3, + 'ꦤ꧀ꦔꦸꦂ': 3, + 'ꦤ꧀ꦔꦺ': 4, + 'ꦤ꧀ꦔꦼ': 3, + 'ꦤ꧀ꦔꦿꦸ': 4, + 'ꦤ꧀ꦗ': 3, + 'ꦤ꧀ꦗꦸ': 3, + 'ꦤ꧀ꦗꦼ': 3, + 'ꦤ꧀ꦚꦶ': 3, + 'ꦤ꧀ꦛꦃ': 4, + 'ꦤ꧀ꦛꦶ': 3, + 'ꦤ꧀ꦝ': 3, + 'ꦤ꧀ꦝꦁ': 3, + 'ꦤ꧀ꦝꦶ': 3, + 'ꦤ꧀ꦝꦸ': 3, + 'ꦤ꧀ꦝꦸꦁ': 3, + 'ꦤ꧀ꦝꦺꦁ': 4, + 'ꦤ꧀ꦝꦺꦴꦁ': 5, + 'ꦤ꧀ꦝꦼ': 3, + 'ꦤ꧀ꦠ': 3, + 'ꦤ꧀ꦠꦂ': 3, + 'ꦤ꧀ꦠꦃ': 4, + 'ꦤ꧀ꦠꦶ': 3, + 'ꦤ꧀ꦠꦸ': 3, + 'ꦤ꧀ꦠꦸꦁ': 3, + 'ꦤ꧀ꦠꦺ': 4, + 'ꦤ꧀ꦠꦼ': 3, + 'ꦤ꧀ꦠꦼꦂ': 3, + 'ꦤ꧀ꦠꦽ': 3, + 'ꦤ꧀ꦢ': 3, + 'ꦤ꧀ꦢꦁ': 3, + 'ꦤ꧀ꦢꦂ': 3, + 'ꦤ꧀ꦢꦶ': 3, + 'ꦤ꧀ꦢꦸ': 3, + 'ꦤ꧀ꦢꦺ': 4, + 'ꦤ꧀ꦢꦼ': 3, + 'ꦤ꧀ꦤ': 3, + 'ꦤ꧀ꦤꦶ': 3, + 'ꦤ꧀ꦤꦶꦁ': 3, + 'ꦤ꧀ꦤꦺ': 4, + 'ꦤ꧀ꦤꦼ': 3, + 'ꦤ꧀ꦥ': 3, + 'ꦤ꧀ꦥꦁ': 3, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 5, + 'ꦤ꧀ꦥꦶ': 3, + 'ꦤ꧀ꦥꦸ': 3, + 'ꦤ꧀ꦥꦼ': 3, + 'ꦤ꧀ꦥꦿ': 4, + 'ꦤ꧀ꦥꦿꦶ': 4, + 'ꦤ꧀ꦧ': 3, + 'ꦤ꧀ꦧꦁ': 3, + 'ꦤ꧀ꦧꦶ': 3, + 'ꦤ꧀ꦧꦸ': 3, + 'ꦤ꧀ꦧꦺ': 4, + 'ꦤ꧀ꦧꦺꦴ': 5, + 'ꦤ꧀ꦧꦼ': 3, + 'ꦤ꧀ꦩ': 3, + 'ꦤ꧀ꦩꦂ': 3, + 'ꦤ꧀ꦩꦶ': 3, + 'ꦤ꧀ꦩꦸꦂ': 3, + 'ꦤ꧀ꦩꦼ': 3, + 'ꦤ꧀ꦭ': 3, + 'ꦤ꧀ꦭꦶ': 3, + 'ꦤ꧀ꦭꦸ': 3, + 'ꦤ꧀ꦮ': 3, + 'ꦤ꧀ꦮꦂ': 3, + 'ꦤ꧀ꦮꦶ': 3, + 'ꦤ꧀ꦮꦸ': 3, + 'ꦤ꧀ꦮꦼ': 3, + 'ꦤ꧀ꦱ': 3, + 'ꦤ꧀ꦱꦂ': 3, + 'ꦤ꧀ꦱꦃ': 4, + 'ꦤ꧀ꦱꦶ': 3, + 'ꦤ꧀ꦱꦶꦁ': 3, + 'ꦤ꧀ꦱꦸ': 3, + 'ꦤ꧀ꦱꦺꦴ': 5, + 'ꦤ꧀ꦱꦼ': 3, + 'ꦤ꧀ꦲ': 3, + 'ꦤ꧀ꦲꦁ': 3, + 'ꦤ꧀ꦲꦶ': 3, + 'ꦤ꧀ꦲꦶꦁ': 3, + 'ꦤ꧀ꦲꦸ': 3, + 'ꦤ꧀ꦲꦺꦴ': 5, + 'ꦥ꦳꧀': 2, + 'ꦥꦺꦴ': 3, + 'ꦥꦿꦃ': 3, + 'ꦥꦿꦺꦴ': 4, + 'ꦥ꧀': 2, + 'ꦥ꧀ꦏ': 3, + 'ꦥ꧀ꦏꦁ': 3, + 'ꦥ꧀ꦠ': 3, + 'ꦥ꧀ꦠꦶ': 3, + 'ꦥ꧀ꦢꦸ': 3, + 'ꦥ꧀ꦤ': 3, + 'ꦥ꧀ꦤꦶ': 3, + 'ꦥ꧀ꦥ': 3, + 'ꦥ꧀ꦥꦶ': 3, + 'ꦥ꧀ꦥꦺ': 4, + 'ꦥ꧀ꦧꦺ': 4, + 'ꦥ꧀ꦩ': 3, + 'ꦥ꧀ꦩꦂ': 3, + 'ꦥ꧀ꦫꦺ': 4, + 'ꦥ꧀ꦭ': 3, + 'ꦥ꧀ꦭꦸ': 3, + 'ꦥ꧀ꦱ': 3, + 'ꦥ꧀ꦱꦶꦂ': 3, + 'ꦥ꧀ꦱꦼ': 3, + 'ꦥ꧀ꦲ': 3, + 'ꦧꦺꦃ': 3, + 'ꦧꦺꦴ': 3, + 'ꦧ꧀': 2, + 'ꦧ꧀ꦏ': 3, + 'ꦧ꧀ꦠꦸ': 3, + 'ꦧ꧀ꦥ': 3, + 'ꦧ꧀ꦧ': 3, + 'ꦧ꧀ꦧꦺ': 4, + 'ꦧ꧀ꦲ': 3, + 'ꦧ꧀ꦲꦶ': 3, + 'ꦩꦺꦃ': 3, + 'ꦩꦺꦴ': 3, + 'ꦩꦿꦃ': 3, + 'ꦩꦿꦶꦃ': 3, + 'ꦩ꧀': 2, + 'ꦩ꧀ꦏꦁ': 3, + 'ꦩ꧀ꦔꦼ': 3, + 'ꦩ꧀ꦠꦸ': 3, + 'ꦩ꧀ꦠꦺꦴ': 5, + 'ꦩ꧀ꦤꦶꦁ': 3, + 'ꦩ꧀ꦥ': 3, + 'ꦩ꧀ꦥꦶ': 3, + 'ꦩ꧀ꦥꦸ': 3, + 'ꦩ꧀ꦥꦼ': 3, + 'ꦩ꧀ꦧ': 3, + 'ꦩ꧀ꦧꦁ': 3, + 'ꦩ꧀ꦧꦂ': 3, + 'ꦩ꧀ꦧꦃ': 4, + 'ꦩ꧀ꦧꦶ': 3, + 'ꦩ꧀ꦧꦸ': 3, + 'ꦩ꧀ꦧꦸꦁ': 3, + 'ꦩ꧀ꦧꦺ': 4, + 'ꦩ꧀ꦧꦺꦂ': 4, + 'ꦩ꧀ꦧꦼꦂ': 3, + 'ꦩ꧀ꦧꦾꦸꦂ': 4, + 'ꦩ꧀ꦩ': 3, + 'ꦩ꧀ꦩꦶ': 3, + 'ꦩ꧀ꦫ': 3, + 'ꦩ꧀ꦫꦃ': 4, + 'ꦩ꧀ꦭ': 3, + 'ꦩ꧀ꦲꦶ': 3, + 'ꦪꦺꦴ': 3, + 'ꦫꦺꦴ': 3, + 'ꦭꦺꦃ': 3, + 'ꦭꦺꦴ': 3, + 'ꦭꦺꦴꦁ': 3, + 'ꦭ꧀': 2, + 'ꦭ꧀ꦏꦁ': 3, + 'ꦭ꧀ꦚꦼꦁ': 3, + 'ꦭ꧀ꦠꦸ': 3, + 'ꦭ꧀ꦧꦸ': 3, + 'ꦭ꧀ꦩꦸ': 3, + 'ꦭ꧀ꦭ': 3, + 'ꦭ꧀ꦭꦶ': 3, + 'ꦭ꧀ꦭꦶꦁ': 3, + 'ꦭ꧀ꦭꦺ': 4, + 'ꦭ꧀ꦮ': 3, + 'ꦭ꧀ꦱ': 3, + 'ꦭ꧀ꦱꦂ': 3, + 'ꦭ꧀ꦱꦶꦁ': 3, + 'ꦭ꧀ꦱꦸ': 3, + 'ꦭ꧀ꦲ': 3, + 'ꦭ꧀ꦲꦁ': 3, + 'ꦭ꧀ꦲꦶꦁ': 3, + 'ꦭ꧀ꦲꦸ': 3, + 'ꦮꦺꦴ': 3, + 'ꦮꦺꦴꦁ': 3, + 'ꦮꦺꦴꦃ': 4, + 'ꦮꦿꦸꦃ': 3, + 'ꦱꦺꦴ': 3, + 'ꦱꦿꦃ': 3, + 'ꦱ꧀': 2, + 'ꦱ꧀ꦏ': 3, + 'ꦱ꧀ꦏꦁ': 3, + 'ꦱ꧀ꦏꦿꦶ': 4, + 'ꦱ꧀ꦒ': 3, + 'ꦱ꧀ꦔꦸ': 3, + 'ꦱ꧀ꦔꦿ': 4, + 'ꦱ꧀ꦛꦶ': 3, + 'ꦱ꧀ꦠ': 3, + 'ꦱ꧀ꦠꦿ': 4, + 'ꦱ꧀ꦢꦂ': 3, + 'ꦱ꧀ꦢꦶ': 3, + 'ꦱ꧀ꦢꦸ': 3, + 'ꦱ꧀ꦥ': 3, + 'ꦱ꧀ꦧ': 3, + 'ꦱ꧀ꦧꦁ': 3, + 'ꦱ꧀ꦩ': 3, + 'ꦱ꧀ꦩꦶ': 3, + 'ꦱ꧀ꦩꦼ': 3, + 'ꦱ꧀ꦩꦿ': 4, + 'ꦱ꧀ꦭ': 3, + 'ꦱ꧀ꦮ': 3, + 'ꦱ꧀ꦱ': 3, + 'ꦱ꧀ꦱꦂ': 3, + 'ꦱ꧀ꦱꦶ': 3, + 'ꦱ꧀ꦱꦶꦁ': 3, + 'ꦱ꧀ꦱꦸ': 3, + 'ꦱ꧀ꦱꦺ': 4, + 'ꦱ꧀ꦲ': 3, + 'ꦱ꧀ꦲꦁ': 3, + 'ꦱ꧀ꦲꦶ': 3, + 'ꦱ꧀ꦲꦶꦁ': 3, + 'ꦱ꧀ꦲꦸ': 3, + 'ꦲꦺꦴ': 3, + '𑄇𑄳𑄠𑄬': 3, + '𑄈𑄳𑄠𑄬': 3, + '𑄌𑄳𑄠𑄬': 3, + '𑄎𑄳𑄠𑄬': 3, + '𑄑𑄳𑄢𑄬': 3, + '𑄖𑄳𑄠𑄬': 3, + '𑄖𑄳𑄢𑄬': 3, + '𑄘𑄳𑄠𑄬': 3, + '𑄚𑄳𑄠𑄬': 3, + '𑄝𑄳𑄢𑄬': 3, + '𑄟𑄳𑄠𑄬': 3, + '𑄡𑄳𑄠𑄬': 3, + '𑄣𑄳𑄦𑄬': 3, + '𑌕𑌾𑌂': 3, + '𑌕𑌾𑌃': 3, + '𑌕𑍍': 2, + '𑌗𑍍': 2, + '𑌚𑍍': 2, + '𑌜𑍍': 2, + '𑌞𑍍': 2, + '𑌟𑌾𑌂': 3, + '𑌟𑌾𑌃': 3, + '𑌟𑍍': 2, + '𑌠𑍈𑌃': 3, + '𑌣𑌾𑌂': 3, + '𑌣𑍍': 2, + '𑌤𑌾𑌂': 3, + '𑌤𑌾𑌃': 3, + '𑌤𑌿𑌂': 3, + '𑌤𑌿𑌃': 3, + '𑌤𑍁𑌂': 3, + '𑌤𑍇𑌃': 3, + '𑌤𑍍': 2, + '𑌥𑌾𑌂': 3, + '𑌦𑍍': 2, + '𑌧𑌾𑌃': 3, + '𑌧𑌿𑌂': 3, + '𑌧𑍇𑌃': 3, + '𑌧𑍈𑌃': 3, + '𑌧𑍍': 2, + '𑌨𑌾𑌂': 3, + '𑌨𑌾𑌃': 3, + '𑌨𑌿𑌃': 3, + '𑌨𑍈𑌃': 3, + '𑌨𑍍': 2, + '𑌪𑍍': 2, + '𑌬𑍍': 2, + '𑌭𑌿𑌃': 3, + '𑌭𑍍': 2, + '𑌮𑌿𑌂': 3, + '𑌮𑍍': 2, + '𑌯𑌾𑌂': 3, + '𑌯𑌾𑌃': 3, + '𑌯𑍁𑌃': 3, + '𑌯𑍈𑌃': 3, + '𑌯𑍋𑌃': 3, + '𑌯𑍍': 2, + '𑌰𑌾𑌃': 3, + '𑌰𑌿𑌂': 3, + '𑌰𑍍': 2, + '𑌲𑌾𑌃': 3, + '𑌲𑌿𑌂': 3, + '𑌲𑍍': 2, + '𑌵𑌾𑌂': 3, + '𑌵𑌾𑌃': 3, + '𑌵𑍍': 2, + '𑌶𑌾𑌃': 3, + '𑌶𑍍': 2, + '𑌷𑌾𑌂': 3, + '𑌷𑌾𑌃': 3, + '𑌷𑍍': 2, + '𑌸𑌾𑌂': 3, + '𑌸𑍍': 2, + '𑌹𑌾𑌃': 3, + '🇦🇨': 4, + '🇦🇩': 4, + '🇦🇪': 4, + '🇦🇫': 4, + '🇦🇬': 4, + '🇦🇮': 4, + '🇦🇱': 4, + '🇦🇲': 4, + '🇦🇴': 4, + '🇦🇶': 4, + '🇦🇷': 4, + '🇦🇸': 4, + '🇦🇹': 4, + '🇦🇺': 4, + '🇦🇼': 4, + '🇦🇽': 4, + '🇦🇿': 4, + '🇧🇦': 4, + '🇧🇧': 4, + '🇧🇩': 4, + '🇧🇪': 4, + '🇧🇫': 4, + '🇧🇬': 4, + '🇧🇭': 4, + '🇧🇮': 4, + '🇧🇯': 4, + '🇧🇱': 4, + '🇧🇲': 4, + '🇧🇳': 4, + '🇧🇴': 4, + '🇧🇶': 4, + '🇧🇷': 4, + '🇧🇸': 4, + '🇧🇹': 4, + '🇧🇻': 4, + '🇧🇼': 4, + '🇧🇾': 4, + '🇧🇿': 4, + '🇨🇦': 4, + '🇨🇨': 4, + '🇨🇩': 4, + '🇨🇫': 4, + '🇨🇬': 4, + '🇨🇭': 4, + '🇨🇮': 4, + '🇨🇰': 4, + '🇨🇱': 4, + '🇨🇲': 4, + '🇨🇳': 4, + '🇨🇴': 4, + '🇨🇵': 4, + '🇨🇶': 4, + '🇨🇷': 4, + '🇨🇺': 4, + '🇨🇻': 4, + '🇨🇼': 4, + '🇨🇽': 4, + '🇨🇾': 4, + '🇨🇿': 4, + '🇩🇪': 4, + '🇩🇬': 4, + '🇩🇯': 4, + '🇩🇰': 4, + '🇩🇲': 4, + '🇩🇴': 4, + '🇩🇿': 4, + '🇪🇦': 4, + '🇪🇨': 4, + '🇪🇪': 4, + '🇪🇬': 4, + '🇪🇭': 4, + '🇪🇷': 4, + '🇪🇸': 4, + '🇪🇹': 4, + '🇪🇺': 4, + '🇫🇮': 4, + '🇫🇯': 4, + '🇫🇰': 4, + '🇫🇲': 4, + '🇫🇴': 4, + '🇫🇷': 4, + '🇬🇦': 4, + '🇬🇧': 4, + '🇬🇩': 4, + '🇬🇪': 4, + '🇬🇫': 4, + '🇬🇬': 4, + '🇬🇭': 4, + '🇬🇮': 4, + '🇬🇱': 4, + '🇬🇲': 4, + '🇬🇳': 4, + '🇬🇵': 4, + '🇬🇶': 4, + '🇬🇷': 4, + '🇬🇸': 4, + '🇬🇹': 4, + '🇬🇺': 4, + '🇬🇼': 4, + '🇬🇾': 4, + '🇭🇰': 4, + '🇭🇲': 4, + '🇭🇳': 4, + '🇭🇷': 4, + '🇭🇹': 4, + '🇭🇺': 4, + '🇮🇨': 4, + '🇮🇩': 4, + '🇮🇪': 4, + '🇮🇱': 4, + '🇮🇲': 4, + '🇮🇳': 4, + '🇮🇴': 4, + '🇮🇶': 4, + '🇮🇷': 4, + '🇮🇸': 4, + '🇮🇹': 4, + '🇯🇪': 4, + '🇯🇲': 4, + '🇯🇴': 4, + '🇯🇵': 4, + '🇰🇪': 4, + '🇰🇬': 4, + '🇰🇭': 4, + '🇰🇮': 4, + '🇰🇲': 4, + '🇰🇳': 4, + '🇰🇵': 4, + '🇰🇷': 4, + '🇰🇼': 4, + '🇰🇾': 4, + '🇰🇿': 4, + '🇱🇦': 4, + '🇱🇧': 4, + '🇱🇨': 4, + '🇱🇮': 4, + '🇱🇰': 4, + '🇱🇷': 4, + '🇱🇸': 4, + '🇱🇹': 4, + '🇱🇺': 4, + '🇱🇻': 4, + '🇱🇾': 4, + '🇲🇦': 4, + '🇲🇨': 4, + '🇲🇩': 4, + '🇲🇪': 4, + '🇲🇫': 4, + '🇲🇬': 4, + '🇲🇭': 4, + '🇲🇰': 4, + '🇲🇱': 4, + '🇲🇲': 4, + '🇲🇳': 4, + '🇲🇴': 4, + '🇲🇵': 4, + '🇲🇶': 4, + '🇲🇷': 4, + '🇲🇸': 4, + '🇲🇹': 4, + '🇲🇺': 4, + '🇲🇻': 4, + '🇲🇼': 4, + '🇲🇽': 4, + '🇲🇾': 4, + '🇲🇿': 4, + '🇳🇦': 4, + '🇳🇨': 4, + '🇳🇪': 4, + '🇳🇫': 4, + '🇳🇬': 4, + '🇳🇮': 4, + '🇳🇱': 4, + '🇳🇴': 4, + '🇳🇵': 4, + '🇳🇷': 4, + '🇳🇺': 4, + '🇳🇿': 4, + '🇴🇲': 4, + '🇵🇦': 4, + '🇵🇪': 4, + '🇵🇫': 4, + '🇵🇬': 4, + '🇵🇭': 4, + '🇵🇰': 4, + '🇵🇱': 4, + '🇵🇲': 4, + '🇵🇳': 4, + '🇵🇷': 4, + '🇵🇸': 4, + '🇵🇹': 4, + '🇵🇼': 4, + '🇵🇾': 4, + '🇶🇦': 4, + '🇷🇪': 4, + '🇷🇴': 4, + '🇷🇸': 4, + '🇷🇺': 4, + '🇷🇼': 4, + '🇸🇦': 4, + '🇸🇧': 4, + '🇸🇨': 4, + '🇸🇩': 4, + '🇸🇪': 4, + '🇸🇬': 4, + '🇸🇭': 4, + '🇸🇮': 4, + '🇸🇯': 4, + '🇸🇰': 4, + '🇸🇱': 4, + '🇸🇲': 4, + '🇸🇳': 4, + '🇸🇴': 4, + '🇸🇷': 4, + '🇸🇸': 4, + '🇸🇹': 4, + '🇸🇻': 4, + '🇸🇽': 4, + '🇸🇾': 4, + '🇸🇿': 4, + '🇹🇦': 4, + '🇹🇨': 4, + '🇹🇩': 4, + '🇹🇫': 4, + '🇹🇬': 4, + '🇹🇭': 4, + '🇹🇯': 4, + '🇹🇰': 4, + '🇹🇱': 4, + '🇹🇲': 4, + '🇹🇳': 4, + '🇹🇴': 4, + '🇹🇷': 4, + '🇹🇹': 4, + '🇹🇻': 4, + '🇹🇼': 4, + '🇹🇿': 4, + '🇺🇦': 4, + '🇺🇬': 4, + '🇺🇲': 4, + '🇺🇳': 4, + '🇺🇸': 4, + '🇺🇾': 4, + '🇺🇿': 4, + '🇻🇦': 4, + '🇻🇨': 4, + '🇻🇪': 4, + '🇻🇬': 4, + '🇻🇮': 4, + '🇻🇳': 4, + '🇻🇺': 4, + '🇼🇫': 4, + '🇼🇸': 4, + '🇽🇰': 4, + '🇾🇪': 4, + '🇾🇹': 4, + '🇿🇦': 4, + '🇿🇲': 4, + '🇿🇼': 4, + '🍄‍🟫': 4, + '🍋‍🟩': 4, + '🏃‍♀️': 4, + '🏃‍♀️‍➡️': 6, + '🏃‍♂️': 4, + '🏃‍♂️‍➡️': 6, + '🏃‍➡️': 4, + '🏃🏻‍♀️': 4, + '🏃🏻‍♀️‍➡️': 6, + '🏃🏻‍♂️': 4, + '🏃🏻‍♂️‍➡️': 6, + '🏃🏻‍➡️': 4, + '🏃🏼‍♀️': 4, + '🏃🏼‍♀️‍➡️': 6, + '🏃🏼‍♂️': 4, + '🏃🏼‍♂️‍➡️': 6, + '🏃🏼‍➡️': 4, + '🏃🏽‍♀️': 4, + '🏃🏽‍♀️‍➡️': 6, + '🏃🏽‍♂️': 4, + '🏃🏽‍♂️‍➡️': 6, + '🏃🏽‍➡️': 4, + '🏃🏾‍♀️': 4, + '🏃🏾‍♀️‍➡️': 6, + '🏃🏾‍♂️': 4, + '🏃🏾‍♂️‍➡️': 6, + '🏃🏾‍➡️': 4, + '🏃🏿‍♀️': 4, + '🏃🏿‍♀️‍➡️': 6, + '🏃🏿‍♂️': 4, + '🏃🏿‍♂️‍➡️': 6, + '🏃🏿‍➡️': 4, + '🏄‍♀️': 4, + '🏄‍♂️': 4, + '🏄🏻‍♀️': 4, + '🏄🏻‍♂️': 4, + '🏄🏼‍♀️': 4, + '🏄🏼‍♂️': 4, + '🏄🏽‍♀️': 4, + '🏄🏽‍♂️': 4, + '🏄🏾‍♀️': 4, + '🏄🏾‍♂️': 4, + '🏄🏿‍♀️': 4, + '🏄🏿‍♂️': 4, + '🏊‍♀️': 4, + '🏊‍♂️': 4, + '🏊🏻‍♀️': 4, + '🏊🏻‍♂️': 4, + '🏊🏼‍♀️': 4, + '🏊🏼‍♂️': 4, + '🏊🏽‍♀️': 4, + '🏊🏽‍♂️': 4, + '🏊🏾‍♀️': 4, + '🏊🏾‍♂️': 4, + '🏊🏿‍♀️': 4, + '🏊🏿‍♂️': 4, + '🏋️‍♀️': 4, + '🏋️‍♂️': 4, + '🏋🏻‍♀️': 3, + '🏋🏻‍♂️': 3, + '🏋🏼‍♀️': 3, + '🏋🏼‍♂️': 3, + '🏋🏽‍♀️': 3, + '🏋🏽‍♂️': 3, + '🏋🏾‍♀️': 3, + '🏋🏾‍♂️': 3, + '🏋🏿‍♀️': 3, + '🏋🏿‍♂️': 3, + '🏌️‍♀️': 4, + '🏌️‍♂️': 4, + '🏌🏻‍♀️': 3, + '🏌🏻‍♂️': 3, + '🏌🏼‍♀️': 3, + '🏌🏼‍♂️': 3, + '🏌🏽‍♀️': 3, + '🏌🏽‍♂️': 3, + '🏌🏾‍♀️': 3, + '🏌🏾‍♂️': 3, + '🏌🏿‍♀️': 3, + '🏌🏿‍♂️': 3, + '🏳️‍⚧️': 4, + '🏳️‍🌈': 4, + '🏴‍☠️': 4, + '🐈‍⬛': 4, + '🐕‍🦺': 4, + '🐦‍⬛': 4, + '🐦‍🔥': 4, + '🐻‍❄️': 4, + '👁️‍🗨️': 4, + '👨‍⚕️': 4, + '👨‍⚖️': 4, + '👨‍✈️': 4, + '👨‍❤️‍👨': 6, + '👨‍❤️‍💋‍👨': 8, + '👨‍🌾': 4, + '👨‍🍳': 4, + '👨‍🍼': 4, + '👨‍🎓': 4, + '👨‍🎤': 4, + '👨‍🎨': 4, + '👨‍🏫': 4, + '👨‍🏭': 4, + '👨‍👦': 4, + '👨‍👦‍👦': 6, + '👨‍👧': 4, + '👨‍👧‍👦': 6, + '👨‍👧‍👧': 6, + '👨‍👨‍👦': 6, + '👨‍👨‍👦‍👦': 8, + '👨‍👨‍👧': 6, + '👨‍👨‍👧‍👦': 8, + '👨‍👨‍👧‍👧': 8, + '👨‍👩‍👦': 6, + '👨‍👩‍👦‍👦': 8, + '👨‍👩‍👧': 6, + '👨‍👩‍👧‍👦': 8, + '👨‍👩‍👧‍👧': 8, + '👨‍💻': 4, + '👨‍💼': 4, + '👨‍🔧': 4, + '👨‍🔬': 4, + '👨‍🚀': 4, + '👨‍🚒': 4, + '👨‍🦯': 4, + '👨‍🦯‍➡️': 6, + '👨‍🦰': 4, + '👨‍🦱': 4, + '👨‍🦲': 4, + '👨‍🦳': 4, + '👨‍🦼': 4, + '👨‍🦼‍➡️': 6, + '👨‍🦽': 4, + '👨‍🦽‍➡️': 6, + '👨🏻‍⚕️': 4, + '👨🏻‍⚖️': 4, + '👨🏻‍✈️': 4, + '👨🏻‍❤️‍👨🏻': 6, + '👨🏻‍❤️‍👨🏽': 6, + '👨🏻‍❤️‍👨🏿': 6, + '👨🏻‍❤️‍💋‍👨🏻': 8, + '👨🏻‍❤️‍💋‍👨🏽': 8, + '👨🏻‍❤️‍💋‍👨🏾': 8, + '👨🏻‍❤️‍💋‍👨🏿': 8, + '👨🏻‍🌾': 4, + '👨🏻‍🍳': 4, + '👨🏻‍🍼': 4, + '👨🏻‍🎓': 4, + '👨🏻‍🎤': 4, + '👨🏻‍🎨': 4, + '👨🏻‍🏫': 4, + '👨🏻‍🏭': 4, + '👨🏻‍🐰‍👨🏼': 6, + '👨🏻‍🐰‍👨🏽': 6, + '👨🏻‍🐰‍👨🏾': 6, + '👨🏻‍🐰‍👨🏿': 6, + '👨🏻‍💻': 4, + '👨🏻‍💼': 4, + '👨🏻‍🔧': 4, + '👨🏻‍🔬': 4, + '👨🏻‍🚀': 4, + '👨🏻‍🚒': 4, + '👨🏻‍🤝‍👨🏼': 6, + '👨🏻‍🤝‍👨🏽': 6, + '👨🏻‍🤝‍👨🏾': 6, + '👨🏻‍🤝‍👨🏿': 6, + '👨🏻‍🦯': 4, + '👨🏻‍🦯‍➡️': 6, + '👨🏻‍🦰': 4, + '👨🏻‍🦱': 4, + '👨🏻‍🦲': 4, + '👨🏻‍🦳': 4, + '👨🏻‍🦼': 4, + '👨🏻‍🦼‍➡️': 6, + '👨🏻‍🦽': 4, + '👨🏻‍🦽‍➡️': 6, + '👨🏻‍🫯‍👨🏼': 6, + '👨🏻‍🫯‍👨🏽': 6, + '👨🏻‍🫯‍👨🏾': 6, + '👨🏻‍🫯‍👨🏿': 6, + '👨🏼‍⚕️': 4, + '👨🏼‍⚖️': 4, + '👨🏼‍✈️': 4, + '👨🏼‍❤️‍👨🏼': 6, + '👨🏼‍❤️‍💋‍👨🏼': 8, + '👨🏼‍❤️‍💋‍👨🏿': 8, + '👨🏼‍🌾': 4, + '👨🏼‍🍳': 4, + '👨🏼‍🍼': 4, + '👨🏼‍🎓': 4, + '👨🏼‍🎤': 4, + '👨🏼‍🎨': 4, + '👨🏼‍🏫': 4, + '👨🏼‍🏭': 4, + '👨🏼‍🐰‍👨🏻': 6, + '👨🏼‍🐰‍👨🏽': 6, + '👨🏼‍🐰‍👨🏿': 6, + '👨🏼‍💻': 4, + '👨🏼‍💼': 4, + '👨🏼‍🔧': 4, + '👨🏼‍🔬': 4, + '👨🏼‍🚀': 4, + '👨🏼‍🚒': 4, + '👨🏼‍🤝‍👨🏻': 6, + '👨🏼‍🤝‍👨🏽': 6, + '👨🏼‍🤝‍👨🏿': 6, + '👨🏼‍🦯': 4, + '👨🏼‍🦯‍➡️': 6, + '👨🏼‍🦰': 4, + '👨🏼‍🦱': 4, + '👨🏼‍🦲': 4, + '👨🏼‍🦳': 4, + '👨🏼‍🦼': 4, + '👨🏼‍🦽': 4, + '👨🏼‍🦽‍➡️': 6, + '👨🏼‍🫯‍👨🏻': 6, + '👨🏼‍🫯‍👨🏽': 6, + '👨🏼‍🫯‍👨🏾': 6, + '👨🏼‍🫯‍👨🏿': 6, + '👨🏽‍⚕️': 4, + '👨🏽‍⚖️': 4, + '👨🏽‍✈️': 4, + '👨🏽‍❤️‍👨🏻': 6, + '👨🏽‍❤️‍👨🏽': 6, + '👨🏽‍❤️‍👨🏿': 6, + '👨🏽‍❤️‍💋‍👨🏻': 8, + '👨🏽‍❤️‍💋‍👨🏽': 8, + '👨🏽‍❤️‍💋‍👨🏿': 8, + '👨🏽‍🌾': 4, + '👨🏽‍🍳': 4, + '👨🏽‍🍼': 4, + '👨🏽‍🎓': 4, + '👨🏽‍🎤': 4, + '👨🏽‍🎨': 4, + '👨🏽‍🏫': 4, + '👨🏽‍🏭': 4, + '👨🏽‍🐰‍👨🏻': 6, + '👨🏽‍🐰‍👨🏼': 6, + '👨🏽‍🐰‍👨🏾': 6, + '👨🏽‍🐰‍👨🏿': 6, + '👨🏽‍💻': 4, + '👨🏽‍💼': 4, + '👨🏽‍🔧': 4, + '👨🏽‍🔬': 4, + '👨🏽‍🚀': 4, + '👨🏽‍🚒': 4, + '👨🏽‍🤝‍👨🏻': 6, + '👨🏽‍🤝‍👨🏼': 6, + '👨🏽‍🤝‍👨🏾': 6, + '👨🏽‍🤝‍👨🏿': 6, + '👨🏽‍🦯': 4, + '👨🏽‍🦯‍➡️': 6, + '👨🏽‍🦰': 4, + '👨🏽‍🦱': 4, + '👨🏽‍🦲': 4, + '👨🏽‍🦳': 4, + '👨🏽‍🦼': 4, + '👨🏽‍🦼‍➡️': 6, + '👨🏽‍🦽': 4, + '👨🏽‍🦽‍➡️': 6, + '👨🏽‍🫯‍👨🏻': 6, + '👨🏽‍🫯‍👨🏼': 6, + '👨🏽‍🫯‍👨🏾': 6, + '👨🏽‍🫯‍👨🏿': 6, + '👨🏾‍⚕️': 4, + '👨🏾‍⚖️': 4, + '👨🏾‍✈️': 4, + '👨🏾‍❤️‍👨🏾': 6, + '👨🏾‍❤️‍💋‍👨🏻': 8, + '👨🏾‍❤️‍💋‍👨🏾': 8, + '👨🏾‍❤️‍💋‍👨🏿': 8, + '👨🏾‍🌾': 4, + '👨🏾‍🍳': 4, + '👨🏾‍🍼': 4, + '👨🏾‍🎓': 4, + '👨🏾‍🎤': 4, + '👨🏾‍🎨': 4, + '👨🏾‍🏫': 4, + '👨🏾‍🏭': 4, + '👨🏾‍🐰‍👨🏻': 6, + '👨🏾‍🐰‍👨🏽': 6, + '👨🏾‍🐰‍👨🏿': 6, + '👨🏾‍💻': 4, + '👨🏾‍💼': 4, + '👨🏾‍🔧': 4, + '👨🏾‍🔬': 4, + '👨🏾‍🚀': 4, + '👨🏾‍🚒': 4, + '👨🏾‍🤝‍👨🏻': 6, + '👨🏾‍🤝‍👨🏽': 6, + '👨🏾‍🤝‍👨🏿': 6, + '👨🏾‍🦯': 4, + '👨🏾‍🦯‍➡️': 6, + '👨🏾‍🦰': 4, + '👨🏾‍🦱': 4, + '👨🏾‍🦲': 4, + '👨🏾‍🦳': 4, + '👨🏾‍🦼': 4, + '👨🏾‍🦽': 4, + '👨🏾‍🦽‍➡️': 6, + '👨🏾‍🫯‍👨🏻': 6, + '👨🏾‍🫯‍👨🏼': 6, + '👨🏾‍🫯‍👨🏽': 6, + '👨🏾‍🫯‍👨🏿': 6, + '👨🏿‍⚕️': 4, + '👨🏿‍⚖️': 4, + '👨🏿‍✈️': 4, + '👨🏿‍❤️‍👨🏻': 6, + '👨🏿‍❤️‍👨🏽': 6, + '👨🏿‍❤️‍👨🏿': 6, + '👨🏿‍❤️‍💋‍👨🏻': 8, + '👨🏿‍❤️‍💋‍👨🏼': 8, + '👨🏿‍❤️‍💋‍👨🏽': 8, + '👨🏿‍❤️‍💋‍👨🏾': 8, + '👨🏿‍❤️‍💋‍👨🏿': 8, + '👨🏿‍🌾': 4, + '👨🏿‍🍳': 4, + '👨🏿‍🍼': 4, + '👨🏿‍🎓': 4, + '👨🏿‍🎤': 4, + '👨🏿‍🎨': 4, + '👨🏿‍🏫': 4, + '👨🏿‍🏭': 4, + '👨🏿‍🐰‍👨🏻': 6, + '👨🏿‍🐰‍👨🏼': 6, + '👨🏿‍🐰‍👨🏽': 6, + '👨🏿‍🐰‍👨🏾': 6, + '👨🏿‍💻': 4, + '👨🏿‍💼': 4, + '👨🏿‍🔧': 4, + '👨🏿‍🔬': 4, + '👨🏿‍🚀': 4, + '👨🏿‍🚒': 4, + '👨🏿‍🤝‍👨🏻': 6, + '👨🏿‍🤝‍👨🏼': 6, + '👨🏿‍🤝‍👨🏽': 6, + '👨🏿‍🤝‍👨🏾': 6, + '👨🏿‍🦯': 4, + '👨🏿‍🦯‍➡️': 6, + '👨🏿‍🦰': 4, + '👨🏿‍🦱': 4, + '👨🏿‍🦲': 4, + '👨🏿‍🦳': 4, + '👨🏿‍🦼': 4, + '👨🏿‍🦼‍➡️': 6, + '👨🏿‍🦽': 4, + '👨🏿‍🦽‍➡️': 6, + '👨🏿‍🫯‍👨🏻': 6, + '👨🏿‍🫯‍👨🏼': 6, + '👨🏿‍🫯‍👨🏽': 6, + '👨🏿‍🫯‍👨🏾': 6, + '👩‍⚕️': 4, + '👩‍⚖️': 4, + '👩‍✈️': 4, + '👩‍❤️‍👨': 6, + '👩‍❤️‍👩': 6, + '👩‍❤️‍💋‍👨': 8, + '👩‍❤️‍💋‍👩': 8, + '👩‍🌾': 4, + '👩‍🍳': 4, + '👩‍🍼': 4, + '👩‍🎓': 4, + '👩‍🎤': 4, + '👩‍🎨': 4, + '👩‍🏫': 4, + '👩‍🏭': 4, + '👩‍👦': 4, + '👩‍👦‍👦': 6, + '👩‍👧': 4, + '👩‍👧‍👦': 6, + '👩‍👧‍👧': 6, + '👩‍👩‍👦': 6, + '👩‍👩‍👦‍👦': 8, + '👩‍👩‍👧': 6, + '👩‍👩‍👧‍👦': 8, + '👩‍👩‍👧‍👧': 8, + '👩‍💻': 4, + '👩‍💼': 4, + '👩‍🔧': 4, + '👩‍🔬': 4, + '👩‍🚀': 4, + '👩‍🚒': 4, + '👩‍🦯': 4, + '👩‍🦯‍➡️': 6, + '👩‍🦰': 4, + '👩‍🦱': 4, + '👩‍🦲': 4, + '👩‍🦳': 4, + '👩‍🦼': 4, + '👩‍🦼‍➡️': 6, + '👩‍🦽': 4, + '👩‍🦽‍➡️': 6, + '👩🏻‍⚕️': 4, + '👩🏻‍⚖️': 4, + '👩🏻‍✈️': 4, + '👩🏻‍❤️‍👨🏻': 6, + '👩🏻‍❤️‍👨🏿': 6, + '👩🏻‍❤️‍👩🏻': 6, + '👩🏻‍❤️‍💋‍👨🏻': 8, + '👩🏻‍❤️‍💋‍👨🏽': 8, + '👩🏻‍❤️‍💋‍👨🏿': 8, + '👩🏻‍❤️‍💋‍👩🏻': 8, + '👩🏻‍❤️‍💋‍👩🏽': 8, + '👩🏻‍❤️‍💋‍👩🏿': 8, + '👩🏻‍🌾': 4, + '👩🏻‍🍳': 4, + '👩🏻‍🍼': 4, + '👩🏻‍🎓': 4, + '👩🏻‍🎤': 4, + '👩🏻‍🎨': 4, + '👩🏻‍🏫': 4, + '👩🏻‍🏭': 4, + '👩🏻‍🐰‍👩🏼': 6, + '👩🏻‍🐰‍👩🏽': 6, + '👩🏻‍🐰‍👩🏾': 6, + '👩🏻‍🐰‍👩🏿': 6, + '👩🏻‍💻': 4, + '👩🏻‍💼': 4, + '👩🏻‍🔧': 4, + '👩🏻‍🔬': 4, + '👩🏻‍🚀': 4, + '👩🏻‍🚒': 4, + '👩🏻‍🤝‍👨🏽': 6, + '👩🏻‍🤝‍👨🏿': 6, + '👩🏻‍🤝‍👩🏼': 6, + '👩🏻‍🤝‍👩🏽': 6, + '👩🏻‍🤝‍👩🏾': 6, + '👩🏻‍🤝‍👩🏿': 6, + '👩🏻‍🦯': 4, + '👩🏻‍🦯‍➡️': 6, + '👩🏻‍🦰': 4, + '👩🏻‍🦱': 4, + '👩🏻‍🦲': 4, + '👩🏻‍🦳': 4, + '👩🏻‍🦼': 4, + '👩🏻‍🦼‍➡️': 6, + '👩🏻‍🦽': 4, + '👩🏻‍🦽‍➡️': 6, + '👩🏻‍🫯‍👩🏼': 6, + '👩🏻‍🫯‍👩🏽': 6, + '👩🏻‍🫯‍👩🏾': 6, + '👩🏻‍🫯‍👩🏿': 6, + '👩🏼‍⚕️': 4, + '👩🏼‍⚖️': 4, + '👩🏼‍✈️': 4, + '👩🏼‍❤️‍👨🏼': 6, + '👩🏼‍❤️‍👩🏼': 6, + '👩🏼‍❤️‍💋‍👨🏼': 8, + '👩🏼‍❤️‍💋‍👩🏼': 8, + '👩🏼‍🌾': 4, + '👩🏼‍🍳': 4, + '👩🏼‍🍼': 4, + '👩🏼‍🎓': 4, + '👩🏼‍🎤': 4, + '👩🏼‍🎨': 4, + '👩🏼‍🏫': 4, + '👩🏼‍🏭': 4, + '👩🏼‍🐰‍👩🏻': 6, + '👩🏼‍🐰‍👩🏿': 6, + '👩🏼‍💻': 4, + '👩🏼‍💼': 4, + '👩🏼‍🔧': 4, + '👩🏼‍🔬': 4, + '👩🏼‍🚀': 4, + '👩🏼‍🚒': 4, + '👩🏼‍🤝‍👩🏻': 6, + '👩🏼‍🤝‍👩🏽': 6, + '👩🏼‍🤝‍👩🏿': 6, + '👩🏼‍🦯': 4, + '👩🏼‍🦯‍➡️': 6, + '👩🏼‍🦰': 4, + '👩🏼‍🦱': 4, + '👩🏼‍🦲': 4, + '👩🏼‍🦳': 4, + '👩🏼‍🦼': 4, + '👩🏼‍🦽': 4, + '👩🏼‍🫯‍👩🏻': 6, + '👩🏼‍🫯‍👩🏽': 6, + '👩🏼‍🫯‍👩🏾': 6, + '👩🏼‍🫯‍👩🏿': 6, + '👩🏽‍⚕️': 4, + '👩🏽‍⚖️': 4, + '👩🏽‍✈️': 4, + '👩🏽‍❤️‍👨🏽': 6, + '👩🏽‍❤️‍👩🏽': 6, + '👩🏽‍❤️‍💋‍👨🏻': 8, + '👩🏽‍❤️‍💋‍👨🏽': 8, + '👩🏽‍❤️‍💋‍👨🏿': 8, + '👩🏽‍❤️‍💋‍👩🏻': 8, + '👩🏽‍❤️‍💋‍👩🏽': 8, + '👩🏽‍❤️‍💋‍👩🏿': 8, + '👩🏽‍🌾': 4, + '👩🏽‍🍳': 4, + '👩🏽‍🍼': 4, + '👩🏽‍🎓': 4, + '👩🏽‍🎤': 4, + '👩🏽‍🎨': 4, + '👩🏽‍🏫': 4, + '👩🏽‍🏭': 4, + '👩🏽‍🐰‍👩🏻': 6, + '👩🏽‍🐰‍👩🏾': 6, + '👩🏽‍🐰‍👩🏿': 6, + '👩🏽‍💻': 4, + '👩🏽‍💼': 4, + '👩🏽‍🔧': 4, + '👩🏽‍🔬': 4, + '👩🏽‍🚀': 4, + '👩🏽‍🚒': 4, + '👩🏽‍🤝‍👨🏻': 6, + '👩🏽‍🤝‍👨🏿': 6, + '👩🏽‍🤝‍👩🏻': 6, + '👩🏽‍🤝‍👩🏼': 6, + '👩🏽‍🤝‍👩🏾': 6, + '👩🏽‍🤝‍👩🏿': 6, + '👩🏽‍🦯': 4, + '👩🏽‍🦯‍➡️': 6, + '👩🏽‍🦰': 4, + '👩🏽‍🦱': 4, + '👩🏽‍🦲': 4, + '👩🏽‍🦳': 4, + '👩🏽‍🦼': 4, + '👩🏽‍🦼‍➡️': 6, + '👩🏽‍🦽': 4, + '👩🏽‍🦽‍➡️': 6, + '👩🏽‍🫯‍👩🏻': 6, + '👩🏽‍🫯‍👩🏼': 6, + '👩🏽‍🫯‍👩🏾': 6, + '👩🏽‍🫯‍👩🏿': 6, + '👩🏾‍⚕️': 4, + '👩🏾‍⚖️': 4, + '👩🏾‍✈️': 4, + '👩🏾‍❤️‍👨🏾': 6, + '👩🏾‍❤️‍👩🏾': 6, + '👩🏾‍❤️‍💋‍👨🏾': 8, + '👩🏾‍❤️‍💋‍👩🏾': 8, + '👩🏾‍🌾': 4, + '👩🏾‍🍳': 4, + '👩🏾‍🍼': 4, + '👩🏾‍🎓': 4, + '👩🏾‍🎤': 4, + '👩🏾‍🎨': 4, + '👩🏾‍🏫': 4, + '👩🏾‍🏭': 4, + '👩🏾‍🐰‍👩🏻': 6, + '👩🏾‍🐰‍👩🏽': 6, + '👩🏾‍🐰‍👩🏿': 6, + '👩🏾‍💻': 4, + '👩🏾‍💼': 4, + '👩🏾‍🔧': 4, + '👩🏾‍🔬': 4, + '👩🏾‍🚀': 4, + '👩🏾‍🚒': 4, + '👩🏾‍🤝‍👩🏻': 6, + '👩🏾‍🤝‍👩🏽': 6, + '👩🏾‍🤝‍👩🏿': 6, + '👩🏾‍🦯': 4, + '👩🏾‍🦯‍➡️': 6, + '👩🏾‍🦰': 4, + '👩🏾‍🦱': 4, + '👩🏾‍🦲': 4, + '👩🏾‍🦳': 4, + '👩🏾‍🦼': 4, + '👩🏾‍🦽': 4, + '👩🏾‍🦽‍➡️': 6, + '👩🏾‍🫯‍👩🏻': 6, + '👩🏾‍🫯‍👩🏼': 6, + '👩🏾‍🫯‍👩🏽': 6, + '👩🏾‍🫯‍👩🏿': 6, + '👩🏿‍⚕️': 4, + '👩🏿‍⚖️': 4, + '👩🏿‍✈️': 4, + '👩🏿‍❤️‍👨🏻': 6, + '👩🏿‍❤️‍👨🏿': 6, + '👩🏿‍❤️‍👩🏿': 6, + '👩🏿‍❤️‍💋‍👨🏻': 8, + '👩🏿‍❤️‍💋‍👨🏽': 8, + '👩🏿‍❤️‍💋‍👨🏿': 8, + '👩🏿‍❤️‍💋‍👩🏻': 8, + '👩🏿‍❤️‍💋‍👩🏽': 8, + '👩🏿‍❤️‍💋‍👩🏿': 8, + '👩🏿‍🌾': 4, + '👩🏿‍🍳': 4, + '👩🏿‍🍼': 4, + '👩🏿‍🎓': 4, + '👩🏿‍🎤': 4, + '👩🏿‍🎨': 4, + '👩🏿‍🏫': 4, + '👩🏿‍🏭': 4, + '👩🏿‍🐰‍👩🏻': 6, + '👩🏿‍🐰‍👩🏼': 6, + '👩🏿‍🐰‍👩🏽': 6, + '👩🏿‍🐰‍👩🏾': 6, + '👩🏿‍💻': 4, + '👩🏿‍💼': 4, + '👩🏿‍🔧': 4, + '👩🏿‍🔬': 4, + '👩🏿‍🚀': 4, + '👩🏿‍🚒': 4, + '👩🏿‍🤝‍👨🏻': 6, + '👩🏿‍🤝‍👨🏽': 6, + '👩🏿‍🤝‍👩🏻': 6, + '👩🏿‍🤝‍👩🏼': 6, + '👩🏿‍🤝‍👩🏽': 6, + '👩🏿‍🤝‍👩🏾': 6, + '👩🏿‍🦯': 4, + '👩🏿‍🦯‍➡️': 6, + '👩🏿‍🦰': 4, + '👩🏿‍🦱': 4, + '👩🏿‍🦲': 4, + '👩🏿‍🦳': 4, + '👩🏿‍🦼': 4, + '👩🏿‍🦼‍➡️': 6, + '👩🏿‍🦽': 4, + '👩🏿‍🦽‍➡️': 6, + '👩🏿‍🫯‍👩🏻': 6, + '👩🏿‍🫯‍👩🏼': 6, + '👩🏿‍🫯‍👩🏽': 6, + '👩🏿‍🫯‍👩🏾': 6, + '👮‍♀️': 4, + '👮‍♂️': 4, + '👮🏻‍♀️': 4, + '👮🏻‍♂️': 4, + '👮🏼‍♀️': 4, + '👮🏼‍♂️': 4, + '👮🏽‍♀️': 4, + '👮🏽‍♂️': 4, + '👮🏾‍♀️': 4, + '👮🏾‍♂️': 4, + '👮🏿‍♀️': 4, + '👮🏿‍♂️': 4, + '👯‍♀️': 4, + '👯‍♂️': 4, + '👯🏻‍♀️': 4, + '👯🏻‍♂️': 4, + '👯🏼‍♀️': 4, + '👯🏼‍♂️': 4, + '👯🏽‍♀️': 4, + '👯🏽‍♂️': 4, + '👯🏾‍♀️': 4, + '👯🏾‍♂️': 4, + '👯🏿‍♀️': 4, + '👯🏿‍♂️': 4, + '👰‍♀️': 4, + '👰‍♂️': 4, + '👰🏻‍♀️': 4, + '👰🏻‍♂️': 4, + '👰🏼‍♀️': 4, + '👰🏼‍♂️': 4, + '👰🏽‍♀️': 4, + '👰🏽‍♂️': 4, + '👰🏾‍♀️': 4, + '👰🏾‍♂️': 4, + '👰🏿‍♀️': 4, + '👰🏿‍♂️': 4, + '👱‍♀️': 4, + '👱‍♂️': 4, + '👱🏻‍♀️': 4, + '👱🏻‍♂️': 4, + '👱🏼‍♀️': 4, + '👱🏼‍♂️': 4, + '👱🏽‍♀️': 4, + '👱🏽‍♂️': 4, + '👱🏾‍♀️': 4, + '👱🏾‍♂️': 4, + '👱🏿‍♀️': 4, + '👱🏿‍♂️': 4, + '👳‍♀️': 4, + '👳‍♂️': 4, + '👳🏻‍♀️': 4, + '👳🏻‍♂️': 4, + '👳🏼‍♀️': 4, + '👳🏼‍♂️': 4, + '👳🏽‍♀️': 4, + '👳🏽‍♂️': 4, + '👳🏾‍♀️': 4, + '👳🏾‍♂️': 4, + '👳🏿‍♀️': 4, + '👳🏿‍♂️': 4, + '👷‍♀️': 4, + '👷‍♂️': 4, + '👷🏻‍♀️': 4, + '👷🏻‍♂️': 4, + '👷🏼‍♀️': 4, + '👷🏼‍♂️': 4, + '👷🏽‍♀️': 4, + '👷🏽‍♂️': 4, + '👷🏾‍♀️': 4, + '👷🏾‍♂️': 4, + '👷🏿‍♀️': 4, + '👷🏿‍♂️': 4, + '💁‍♀️': 4, + '💁‍♂️': 4, + '💁🏻‍♀️': 4, + '💁🏻‍♂️': 4, + '💁🏼‍♀️': 4, + '💁🏼‍♂️': 4, + '💁🏽‍♀️': 4, + '💁🏽‍♂️': 4, + '💁🏾‍♀️': 4, + '💁🏾‍♂️': 4, + '💁🏿‍♀️': 4, + '💁🏿‍♂️': 4, + '💂‍♀️': 4, + '💂‍♂️': 4, + '💂🏻‍♀️': 4, + '💂🏻‍♂️': 4, + '💂🏼‍♀️': 4, + '💂🏼‍♂️': 4, + '💂🏽‍♀️': 4, + '💂🏽‍♂️': 4, + '💂🏾‍♀️': 4, + '💂🏾‍♂️': 4, + '💂🏿‍♀️': 4, + '💂🏿‍♂️': 4, + '💆‍♀️': 4, + '💆‍♂️': 4, + '💆🏻‍♀️': 4, + '💆🏻‍♂️': 4, + '💆🏼‍♀️': 4, + '💆🏼‍♂️': 4, + '💆🏽‍♀️': 4, + '💆🏽‍♂️': 4, + '💆🏾‍♀️': 4, + '💆🏾‍♂️': 4, + '💆🏿‍♀️': 4, + '💆🏿‍♂️': 4, + '💇‍♀️': 4, + '💇‍♂️': 4, + '💇🏻‍♀️': 4, + '💇🏻‍♂️': 4, + '💇🏼‍♀️': 4, + '💇🏼‍♂️': 4, + '💇🏽‍♀️': 4, + '💇🏽‍♂️': 4, + '💇🏾‍♀️': 4, + '💇🏾‍♂️': 4, + '💇🏿‍♀️': 4, + '💇🏿‍♂️': 4, + '🕵️‍♀️': 4, + '🕵️‍♂️': 4, + '🕵🏻‍♀️': 3, + '🕵🏻‍♂️': 3, + '🕵🏼‍♀️': 3, + '🕵🏼‍♂️': 3, + '🕵🏽‍♀️': 3, + '🕵🏽‍♂️': 3, + '🕵🏾‍♀️': 3, + '🕵🏾‍♂️': 3, + '🕵🏿‍♀️': 3, + '🕵🏿‍♂️': 3, + '😮‍💨': 4, + '😵‍💫': 4, + '😶‍🌫️': 4, + '🙂‍↔️': 4, + '🙂‍↕️': 4, + '🙅‍♀️': 4, + '🙅‍♂️': 4, + '🙅🏻‍♀️': 4, + '🙅🏻‍♂️': 4, + '🙅🏼‍♀️': 4, + '🙅🏼‍♂️': 4, + '🙅🏽‍♀️': 4, + '🙅🏽‍♂️': 4, + '🙅🏾‍♀️': 4, + '🙅🏾‍♂️': 4, + '🙅🏿‍♀️': 4, + '🙅🏿‍♂️': 4, + '🙆‍♀️': 4, + '🙆‍♂️': 4, + '🙆🏻‍♀️': 4, + '🙆🏻‍♂️': 4, + '🙆🏼‍♀️': 4, + '🙆🏼‍♂️': 4, + '🙆🏽‍♀️': 4, + '🙆🏽‍♂️': 4, + '🙆🏾‍♀️': 4, + '🙆🏾‍♂️': 4, + '🙆🏿‍♀️': 4, + '🙆🏿‍♂️': 4, + '🙇‍♀️': 4, + '🙇‍♂️': 4, + '🙇🏻‍♀️': 4, + '🙇🏻‍♂️': 4, + '🙇🏼‍♀️': 4, + '🙇🏼‍♂️': 4, + '🙇🏽‍♀️': 4, + '🙇🏽‍♂️': 4, + '🙇🏾‍♀️': 4, + '🙇🏾‍♂️': 4, + '🙇🏿‍♀️': 4, + '🙇🏿‍♂️': 4, + '🙋‍♀️': 4, + '🙋‍♂️': 4, + '🙋🏻‍♀️': 4, + '🙋🏻‍♂️': 4, + '🙋🏼‍♀️': 4, + '🙋🏼‍♂️': 4, + '🙋🏽‍♀️': 4, + '🙋🏽‍♂️': 4, + '🙋🏾‍♀️': 4, + '🙋🏾‍♂️': 4, + '🙋🏿‍♀️': 4, + '🙋🏿‍♂️': 4, + '🙍‍♀️': 4, + '🙍‍♂️': 4, + '🙍🏻‍♀️': 4, + '🙍🏻‍♂️': 4, + '🙍🏼‍♀️': 4, + '🙍🏼‍♂️': 4, + '🙍🏽‍♀️': 4, + '🙍🏽‍♂️': 4, + '🙍🏾‍♀️': 4, + '🙍🏾‍♂️': 4, + '🙍🏿‍♀️': 4, + '🙍🏿‍♂️': 4, + '🙎‍♀️': 4, + '🙎‍♂️': 4, + '🙎🏻‍♀️': 4, + '🙎🏻‍♂️': 4, + '🙎🏼‍♀️': 4, + '🙎🏼‍♂️': 4, + '🙎🏽‍♀️': 4, + '🙎🏽‍♂️': 4, + '🙎🏾‍♀️': 4, + '🙎🏾‍♂️': 4, + '🙎🏿‍♀️': 4, + '🙎🏿‍♂️': 4, + '🚣‍♀️': 4, + '🚣‍♂️': 4, + '🚣🏻‍♀️': 4, + '🚣🏻‍♂️': 4, + '🚣🏼‍♀️': 4, + '🚣🏼‍♂️': 4, + '🚣🏽‍♀️': 4, + '🚣🏽‍♂️': 4, + '🚣🏾‍♀️': 4, + '🚣🏾‍♂️': 4, + '🚣🏿‍♀️': 4, + '🚣🏿‍♂️': 4, + '🚴‍♀️': 4, + '🚴‍♂️': 4, + '🚴🏻‍♀️': 4, + '🚴🏻‍♂️': 4, + '🚴🏼‍♀️': 4, + '🚴🏼‍♂️': 4, + '🚴🏽‍♀️': 4, + '🚴🏽‍♂️': 4, + '🚴🏾‍♀️': 4, + '🚴🏾‍♂️': 4, + '🚴🏿‍♀️': 4, + '🚴🏿‍♂️': 4, + '🚵‍♀️': 4, + '🚵‍♂️': 4, + '🚵🏻‍♀️': 4, + '🚵🏻‍♂️': 4, + '🚵🏼‍♀️': 4, + '🚵🏼‍♂️': 4, + '🚵🏽‍♀️': 4, + '🚵🏽‍♂️': 4, + '🚵🏾‍♀️': 4, + '🚵🏾‍♂️': 4, + '🚵🏿‍♀️': 4, + '🚵🏿‍♂️': 4, + '🚶‍♀️': 4, + '🚶‍♀️‍➡️': 6, + '🚶‍♂️': 4, + '🚶‍♂️‍➡️': 6, + '🚶‍➡️': 4, + '🚶🏻‍♀️': 4, + '🚶🏻‍♀️‍➡️': 6, + '🚶🏻‍♂️': 4, + '🚶🏻‍♂️‍➡️': 6, + '🚶🏻‍➡️': 4, + '🚶🏼‍♀️': 4, + '🚶🏼‍♀️‍➡️': 6, + '🚶🏼‍♂️': 4, + '🚶🏼‍♂️‍➡️': 6, + '🚶🏼‍➡️': 4, + '🚶🏽‍♀️': 4, + '🚶🏽‍♀️‍➡️': 6, + '🚶🏽‍♂️': 4, + '🚶🏽‍♂️‍➡️': 6, + '🚶🏽‍➡️': 4, + '🚶🏾‍♀️': 4, + '🚶🏾‍♀️‍➡️': 6, + '🚶🏾‍♂️': 4, + '🚶🏾‍♂️‍➡️': 6, + '🚶🏾‍➡️': 4, + '🚶🏿‍♀️': 4, + '🚶🏿‍♀️‍➡️': 6, + '🚶🏿‍♂️': 4, + '🚶🏿‍♂️‍➡️': 6, + '🚶🏿‍➡️': 4, + '🤦‍♀️': 4, + '🤦‍♂️': 4, + '🤦🏻‍♀️': 4, + '🤦🏻‍♂️': 4, + '🤦🏼‍♀️': 4, + '🤦🏼‍♂️': 4, + '🤦🏽‍♀️': 4, + '🤦🏽‍♂️': 4, + '🤦🏾‍♀️': 4, + '🤦🏾‍♂️': 4, + '🤦🏿‍♀️': 4, + '🤦🏿‍♂️': 4, + '🤵‍♀️': 4, + '🤵‍♂️': 4, + '🤵🏻‍♀️': 4, + '🤵🏻‍♂️': 4, + '🤵🏼‍♀️': 4, + '🤵🏼‍♂️': 4, + '🤵🏽‍♀️': 4, + '🤵🏽‍♂️': 4, + '🤵🏾‍♀️': 4, + '🤵🏾‍♂️': 4, + '🤵🏿‍♀️': 4, + '🤵🏿‍♂️': 4, + '🤷‍♀️': 4, + '🤷‍♂️': 4, + '🤷🏻‍♀️': 4, + '🤷🏻‍♂️': 4, + '🤷🏼‍♀️': 4, + '🤷🏼‍♂️': 4, + '🤷🏽‍♀️': 4, + '🤷🏽‍♂️': 4, + '🤷🏾‍♀️': 4, + '🤷🏾‍♂️': 4, + '🤷🏿‍♀️': 4, + '🤷🏿‍♂️': 4, + '🤸‍♀️': 4, + '🤸‍♂️': 4, + '🤸🏻‍♀️': 4, + '🤸🏻‍♂️': 4, + '🤸🏼‍♀️': 4, + '🤸🏼‍♂️': 4, + '🤸🏽‍♀️': 4, + '🤸🏽‍♂️': 4, + '🤸🏾‍♀️': 4, + '🤸🏾‍♂️': 4, + '🤸🏿‍♀️': 4, + '🤸🏿‍♂️': 4, + '🤹‍♀️': 4, + '🤹‍♂️': 4, + '🤹🏻‍♀️': 4, + '🤹🏻‍♂️': 4, + '🤹🏼‍♀️': 4, + '🤹🏼‍♂️': 4, + '🤹🏽‍♀️': 4, + '🤹🏽‍♂️': 4, + '🤹🏾‍♀️': 4, + '🤹🏾‍♂️': 4, + '🤹🏿‍♀️': 4, + '🤹🏿‍♂️': 4, + '🤼‍♀️': 4, + '🤼‍♂️': 4, + '🤼🏻‍♀️': 4, + '🤼🏻‍♂️': 4, + '🤼🏼‍♀️': 4, + '🤼🏼‍♂️': 4, + '🤼🏽‍♀️': 4, + '🤼🏽‍♂️': 4, + '🤼🏾‍♀️': 4, + '🤼🏾‍♂️': 4, + '🤼🏿‍♀️': 4, + '🤼🏿‍♂️': 4, + '🤽‍♀️': 4, + '🤽‍♂️': 4, + '🤽🏻‍♀️': 4, + '🤽🏻‍♂️': 4, + '🤽🏼‍♀️': 4, + '🤽🏼‍♂️': 4, + '🤽🏽‍♀️': 4, + '🤽🏽‍♂️': 4, + '🤽🏾‍♀️': 4, + '🤽🏾‍♂️': 4, + '🤽🏿‍♀️': 4, + '🤽🏿‍♂️': 4, + '🤾‍♀️': 4, + '🤾‍♂️': 4, + '🤾🏻‍♀️': 4, + '🤾🏻‍♂️': 4, + '🤾🏼‍♀️': 4, + '🤾🏼‍♂️': 4, + '🤾🏽‍♀️': 4, + '🤾🏽‍♂️': 4, + '🤾🏾‍♀️': 4, + '🤾🏾‍♂️': 4, + '🤾🏿‍♀️': 4, + '🤾🏿‍♂️': 4, + '🦸‍♀️': 4, + '🦸‍♂️': 4, + '🦸🏻‍♀️': 4, + '🦸🏻‍♂️': 4, + '🦸🏼‍♀️': 4, + '🦸🏼‍♂️': 4, + '🦸🏽‍♀️': 4, + '🦸🏽‍♂️': 4, + '🦸🏾‍♀️': 4, + '🦸🏾‍♂️': 4, + '🦸🏿‍♀️': 4, + '🦸🏿‍♂️': 4, + '🦹‍♀️': 4, + '🦹‍♂️': 4, + '🦹🏻‍♀️': 4, + '🦹🏻‍♂️': 4, + '🦹🏼‍♀️': 4, + '🦹🏼‍♂️': 4, + '🦹🏽‍♀️': 4, + '🦹🏽‍♂️': 4, + '🦹🏾‍♀️': 4, + '🦹🏾‍♂️': 4, + '🦹🏿‍♀️': 4, + '🦹🏿‍♂️': 4, + '🧍‍♀️': 4, + '🧍‍♂️': 4, + '🧍🏻‍♀️': 4, + '🧍🏻‍♂️': 4, + '🧍🏼‍♀️': 4, + '🧍🏼‍♂️': 4, + '🧍🏽‍♀️': 4, + '🧍🏽‍♂️': 4, + '🧍🏾‍♀️': 4, + '🧍🏾‍♂️': 4, + '🧍🏿‍♀️': 4, + '🧍🏿‍♂️': 4, + '🧎‍♀️': 4, + '🧎‍♀️‍➡️': 6, + '🧎‍♂️': 4, + '🧎‍♂️‍➡️': 6, + '🧎‍➡️': 4, + '🧎🏻‍♀️': 4, + '🧎🏻‍♀️‍➡️': 6, + '🧎🏻‍♂️': 4, + '🧎🏻‍♂️‍➡️': 6, + '🧎🏻‍➡️': 4, + '🧎🏼‍♀️': 4, + '🧎🏼‍♀️‍➡️': 6, + '🧎🏼‍♂️': 4, + '🧎🏼‍♂️‍➡️': 6, + '🧎🏼‍➡️': 4, + '🧎🏽‍♀️': 4, + '🧎🏽‍♀️‍➡️': 6, + '🧎🏽‍♂️': 4, + '🧎🏽‍♂️‍➡️': 6, + '🧎🏽‍➡️': 4, + '🧎🏾‍♀️': 4, + '🧎🏾‍♀️‍➡️': 6, + '🧎🏾‍♂️': 4, + '🧎🏾‍♂️‍➡️': 6, + '🧎🏾‍➡️': 4, + '🧎🏿‍♀️': 4, + '🧎🏿‍♀️‍➡️': 6, + '🧎🏿‍♂️': 4, + '🧎🏿‍♂️‍➡️': 6, + '🧎🏿‍➡️': 4, + '🧏‍♀️': 4, + '🧏‍♂️': 4, + '🧏🏻‍♀️': 4, + '🧏🏻‍♂️': 4, + '🧏🏼‍♀️': 4, + '🧏🏼‍♂️': 4, + '🧏🏽‍♀️': 4, + '🧏🏽‍♂️': 4, + '🧏🏾‍♀️': 4, + '🧏🏾‍♂️': 4, + '🧏🏿‍♀️': 4, + '🧏🏿‍♂️': 4, + '🧑‍⚕️': 4, + '🧑‍⚖️': 4, + '🧑‍✈️': 4, + '🧑‍🌾': 4, + '🧑‍🍳': 4, + '🧑‍🍼': 4, + '🧑‍🎄': 4, + '🧑‍🎓': 4, + '🧑‍🎤': 4, + '🧑‍🎨': 4, + '🧑‍🏫': 4, + '🧑‍🏭': 4, + '🧑‍💻': 4, + '🧑‍💼': 4, + '🧑‍🔧': 4, + '🧑‍🔬': 4, + '🧑‍🚀': 4, + '🧑‍🚒': 4, + '🧑‍🤝‍🧑': 6, + '🧑‍🦯': 4, + '🧑‍🦯‍➡️': 6, + '🧑‍🦰': 4, + '🧑‍🦱': 4, + '🧑‍🦲': 4, + '🧑‍🦳': 4, + '🧑‍🦼': 4, + '🧑‍🦼‍➡️': 6, + '🧑‍🦽': 4, + '🧑‍🦽‍➡️': 6, + '🧑‍🧑‍🧒': 6, + '🧑‍🧑‍🧒‍🧒': 8, + '🧑‍🧒': 4, + '🧑‍🧒‍🧒': 6, + '🧑‍🩰': 4, + '🧑🏻‍⚕️': 4, + '🧑🏻‍⚖️': 4, + '🧑🏻‍✈️': 4, + '🧑🏻‍❤️‍💋‍🧑🏿': 8, + '🧑🏻‍🌾': 4, + '🧑🏻‍🍳': 4, + '🧑🏻‍🍼': 4, + '🧑🏻‍🎄': 4, + '🧑🏻‍🎓': 4, + '🧑🏻‍🎤': 4, + '🧑🏻‍🎨': 4, + '🧑🏻‍🏫': 4, + '🧑🏻‍🏭': 4, + '🧑🏻‍🐰‍🧑🏽': 6, + '🧑🏻‍🐰‍🧑🏾': 6, + '🧑🏻‍🐰‍🧑🏿': 6, + '🧑🏻‍💻': 4, + '🧑🏻‍💼': 4, + '🧑🏻‍🔧': 4, + '🧑🏻‍🔬': 4, + '🧑🏻‍🚀': 4, + '🧑🏻‍🚒': 4, + '🧑🏻‍🤝‍🧑🏻': 6, + '🧑🏻‍🤝‍🧑🏼': 6, + '🧑🏻‍🤝‍🧑🏽': 6, + '🧑🏻‍🤝‍🧑🏾': 6, + '🧑🏻‍🤝‍🧑🏿': 6, + '🧑🏻‍🦯': 4, + '🧑🏻‍🦯‍➡️': 6, + '🧑🏻‍🦰': 4, + '🧑🏻‍🦱': 4, + '🧑🏻‍🦲': 4, + '🧑🏻‍🦳': 4, + '🧑🏻‍🦼': 4, + '🧑🏻‍🦼‍➡️': 6, + '🧑🏻‍🦽': 4, + '🧑🏻‍🦽‍➡️': 6, + '🧑🏻‍🩰': 4, + '🧑🏻‍🫯‍🧑🏼': 6, + '🧑🏻‍🫯‍🧑🏽': 6, + '🧑🏻‍🫯‍🧑🏾': 6, + '🧑🏻‍🫯‍🧑🏿': 6, + '🧑🏼‍⚕️': 4, + '🧑🏼‍⚖️': 4, + '🧑🏼‍✈️': 4, + '🧑🏼‍🌾': 4, + '🧑🏼‍🍳': 4, + '🧑🏼‍🍼': 4, + '🧑🏼‍🎄': 4, + '🧑🏼‍🎓': 4, + '🧑🏼‍🎤': 4, + '🧑🏼‍🎨': 4, + '🧑🏼‍🏫': 4, + '🧑🏼‍🏭': 4, + '🧑🏼‍🐰‍🧑🏿': 6, + '🧑🏼‍💻': 4, + '🧑🏼‍💼': 4, + '🧑🏼‍🔧': 4, + '🧑🏼‍🔬': 4, + '🧑🏼‍🚀': 4, + '🧑🏼‍🚒': 4, + '🧑🏼‍🤝‍🧑🏻': 6, + '🧑🏼‍🤝‍🧑🏼': 6, + '🧑🏼‍🤝‍🧑🏽': 6, + '🧑🏼‍🤝‍🧑🏿': 6, + '🧑🏼‍🦯': 4, + '🧑🏼‍🦯‍➡️': 6, + '🧑🏼‍🦰': 4, + '🧑🏼‍🦱': 4, + '🧑🏼‍🦲': 4, + '🧑🏼‍🦳': 4, + '🧑🏼‍🦼': 4, + '🧑🏼‍🦽': 4, + '🧑🏼‍🩰': 4, + '🧑🏼‍🫯‍🧑🏻': 6, + '🧑🏼‍🫯‍🧑🏽': 6, + '🧑🏼‍🫯‍🧑🏿': 6, + '🧑🏽‍⚕️': 4, + '🧑🏽‍⚖️': 4, + '🧑🏽‍✈️': 4, + '🧑🏽‍❤️‍💋‍🧑🏿': 8, + '🧑🏽‍🌾': 4, + '🧑🏽‍🍳': 4, + '🧑🏽‍🍼': 4, + '🧑🏽‍🎄': 4, + '🧑🏽‍🎓': 4, + '🧑🏽‍🎤': 4, + '🧑🏽‍🎨': 4, + '🧑🏽‍🏫': 4, + '🧑🏽‍🏭': 4, + '🧑🏽‍🐰‍🧑🏻': 6, + '🧑🏽‍🐰‍🧑🏿': 6, + '🧑🏽‍💻': 4, + '🧑🏽‍💼': 4, + '🧑🏽‍🔧': 4, + '🧑🏽‍🔬': 4, + '🧑🏽‍🚀': 4, + '🧑🏽‍🚒': 4, + '🧑🏽‍🤝‍🧑🏻': 6, + '🧑🏽‍🤝‍🧑🏼': 6, + '🧑🏽‍🤝‍🧑🏽': 6, + '🧑🏽‍🤝‍🧑🏾': 6, + '🧑🏽‍🤝‍🧑🏿': 6, + '🧑🏽‍🦯': 4, + '🧑🏽‍🦯‍➡️': 6, + '🧑🏽‍🦰': 4, + '🧑🏽‍🦱': 4, + '🧑🏽‍🦲': 4, + '🧑🏽‍🦳': 4, + '🧑🏽‍🦼': 4, + '🧑🏽‍🦼‍➡️': 6, + '🧑🏽‍🦽': 4, + '🧑🏽‍🦽‍➡️': 6, + '🧑🏽‍🩰': 4, + '🧑🏽‍🫯‍🧑🏻': 6, + '🧑🏽‍🫯‍🧑🏼': 6, + '🧑🏽‍🫯‍🧑🏾': 6, + '🧑🏽‍🫯‍🧑🏿': 6, + '🧑🏾‍⚕️': 4, + '🧑🏾‍⚖️': 4, + '🧑🏾‍✈️': 4, + '🧑🏾‍🌾': 4, + '🧑🏾‍🍳': 4, + '🧑🏾‍🍼': 4, + '🧑🏾‍🎄': 4, + '🧑🏾‍🎓': 4, + '🧑🏾‍🎤': 4, + '🧑🏾‍🎨': 4, + '🧑🏾‍🏫': 4, + '🧑🏾‍🏭': 4, + '🧑🏾‍🐰‍🧑🏻': 6, + '🧑🏾‍🐰‍🧑🏿': 6, + '🧑🏾‍💻': 4, + '🧑🏾‍💼': 4, + '🧑🏾‍🔧': 4, + '🧑🏾‍🔬': 4, + '🧑🏾‍🚀': 4, + '🧑🏾‍🚒': 4, + '🧑🏾‍🤝‍🧑🏻': 6, + '🧑🏾‍🤝‍🧑🏽': 6, + '🧑🏾‍🤝‍🧑🏾': 6, + '🧑🏾‍🤝‍🧑🏿': 6, + '🧑🏾‍🦯': 4, + '🧑🏾‍🦯‍➡️': 6, + '🧑🏾‍🦰': 4, + '🧑🏾‍🦱': 4, + '🧑🏾‍🦲': 4, + '🧑🏾‍🦳': 4, + '🧑🏾‍🦼': 4, + '🧑🏾‍🦽': 4, + '🧑🏾‍🩰': 4, + '🧑🏾‍🫯‍🧑🏻': 6, + '🧑🏾‍🫯‍🧑🏽': 6, + '🧑🏾‍🫯‍🧑🏿': 6, + '🧑🏿‍⚕️': 4, + '🧑🏿‍⚖️': 4, + '🧑🏿‍✈️': 4, + '🧑🏿‍❤️‍💋‍🧑🏻': 8, + '🧑🏿‍❤️‍💋‍🧑🏽': 8, + '🧑🏿‍🌾': 4, + '🧑🏿‍🍳': 4, + '🧑🏿‍🍼': 4, + '🧑🏿‍🎄': 4, + '🧑🏿‍🎓': 4, + '🧑🏿‍🎤': 4, + '🧑🏿‍🎨': 4, + '🧑🏿‍🏫': 4, + '🧑🏿‍🏭': 4, + '🧑🏿‍🐰‍🧑🏻': 6, + '🧑🏿‍🐰‍🧑🏼': 6, + '🧑🏿‍🐰‍🧑🏽': 6, + '🧑🏿‍🐰‍🧑🏾': 6, + '🧑🏿‍💻': 4, + '🧑🏿‍💼': 4, + '🧑🏿‍🔧': 4, + '🧑🏿‍🔬': 4, + '🧑🏿‍🚀': 4, + '🧑🏿‍🚒': 4, + '🧑🏿‍🤝‍🧑🏻': 6, + '🧑🏿‍🤝‍🧑🏼': 6, + '🧑🏿‍🤝‍🧑🏽': 6, + '🧑🏿‍🤝‍🧑🏾': 6, + '🧑🏿‍🤝‍🧑🏿': 6, + '🧑🏿‍🦯': 4, + '🧑🏿‍🦯‍➡️': 6, + '🧑🏿‍🦰': 4, + '🧑🏿‍🦱': 4, + '🧑🏿‍🦲': 4, + '🧑🏿‍🦳': 4, + '🧑🏿‍🦼': 4, + '🧑🏿‍🦼‍➡️': 6, + '🧑🏿‍🦽': 4, + '🧑🏿‍🦽‍➡️': 6, + '🧑🏿‍🩰': 4, + '🧑🏿‍🫯‍🧑🏻': 6, + '🧑🏿‍🫯‍🧑🏼': 6, + '🧑🏿‍🫯‍🧑🏽': 6, + '🧑🏿‍🫯‍🧑🏾': 6, + '🧔‍♀️': 4, + '🧔‍♂️': 4, + '🧔🏻‍♀️': 4, + '🧔🏻‍♂️': 4, + '🧔🏼‍♀️': 4, + '🧔🏼‍♂️': 4, + '🧔🏽‍♀️': 4, + '🧔🏽‍♂️': 4, + '🧔🏾‍♀️': 4, + '🧔🏾‍♂️': 4, + '🧔🏿‍♀️': 4, + '🧔🏿‍♂️': 4, + '🧖‍♀️': 4, + '🧖‍♂️': 4, + '🧖🏻‍♀️': 4, + '🧖🏻‍♂️': 4, + '🧖🏼‍♀️': 4, + '🧖🏼‍♂️': 4, + '🧖🏽‍♀️': 4, + '🧖🏽‍♂️': 4, + '🧖🏾‍♀️': 4, + '🧖🏾‍♂️': 4, + '🧖🏿‍♀️': 4, + '🧖🏿‍♂️': 4, + '🧗‍♀️': 4, + '🧗‍♂️': 4, + '🧗🏻‍♀️': 4, + '🧗🏻‍♂️': 4, + '🧗🏼‍♀️': 4, + '🧗🏼‍♂️': 4, + '🧗🏽‍♀️': 4, + '🧗🏽‍♂️': 4, + '🧗🏾‍♀️': 4, + '🧗🏾‍♂️': 4, + '🧗🏿‍♀️': 4, + '🧗🏿‍♂️': 4, + '🧘‍♀️': 4, + '🧘‍♂️': 4, + '🧘🏻‍♀️': 4, + '🧘🏻‍♂️': 4, + '🧘🏼‍♀️': 4, + '🧘🏼‍♂️': 4, + '🧘🏽‍♀️': 4, + '🧘🏽‍♂️': 4, + '🧘🏾‍♀️': 4, + '🧘🏾‍♂️': 4, + '🧘🏿‍♀️': 4, + '🧘🏿‍♂️': 4, + '🧙‍♀️': 4, + '🧙‍♂️': 4, + '🧙🏻‍♀️': 4, + '🧙🏻‍♂️': 4, + '🧙🏼‍♀️': 4, + '🧙🏼‍♂️': 4, + '🧙🏽‍♀️': 4, + '🧙🏽‍♂️': 4, + '🧙🏾‍♀️': 4, + '🧙🏾‍♂️': 4, + '🧙🏿‍♀️': 4, + '🧙🏿‍♂️': 4, + '🧚‍♀️': 4, + '🧚‍♂️': 4, + '🧚🏻‍♀️': 4, + '🧚🏻‍♂️': 4, + '🧚🏼‍♀️': 4, + '🧚🏼‍♂️': 4, + '🧚🏽‍♀️': 4, + '🧚🏽‍♂️': 4, + '🧚🏾‍♀️': 4, + '🧚🏾‍♂️': 4, + '🧚🏿‍♀️': 4, + '🧚🏿‍♂️': 4, + '🧛‍♀️': 4, + '🧛‍♂️': 4, + '🧛🏻‍♀️': 4, + '🧛🏻‍♂️': 4, + '🧛🏼‍♀️': 4, + '🧛🏼‍♂️': 4, + '🧛🏽‍♀️': 4, + '🧛🏽‍♂️': 4, + '🧛🏾‍♀️': 4, + '🧛🏾‍♂️': 4, + '🧛🏿‍♀️': 4, + '🧛🏿‍♂️': 4, + '🧜‍♀️': 4, + '🧜‍♂️': 4, + '🧜🏻‍♀️': 4, + '🧜🏻‍♂️': 4, + '🧜🏼‍♀️': 4, + '🧜🏼‍♂️': 4, + '🧜🏽‍♀️': 4, + '🧜🏽‍♂️': 4, + '🧜🏾‍♀️': 4, + '🧜🏾‍♂️': 4, + '🧜🏿‍♀️': 4, + '🧜🏿‍♂️': 4, + '🧝‍♀️': 4, + '🧝‍♂️': 4, + '🧝🏻‍♀️': 4, + '🧝🏻‍♂️': 4, + '🧝🏼‍♀️': 4, + '🧝🏼‍♂️': 4, + '🧝🏽‍♀️': 4, + '🧝🏽‍♂️': 4, + '🧝🏾‍♀️': 4, + '🧝🏾‍♂️': 4, + '🧝🏿‍♀️': 4, + '🧝🏿‍♂️': 4, + '🧞‍♀️': 4, + '🧞‍♂️': 4, + '🧟‍♀️': 4, + '🧟‍♂️': 4, + '🫱🏻‍🫲🏼': 4, + '🫱🏻‍🫲🏽': 4, + '🫱🏻‍🫲🏾': 4, + '🫱🏻‍🫲🏿': 4, + '🫱🏼‍🫲🏻': 4, + '🫱🏼‍🫲🏽': 4, + '🫱🏼‍🫲🏾': 4, + '🫱🏼‍🫲🏿': 4, + '🫱🏽‍🫲🏻': 4, + '🫱🏽‍🫲🏼': 4, + '🫱🏽‍🫲🏾': 4, + '🫱🏽‍🫲🏿': 4, + '🫱🏾‍🫲🏻': 4, + '🫱🏾‍🫲🏼': 4, + '🫱🏾‍🫲🏽': 4, + '🫱🏾‍🫲🏿': 4, + '🫱🏿‍🫲🏻': 4, + '🫱🏿‍🫲🏼': 4, + '🫱🏿‍🫲🏽': 4, + '🫱🏿‍🫲🏾': 4, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_fdc99132.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_fdc99132.py new file mode 100644 index 0000000000000000000000000000000000000000..fc54e93a28eb49a8448ed4b904e977c55ca822ad --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_known_fdc99132.py @@ -0,0 +1,2642 @@ +""" +Grapheme overrides for _known_fdc99132. + +This code generated by python wcwidth using ucs-detect project data. + +Terminals: vte +""" +# pylint: skip-file +GRAPHEMES = { + '؁۱': 1, + 'क्का': 3, + 'क्कां': 3, + 'क्को': 3, + 'क्घ्घि्': 4, + 'क्ता': 3, + 'क्ति': 3, + 'क्ती': 3, + 'क्तीं': 3, + 'क्तेः': 3, + 'क्त्योः': 5, + 'क्ना': 3, + 'क्नि': 3, + 'क्या': 3, + 'क्रा': 3, + 'क्रि': 3, + 'क्षा': 3, + 'क्षां': 3, + 'क्षाः': 4, + 'क्षि': 3, + 'क्षो': 3, + 'क्ष्ण': 3, + 'क्ष्य': 3, + 'क्ष्या': 4, + 'क्सा': 3, + 'ख्यः': 3, + 'ख्या': 3, + 'ग्या': 3, + 'ग्यैः': 3, + 'ग्र्य': 3, + 'घ्का': 3, + 'घ्र्व्य': 4, + 'घ्लि': 3, + 'घ्श्य': 3, + 'घ्स्ट': 3, + 'च्चा': 3, + 'च्चों': 3, + 'च्छा': 3, + 'च्छि': 3, + 'च्या': 3, + 'च्यां': 3, + 'च्यो': 3, + 'ज्ञा': 3, + 'ज्या': 3, + 'ज्या‌': 3, + 'ज्रा': 3, + 'ञ्चा': 3, + 'ञ्चि': 3, + 'ट्टि': 3, + 'ट्टी': 3, + 'ट्या': 3, + 'ट्रा': 3, + 'ण्डः': 3, + 'ण्डि': 3, + 'ण्या': 3, + 'ण्यां': 3, + 'ताः': 3, + 'त्का': 3, + 'त्ता': 3, + 'त्ति': 3, + 'त्त्थि': 4, + 'त्त्व': 3, + 'त्त्वा': 4, + 'त्त्वे': 3, + 'त्नी': 3, + 'त्नों': 3, + 'त्पा': 3, + 'त्पी': 3, + 'त्मा': 3, + 'त्या': 3, + 'त्यां': 3, + 'त्यि': 3, + 'त्रा': 3, + 'त्राा': 4, + 'त्राि': 4, + 'त्रि': 3, + 'त्री': 3, + 'त्र्त': 3, + 'त्र्य': 3, + 'त्र्या': 4, + 'त्र्ये': 3, + 'त्वा': 3, + 'त्वां': 3, + 'त्सा': 3, + 'त्सो': 3, + 'त्स्वा': 4, + 'द्घि': 3, + 'द्घो': 3, + 'द्दा': 3, + 'द्दि': 3, + 'द्दी': 3, + 'द्धः': 3, + 'द्धा': 3, + 'द्धां': 3, + 'द्धि': 3, + 'द्धिं': 3, + 'द्धी': 3, + 'द्धीं': 3, + 'द्धैः': 3, + 'द्भा': 3, + 'द्या': 3, + 'द्रो': 3, + 'द्वा': 3, + 'द्वि': 3, + 'धाः': 3, + 'ध्या': 3, + 'नाः': 3, + 'निः': 3, + 'न्का': 3, + 'न्चि': 3, + 'न्ञ्या': 4, + 'न्तः': 3, + 'न्ता': 3, + 'न्ति': 3, + 'न्तो': 3, + 'न्तों': 3, + 'न्त्र': 3, + 'न्त्रा': 4, + 'न्त्राः': 5, + 'न्त्रि': 4, + 'न्त्री': 4, + 'न्त्र्य': 4, + 'न्त्र्यं': 4, + 'न्त्र्या': 5, + 'न्त्र्ये': 4, + 'न्दा': 3, + 'न्दी': 3, + 'न्दो': 3, + 'न्धा': 3, + 'न्धि': 3, + 'न्धी': 3, + 'न्धों': 3, + 'न्ना': 3, + 'न्नाः': 4, + 'न्नि': 3, + 'न्मा': 3, + 'न्या': 3, + 'न्यो': 3, + 'न्हा': 3, + 'न्ह्यां': 4, + 'प्ति': 3, + 'प्तौ': 3, + 'प्या': 3, + 'प्रा': 3, + 'फ्ता': 3, + 'फ्ना': 3, + 'फ्नो': 3, + 'फ्रां': 3, + 'ब्धि': 3, + 'भिः': 3, + 'भ्यः': 3, + 'भ्या': 3, + 'भ्यां': 3, + 'भ्यो': 3, + 'म्ति': 3, + 'म्नि': 3, + 'म्पा': 3, + 'म्प्र': 3, + 'म्भि': 3, + 'म्मा': 3, + 'म्मि': 3, + 'म्या': 3, + 'म्ही': 3, + 'म्हो': 3, + 'याः': 3, + 'य्यो': 3, + 'राः': 3, + 'र्कि': 3, + 'र्गी': 3, + 'र्चि': 3, + 'र्जा': 3, + 'र्जि': 3, + 'र्जी': 3, + 'र्णां': 3, + 'र्णी': 3, + 'र्ता': 3, + 'र्ति': 3, + 'र्तिः': 4, + 'र्ती': 3, + 'र्त्त': 3, + 'र्त्ति': 4, + 'र्थि': 3, + 'र्थी': 3, + 'र्दा': 3, + 'र्दि': 3, + 'र्दो': 3, + 'र्द्ध': 3, + 'र्धा': 3, + 'र्धि': 3, + 'र्नि': 3, + 'र्बा': 3, + 'र्भा': 3, + 'र्मा': 3, + 'र्मि': 3, + 'र्या': 3, + 'र्यां': 3, + 'र्यों': 3, + 'र्रा': 3, + 'र्वा': 3, + 'र्वां': 3, + 'र्वो': 3, + 'र्सा': 3, + 'र्हाः': 4, + 'र्हि': 3, + 'र्हो': 3, + 'र्‍या': 3, + 'लाः': 3, + 'ल्का': 3, + 'ल्पि': 3, + 'ल्या': 3, + 'ल्यां': 3, + 'ल्याः': 4, + 'ल्ला': 3, + 'ल्लि': 3, + 'वाः': 3, + 'व्या': 3, + 'व्यों': 3, + 'शाः': 3, + 'श्चि': 3, + 'श्या': 3, + 'श्यि': 3, + 'श्यों': 3, + 'श्रा': 3, + 'श्रां': 3, + 'श्वा': 3, + 'श्वि': 3, + 'षाः': 3, + 'ष्का': 3, + 'ष्टः': 3, + 'ष्टा': 3, + 'ष्टां': 3, + 'ष्टाः': 4, + 'ष्टि': 3, + 'ष्टी': 3, + 'ष्टीं': 3, + 'ष्ट्र': 3, + 'ष्ट्रा': 4, + 'ष्ट्रां': 4, + 'ष्ट्रि': 4, + 'ष्ट्री': 4, + 'ष्ट्रे': 3, + 'ष्ट्रो': 4, + 'ष्ट्रों': 4, + 'ष्ठा': 3, + 'ष्ठों': 3, + 'ष्प्र': 3, + 'ष्यः': 3, + 'ष्यों': 3, + 'स्का': 3, + 'स्काः': 4, + 'स्ट्या': 4, + 'स्ता': 3, + 'स्ति': 3, + 'स्ती': 3, + 'स्तो': 3, + 'स्त्र': 3, + 'स्त्रा': 4, + 'स्त्रि': 4, + 'स्त्री': 4, + 'स्था': 3, + 'स्थां': 3, + 'स्थि': 3, + 'स्थी': 3, + 'स्थ्य': 3, + 'स्धी': 3, + 'स्मि': 3, + 'स्मिं': 3, + 'स्या': 3, + 'स्यां': 3, + 'स्याः': 4, + 'स्युः': 3, + 'स्यों': 3, + 'स्रो': 3, + 'स्वा': 3, + 'स्वी': 3, + 'स्सा': 3, + 'ह्या': 3, + 'ह्रा': 3, + 'फ़्ता': 3, + 'কিং': 3, + 'ক্তি': 3, + 'ক্রী': 3, + 'ক্ষা': 3, + 'ক্ষি': 3, + 'ক্ষে': 3, + 'ক্ষ্য': 3, + 'ক্ষ্যে': 4, + 'খ্যা': 3, + 'গ্রা': 3, + 'গ্রে': 3, + 'ঘো': 3, + 'ঙ্খা': 3, + 'ঙ্গী': 3, + 'ঙ্গে': 3, + 'চ্ছা': 3, + 'চ্ছা‌': 3, + 'চ্ছে': 3, + 'জ্ঞা': 3, + 'ঞ্চি': 3, + 'ঞ্ছি': 3, + 'ট্রে': 3, + 'ণ্ডে': 3, + 'ত্তা': 3, + 'ত্তি': 3, + 'ত্বে': 3, + 'ত্যা': 3, + 'ত্যি': 3, + 'ত্যে': 3, + 'ত্রা': 3, + 'ত্রে': 3, + 'ত্‍পী': 3, + 'ত্‍সা': 3, + 'দ্দি': 3, + 'দ্দে': 3, + 'দ্ধা': 3, + 'দ্ধি': 3, + 'দ্ধে': 3, + 'দ্বা': 3, + 'দ্রো': 3, + 'ধ্যে': 3, + 'ন্তা': 3, + 'ন্তি': 3, + 'ন্তে': 3, + 'ন্ত্রি': 4, + 'ন্ত্রে': 4, + 'ন্থী': 3, + 'ন্ধা': 3, + 'ন্মা': 3, + 'ন্যা': 3, + 'ন্যে': 3, + 'প্তা': 3, + 'প্রা': 3, + 'ব্ধি': 3, + 'ব্যা': 3, + 'ভ্রা': 3, + 'ম্পা': 3, + 'ম্মা': 3, + 'রাং': 3, + 'র্জা': 3, + 'র্থে': 3, + 'র্দো': 3, + 'র্ধা': 3, + 'র্নী': 3, + 'র্বা': 3, + 'র্বি': 3, + 'র্বো': 3, + 'র্ব্য': 3, + 'র্মে': 3, + 'র্যা': 3, + 'ল্যা': 3, + 'ল্যে': 3, + 'ল্লে': 3, + 'শ্চি': 3, + 'শ্বা': 3, + 'শ্বে': 3, + 'শ্যে': 3, + 'শ্রা': 3, + 'ষ্টা': 3, + 'ষ্টি': 3, + 'ষ্ট্র': 3, + 'ষ্ট্রী': 4, + 'ষ্ট্রে': 4, + 'ষ্ঠা': 3, + 'ষ্ঠি': 3, + 'ষ্ঠী': 3, + 'সাং': 3, + 'স্তি': 3, + 'স্তি‌': 3, + 'স্ত্র': 3, + 'স্থা': 3, + 'স্থ্য': 3, + 'স্বা': 3, + 'স্বী': 3, + 'স্যা': 3, + 'স্যে': 3, + 'ક્કા': 3, + 'ક્કો': 3, + 'ક્તિ': 3, + 'ક્ષા': 3, + 'ચ્ચા': 3, + 'ચ્છા': 3, + 'જ્ઞા': 3, + 'જ્યો': 3, + 'ત્તા': 3, + 'ત્તિ': 3, + 'ત્ત્વ': 3, + 'ત્ત્વા': 4, + 'ત્યા': 3, + 'ત્યાં': 3, + 'ત્યિ': 3, + 'ત્યો': 3, + 'ત્રી': 3, + 'ત્ર્ય': 3, + 'દ્ધા': 3, + 'દ્ધાં': 3, + 'દ્ધિ': 3, + 'દ્વા': 3, + 'ધ્યા': 3, + 'ન્તો': 3, + 'ન્મા': 3, + 'ન્યા': 3, + 'પ્રા': 3, + 'મ્યાં': 3, + 'ર્તા': 3, + 'ર્થિ': 3, + 'ર્દો': 3, + 'ર્મિ': 3, + 'ર્યા': 3, + 'ર્યો': 3, + 'વ્યા': 3, + 'વ્યો': 3, + 'ષ્ટિ': 3, + 'ષ્ટ્ર': 3, + 'ષ્ટ્રી': 4, + 'ષ્ટ્રો': 4, + 'ષ્ઠા': 3, + 'સ્તિ': 3, + 'સ્તી': 3, + 'સ્ત્રી': 4, + 'સ્થા': 3, + 'સ્થિ': 3, + 'સ્રી': 3, + 'સ્વા': 3, + 'સ્વી': 3, + 'સ્સા': 3, + 'కుం': 3, + 'క్కు': 3, + 'క్తు': 3, + 'క్రాం': 3, + 'క్రూ': 3, + 'క్షిం': 3, + 'క్స్వా': 3, + 'చ్చు': 3, + 'టుం': 3, + 'ట్లు': 3, + 'డ్రు': 3, + 'త్తు': 3, + 'త్నిం': 3, + 'త్యం': 3, + 'త్రు': 3, + 'త్ర్య': 3, + 'దుం': 3, + 'ద్దు': 3, + 'ద్ధిం': 3, + 'ద్ర్య': 3, + 'నుం': 3, + 'న్ను': 3, + 'భ్యు': 3, + 'యుం': 3, + 'ర్చు': 3, + 'ర్ణాం': 3, + 'ర్ణు': 3, + 'ర్తిం': 3, + 'ర్తృ': 3, + 'ర్థిం': 3, + 'ర్బం': 3, + 'ర్హాం': 3, + 'ర్హు': 3, + 'శ్రాం': 3, + 'ష్టు': 3, + 'ష్ట్ర': 3, + 'ష్ట్రీ': 3, + 'ష్ఠు': 3, + 'స్కృ': 3, + 'స్త్ర': 3, + 'స్త్రీ': 3, + 'స్థ్య': 3, + 'ಕಾಂ': 3, + 'ಕುಂ': 3, + 'ಕೊಂ': 3, + 'ಖಾಂ': 3, + 'ಗಾಂ': 3, + 'ಗೊಂ': 3, + 'ಟುಂ': 3, + 'ನಾಂ': 3, + 'ಯುಂ': 3, + 'ರಾಂ': 3, + 'ವುಂ': 3, + 'ಶಾಂ': 3, + 'ಸಾಂ': 3, + 'ಹೊಂ': 3, + 'ക്കാ': 3, + 'ക്കി': 3, + 'ക്കും': 3, + 'ക്കെ': 3, + 'ക്കേ': 3, + 'ക്കൊ': 3, + 'ക്കോ': 3, + 'ക്തി': 3, + 'ക്യം': 3, + 'ക്ഷാ': 3, + 'ക്ഷി': 3, + 'ക്ഷേ': 3, + 'ഖ്യാ': 3, + 'ഗ്ഗം': 3, + 'ഗ്ദാ': 3, + 'ഗ്യം': 3, + 'ങ്കി': 3, + 'ങ്കെ': 3, + 'ങ്കേ': 3, + 'ങ്ങി': 3, + 'ച്ചി': 3, + 'ച്ചും': 3, + 'ച്ചെ': 3, + 'ച്ചേ': 3, + 'ജ്യാ': 3, + 'ഞ്ഞി': 3, + 'ഞ്ഞെ': 3, + 'ട്ടാ': 3, + 'ട്ടി': 3, + 'ട്ടോ': 3, + 'ണ്ടാ': 3, + 'ണ്ടി': 3, + 'ണ്ടും': 3, + 'ണ്ടെ': 3, + 'ത്താ': 3, + 'ത്തി': 3, + 'ത്തും': 3, + 'ത്തെ': 3, + 'ത്തേ': 3, + 'ത്തോ': 3, + 'ത്നം': 3, + 'ത്നി': 3, + 'ത്യാ': 3, + 'ത്യേ': 3, + 'ത്വം': 3, + 'ദ്ധി': 3, + 'ദ്യാ': 3, + 'ന്തം': 3, + 'ന്തെ': 3, + 'ന്ത്ര': 3, + 'ന്ത്ര്യ': 4, + 'ന്ത്ര്യം': 5, + 'ന്ധി': 3, + 'ന്നാ': 3, + 'ന്നി': 3, + 'ന്നീ': 3, + 'ന്നും': 3, + 'ന്നെ': 3, + 'ന്നേ': 3, + 'ന്നോ': 3, + 'ന്മാ': 3, + 'ന്യം': 3, + 'ന്യാ': 3, + 'ന്യേ': 3, + 'ന്യോ': 3, + 'ന്റെ': 3, + 'ന്‍പി': 3, + 'പ്പി': 3, + 'പ്പെ': 3, + 'പ്പോ': 3, + 'പ്രാ': 3, + 'ബ്ലി': 3, + 'ഭ്യാ': 3, + 'ഭ്രാ': 3, + 'മ്പാ': 3, + 'മ്പ്ര': 3, + 'മ്മി': 3, + 'യ്ക്കു': 3, + 'യ്തി': 3, + 'യ്യാ': 3, + 'യ്യി': 3, + 'ര്യം': 3, + 'ര്‍ക്കു': 3, + 'ര്‍ക്കും': 4, + 'ര്‍ക്ക്‌': 3, + 'ര്‍ഗ്ഗം': 4, + 'ര്‍ച്ച': 3, + 'ര്‍ണ്ണ': 3, + 'ര്‍ത്ത': 3, + 'ര്‍ത്തി': 4, + 'ര്‍ത്തു': 3, + 'ര്‍ത്തേ': 4, + 'ര്‍ദേ': 3, + 'ര്‍ദ്ദ': 3, + 'ര്‍പ്പെ': 4, + 'ര്‍മ്മി': 4, + 'ര്‍രാ': 3, + 'ര്‍വ്വ': 3, + 'ര്‍ഹി': 3, + 'റ്റം': 3, + 'റ്റേ': 3, + 'ല്യാ': 3, + 'ല്ലാ': 3, + 'ല്ലാം': 4, + 'ല്ലെ': 3, + 'ല്‍കി': 3, + 'ല്‍കേ': 3, + 'ല്‍നി': 3, + 'ല്‍പ്പ': 3, + 'ള്ളാ': 3, + 'ള്ളി': 3, + 'ള്‍കൊ': 3, + 'ള്‍ക്ക': 3, + 'ള്‍ക്കി': 4, + 'ള്‍ക്കു': 3, + 'ള്‍ക്കും': 4, + 'ള്‍ക്കെ': 4, + 'ള്‍ക്ക്‌': 3, + 'വ്യം': 3, + 'വ്യാ': 3, + 'ശ്വാ': 3, + 'ഷ്ട്യാ': 4, + 'ഷ്ട്ര': 3, + 'ഷ്ട്രീ': 4, + 'ഷ്യാ': 3, + 'സാം': 3, + 'സ്കാ': 3, + 'സ്ത്രം': 4, + 'സ്ത്രീ': 4, + 'സ്ഥാ': 3, + 'സ്ഥി': 3, + 'സ്റ്റ്‌': 3, + 'സ്വാ': 3, + 'സ്വീ': 3, + 'സ്സാ': 3, + 'സ്സി': 3, + 'സ്സും': 3, + 'സ്സോ': 3, + 'ഹിം': 3, + 'ൻ്റെ': 3, + 'ကျေ': 3, + 'ကြေ': 3, + 'ကြွေ': 3, + 'ချေ': 3, + 'ခြေ': 3, + 'ဇြေ': 3, + 'ဒ္ဂေ': 3, + 'ပျေ': 3, + 'ပြေ': 3, + 'ဖျေံ': 3, + 'ဗ္တေ': 3, + 'ဗ္ၜေ': 3, + 'ဗြေ': 3, + 'မြေ': 3, + 'လျေ': 3, + 'လျှေ': 3, + 'သ္ဂေ': 3, + 'ក្ដៅ': 3, + 'ក្រោ': 3, + 'ក្សា': 3, + 'ខ្ជា': 3, + 'ខ្លា': 3, + 'គ្នា': 3, + 'គ្មា': 3, + 'គ្រា': 3, + 'គ្រឹះ': 3, + 'ង្កើ': 3, + 'ង្រៀ': 3, + 'ង្ហា': 3, + 'ច្ចេ': 3, + 'ច្បា': 3, + 'ឆ្នាំ': 3, + 'ឆ្នោ': 3, + 'ឆ្លើ': 3, + 'ជ្ជា': 3, + 'ជ្ញា': 3, + 'ជ្រើ': 3, + 'ជ្រៀ': 3, + 'ជ្រែ': 3, + 'ឈ្មោះ': 4, + 'ញ្ជា': 3, + 'ញ្ញា': 3, + 'ញ្ញៈ': 3, + 'ដ្ឋា': 3, + 'ណោះ': 3, + 'ណ្ដា': 3, + 'ណ្ដុះ': 3, + 'ណ្ណោះ': 4, + 'ត្រា': 3, + 'ថ្ងៃ': 3, + 'ថ្នា': 3, + 'ថ្លៃ': 3, + 'ទោះ': 3, + 'ទ្យា': 3, + 'ធ្នា': 3, + 'ធ្យា': 3, + 'ធ្យោ': 3, + 'ធ្វើ': 3, + 'នេះ': 3, + 'នោះ': 3, + 'ន្ថែ': 3, + 'ន្ថោ': 3, + 'ន្ទា': 3, + 'ន្ទៈ': 3, + 'ន្យា': 3, + 'ន្លែ': 3, + 'បោះ': 3, + 'ប្ដេ': 3, + 'ប្រា': 3, + 'ប្រើ': 3, + 'ប្រែ': 3, + 'ផ្ដា': 3, + 'ផ្ទា': 3, + 'ផ្ទេ': 3, + 'ផ្នែ': 3, + 'ផ្លា': 3, + 'ផ្សា': 3, + 'ផ្សេ': 3, + 'ផ្សៃ': 3, + 'ពោះ': 3, + 'ព្យា': 3, + 'ព្រៀ': 3, + 'ព្រៃ': 3, + 'ម្ងា': 3, + 'ម្ចា': 3, + 'ម្ដា': 3, + 'ម្ដែ': 3, + 'ម្នា': 3, + 'ម្នេ': 3, + 'ម្ភា': 3, + 'ម្រា': 3, + 'ម្រើ': 3, + 'ម្រេ': 3, + 'ម្លៀ': 3, + 'ម្លៃ': 3, + 'ល្បៈ': 3, + 'ល្មើ': 3, + 'ស្គា': 3, + 'ស្ដ្រី': 3, + 'ស្ត្រ': 3, + 'ស្ថា': 3, + 'ស្នា': 3, + 'ស្មា': 3, + 'ស្មើ': 3, + 'ស្រា': 3, + 'ស្លា': 3, + 'ស្វែ': 3, + 'ᨠᩮ᩠ᨯᩨ': 3, + 'ᨠᩯ᩠ᨯ': 3, + 'ᨠᩯ᩠ᨶ᩵': 3, + 'ᨡᩮ᩠ᨲ': 3, + 'ᨡᩯ᩠ᨠ': 3, + 'ᨡᩯ᩠ᨦ': 3, + 'ᨣᩕ᩠ᩋ': 3, + 'ᨣᩕᩮ᩠ᨦᩨ᩵': 4, + 'ᨣᩯ᩠ᨶᩢ': 3, + 'ᨣᩯ᩠ᩅ': 3, + 'ᨧᩮ᩠ᨷ': 3, + 'ᨧᩱ᩠ᨿ': 3, + 'ᨩᩮ᩠ᩋᩨ': 3, + 'ᨩᩮ᩠ᩋᩨ᩵': 3, + 'ᨩᩮ᩠ᩋᩨ᩶': 3, + 'ᨯ᩠ᩅ᩠ᨿᩢ': 3, + 'ᨯᩢ᩠ᩅ᩠ᨿ': 3, + 'ᨯᩯ᩠ᨦ': 3, + 'ᨯᩯ᩠ᨶ': 3, + 'ᨯᩰ᩠ᨿ': 3, + 'ᨲᩮ᩠ᨠ': 3, + 'ᨲᩮ᩠ᨦ': 3, + 'ᨲᩮ᩠ᨾ': 3, + 'ᨲᩮ᩠ᨾᩨ᩵': 3, + 'ᨲᩯ᩠ᨠ': 3, + 'ᨲᩯ᩠ᨦ᩵': 3, + 'ᨲᩯ᩠ᨾᩢ': 3, + 'ᨲᩱ᩠ᨿ': 3, + 'ᨳᩮ᩠ᨶᩨ᩵': 3, + 'ᨳᩯ᩠ᨦᩢ': 3, + 'ᨳᩯ᩠ᨾ': 3, + 'ᨴᩮ᩠ᩈ': 3, + 'ᨴᩮ᩠ᩈᩱ': 4, + 'ᨴᩯ᩠ᨶ': 3, + 'ᨴᩰ᩠ᩈ': 3, + 'ᨶᩯ᩠ᨶ': 3, + 'ᨷᩮ᩠ᨦᩨ᩶': 3, + 'ᨸᩮ᩠ᨦᩨ': 3, + 'ᨸᩮ᩠ᨶ': 3, + 'ᨹᩮᩨ᩠ᨿ': 3, + 'ᨻᩕ᩠ᩋᩢ': 3, + 'ᨻᩮ᩠ᩋᩨ᩵': 3, + 'ᨽᩱ᩠ᨿ': 3, + 'ᨾᩮ᩠ᨠᩨ': 3, + 'ᨾᩮ᩠ᨦᩨ': 3, + 'ᨾᩮ᩠ᩋᩨ᩵': 3, + 'ᨿᩮ᩠ᨶ': 3, + 'ᨿᩮ᩠ᨾᩨ': 3, + 'ᩁᩮ᩠ᨦᩨ᩵': 3, + 'ᩁᩮ᩠ᨧ': 3, + 'ᩁᩮ᩠ᨶᩨ': 3, + 'ᩁᩮᩨ᩠ᨬ': 3, + 'ᩁᩯ᩠ᨦ': 3, + 'ᩃᩮ᩠ᨠᩨ': 3, + 'ᩃᩮ᩠ᨦᩨ': 3, + 'ᩃᩰ᩠ᨠ': 3, + 'ᩅᩮ᩠ᨶ': 3, + 'ᩅᩮ᩠ᨶᩢ': 3, + 'ᩈᩮ᩠ᩈ': 3, + 'ᩈᩯ᩠ᩅ': 3, + 'ᩈᩱ᩠ᨿ': 3, + 'ᩉ᩠ᨿᩢ᩠ᩋ': 3, + 'ᩉᩮ᩠ᨦᩢᩢ': 3, + 'ᩉᩮ᩠ᨯ': 3, + 'ᩉᩮ᩠ᨲᩩ': 3, + 'ᩉᩮ᩠ᨶᩨ': 3, + 'ᩉᩮ᩠ᨾᩨ': 3, + 'ᩉᩮ᩠ᨾᩨᩨ': 3, + 'ᩉᩯ᩠ᨦ᩵': 3, + 'ᩉᩯ᩠ᨶᩢ': 3, + 'ᩉᩯ᩠ᨾ': 3, + 'ᩉᩱ᩠ᨾ᩵': 3, + 'ᩉᩱ᩠ᨿ᩵': 3, + 'ᩣ᩠ᨲᩱ': 3, + '⛓️‍💥': 3, + '⛹🏻‍♀️': 4, + '⛹🏻‍♂️': 4, + '⛹🏼‍♀️': 4, + '⛹🏼‍♂️': 4, + '⛹🏽‍♀️': 4, + '⛹🏽‍♂️': 4, + '⛹🏾‍♀️': 4, + '⛹🏾‍♂️': 4, + '⛹🏿‍♀️': 4, + '⛹🏿‍♂️': 4, + '❤️‍🔥': 3, + '❤️‍🩹': 3, + 'ꦏꦺꦴ': 3, + 'ꦏ꧀': 2, + 'ꦏ꧀ꦏ': 3, + 'ꦏ꧀ꦏꦁ': 3, + 'ꦏ꧀ꦏꦺ': 4, + 'ꦏ꧀ꦏꦼ': 3, + 'ꦏ꧀ꦔ': 3, + 'ꦏ꧀ꦔꦸ': 3, + 'ꦏ꧀ꦔꦿ': 4, + 'ꦏ꧀ꦕ': 3, + 'ꦏ꧀ꦠ': 3, + 'ꦏ꧀ꦠꦶ': 3, + 'ꦏ꧀ꦠꦸ': 3, + 'ꦏ꧀ꦠꦺ': 4, + 'ꦏ꧀ꦢ': 3, + 'ꦏ꧀ꦢꦂ': 3, + 'ꦏ꧀ꦢꦶ': 3, + 'ꦏ꧀ꦤ': 3, + 'ꦏ꧀ꦤꦶꦁ': 3, + 'ꦏ꧀ꦥ': 3, + 'ꦏ꧀ꦥꦶ': 3, + 'ꦏ꧀ꦥꦿꦶ': 4, + 'ꦏ꧀ꦧ': 3, + 'ꦏ꧀ꦧꦶ': 3, + 'ꦏ꧀ꦧꦺ': 4, + 'ꦏ꧀ꦩ': 3, + 'ꦏ꧀ꦩꦸ': 3, + 'ꦏ꧀ꦪ': 3, + 'ꦏ꧀ꦭ': 3, + 'ꦏ꧀ꦮ': 3, + 'ꦏ꧀ꦱ': 3, + 'ꦏ꧀ꦱꦂ': 3, + 'ꦏ꧀ꦱꦶ': 3, + 'ꦏ꧀ꦱꦸ': 3, + 'ꦏ꧀ꦱꦺ': 4, + 'ꦏ꧀ꦲ': 3, + 'ꦏ꧀ꦲꦁ': 3, + 'ꦏ꧀ꦲꦶꦁ': 3, + 'ꦏ꧀ꦲꦸ': 3, + 'ꦏ꧀ꦲꦺ': 4, + 'ꦏ꧀ꦲꦺꦴ': 5, + 'ꦒꦺꦴ': 3, + 'ꦒꦿꦺ': 3, + 'ꦒ꧀ꦒ': 3, + 'ꦔꦺꦴ': 3, + 'ꦔ꧀ꦒꦼ': 3, + 'ꦔ꧀ꦒꦿꦼꦁ': 4, + 'ꦔ꧀ꦭ': 3, + 'ꦔ꧀ꦭꦁ': 3, + 'ꦔ꧀ꦭꦸ': 3, + 'ꦔ꧀ꦭꦼ': 3, + 'ꦕꦺꦴ': 3, + 'ꦗꦿꦺꦴ': 4, + 'ꦚ꧀ꦕ': 3, + 'ꦚ꧀ꦕꦶ': 3, + 'ꦚ꧀ꦗ': 3, + 'ꦚ꧀ꦗꦶ': 3, + 'ꦚ꧀ꦗꦸꦁ': 3, + 'ꦚ꧀ꦗꦸꦂ': 3, + 'ꦝꦺꦴ': 3, + 'ꦝꦺꦴꦂ': 3, + 'ꦠꦺꦃ': 3, + 'ꦠꦺꦴ': 3, + 'ꦠ꧀': 2, + 'ꦠ꧀ꦏꦁ': 3, + 'ꦠ꧀ꦏꦸ': 3, + 'ꦠ꧀ꦒ': 3, + 'ꦠ꧀ꦔꦸ': 3, + 'ꦠ꧀ꦚ': 3, + 'ꦠ꧀ꦠ': 3, + 'ꦠ꧀ꦠꦶ': 3, + 'ꦠ꧀ꦠꦶꦁ': 3, + 'ꦠ꧀ꦠꦸ': 3, + 'ꦠ꧀ꦠꦺ': 4, + 'ꦠ꧀ꦤ': 3, + 'ꦠ꧀ꦤꦶ': 3, + 'ꦠ꧀ꦩ': 3, + 'ꦠ꧀ꦩꦼ': 3, + 'ꦠ꧀ꦭ': 3, + 'ꦠ꧀ꦭꦺ': 4, + 'ꦠ꧀ꦱ': 3, + 'ꦠ꧀ꦱꦶꦁ': 3, + 'ꦠ꧀ꦱꦶꦃ': 4, + 'ꦠ꧀ꦱꦾ': 4, + 'ꦠ꧀ꦱ꧀ꦮ': 5, + 'ꦠ꧀ꦲ': 3, + 'ꦠ꧀ꦲꦶꦁ': 3, + 'ꦠ꧀ꦲꦺꦴ': 5, + 'ꦢꦺꦴ': 3, + 'ꦢ꧀': 2, + 'ꦢ꧀ꦏ': 3, + 'ꦢ꧀ꦠ': 3, + 'ꦢ꧀ꦠꦶꦁ': 3, + 'ꦢ꧀ꦢ': 3, + 'ꦢ꧀ꦥ': 3, + 'ꦢ꧀ꦩꦺꦴ': 5, + 'ꦢ꧀ꦲ': 3, + 'ꦤꦺꦃ': 3, + 'ꦤꦺꦴ': 3, + 'ꦤ꧀': 2, + 'ꦤ꧀ꦏ': 3, + 'ꦤ꧀ꦏꦁ': 3, + 'ꦤ꧀ꦏꦸ': 3, + 'ꦤ꧀ꦏꦼ': 3, + 'ꦤ꧀ꦒ': 3, + 'ꦤ꧀ꦔ': 3, + 'ꦤ꧀ꦔꦁ': 3, + 'ꦤ꧀ꦔꦶ': 3, + 'ꦤ꧀ꦔꦸ': 3, + 'ꦤ꧀ꦔꦸꦂ': 3, + 'ꦤ꧀ꦔꦺ': 4, + 'ꦤ꧀ꦔꦼ': 3, + 'ꦤ꧀ꦔꦿꦸ': 4, + 'ꦤ꧀ꦗ': 3, + 'ꦤ꧀ꦗꦸ': 3, + 'ꦤ꧀ꦗꦼ': 3, + 'ꦤ꧀ꦚꦶ': 3, + 'ꦤ꧀ꦛꦃ': 4, + 'ꦤ꧀ꦛꦶ': 3, + 'ꦤ꧀ꦝ': 3, + 'ꦤ꧀ꦝꦁ': 3, + 'ꦤ꧀ꦝꦶ': 3, + 'ꦤ꧀ꦝꦸ': 3, + 'ꦤ꧀ꦝꦸꦁ': 3, + 'ꦤ꧀ꦝꦺꦁ': 4, + 'ꦤ꧀ꦝꦺꦴꦁ': 5, + 'ꦤ꧀ꦝꦼ': 3, + 'ꦤ꧀ꦠ': 3, + 'ꦤ꧀ꦠꦂ': 3, + 'ꦤ꧀ꦠꦃ': 4, + 'ꦤ꧀ꦠꦶ': 3, + 'ꦤ꧀ꦠꦸ': 3, + 'ꦤ꧀ꦠꦸꦁ': 3, + 'ꦤ꧀ꦠꦺ': 4, + 'ꦤ꧀ꦠꦼ': 3, + 'ꦤ꧀ꦠꦼꦂ': 3, + 'ꦤ꧀ꦠꦽ': 3, + 'ꦤ꧀ꦢ': 3, + 'ꦤ꧀ꦢꦁ': 3, + 'ꦤ꧀ꦢꦂ': 3, + 'ꦤ꧀ꦢꦶ': 3, + 'ꦤ꧀ꦢꦸ': 3, + 'ꦤ꧀ꦢꦺ': 4, + 'ꦤ꧀ꦢꦼ': 3, + 'ꦤ꧀ꦤ': 3, + 'ꦤ꧀ꦤꦶ': 3, + 'ꦤ꧀ꦤꦶꦁ': 3, + 'ꦤ꧀ꦤꦺ': 4, + 'ꦤ꧀ꦤꦼ': 3, + 'ꦤ꧀ꦥ': 3, + 'ꦤ꧀ꦥꦁ': 3, + 'ꦤ꧀ꦥ꦳ꦺꦴꦂ': 5, + 'ꦤ꧀ꦥꦶ': 3, + 'ꦤ꧀ꦥꦸ': 3, + 'ꦤ꧀ꦥꦼ': 3, + 'ꦤ꧀ꦥꦿ': 4, + 'ꦤ꧀ꦥꦿꦶ': 4, + 'ꦤ꧀ꦧ': 3, + 'ꦤ꧀ꦧꦁ': 3, + 'ꦤ꧀ꦧꦶ': 3, + 'ꦤ꧀ꦧꦸ': 3, + 'ꦤ꧀ꦧꦺ': 4, + 'ꦤ꧀ꦧꦺꦴ': 5, + 'ꦤ꧀ꦧꦼ': 3, + 'ꦤ꧀ꦩ': 3, + 'ꦤ꧀ꦩꦂ': 3, + 'ꦤ꧀ꦩꦶ': 3, + 'ꦤ꧀ꦩꦸꦂ': 3, + 'ꦤ꧀ꦩꦼ': 3, + 'ꦤ꧀ꦭ': 3, + 'ꦤ꧀ꦭꦶ': 3, + 'ꦤ꧀ꦭꦸ': 3, + 'ꦤ꧀ꦮ': 3, + 'ꦤ꧀ꦮꦂ': 3, + 'ꦤ꧀ꦮꦶ': 3, + 'ꦤ꧀ꦮꦸ': 3, + 'ꦤ꧀ꦮꦼ': 3, + 'ꦤ꧀ꦱ': 3, + 'ꦤ꧀ꦱꦂ': 3, + 'ꦤ꧀ꦱꦃ': 4, + 'ꦤ꧀ꦱꦶ': 3, + 'ꦤ꧀ꦱꦶꦁ': 3, + 'ꦤ꧀ꦱꦸ': 3, + 'ꦤ꧀ꦱꦺꦴ': 5, + 'ꦤ꧀ꦱꦼ': 3, + 'ꦤ꧀ꦲ': 3, + 'ꦤ꧀ꦲꦁ': 3, + 'ꦤ꧀ꦲꦶ': 3, + 'ꦤ꧀ꦲꦶꦁ': 3, + 'ꦤ꧀ꦲꦸ': 3, + 'ꦤ꧀ꦲꦺꦴ': 5, + 'ꦥ꦳꧀': 2, + 'ꦥꦺꦴ': 3, + 'ꦥꦿꦃ': 3, + 'ꦥꦿꦺꦴ': 4, + 'ꦥ꧀': 2, + 'ꦥ꧀ꦏ': 3, + 'ꦥ꧀ꦏꦁ': 3, + 'ꦥ꧀ꦠ': 3, + 'ꦥ꧀ꦠꦶ': 3, + 'ꦥ꧀ꦢꦸ': 3, + 'ꦥ꧀ꦤ': 3, + 'ꦥ꧀ꦤꦶ': 3, + 'ꦥ꧀ꦥ': 3, + 'ꦥ꧀ꦥꦶ': 3, + 'ꦥ꧀ꦥꦺ': 4, + 'ꦥ꧀ꦧꦺ': 4, + 'ꦥ꧀ꦩ': 3, + 'ꦥ꧀ꦩꦂ': 3, + 'ꦥ꧀ꦫꦺ': 4, + 'ꦥ꧀ꦭ': 3, + 'ꦥ꧀ꦭꦸ': 3, + 'ꦥ꧀ꦱ': 3, + 'ꦥ꧀ꦱꦶꦂ': 3, + 'ꦥ꧀ꦱꦼ': 3, + 'ꦥ꧀ꦲ': 3, + 'ꦧꦺꦃ': 3, + 'ꦧꦺꦴ': 3, + 'ꦧ꧀': 2, + 'ꦧ꧀ꦏ': 3, + 'ꦧ꧀ꦠꦸ': 3, + 'ꦧ꧀ꦥ': 3, + 'ꦧ꧀ꦧ': 3, + 'ꦧ꧀ꦧꦺ': 4, + 'ꦧ꧀ꦲ': 3, + 'ꦧ꧀ꦲꦶ': 3, + 'ꦩꦺꦃ': 3, + 'ꦩꦺꦴ': 3, + 'ꦩꦿꦃ': 3, + 'ꦩꦿꦶꦃ': 3, + 'ꦩ꧀': 2, + 'ꦩ꧀ꦏꦁ': 3, + 'ꦩ꧀ꦔꦼ': 3, + 'ꦩ꧀ꦠꦸ': 3, + 'ꦩ꧀ꦠꦺꦴ': 5, + 'ꦩ꧀ꦤꦶꦁ': 3, + 'ꦩ꧀ꦥ': 3, + 'ꦩ꧀ꦥꦶ': 3, + 'ꦩ꧀ꦥꦸ': 3, + 'ꦩ꧀ꦥꦼ': 3, + 'ꦩ꧀ꦧ': 3, + 'ꦩ꧀ꦧꦁ': 3, + 'ꦩ꧀ꦧꦂ': 3, + 'ꦩ꧀ꦧꦃ': 4, + 'ꦩ꧀ꦧꦶ': 3, + 'ꦩ꧀ꦧꦸ': 3, + 'ꦩ꧀ꦧꦸꦁ': 3, + 'ꦩ꧀ꦧꦺ': 4, + 'ꦩ꧀ꦧꦺꦂ': 4, + 'ꦩ꧀ꦧꦼꦂ': 3, + 'ꦩ꧀ꦧꦾꦸꦂ': 4, + 'ꦩ꧀ꦩ': 3, + 'ꦩ꧀ꦩꦶ': 3, + 'ꦩ꧀ꦫ': 3, + 'ꦩ꧀ꦫꦃ': 4, + 'ꦩ꧀ꦭ': 3, + 'ꦩ꧀ꦲꦶ': 3, + 'ꦪꦺꦴ': 3, + 'ꦫꦺꦴ': 3, + 'ꦭꦺꦃ': 3, + 'ꦭꦺꦴ': 3, + 'ꦭꦺꦴꦁ': 3, + 'ꦭ꧀': 2, + 'ꦭ꧀ꦏꦁ': 3, + 'ꦭ꧀ꦚꦼꦁ': 3, + 'ꦭ꧀ꦠꦸ': 3, + 'ꦭ꧀ꦧꦸ': 3, + 'ꦭ꧀ꦩꦸ': 3, + 'ꦭ꧀ꦭ': 3, + 'ꦭ꧀ꦭꦶ': 3, + 'ꦭ꧀ꦭꦶꦁ': 3, + 'ꦭ꧀ꦭꦺ': 4, + 'ꦭ꧀ꦮ': 3, + 'ꦭ꧀ꦱ': 3, + 'ꦭ꧀ꦱꦂ': 3, + 'ꦭ꧀ꦱꦶꦁ': 3, + 'ꦭ꧀ꦱꦸ': 3, + 'ꦭ꧀ꦲ': 3, + 'ꦭ꧀ꦲꦁ': 3, + 'ꦭ꧀ꦲꦶꦁ': 3, + 'ꦭ꧀ꦲꦸ': 3, + 'ꦮꦺꦴ': 3, + 'ꦮꦺꦴꦁ': 3, + 'ꦮꦺꦴꦃ': 4, + 'ꦮꦿꦸꦃ': 3, + 'ꦱꦺꦴ': 3, + 'ꦱꦿꦃ': 3, + 'ꦱ꧀': 2, + 'ꦱ꧀ꦏ': 3, + 'ꦱ꧀ꦏꦁ': 3, + 'ꦱ꧀ꦏꦿꦶ': 4, + 'ꦱ꧀ꦒ': 3, + 'ꦱ꧀ꦔꦸ': 3, + 'ꦱ꧀ꦔꦿ': 4, + 'ꦱ꧀ꦛꦶ': 3, + 'ꦱ꧀ꦠ': 3, + 'ꦱ꧀ꦠꦿ': 4, + 'ꦱ꧀ꦢꦂ': 3, + 'ꦱ꧀ꦢꦶ': 3, + 'ꦱ꧀ꦢꦸ': 3, + 'ꦱ꧀ꦥ': 3, + 'ꦱ꧀ꦧ': 3, + 'ꦱ꧀ꦧꦁ': 3, + 'ꦱ꧀ꦩ': 3, + 'ꦱ꧀ꦩꦶ': 3, + 'ꦱ꧀ꦩꦼ': 3, + 'ꦱ꧀ꦩꦿ': 4, + 'ꦱ꧀ꦭ': 3, + 'ꦱ꧀ꦮ': 3, + 'ꦱ꧀ꦱ': 3, + 'ꦱ꧀ꦱꦂ': 3, + 'ꦱ꧀ꦱꦶ': 3, + 'ꦱ꧀ꦱꦶꦁ': 3, + 'ꦱ꧀ꦱꦸ': 3, + 'ꦱ꧀ꦱꦺ': 4, + 'ꦱ꧀ꦲ': 3, + 'ꦱ꧀ꦲꦁ': 3, + 'ꦱ꧀ꦲꦶ': 3, + 'ꦱ꧀ꦲꦶꦁ': 3, + 'ꦱ꧀ꦲꦸ': 3, + 'ꦲꦺꦴ': 3, + '𑄇𑄳𑄠𑄬': 3, + '𑄈𑄳𑄠𑄬': 3, + '𑄌𑄳𑄠𑄬': 3, + '𑄎𑄳𑄠𑄬': 3, + '𑄑𑄳𑄢𑄬': 3, + '𑄖𑄳𑄠𑄬': 3, + '𑄖𑄳𑄢𑄬': 3, + '𑄘𑄳𑄠𑄬': 3, + '𑄚𑄳𑄠𑄬': 3, + '𑄝𑄳𑄢𑄬': 3, + '𑄟𑄳𑄠𑄬': 3, + '𑄡𑄳𑄠𑄬': 3, + '𑄣𑄳𑄦𑄬': 3, + '𑌕𑌾𑌂': 3, + '𑌕𑌾𑌃': 3, + '𑌕𑍍': 2, + '𑌗𑍍': 2, + '𑌚𑍍': 2, + '𑌜𑍍': 2, + '𑌞𑍍': 2, + '𑌟𑌾𑌂': 3, + '𑌟𑌾𑌃': 3, + '𑌟𑍍': 2, + '𑌠𑍈𑌃': 3, + '𑌣𑌾𑌂': 3, + '𑌣𑍍': 2, + '𑌤𑌾𑌂': 3, + '𑌤𑌾𑌃': 3, + '𑌤𑌿𑌂': 3, + '𑌤𑌿𑌃': 3, + '𑌤𑍁𑌂': 3, + '𑌤𑍇𑌃': 3, + '𑌤𑍍': 2, + '𑌥𑌾𑌂': 3, + '𑌦𑍍': 2, + '𑌧𑌾𑌃': 3, + '𑌧𑌿𑌂': 3, + '𑌧𑍇𑌃': 3, + '𑌧𑍈𑌃': 3, + '𑌧𑍍': 2, + '𑌨𑌾𑌂': 3, + '𑌨𑌾𑌃': 3, + '𑌨𑌿𑌃': 3, + '𑌨𑍈𑌃': 3, + '𑌨𑍍': 2, + '𑌪𑍍': 2, + '𑌬𑍍': 2, + '𑌭𑌿𑌃': 3, + '𑌭𑍍': 2, + '𑌮𑌿𑌂': 3, + '𑌮𑍍': 2, + '𑌯𑌾𑌂': 3, + '𑌯𑌾𑌃': 3, + '𑌯𑍁𑌃': 3, + '𑌯𑍈𑌃': 3, + '𑌯𑍋𑌃': 3, + '𑌯𑍍': 2, + '𑌰𑌾𑌃': 3, + '𑌰𑌿𑌂': 3, + '𑌰𑍍': 2, + '𑌲𑌾𑌃': 3, + '𑌲𑌿𑌂': 3, + '𑌲𑍍': 2, + '𑌵𑌾𑌂': 3, + '𑌵𑌾𑌃': 3, + '𑌵𑍍': 2, + '𑌶𑌾𑌃': 3, + '𑌶𑍍': 2, + '𑌷𑌾𑌂': 3, + '𑌷𑌾𑌃': 3, + '𑌷𑍍': 2, + '𑌸𑌾𑌂': 3, + '𑌸𑍍': 2, + '𑌹𑌾𑌃': 3, + '🍄‍🟫': 4, + '🍋‍🟩': 4, + '🏃‍♀️': 3, + '🏃‍♀️‍➡️': 4, + '🏃‍♂️': 3, + '🏃‍♂️‍➡️': 4, + '🏃‍➡️': 3, + '🏃🏻‍♀️': 5, + '🏃🏻‍♀️‍➡️': 6, + '🏃🏻‍♂️': 5, + '🏃🏻‍♂️‍➡️': 6, + '🏃🏻‍➡️': 5, + '🏃🏼‍♀️': 5, + '🏃🏼‍♀️‍➡️': 6, + '🏃🏼‍♂️': 5, + '🏃🏼‍♂️‍➡️': 6, + '🏃🏼‍➡️': 5, + '🏃🏽‍♀️': 5, + '🏃🏽‍♀️‍➡️': 6, + '🏃🏽‍♂️': 5, + '🏃🏽‍♂️‍➡️': 6, + '🏃🏽‍➡️': 5, + '🏃🏾‍♀️': 5, + '🏃🏾‍♀️‍➡️': 6, + '🏃🏾‍♂️': 5, + '🏃🏾‍♂️‍➡️': 6, + '🏃🏾‍➡️': 5, + '🏃🏿‍♀️': 5, + '🏃🏿‍♀️‍➡️': 6, + '🏃🏿‍♂️': 5, + '🏃🏿‍♂️‍➡️': 6, + '🏃🏿‍➡️': 5, + '🏄‍♀️': 3, + '🏄‍♂️': 3, + '🏄🏻‍♀️': 5, + '🏄🏻‍♂️': 5, + '🏄🏼‍♀️': 5, + '🏄🏼‍♂️': 5, + '🏄🏽‍♀️': 5, + '🏄🏽‍♂️': 5, + '🏄🏾‍♀️': 5, + '🏄🏾‍♂️': 5, + '🏄🏿‍♀️': 5, + '🏄🏿‍♂️': 5, + '🏊‍♀️': 3, + '🏊‍♂️': 3, + '🏊🏻‍♀️': 5, + '🏊🏻‍♂️': 5, + '🏊🏼‍♀️': 5, + '🏊🏼‍♂️': 5, + '🏊🏽‍♀️': 5, + '🏊🏽‍♂️': 5, + '🏊🏾‍♀️': 5, + '🏊🏾‍♂️': 5, + '🏊🏿‍♀️': 5, + '🏊🏿‍♂️': 5, + '🏋🏻‍♀️': 4, + '🏋🏻‍♂️': 4, + '🏋🏼‍♀️': 4, + '🏋🏼‍♂️': 4, + '🏋🏽‍♀️': 4, + '🏋🏽‍♂️': 4, + '🏋🏾‍♀️': 4, + '🏋🏾‍♂️': 4, + '🏋🏿‍♀️': 4, + '🏋🏿‍♂️': 4, + '🏌🏻‍♀️': 4, + '🏌🏻‍♂️': 4, + '🏌🏼‍♀️': 4, + '🏌🏼‍♂️': 4, + '🏌🏽‍♀️': 4, + '🏌🏽‍♂️': 4, + '🏌🏾‍♀️': 4, + '🏌🏾‍♂️': 4, + '🏌🏿‍♀️': 4, + '🏌🏿‍♂️': 4, + '🏳️‍🌈': 3, + '🏴‍☠️': 3, + '🐈‍⬛': 4, + '🐕‍🦺': 4, + '🐦‍⬛': 4, + '🐦‍🔥': 4, + '🐻‍❄️': 3, + '👨‍⚕️': 3, + '👨‍⚖️': 3, + '👨‍✈️': 3, + '👨‍❤️‍👨': 5, + '👨‍❤️‍💋‍👨': 7, + '👨‍🌾': 4, + '👨‍🍳': 4, + '👨‍🍼': 4, + '👨‍🎓': 4, + '👨‍🎤': 4, + '👨‍🎨': 4, + '👨‍🏫': 4, + '👨‍🏭': 4, + '👨‍👦': 4, + '👨‍👦‍👦': 6, + '👨‍👧': 4, + '👨‍👧‍👦': 6, + '👨‍👧‍👧': 6, + '👨‍👨‍👦': 6, + '👨‍👨‍👦‍👦': 8, + '👨‍👨‍👧': 6, + '👨‍👨‍👧‍👦': 8, + '👨‍👨‍👧‍👧': 8, + '👨‍👩‍👦': 6, + '👨‍👩‍👦‍👦': 8, + '👨‍👩‍👧': 6, + '👨‍👩‍👧‍👦': 8, + '👨‍👩‍👧‍👧': 8, + '👨‍💻': 4, + '👨‍💼': 4, + '👨‍🔧': 4, + '👨‍🔬': 4, + '👨‍🚀': 4, + '👨‍🚒': 4, + '👨‍🦯': 4, + '👨‍🦯‍➡️': 5, + '👨‍🦰': 4, + '👨‍🦱': 4, + '👨‍🦲': 4, + '👨‍🦳': 4, + '👨‍🦼': 4, + '👨‍🦼‍➡️': 5, + '👨‍🦽': 4, + '👨‍🦽‍➡️': 5, + '👨🏻‍⚕️': 5, + '👨🏻‍⚖️': 5, + '👨🏻‍✈️': 5, + '👨🏻‍❤️‍👨🏻': 9, + '👨🏻‍❤️‍👨🏽': 9, + '👨🏻‍❤️‍👨🏿': 9, + '👨🏻‍❤️‍💋‍👨🏻': 11, + '👨🏻‍❤️‍💋‍👨🏽': 11, + '👨🏻‍❤️‍💋‍👨🏾': 11, + '👨🏻‍❤️‍💋‍👨🏿': 11, + '👨🏻‍🌾': 6, + '👨🏻‍🍳': 6, + '👨🏻‍🍼': 6, + '👨🏻‍🎓': 6, + '👨🏻‍🎤': 6, + '👨🏻‍🎨': 6, + '👨🏻‍🏫': 6, + '👨🏻‍🏭': 6, + '👨🏻‍🐰‍👨🏼': 10, + '👨🏻‍🐰‍👨🏽': 10, + '👨🏻‍🐰‍👨🏾': 10, + '👨🏻‍🐰‍👨🏿': 10, + '👨🏻‍💻': 6, + '👨🏻‍💼': 6, + '👨🏻‍🔧': 6, + '👨🏻‍🔬': 6, + '👨🏻‍🚀': 6, + '👨🏻‍🚒': 6, + '👨🏻‍🤝‍👨🏼': 10, + '👨🏻‍🤝‍👨🏽': 10, + '👨🏻‍🤝‍👨🏾': 10, + '👨🏻‍🤝‍👨🏿': 10, + '👨🏻‍🦯': 6, + '👨🏻‍🦯‍➡️': 7, + '👨🏻‍🦰': 6, + '👨🏻‍🦱': 6, + '👨🏻‍🦲': 6, + '👨🏻‍🦳': 6, + '👨🏻‍🦼': 6, + '👨🏻‍🦼‍➡️': 7, + '👨🏻‍🦽': 6, + '👨🏻‍🦽‍➡️': 7, + '👨🏻‍🫯‍👨🏼': 9, + '👨🏻‍🫯‍👨🏽': 9, + '👨🏻‍🫯‍👨🏾': 9, + '👨🏻‍🫯‍👨🏿': 9, + '👨🏼‍⚕️': 5, + '👨🏼‍⚖️': 5, + '👨🏼‍✈️': 5, + '👨🏼‍❤️‍👨🏼': 9, + '👨🏼‍❤️‍💋‍👨🏼': 11, + '👨🏼‍❤️‍💋‍👨🏿': 11, + '👨🏼‍🌾': 6, + '👨🏼‍🍳': 6, + '👨🏼‍🍼': 6, + '👨🏼‍🎓': 6, + '👨🏼‍🎤': 6, + '👨🏼‍🎨': 6, + '👨🏼‍🏫': 6, + '👨🏼‍🏭': 6, + '👨🏼‍🐰‍👨🏻': 10, + '👨🏼‍🐰‍👨🏽': 10, + '👨🏼‍🐰‍👨🏿': 10, + '👨🏼‍💻': 6, + '👨🏼‍💼': 6, + '👨🏼‍🔧': 6, + '👨🏼‍🔬': 6, + '👨🏼‍🚀': 6, + '👨🏼‍🚒': 6, + '👨🏼‍🤝‍👨🏻': 10, + '👨🏼‍🤝‍👨🏽': 10, + '👨🏼‍🤝‍👨🏿': 10, + '👨🏼‍🦯': 6, + '👨🏼‍🦯‍➡️': 7, + '👨🏼‍🦰': 6, + '👨🏼‍🦱': 6, + '👨🏼‍🦲': 6, + '👨🏼‍🦳': 6, + '👨🏼‍🦼': 6, + '👨🏼‍🦽': 6, + '👨🏼‍🦽‍➡️': 7, + '👨🏼‍🫯‍👨🏻': 9, + '👨🏼‍🫯‍👨🏽': 9, + '👨🏼‍🫯‍👨🏾': 9, + '👨🏼‍🫯‍👨🏿': 9, + '👨🏽‍⚕️': 5, + '👨🏽‍⚖️': 5, + '👨🏽‍✈️': 5, + '👨🏽‍❤️‍👨🏻': 9, + '👨🏽‍❤️‍👨🏽': 9, + '👨🏽‍❤️‍👨🏿': 9, + '👨🏽‍❤️‍💋‍👨🏻': 11, + '👨🏽‍❤️‍💋‍👨🏽': 11, + '👨🏽‍❤️‍💋‍👨🏿': 11, + '👨🏽‍🌾': 6, + '👨🏽‍🍳': 6, + '👨🏽‍🍼': 6, + '👨🏽‍🎓': 6, + '👨🏽‍🎤': 6, + '👨🏽‍🎨': 6, + '👨🏽‍🏫': 6, + '👨🏽‍🏭': 6, + '👨🏽‍🐰‍👨🏻': 10, + '👨🏽‍🐰‍👨🏼': 10, + '👨🏽‍🐰‍👨🏾': 10, + '👨🏽‍🐰‍👨🏿': 10, + '👨🏽‍💻': 6, + '👨🏽‍💼': 6, + '👨🏽‍🔧': 6, + '👨🏽‍🔬': 6, + '👨🏽‍🚀': 6, + '👨🏽‍🚒': 6, + '👨🏽‍🤝‍👨🏻': 10, + '👨🏽‍🤝‍👨🏼': 10, + '👨🏽‍🤝‍👨🏾': 10, + '👨🏽‍🤝‍👨🏿': 10, + '👨🏽‍🦯': 6, + '👨🏽‍🦯‍➡️': 7, + '👨🏽‍🦰': 6, + '👨🏽‍🦱': 6, + '👨🏽‍🦲': 6, + '👨🏽‍🦳': 6, + '👨🏽‍🦼': 6, + '👨🏽‍🦼‍➡️': 7, + '👨🏽‍🦽': 6, + '👨🏽‍🦽‍➡️': 7, + '👨🏽‍🫯‍👨🏻': 9, + '👨🏽‍🫯‍👨🏼': 9, + '👨🏽‍🫯‍👨🏾': 9, + '👨🏽‍🫯‍👨🏿': 9, + '👨🏾‍⚕️': 5, + '👨🏾‍⚖️': 5, + '👨🏾‍✈️': 5, + '👨🏾‍❤️‍👨🏾': 9, + '👨🏾‍❤️‍💋‍👨🏻': 11, + '👨🏾‍❤️‍💋‍👨🏾': 11, + '👨🏾‍❤️‍💋‍👨🏿': 11, + '👨🏾‍🌾': 6, + '👨🏾‍🍳': 6, + '👨🏾‍🍼': 6, + '👨🏾‍🎓': 6, + '👨🏾‍🎤': 6, + '👨🏾‍🎨': 6, + '👨🏾‍🏫': 6, + '👨🏾‍🏭': 6, + '👨🏾‍🐰‍👨🏻': 10, + '👨🏾‍🐰‍👨🏽': 10, + '👨🏾‍🐰‍👨🏿': 10, + '👨🏾‍💻': 6, + '👨🏾‍💼': 6, + '👨🏾‍🔧': 6, + '👨🏾‍🔬': 6, + '👨🏾‍🚀': 6, + '👨🏾‍🚒': 6, + '👨🏾‍🤝‍👨🏻': 10, + '👨🏾‍🤝‍👨🏽': 10, + '👨🏾‍🤝‍👨🏿': 10, + '👨🏾‍🦯': 6, + '👨🏾‍🦯‍➡️': 7, + '👨🏾‍🦰': 6, + '👨🏾‍🦱': 6, + '👨🏾‍🦲': 6, + '👨🏾‍🦳': 6, + '👨🏾‍🦼': 6, + '👨🏾‍🦽': 6, + '👨🏾‍🦽‍➡️': 7, + '👨🏾‍🫯‍👨🏻': 9, + '👨🏾‍🫯‍👨🏼': 9, + '👨🏾‍🫯‍👨🏽': 9, + '👨🏾‍🫯‍👨🏿': 9, + '👨🏿‍⚕️': 5, + '👨🏿‍⚖️': 5, + '👨🏿‍✈️': 5, + '👨🏿‍❤️‍👨🏻': 9, + '👨🏿‍❤️‍👨🏽': 9, + '👨🏿‍❤️‍👨🏿': 9, + '👨🏿‍❤️‍💋‍👨🏻': 11, + '👨🏿‍❤️‍💋‍👨🏼': 11, + '👨🏿‍❤️‍💋‍👨🏽': 11, + '👨🏿‍❤️‍💋‍👨🏾': 11, + '👨🏿‍❤️‍💋‍👨🏿': 11, + '👨🏿‍🌾': 6, + '👨🏿‍🍳': 6, + '👨🏿‍🍼': 6, + '👨🏿‍🎓': 6, + '👨🏿‍🎤': 6, + '👨🏿‍🎨': 6, + '👨🏿‍🏫': 6, + '👨🏿‍🏭': 6, + '👨🏿‍🐰‍👨🏻': 10, + '👨🏿‍🐰‍👨🏼': 10, + '👨🏿‍🐰‍👨🏽': 10, + '👨🏿‍🐰‍👨🏾': 10, + '👨🏿‍💻': 6, + '👨🏿‍💼': 6, + '👨🏿‍🔧': 6, + '👨🏿‍🔬': 6, + '👨🏿‍🚀': 6, + '👨🏿‍🚒': 6, + '👨🏿‍🤝‍👨🏻': 10, + '👨🏿‍🤝‍👨🏼': 10, + '👨🏿‍🤝‍👨🏽': 10, + '👨🏿‍🤝‍👨🏾': 10, + '👨🏿‍🦯': 6, + '👨🏿‍🦯‍➡️': 7, + '👨🏿‍🦰': 6, + '👨🏿‍🦱': 6, + '👨🏿‍🦲': 6, + '👨🏿‍🦳': 6, + '👨🏿‍🦼': 6, + '👨🏿‍🦼‍➡️': 7, + '👨🏿‍🦽': 6, + '👨🏿‍🦽‍➡️': 7, + '👨🏿‍🫯‍👨🏻': 9, + '👨🏿‍🫯‍👨🏼': 9, + '👨🏿‍🫯‍👨🏽': 9, + '👨🏿‍🫯‍👨🏾': 9, + '👩‍⚕️': 3, + '👩‍⚖️': 3, + '👩‍✈️': 3, + '👩‍❤️‍👨': 5, + '👩‍❤️‍👩': 5, + '👩‍❤️‍💋‍👨': 7, + '👩‍❤️‍💋‍👩': 7, + '👩‍🌾': 4, + '👩‍🍳': 4, + '👩‍🍼': 4, + '👩‍🎓': 4, + '👩‍🎤': 4, + '👩‍🎨': 4, + '👩‍🏫': 4, + '👩‍🏭': 4, + '👩‍👦': 4, + '👩‍👦‍👦': 6, + '👩‍👧': 4, + '👩‍👧‍👦': 6, + '👩‍👧‍👧': 6, + '👩‍👩‍👦': 6, + '👩‍👩‍👦‍👦': 8, + '👩‍👩‍👧': 6, + '👩‍👩‍👧‍👦': 8, + '👩‍👩‍👧‍👧': 8, + '👩‍💻': 4, + '👩‍💼': 4, + '👩‍🔧': 4, + '👩‍🔬': 4, + '👩‍🚀': 4, + '👩‍🚒': 4, + '👩‍🦯': 4, + '👩‍🦯‍➡️': 5, + '👩‍🦰': 4, + '👩‍🦱': 4, + '👩‍🦲': 4, + '👩‍🦳': 4, + '👩‍🦼': 4, + '👩‍🦼‍➡️': 5, + '👩‍🦽': 4, + '👩‍🦽‍➡️': 5, + '👩🏻‍⚕️': 5, + '👩🏻‍⚖️': 5, + '👩🏻‍✈️': 5, + '👩🏻‍❤️‍👨🏻': 9, + '👩🏻‍❤️‍👨🏿': 9, + '👩🏻‍❤️‍👩🏻': 9, + '👩🏻‍❤️‍💋‍👨🏻': 11, + '👩🏻‍❤️‍💋‍👨🏽': 11, + '👩🏻‍❤️‍💋‍👨🏿': 11, + '👩🏻‍❤️‍💋‍👩🏻': 11, + '👩🏻‍❤️‍💋‍👩🏽': 11, + '👩🏻‍❤️‍💋‍👩🏿': 11, + '👩🏻‍🌾': 6, + '👩🏻‍🍳': 6, + '👩🏻‍🍼': 6, + '👩🏻‍🎓': 6, + '👩🏻‍🎤': 6, + '👩🏻‍🎨': 6, + '👩🏻‍🏫': 6, + '👩🏻‍🏭': 6, + '👩🏻‍🐰‍👩🏼': 10, + '👩🏻‍🐰‍👩🏽': 10, + '👩🏻‍🐰‍👩🏾': 10, + '👩🏻‍🐰‍👩🏿': 10, + '👩🏻‍💻': 6, + '👩🏻‍💼': 6, + '👩🏻‍🔧': 6, + '👩🏻‍🔬': 6, + '👩🏻‍🚀': 6, + '👩🏻‍🚒': 6, + '👩🏻‍🤝‍👨🏽': 10, + '👩🏻‍🤝‍👨🏿': 10, + '👩🏻‍🤝‍👩🏼': 10, + '👩🏻‍🤝‍👩🏽': 10, + '👩🏻‍🤝‍👩🏾': 10, + '👩🏻‍🤝‍👩🏿': 10, + '👩🏻‍🦯': 6, + '👩🏻‍🦯‍➡️': 7, + '👩🏻‍🦰': 6, + '👩🏻‍🦱': 6, + '👩🏻‍🦲': 6, + '👩🏻‍🦳': 6, + '👩🏻‍🦼': 6, + '👩🏻‍🦼‍➡️': 7, + '👩🏻‍🦽': 6, + '👩🏻‍🦽‍➡️': 7, + '👩🏻‍🫯‍👩🏼': 9, + '👩🏻‍🫯‍👩🏽': 9, + '👩🏻‍🫯‍👩🏾': 9, + '👩🏻‍🫯‍👩🏿': 9, + '👩🏼‍⚕️': 5, + '👩🏼‍⚖️': 5, + '👩🏼‍✈️': 5, + '👩🏼‍❤️‍👨🏼': 9, + '👩🏼‍❤️‍👩🏼': 9, + '👩🏼‍❤️‍💋‍👨🏼': 11, + '👩🏼‍❤️‍💋‍👩🏼': 11, + '👩🏼‍🌾': 6, + '👩🏼‍🍳': 6, + '👩🏼‍🍼': 6, + '👩🏼‍🎓': 6, + '👩🏼‍🎤': 6, + '👩🏼‍🎨': 6, + '👩🏼‍🏫': 6, + '👩🏼‍🏭': 6, + '👩🏼‍🐰‍👩🏻': 10, + '👩🏼‍🐰‍👩🏿': 10, + '👩🏼‍💻': 6, + '👩🏼‍💼': 6, + '👩🏼‍🔧': 6, + '👩🏼‍🔬': 6, + '👩🏼‍🚀': 6, + '👩🏼‍🚒': 6, + '👩🏼‍🤝‍👩🏻': 10, + '👩🏼‍🤝‍👩🏽': 10, + '👩🏼‍🤝‍👩🏿': 10, + '👩🏼‍🦯': 6, + '👩🏼‍🦯‍➡️': 7, + '👩🏼‍🦰': 6, + '👩🏼‍🦱': 6, + '👩🏼‍🦲': 6, + '👩🏼‍🦳': 6, + '👩🏼‍🦼': 6, + '👩🏼‍🦽': 6, + '👩🏼‍🫯‍👩🏻': 9, + '👩🏼‍🫯‍👩🏽': 9, + '👩🏼‍🫯‍👩🏾': 9, + '👩🏼‍🫯‍👩🏿': 9, + '👩🏽‍⚕️': 5, + '👩🏽‍⚖️': 5, + '👩🏽‍✈️': 5, + '👩🏽‍❤️‍👨🏽': 9, + '👩🏽‍❤️‍👩🏽': 9, + '👩🏽‍❤️‍💋‍👨🏻': 11, + '👩🏽‍❤️‍💋‍👨🏽': 11, + '👩🏽‍❤️‍💋‍👨🏿': 11, + '👩🏽‍❤️‍💋‍👩🏻': 11, + '👩🏽‍❤️‍💋‍👩🏽': 11, + '👩🏽‍❤️‍💋‍👩🏿': 11, + '👩🏽‍🌾': 6, + '👩🏽‍🍳': 6, + '👩🏽‍🍼': 6, + '👩🏽‍🎓': 6, + '👩🏽‍🎤': 6, + '👩🏽‍🎨': 6, + '👩🏽‍🏫': 6, + '👩🏽‍🏭': 6, + '👩🏽‍🐰‍👩🏻': 10, + '👩🏽‍🐰‍👩🏾': 10, + '👩🏽‍🐰‍👩🏿': 10, + '👩🏽‍💻': 6, + '👩🏽‍💼': 6, + '👩🏽‍🔧': 6, + '👩🏽‍🔬': 6, + '👩🏽‍🚀': 6, + '👩🏽‍🚒': 6, + '👩🏽‍🤝‍👨🏻': 10, + '👩🏽‍🤝‍👨🏿': 10, + '👩🏽‍🤝‍👩🏻': 10, + '👩🏽‍🤝‍👩🏼': 10, + '👩🏽‍🤝‍👩🏾': 10, + '👩🏽‍🤝‍👩🏿': 10, + '👩🏽‍🦯': 6, + '👩🏽‍🦯‍➡️': 7, + '👩🏽‍🦰': 6, + '👩🏽‍🦱': 6, + '👩🏽‍🦲': 6, + '👩🏽‍🦳': 6, + '👩🏽‍🦼': 6, + '👩🏽‍🦼‍➡️': 7, + '👩🏽‍🦽': 6, + '👩🏽‍🦽‍➡️': 7, + '👩🏽‍🫯‍👩🏻': 9, + '👩🏽‍🫯‍👩🏼': 9, + '👩🏽‍🫯‍👩🏾': 9, + '👩🏽‍🫯‍👩🏿': 9, + '👩🏾‍⚕️': 5, + '👩🏾‍⚖️': 5, + '👩🏾‍✈️': 5, + '👩🏾‍❤️‍👨🏾': 9, + '👩🏾‍❤️‍👩🏾': 9, + '👩🏾‍❤️‍💋‍👨🏾': 11, + '👩🏾‍❤️‍💋‍👩🏾': 11, + '👩🏾‍🌾': 6, + '👩🏾‍🍳': 6, + '👩🏾‍🍼': 6, + '👩🏾‍🎓': 6, + '👩🏾‍🎤': 6, + '👩🏾‍🎨': 6, + '👩🏾‍🏫': 6, + '👩🏾‍🏭': 6, + '👩🏾‍🐰‍👩🏻': 10, + '👩🏾‍🐰‍👩🏽': 10, + '👩🏾‍🐰‍👩🏿': 10, + '👩🏾‍💻': 6, + '👩🏾‍💼': 6, + '👩🏾‍🔧': 6, + '👩🏾‍🔬': 6, + '👩🏾‍🚀': 6, + '👩🏾‍🚒': 6, + '👩🏾‍🤝‍👩🏻': 10, + '👩🏾‍🤝‍👩🏽': 10, + '👩🏾‍🤝‍👩🏿': 10, + '👩🏾‍🦯': 6, + '👩🏾‍🦯‍➡️': 7, + '👩🏾‍🦰': 6, + '👩🏾‍🦱': 6, + '👩🏾‍🦲': 6, + '👩🏾‍🦳': 6, + '👩🏾‍🦼': 6, + '👩🏾‍🦽': 6, + '👩🏾‍🦽‍➡️': 7, + '👩🏾‍🫯‍👩🏻': 9, + '👩🏾‍🫯‍👩🏼': 9, + '👩🏾‍🫯‍👩🏽': 9, + '👩🏾‍🫯‍👩🏿': 9, + '👩🏿‍⚕️': 5, + '👩🏿‍⚖️': 5, + '👩🏿‍✈️': 5, + '👩🏿‍❤️‍👨🏻': 9, + '👩🏿‍❤️‍👨🏿': 9, + '👩🏿‍❤️‍👩🏿': 9, + '👩🏿‍❤️‍💋‍👨🏻': 11, + '👩🏿‍❤️‍💋‍👨🏽': 11, + '👩🏿‍❤️‍💋‍👨🏿': 11, + '👩🏿‍❤️‍💋‍👩🏻': 11, + '👩🏿‍❤️‍💋‍👩🏽': 11, + '👩🏿‍❤️‍💋‍👩🏿': 11, + '👩🏿‍🌾': 6, + '👩🏿‍🍳': 6, + '👩🏿‍🍼': 6, + '👩🏿‍🎓': 6, + '👩🏿‍🎤': 6, + '👩🏿‍🎨': 6, + '👩🏿‍🏫': 6, + '👩🏿‍🏭': 6, + '👩🏿‍🐰‍👩🏻': 10, + '👩🏿‍🐰‍👩🏼': 10, + '👩🏿‍🐰‍👩🏽': 10, + '👩🏿‍🐰‍👩🏾': 10, + '👩🏿‍💻': 6, + '👩🏿‍💼': 6, + '👩🏿‍🔧': 6, + '👩🏿‍🔬': 6, + '👩🏿‍🚀': 6, + '👩🏿‍🚒': 6, + '👩🏿‍🤝‍👨🏻': 10, + '👩🏿‍🤝‍👨🏽': 10, + '👩🏿‍🤝‍👩🏻': 10, + '👩🏿‍🤝‍👩🏼': 10, + '👩🏿‍🤝‍👩🏽': 10, + '👩🏿‍🤝‍👩🏾': 10, + '👩🏿‍🦯': 6, + '👩🏿‍🦯‍➡️': 7, + '👩🏿‍🦰': 6, + '👩🏿‍🦱': 6, + '👩🏿‍🦲': 6, + '👩🏿‍🦳': 6, + '👩🏿‍🦼': 6, + '👩🏿‍🦼‍➡️': 7, + '👩🏿‍🦽': 6, + '👩🏿‍🦽‍➡️': 7, + '👩🏿‍🫯‍👩🏻': 9, + '👩🏿‍🫯‍👩🏼': 9, + '👩🏿‍🫯‍👩🏽': 9, + '👩🏿‍🫯‍👩🏾': 9, + '👮‍♀️': 3, + '👮‍♂️': 3, + '👮🏻‍♀️': 5, + '👮🏻‍♂️': 5, + '👮🏼‍♀️': 5, + '👮🏼‍♂️': 5, + '👮🏽‍♀️': 5, + '👮🏽‍♂️': 5, + '👮🏾‍♀️': 5, + '👮🏾‍♂️': 5, + '👮🏿‍♀️': 5, + '👮🏿‍♂️': 5, + '👯‍♀️': 3, + '👯‍♂️': 3, + '👯🏻‍♀️': 5, + '👯🏻‍♂️': 5, + '👯🏼‍♀️': 5, + '👯🏼‍♂️': 5, + '👯🏽‍♀️': 5, + '👯🏽‍♂️': 5, + '👯🏾‍♀️': 5, + '👯🏾‍♂️': 5, + '👯🏿‍♀️': 5, + '👯🏿‍♂️': 5, + '👰‍♀️': 3, + '👰‍♂️': 3, + '👰🏻‍♀️': 5, + '👰🏻‍♂️': 5, + '👰🏼‍♀️': 5, + '👰🏼‍♂️': 5, + '👰🏽‍♀️': 5, + '👰🏽‍♂️': 5, + '👰🏾‍♀️': 5, + '👰🏾‍♂️': 5, + '👰🏿‍♀️': 5, + '👰🏿‍♂️': 5, + '👱‍♀️': 3, + '👱‍♂️': 3, + '👱🏻‍♀️': 5, + '👱🏻‍♂️': 5, + '👱🏼‍♀️': 5, + '👱🏼‍♂️': 5, + '👱🏽‍♀️': 5, + '👱🏽‍♂️': 5, + '👱🏾‍♀️': 5, + '👱🏾‍♂️': 5, + '👱🏿‍♀️': 5, + '👱🏿‍♂️': 5, + '👳‍♀️': 3, + '👳‍♂️': 3, + '👳🏻‍♀️': 5, + '👳🏻‍♂️': 5, + '👳🏼‍♀️': 5, + '👳🏼‍♂️': 5, + '👳🏽‍♀️': 5, + '👳🏽‍♂️': 5, + '👳🏾‍♀️': 5, + '👳🏾‍♂️': 5, + '👳🏿‍♀️': 5, + '👳🏿‍♂️': 5, + '👷‍♀️': 3, + '👷‍♂️': 3, + '👷🏻‍♀️': 5, + '👷🏻‍♂️': 5, + '👷🏼‍♀️': 5, + '👷🏼‍♂️': 5, + '👷🏽‍♀️': 5, + '👷🏽‍♂️': 5, + '👷🏾‍♀️': 5, + '👷🏾‍♂️': 5, + '👷🏿‍♀️': 5, + '👷🏿‍♂️': 5, + '💁‍♀️': 3, + '💁‍♂️': 3, + '💁🏻‍♀️': 5, + '💁🏻‍♂️': 5, + '💁🏼‍♀️': 5, + '💁🏼‍♂️': 5, + '💁🏽‍♀️': 5, + '💁🏽‍♂️': 5, + '💁🏾‍♀️': 5, + '💁🏾‍♂️': 5, + '💁🏿‍♀️': 5, + '💁🏿‍♂️': 5, + '💂‍♀️': 3, + '💂‍♂️': 3, + '💂🏻‍♀️': 5, + '💂🏻‍♂️': 5, + '💂🏼‍♀️': 5, + '💂🏼‍♂️': 5, + '💂🏽‍♀️': 5, + '💂🏽‍♂️': 5, + '💂🏾‍♀️': 5, + '💂🏾‍♂️': 5, + '💂🏿‍♀️': 5, + '💂🏿‍♂️': 5, + '💆‍♀️': 3, + '💆‍♂️': 3, + '💆🏻‍♀️': 5, + '💆🏻‍♂️': 5, + '💆🏼‍♀️': 5, + '💆🏼‍♂️': 5, + '💆🏽‍♀️': 5, + '💆🏽‍♂️': 5, + '💆🏾‍♀️': 5, + '💆🏾‍♂️': 5, + '💆🏿‍♀️': 5, + '💆🏿‍♂️': 5, + '💇‍♀️': 3, + '💇‍♂️': 3, + '💇🏻‍♀️': 5, + '💇🏻‍♂️': 5, + '💇🏼‍♀️': 5, + '💇🏼‍♂️': 5, + '💇🏽‍♀️': 5, + '💇🏽‍♂️': 5, + '💇🏾‍♀️': 5, + '💇🏾‍♂️': 5, + '💇🏿‍♀️': 5, + '💇🏿‍♂️': 5, + '🕵🏻‍♀️': 4, + '🕵🏻‍♂️': 4, + '🕵🏼‍♀️': 4, + '🕵🏼‍♂️': 4, + '🕵🏽‍♀️': 4, + '🕵🏽‍♂️': 4, + '🕵🏾‍♀️': 4, + '🕵🏾‍♂️': 4, + '🕵🏿‍♀️': 4, + '🕵🏿‍♂️': 4, + '😮‍💨': 4, + '😵‍💫': 4, + '😶‍🌫️': 3, + '🙂‍↔️': 3, + '🙂‍↕️': 3, + '🙅‍♀️': 3, + '🙅‍♂️': 3, + '🙅🏻‍♀️': 5, + '🙅🏻‍♂️': 5, + '🙅🏼‍♀️': 5, + '🙅🏼‍♂️': 5, + '🙅🏽‍♀️': 5, + '🙅🏽‍♂️': 5, + '🙅🏾‍♀️': 5, + '🙅🏾‍♂️': 5, + '🙅🏿‍♀️': 5, + '🙅🏿‍♂️': 5, + '🙆‍♀️': 3, + '🙆‍♂️': 3, + '🙆🏻‍♀️': 5, + '🙆🏻‍♂️': 5, + '🙆🏼‍♀️': 5, + '🙆🏼‍♂️': 5, + '🙆🏽‍♀️': 5, + '🙆🏽‍♂️': 5, + '🙆🏾‍♀️': 5, + '🙆🏾‍♂️': 5, + '🙆🏿‍♀️': 5, + '🙆🏿‍♂️': 5, + '🙇‍♀️': 3, + '🙇‍♂️': 3, + '🙇🏻‍♀️': 5, + '🙇🏻‍♂️': 5, + '🙇🏼‍♀️': 5, + '🙇🏼‍♂️': 5, + '🙇🏽‍♀️': 5, + '🙇🏽‍♂️': 5, + '🙇🏾‍♀️': 5, + '🙇🏾‍♂️': 5, + '🙇🏿‍♀️': 5, + '🙇🏿‍♂️': 5, + '🙋‍♀️': 3, + '🙋‍♂️': 3, + '🙋🏻‍♀️': 5, + '🙋🏻‍♂️': 5, + '🙋🏼‍♀️': 5, + '🙋🏼‍♂️': 5, + '🙋🏽‍♀️': 5, + '🙋🏽‍♂️': 5, + '🙋🏾‍♀️': 5, + '🙋🏾‍♂️': 5, + '🙋🏿‍♀️': 5, + '🙋🏿‍♂️': 5, + '🙍‍♀️': 3, + '🙍‍♂️': 3, + '🙍🏻‍♀️': 5, + '🙍🏻‍♂️': 5, + '🙍🏼‍♀️': 5, + '🙍🏼‍♂️': 5, + '🙍🏽‍♀️': 5, + '🙍🏽‍♂️': 5, + '🙍🏾‍♀️': 5, + '🙍🏾‍♂️': 5, + '🙍🏿‍♀️': 5, + '🙍🏿‍♂️': 5, + '🙎‍♀️': 3, + '🙎‍♂️': 3, + '🙎🏻‍♀️': 5, + '🙎🏻‍♂️': 5, + '🙎🏼‍♀️': 5, + '🙎🏼‍♂️': 5, + '🙎🏽‍♀️': 5, + '🙎🏽‍♂️': 5, + '🙎🏾‍♀️': 5, + '🙎🏾‍♂️': 5, + '🙎🏿‍♀️': 5, + '🙎🏿‍♂️': 5, + '🚣‍♀️': 3, + '🚣‍♂️': 3, + '🚣🏻‍♀️': 5, + '🚣🏻‍♂️': 5, + '🚣🏼‍♀️': 5, + '🚣🏼‍♂️': 5, + '🚣🏽‍♀️': 5, + '🚣🏽‍♂️': 5, + '🚣🏾‍♀️': 5, + '🚣🏾‍♂️': 5, + '🚣🏿‍♀️': 5, + '🚣🏿‍♂️': 5, + '🚴‍♀️': 3, + '🚴‍♂️': 3, + '🚴🏻‍♀️': 5, + '🚴🏻‍♂️': 5, + '🚴🏼‍♀️': 5, + '🚴🏼‍♂️': 5, + '🚴🏽‍♀️': 5, + '🚴🏽‍♂️': 5, + '🚴🏾‍♀️': 5, + '🚴🏾‍♂️': 5, + '🚴🏿‍♀️': 5, + '🚴🏿‍♂️': 5, + '🚵‍♀️': 3, + '🚵‍♂️': 3, + '🚵🏻‍♀️': 5, + '🚵🏻‍♂️': 5, + '🚵🏼‍♀️': 5, + '🚵🏼‍♂️': 5, + '🚵🏽‍♀️': 5, + '🚵🏽‍♂️': 5, + '🚵🏾‍♀️': 5, + '🚵🏾‍♂️': 5, + '🚵🏿‍♀️': 5, + '🚵🏿‍♂️': 5, + '🚶‍♀️': 3, + '🚶‍♀️‍➡️': 4, + '🚶‍♂️': 3, + '🚶‍♂️‍➡️': 4, + '🚶‍➡️': 3, + '🚶🏻‍♀️': 5, + '🚶🏻‍♀️‍➡️': 6, + '🚶🏻‍♂️': 5, + '🚶🏻‍♂️‍➡️': 6, + '🚶🏻‍➡️': 5, + '🚶🏼‍♀️': 5, + '🚶🏼‍♀️‍➡️': 6, + '🚶🏼‍♂️': 5, + '🚶🏼‍♂️‍➡️': 6, + '🚶🏼‍➡️': 5, + '🚶🏽‍♀️': 5, + '🚶🏽‍♀️‍➡️': 6, + '🚶🏽‍♂️': 5, + '🚶🏽‍♂️‍➡️': 6, + '🚶🏽‍➡️': 5, + '🚶🏾‍♀️': 5, + '🚶🏾‍♀️‍➡️': 6, + '🚶🏾‍♂️': 5, + '🚶🏾‍♂️‍➡️': 6, + '🚶🏾‍➡️': 5, + '🚶🏿‍♀️': 5, + '🚶🏿‍♀️‍➡️': 6, + '🚶🏿‍♂️': 5, + '🚶🏿‍♂️‍➡️': 6, + '🚶🏿‍➡️': 5, + '🤦‍♀️': 3, + '🤦‍♂️': 3, + '🤦🏻‍♀️': 5, + '🤦🏻‍♂️': 5, + '🤦🏼‍♀️': 5, + '🤦🏼‍♂️': 5, + '🤦🏽‍♀️': 5, + '🤦🏽‍♂️': 5, + '🤦🏾‍♀️': 5, + '🤦🏾‍♂️': 5, + '🤦🏿‍♀️': 5, + '🤦🏿‍♂️': 5, + '🤵‍♀️': 3, + '🤵‍♂️': 3, + '🤵🏻‍♀️': 5, + '🤵🏻‍♂️': 5, + '🤵🏼‍♀️': 5, + '🤵🏼‍♂️': 5, + '🤵🏽‍♀️': 5, + '🤵🏽‍♂️': 5, + '🤵🏾‍♀️': 5, + '🤵🏾‍♂️': 5, + '🤵🏿‍♀️': 5, + '🤵🏿‍♂️': 5, + '🤷‍♀️': 3, + '🤷‍♂️': 3, + '🤷🏻‍♀️': 5, + '🤷🏻‍♂️': 5, + '🤷🏼‍♀️': 5, + '🤷🏼‍♂️': 5, + '🤷🏽‍♀️': 5, + '🤷🏽‍♂️': 5, + '🤷🏾‍♀️': 5, + '🤷🏾‍♂️': 5, + '🤷🏿‍♀️': 5, + '🤷🏿‍♂️': 5, + '🤸‍♀️': 3, + '🤸‍♂️': 3, + '🤸🏻‍♀️': 5, + '🤸🏻‍♂️': 5, + '🤸🏼‍♀️': 5, + '🤸🏼‍♂️': 5, + '🤸🏽‍♀️': 5, + '🤸🏽‍♂️': 5, + '🤸🏾‍♀️': 5, + '🤸🏾‍♂️': 5, + '🤸🏿‍♀️': 5, + '🤸🏿‍♂️': 5, + '🤹‍♀️': 3, + '🤹‍♂️': 3, + '🤹🏻‍♀️': 5, + '🤹🏻‍♂️': 5, + '🤹🏼‍♀️': 5, + '🤹🏼‍♂️': 5, + '🤹🏽‍♀️': 5, + '🤹🏽‍♂️': 5, + '🤹🏾‍♀️': 5, + '🤹🏾‍♂️': 5, + '🤹🏿‍♀️': 5, + '🤹🏿‍♂️': 5, + '🤼‍♀️': 3, + '🤼‍♂️': 3, + '🤼🏻‍♀️': 5, + '🤼🏻‍♂️': 5, + '🤼🏼‍♀️': 5, + '🤼🏼‍♂️': 5, + '🤼🏽‍♀️': 5, + '🤼🏽‍♂️': 5, + '🤼🏾‍♀️': 5, + '🤼🏾‍♂️': 5, + '🤼🏿‍♀️': 5, + '🤼🏿‍♂️': 5, + '🤽‍♀️': 3, + '🤽‍♂️': 3, + '🤽🏻‍♀️': 5, + '🤽🏻‍♂️': 5, + '🤽🏼‍♀️': 5, + '🤽🏼‍♂️': 5, + '🤽🏽‍♀️': 5, + '🤽🏽‍♂️': 5, + '🤽🏾‍♀️': 5, + '🤽🏾‍♂️': 5, + '🤽🏿‍♀️': 5, + '🤽🏿‍♂️': 5, + '🤾‍♀️': 3, + '🤾‍♂️': 3, + '🤾🏻‍♀️': 5, + '🤾🏻‍♂️': 5, + '🤾🏼‍♀️': 5, + '🤾🏼‍♂️': 5, + '🤾🏽‍♀️': 5, + '🤾🏽‍♂️': 5, + '🤾🏾‍♀️': 5, + '🤾🏾‍♂️': 5, + '🤾🏿‍♀️': 5, + '🤾🏿‍♂️': 5, + '🦸‍♀️': 3, + '🦸‍♂️': 3, + '🦸🏻‍♀️': 5, + '🦸🏻‍♂️': 5, + '🦸🏼‍♀️': 5, + '🦸🏼‍♂️': 5, + '🦸🏽‍♀️': 5, + '🦸🏽‍♂️': 5, + '🦸🏾‍♀️': 5, + '🦸🏾‍♂️': 5, + '🦸🏿‍♀️': 5, + '🦸🏿‍♂️': 5, + '🦹‍♀️': 3, + '🦹‍♂️': 3, + '🦹🏻‍♀️': 5, + '🦹🏻‍♂️': 5, + '🦹🏼‍♀️': 5, + '🦹🏼‍♂️': 5, + '🦹🏽‍♀️': 5, + '🦹🏽‍♂️': 5, + '🦹🏾‍♀️': 5, + '🦹🏾‍♂️': 5, + '🦹🏿‍♀️': 5, + '🦹🏿‍♂️': 5, + '🧍‍♀️': 3, + '🧍‍♂️': 3, + '🧍🏻‍♀️': 5, + '🧍🏻‍♂️': 5, + '🧍🏼‍♀️': 5, + '🧍🏼‍♂️': 5, + '🧍🏽‍♀️': 5, + '🧍🏽‍♂️': 5, + '🧍🏾‍♀️': 5, + '🧍🏾‍♂️': 5, + '🧍🏿‍♀️': 5, + '🧍🏿‍♂️': 5, + '🧎‍♀️': 3, + '🧎‍♀️‍➡️': 4, + '🧎‍♂️': 3, + '🧎‍♂️‍➡️': 4, + '🧎‍➡️': 3, + '🧎🏻‍♀️': 5, + '🧎🏻‍♀️‍➡️': 6, + '🧎🏻‍♂️': 5, + '🧎🏻‍♂️‍➡️': 6, + '🧎🏻‍➡️': 5, + '🧎🏼‍♀️': 5, + '🧎🏼‍♀️‍➡️': 6, + '🧎🏼‍♂️': 5, + '🧎🏼‍♂️‍➡️': 6, + '🧎🏼‍➡️': 5, + '🧎🏽‍♀️': 5, + '🧎🏽‍♀️‍➡️': 6, + '🧎🏽‍♂️': 5, + '🧎🏽‍♂️‍➡️': 6, + '🧎🏽‍➡️': 5, + '🧎🏾‍♀️': 5, + '🧎🏾‍♀️‍➡️': 6, + '🧎🏾‍♂️': 5, + '🧎🏾‍♂️‍➡️': 6, + '🧎🏾‍➡️': 5, + '🧎🏿‍♀️': 5, + '🧎🏿‍♀️‍➡️': 6, + '🧎🏿‍♂️': 5, + '🧎🏿‍♂️‍➡️': 6, + '🧎🏿‍➡️': 5, + '🧏‍♀️': 3, + '🧏‍♂️': 3, + '🧏🏻‍♀️': 5, + '🧏🏻‍♂️': 5, + '🧏🏼‍♀️': 5, + '🧏🏼‍♂️': 5, + '🧏🏽‍♀️': 5, + '🧏🏽‍♂️': 5, + '🧏🏾‍♀️': 5, + '🧏🏾‍♂️': 5, + '🧏🏿‍♀️': 5, + '🧏🏿‍♂️': 5, + '🧑‍⚕️': 3, + '🧑‍⚖️': 3, + '🧑‍✈️': 3, + '🧑‍🌾': 4, + '🧑‍🍳': 4, + '🧑‍🍼': 4, + '🧑‍🎄': 4, + '🧑‍🎓': 4, + '🧑‍🎤': 4, + '🧑‍🎨': 4, + '🧑‍🏫': 4, + '🧑‍🏭': 4, + '🧑‍💻': 4, + '🧑‍💼': 4, + '🧑‍🔧': 4, + '🧑‍🔬': 4, + '🧑‍🚀': 4, + '🧑‍🚒': 4, + '🧑‍🤝‍🧑': 6, + '🧑‍🦯': 4, + '🧑‍🦯‍➡️': 5, + '🧑‍🦰': 4, + '🧑‍🦱': 4, + '🧑‍🦲': 4, + '🧑‍🦳': 4, + '🧑‍🦼': 4, + '🧑‍🦼‍➡️': 5, + '🧑‍🦽': 4, + '🧑‍🦽‍➡️': 5, + '🧑‍🧑‍🧒': 6, + '🧑‍🧑‍🧒‍🧒': 8, + '🧑‍🧒': 4, + '🧑‍🧒‍🧒': 6, + '🧑‍🩰': 4, + '🧑🏻‍⚕️': 5, + '🧑🏻‍⚖️': 5, + '🧑🏻‍✈️': 5, + '🧑🏻‍❤️‍💋‍🧑🏿': 11, + '🧑🏻‍🌾': 6, + '🧑🏻‍🍳': 6, + '🧑🏻‍🍼': 6, + '🧑🏻‍🎄': 6, + '🧑🏻‍🎓': 6, + '🧑🏻‍🎤': 6, + '🧑🏻‍🎨': 6, + '🧑🏻‍🏫': 6, + '🧑🏻‍🏭': 6, + '🧑🏻‍🐰‍🧑🏽': 10, + '🧑🏻‍🐰‍🧑🏾': 10, + '🧑🏻‍🐰‍🧑🏿': 10, + '🧑🏻‍💻': 6, + '🧑🏻‍💼': 6, + '🧑🏻‍🔧': 6, + '🧑🏻‍🔬': 6, + '🧑🏻‍🚀': 6, + '🧑🏻‍🚒': 6, + '🧑🏻‍🤝‍🧑🏻': 10, + '🧑🏻‍🤝‍🧑🏼': 10, + '🧑🏻‍🤝‍🧑🏽': 10, + '🧑🏻‍🤝‍🧑🏾': 10, + '🧑🏻‍🤝‍🧑🏿': 10, + '🧑🏻‍🦯': 6, + '🧑🏻‍🦯‍➡️': 7, + '🧑🏻‍🦰': 6, + '🧑🏻‍🦱': 6, + '🧑🏻‍🦲': 6, + '🧑🏻‍🦳': 6, + '🧑🏻‍🦼': 6, + '🧑🏻‍🦼‍➡️': 7, + '🧑🏻‍🦽': 6, + '🧑🏻‍🦽‍➡️': 7, + '🧑🏻‍🩰': 6, + '🧑🏻‍🫯‍🧑🏼': 9, + '🧑🏻‍🫯‍🧑🏽': 9, + '🧑🏻‍🫯‍🧑🏾': 9, + '🧑🏻‍🫯‍🧑🏿': 9, + '🧑🏼‍⚕️': 5, + '🧑🏼‍⚖️': 5, + '🧑🏼‍✈️': 5, + '🧑🏼‍🌾': 6, + '🧑🏼‍🍳': 6, + '🧑🏼‍🍼': 6, + '🧑🏼‍🎄': 6, + '🧑🏼‍🎓': 6, + '🧑🏼‍🎤': 6, + '🧑🏼‍🎨': 6, + '🧑🏼‍🏫': 6, + '🧑🏼‍🏭': 6, + '🧑🏼‍🐰‍🧑🏿': 10, + '🧑🏼‍💻': 6, + '🧑🏼‍💼': 6, + '🧑🏼‍🔧': 6, + '🧑🏼‍🔬': 6, + '🧑🏼‍🚀': 6, + '🧑🏼‍🚒': 6, + '🧑🏼‍🤝‍🧑🏻': 10, + '🧑🏼‍🤝‍🧑🏼': 10, + '🧑🏼‍🤝‍🧑🏽': 10, + '🧑🏼‍🤝‍🧑🏿': 10, + '🧑🏼‍🦯': 6, + '🧑🏼‍🦯‍➡️': 7, + '🧑🏼‍🦰': 6, + '🧑🏼‍🦱': 6, + '🧑🏼‍🦲': 6, + '🧑🏼‍🦳': 6, + '🧑🏼‍🦼': 6, + '🧑🏼‍🦽': 6, + '🧑🏼‍🩰': 6, + '🧑🏼‍🫯‍🧑🏻': 9, + '🧑🏼‍🫯‍🧑🏽': 9, + '🧑🏼‍🫯‍🧑🏿': 9, + '🧑🏽‍⚕️': 5, + '🧑🏽‍⚖️': 5, + '🧑🏽‍✈️': 5, + '🧑🏽‍❤️‍💋‍🧑🏿': 11, + '🧑🏽‍🌾': 6, + '🧑🏽‍🍳': 6, + '🧑🏽‍🍼': 6, + '🧑🏽‍🎄': 6, + '🧑🏽‍🎓': 6, + '🧑🏽‍🎤': 6, + '🧑🏽‍🎨': 6, + '🧑🏽‍🏫': 6, + '🧑🏽‍🏭': 6, + '🧑🏽‍🐰‍🧑🏻': 10, + '🧑🏽‍🐰‍🧑🏿': 10, + '🧑🏽‍💻': 6, + '🧑🏽‍💼': 6, + '🧑🏽‍🔧': 6, + '🧑🏽‍🔬': 6, + '🧑🏽‍🚀': 6, + '🧑🏽‍🚒': 6, + '🧑🏽‍🤝‍🧑🏻': 10, + '🧑🏽‍🤝‍🧑🏼': 10, + '🧑🏽‍🤝‍🧑🏽': 10, + '🧑🏽‍🤝‍🧑🏾': 10, + '🧑🏽‍🤝‍🧑🏿': 10, + '🧑🏽‍🦯': 6, + '🧑🏽‍🦯‍➡️': 7, + '🧑🏽‍🦰': 6, + '🧑🏽‍🦱': 6, + '🧑🏽‍🦲': 6, + '🧑🏽‍🦳': 6, + '🧑🏽‍🦼': 6, + '🧑🏽‍🦼‍➡️': 7, + '🧑🏽‍🦽': 6, + '🧑🏽‍🦽‍➡️': 7, + '🧑🏽‍🩰': 6, + '🧑🏽‍🫯‍🧑🏻': 9, + '🧑🏽‍🫯‍🧑🏼': 9, + '🧑🏽‍🫯‍🧑🏾': 9, + '🧑🏽‍🫯‍🧑🏿': 9, + '🧑🏾‍⚕️': 5, + '🧑🏾‍⚖️': 5, + '🧑🏾‍✈️': 5, + '🧑🏾‍🌾': 6, + '🧑🏾‍🍳': 6, + '🧑🏾‍🍼': 6, + '🧑🏾‍🎄': 6, + '🧑🏾‍🎓': 6, + '🧑🏾‍🎤': 6, + '🧑🏾‍🎨': 6, + '🧑🏾‍🏫': 6, + '🧑🏾‍🏭': 6, + '🧑🏾‍🐰‍🧑🏻': 10, + '🧑🏾‍🐰‍🧑🏿': 10, + '🧑🏾‍💻': 6, + '🧑🏾‍💼': 6, + '🧑🏾‍🔧': 6, + '🧑🏾‍🔬': 6, + '🧑🏾‍🚀': 6, + '🧑🏾‍🚒': 6, + '🧑🏾‍🤝‍🧑🏻': 10, + '🧑🏾‍🤝‍🧑🏽': 10, + '🧑🏾‍🤝‍🧑🏾': 10, + '🧑🏾‍🤝‍🧑🏿': 10, + '🧑🏾‍🦯': 6, + '🧑🏾‍🦯‍➡️': 7, + '🧑🏾‍🦰': 6, + '🧑🏾‍🦱': 6, + '🧑🏾‍🦲': 6, + '🧑🏾‍🦳': 6, + '🧑🏾‍🦼': 6, + '🧑🏾‍🦽': 6, + '🧑🏾‍🩰': 6, + '🧑🏾‍🫯‍🧑🏻': 9, + '🧑🏾‍🫯‍🧑🏽': 9, + '🧑🏾‍🫯‍🧑🏿': 9, + '🧑🏿‍⚕️': 5, + '🧑🏿‍⚖️': 5, + '🧑🏿‍✈️': 5, + '🧑🏿‍❤️‍💋‍🧑🏻': 11, + '🧑🏿‍❤️‍💋‍🧑🏽': 11, + '🧑🏿‍🌾': 6, + '🧑🏿‍🍳': 6, + '🧑🏿‍🍼': 6, + '🧑🏿‍🎄': 6, + '🧑🏿‍🎓': 6, + '🧑🏿‍🎤': 6, + '🧑🏿‍🎨': 6, + '🧑🏿‍🏫': 6, + '🧑🏿‍🏭': 6, + '🧑🏿‍🐰‍🧑🏻': 10, + '🧑🏿‍🐰‍🧑🏼': 10, + '🧑🏿‍🐰‍🧑🏽': 10, + '🧑🏿‍🐰‍🧑🏾': 10, + '🧑🏿‍💻': 6, + '🧑🏿‍💼': 6, + '🧑🏿‍🔧': 6, + '🧑🏿‍🔬': 6, + '🧑🏿‍🚀': 6, + '🧑🏿‍🚒': 6, + '🧑🏿‍🤝‍🧑🏻': 10, + '🧑🏿‍🤝‍🧑🏼': 10, + '🧑🏿‍🤝‍🧑🏽': 10, + '🧑🏿‍🤝‍🧑🏾': 10, + '🧑🏿‍🤝‍🧑🏿': 10, + '🧑🏿‍🦯': 6, + '🧑🏿‍🦯‍➡️': 7, + '🧑🏿‍🦰': 6, + '🧑🏿‍🦱': 6, + '🧑🏿‍🦲': 6, + '🧑🏿‍🦳': 6, + '🧑🏿‍🦼': 6, + '🧑🏿‍🦼‍➡️': 7, + '🧑🏿‍🦽': 6, + '🧑🏿‍🦽‍➡️': 7, + '🧑🏿‍🩰': 6, + '🧑🏿‍🫯‍🧑🏻': 9, + '🧑🏿‍🫯‍🧑🏼': 9, + '🧑🏿‍🫯‍🧑🏽': 9, + '🧑🏿‍🫯‍🧑🏾': 9, + '🧔‍♀️': 3, + '🧔‍♂️': 3, + '🧔🏻‍♀️': 5, + '🧔🏻‍♂️': 5, + '🧔🏼‍♀️': 5, + '🧔🏼‍♂️': 5, + '🧔🏽‍♀️': 5, + '🧔🏽‍♂️': 5, + '🧔🏾‍♀️': 5, + '🧔🏾‍♂️': 5, + '🧔🏿‍♀️': 5, + '🧔🏿‍♂️': 5, + '🧖‍♀️': 3, + '🧖‍♂️': 3, + '🧖🏻‍♀️': 5, + '🧖🏻‍♂️': 5, + '🧖🏼‍♀️': 5, + '🧖🏼‍♂️': 5, + '🧖🏽‍♀️': 5, + '🧖🏽‍♂️': 5, + '🧖🏾‍♀️': 5, + '🧖🏾‍♂️': 5, + '🧖🏿‍♀️': 5, + '🧖🏿‍♂️': 5, + '🧗‍♀️': 3, + '🧗‍♂️': 3, + '🧗🏻‍♀️': 5, + '🧗🏻‍♂️': 5, + '🧗🏼‍♀️': 5, + '🧗🏼‍♂️': 5, + '🧗🏽‍♀️': 5, + '🧗🏽‍♂️': 5, + '🧗🏾‍♀️': 5, + '🧗🏾‍♂️': 5, + '🧗🏿‍♀️': 5, + '🧗🏿‍♂️': 5, + '🧘‍♀️': 3, + '🧘‍♂️': 3, + '🧘🏻‍♀️': 5, + '🧘🏻‍♂️': 5, + '🧘🏼‍♀️': 5, + '🧘🏼‍♂️': 5, + '🧘🏽‍♀️': 5, + '🧘🏽‍♂️': 5, + '🧘🏾‍♀️': 5, + '🧘🏾‍♂️': 5, + '🧘🏿‍♀️': 5, + '🧘🏿‍♂️': 5, + '🧙‍♀️': 3, + '🧙‍♂️': 3, + '🧙🏻‍♀️': 5, + '🧙🏻‍♂️': 5, + '🧙🏼‍♀️': 5, + '🧙🏼‍♂️': 5, + '🧙🏽‍♀️': 5, + '🧙🏽‍♂️': 5, + '🧙🏾‍♀️': 5, + '🧙🏾‍♂️': 5, + '🧙🏿‍♀️': 5, + '🧙🏿‍♂️': 5, + '🧚‍♀️': 3, + '🧚‍♂️': 3, + '🧚🏻‍♀️': 5, + '🧚🏻‍♂️': 5, + '🧚🏼‍♀️': 5, + '🧚🏼‍♂️': 5, + '🧚🏽‍♀️': 5, + '🧚🏽‍♂️': 5, + '🧚🏾‍♀️': 5, + '🧚🏾‍♂️': 5, + '🧚🏿‍♀️': 5, + '🧚🏿‍♂️': 5, + '🧛‍♀️': 3, + '🧛‍♂️': 3, + '🧛🏻‍♀️': 5, + '🧛🏻‍♂️': 5, + '🧛🏼‍♀️': 5, + '🧛🏼‍♂️': 5, + '🧛🏽‍♀️': 5, + '🧛🏽‍♂️': 5, + '🧛🏾‍♀️': 5, + '🧛🏾‍♂️': 5, + '🧛🏿‍♀️': 5, + '🧛🏿‍♂️': 5, + '🧜‍♀️': 3, + '🧜‍♂️': 3, + '🧜🏻‍♀️': 5, + '🧜🏻‍♂️': 5, + '🧜🏼‍♀️': 5, + '🧜🏼‍♂️': 5, + '🧜🏽‍♀️': 5, + '🧜🏽‍♂️': 5, + '🧜🏾‍♀️': 5, + '🧜🏾‍♂️': 5, + '🧜🏿‍♀️': 5, + '🧜🏿‍♂️': 5, + '🧝‍♀️': 3, + '🧝‍♂️': 3, + '🧝🏻‍♀️': 5, + '🧝🏻‍♂️': 5, + '🧝🏼‍♀️': 5, + '🧝🏼‍♂️': 5, + '🧝🏽‍♀️': 5, + '🧝🏽‍♂️': 5, + '🧝🏾‍♀️': 5, + '🧝🏾‍♂️': 5, + '🧝🏿‍♀️': 5, + '🧝🏿‍♂️': 5, + '🧞‍♀️': 3, + '🧞‍♂️': 3, + '🧟‍♀️': 3, + '🧟‍♂️': 3, + '🫱🏻‍🫲🏼': 8, + '🫱🏻‍🫲🏽': 8, + '🫱🏻‍🫲🏾': 8, + '🫱🏻‍🫲🏿': 8, + '🫱🏼‍🫲🏻': 8, + '🫱🏼‍🫲🏽': 8, + '🫱🏼‍🫲🏾': 8, + '🫱🏼‍🫲🏿': 8, + '🫱🏽‍🫲🏻': 8, + '🫱🏽‍🫲🏼': 8, + '🫱🏽‍🫲🏾': 8, + '🫱🏽‍🫲🏿': 8, + '🫱🏾‍🫲🏻': 8, + '🫱🏾‍🫲🏼': 8, + '🫱🏾‍🫲🏽': 8, + '🫱🏾‍🫲🏿': 8, + '🫱🏿‍🫲🏻': 8, + '🫱🏿‍🫲🏼': 8, + '🫱🏿‍🫲🏽': 8, + '🫱🏿‍🫲🏾': 8, +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_registry.py b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..82e870814a2d782fa134bf7d96c3c61fe52a59fc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_grapheme_overrides/_registry.py @@ -0,0 +1,32 @@ +""" +Terminal to grapheme mapping of overrides, using a hash registry. + +This code generated by python wcwidth using ucs-detect project data. +""" +# pylint: skip-file +_REGISTRY = { + 'alacritty': '33ac73f2', + 'apple_terminal': '8c2ae14d', + 'bobcat': 'fb5fd79b', + 'contour': '244dc88b', + 'extraterm': 'e18ac6a7', + 'foot': 'cf02297d', + 'ghostty': 'e2b75ee3', + 'iterm2': '59180a0d', + 'kitty': '336a71a1', + 'konsole': '78f828e8', + 'mintty': '3a1895d5', + 'mlterm': 'b6d33cf4', + 'pterm': '97904ece', + 'rio': '900356bf', + 'st': 'a5880eeb', + 'terminology': 'c57c295b', + 'urxvt': 'a5880eeb', + 'vte': 'fdc99132', + 'warp': '65c6beb5', + 'wezterm': '2148ff29', + 'xterm': 'a5880eeb', + 'xterm.js': '058c7585', +} + +__all__ = ('_REGISTRY',) diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_mc.py b/.venv/lib/python3.12/site-packages/wcwidth/table_mc.py new file mode 100644 index 0000000000000000000000000000000000000000..4c5d21c8fb1d086a962c3d4eef454134e4cd5487 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_mc.py @@ -0,0 +1,209 @@ +""" +Exports CATEGORY_MC table keyed by supporting unicode version level. + +This code generated by python wcwidth project. +""" +# pylint: disable=duplicate-code +CATEGORY_MC = { + '18.0.0': ( + # Source: DerivedGeneralCategory-18.0.0.txt + # Date: 2026-06-29, 15:25:02 GMT + # + (0x00903, 0x00903,), # Devanagari Sign Visarga + (0x0093b, 0x0093b,), # Devanagari Vowel Sign Ooe + (0x0093e, 0x00940,), # Devanagari Vowel Sign Aa..Devanagari Vowel Sign Ii + (0x00949, 0x0094c,), # Devanagari Vowel Sign Ca..Devanagari Vowel Sign Au + (0x0094e, 0x0094f,), # Devanagari Vowel Sign Pr..Devanagari Vowel Sign Aw + (0x00982, 0x00983,), # Bengali Sign Anusvara ..Bengali Sign Visarga + (0x009be, 0x009c0,), # Bengali Vowel Sign Aa ..Bengali Vowel Sign Ii + (0x009c7, 0x009c8,), # Bengali Vowel Sign E ..Bengali Vowel Sign Ai + (0x009cb, 0x009cc,), # Bengali Vowel Sign O ..Bengali Vowel Sign Au + (0x009d7, 0x009d7,), # Bengali Au Length Mark + (0x00a03, 0x00a03,), # Gurmukhi Sign Visarga + (0x00a3e, 0x00a40,), # Gurmukhi Vowel Sign Aa ..Gurmukhi Vowel Sign Ii + (0x00a83, 0x00a83,), # Gujarati Sign Visarga + (0x00abe, 0x00ac0,), # Gujarati Vowel Sign Aa ..Gujarati Vowel Sign Ii + (0x00ac9, 0x00ac9,), # Gujarati Vowel Sign Candra O + (0x00acb, 0x00acc,), # Gujarati Vowel Sign O ..Gujarati Vowel Sign Au + (0x00b02, 0x00b03,), # Oriya Sign Anusvara ..Oriya Sign Visarga + (0x00b3e, 0x00b3e,), # Oriya Vowel Sign Aa + (0x00b40, 0x00b40,), # Oriya Vowel Sign Ii + (0x00b47, 0x00b48,), # Oriya Vowel Sign E ..Oriya Vowel Sign Ai + (0x00b4b, 0x00b4c,), # Oriya Vowel Sign O ..Oriya Vowel Sign Au + (0x00b57, 0x00b57,), # Oriya Au Length Mark + (0x00bbe, 0x00bbf,), # Tamil Vowel Sign Aa ..Tamil Vowel Sign I + (0x00bc1, 0x00bc2,), # Tamil Vowel Sign U ..Tamil Vowel Sign Uu + (0x00bc6, 0x00bc8,), # Tamil Vowel Sign E ..Tamil Vowel Sign Ai + (0x00bca, 0x00bcc,), # Tamil Vowel Sign O ..Tamil Vowel Sign Au + (0x00bd7, 0x00bd7,), # Tamil Au Length Mark + (0x00c01, 0x00c03,), # Telugu Sign Candrabindu ..Telugu Sign Visarga + (0x00c41, 0x00c44,), # Telugu Vowel Sign U ..Telugu Vowel Sign Vocali + (0x00c82, 0x00c83,), # Kannada Sign Anusvara ..Kannada Sign Visarga + (0x00cbe, 0x00cbe,), # Kannada Vowel Sign Aa + (0x00cc0, 0x00cc4,), # Kannada Vowel Sign Ii ..Kannada Vowel Sign Vocal + (0x00cc7, 0x00cc8,), # Kannada Vowel Sign Ee ..Kannada Vowel Sign Ai + (0x00cca, 0x00ccb,), # Kannada Vowel Sign O ..Kannada Vowel Sign Oo + (0x00cd5, 0x00cd6,), # Kannada Length Mark ..Kannada Ai Length Mark + (0x00cf3, 0x00cf3,), # Kannada Sign Combining Anusvara Above Right + (0x00d02, 0x00d03,), # Malayalam Sign Anusvara ..Malayalam Sign Visarga + (0x00d3e, 0x00d40,), # Malayalam Vowel Sign Aa ..Malayalam Vowel Sign Ii + (0x00d46, 0x00d48,), # Malayalam Vowel Sign E ..Malayalam Vowel Sign Ai + (0x00d4a, 0x00d4c,), # Malayalam Vowel Sign O ..Malayalam Vowel Sign Au + (0x00d57, 0x00d57,), # Malayalam Au Length Mark + (0x00d82, 0x00d83,), # Sinhala Sign Anusvaraya ..Sinhala Sign Visargaya + (0x00dcf, 0x00dd1,), # Sinhala Vowel Sign Aela-..Sinhala Vowel Sign Diga + (0x00dd8, 0x00ddf,), # Sinhala Vowel Sign Gaett..Sinhala Vowel Sign Gayan + (0x00df2, 0x00df3,), # Sinhala Vowel Sign Diga ..Sinhala Vowel Sign Diga + (0x00f3e, 0x00f3f,), # Tibetan Sign Yar Tshes ..Tibetan Sign Mar Tshes + (0x00f7f, 0x00f7f,), # Tibetan Sign Rnam Bcad + (0x0102b, 0x0102c,), # Myanmar Vowel Sign Tall ..Myanmar Vowel Sign Aa + (0x01031, 0x01031,), # Myanmar Vowel Sign E + (0x01038, 0x01038,), # Myanmar Sign Visarga + (0x0103b, 0x0103c,), # Myanmar Consonant Sign M..Myanmar Consonant Sign M + (0x01056, 0x01057,), # Myanmar Vowel Sign Vocal..Myanmar Vowel Sign Vocal + (0x01062, 0x01064,), # Myanmar Vowel Sign Sgaw ..Myanmar Tone Mark Sgaw K + (0x01067, 0x0106d,), # Myanmar Vowel Sign Weste..Myanmar Sign Western Pwo + (0x01083, 0x01084,), # Myanmar Vowel Sign Shan ..Myanmar Vowel Sign Shan + (0x01087, 0x0108c,), # Myanmar Sign Shan Tone-2..Myanmar Sign Shan Counci + (0x0108f, 0x0108f,), # Myanmar Sign Rumai Palaung Tone-5 + (0x0109a, 0x0109c,), # Myanmar Sign Khamti Tone..Myanmar Vowel Sign Aiton + (0x01715, 0x01715,), # Tagalog Sign Pamudpod + (0x01734, 0x01734,), # Hanunoo Sign Pamudpod + (0x017b6, 0x017b6,), # Khmer Vowel Sign Aa + (0x017be, 0x017c5,), # Khmer Vowel Sign Oe ..Khmer Vowel Sign Au + (0x017c7, 0x017c8,), # Khmer Sign Reahmuk ..Khmer Sign Yuukaleapintu + (0x01923, 0x01926,), # Limbu Vowel Sign Ee ..Limbu Vowel Sign Au + (0x01929, 0x0192b,), # Limbu Subjoined Letter Y..Limbu Subjoined Letter W + (0x01930, 0x01931,), # Limbu Small Letter Ka ..Limbu Small Letter Nga + (0x01933, 0x01938,), # Limbu Small Letter Ta ..Limbu Small Letter La + (0x01a19, 0x01a1a,), # Buginese Vowel Sign E ..Buginese Vowel Sign O + (0x01a55, 0x01a55,), # Tai Tham Consonant Sign Medial Ra + (0x01a57, 0x01a57,), # Tai Tham Consonant Sign La Tang Lai + (0x01a61, 0x01a61,), # Tai Tham Vowel Sign A + (0x01a63, 0x01a64,), # Tai Tham Vowel Sign Aa ..Tai Tham Vowel Sign Tall + (0x01a6d, 0x01a72,), # Tai Tham Vowel Sign Oy ..Tai Tham Vowel Sign Tham + (0x01b04, 0x01b04,), # Balinese Sign Bisah + (0x01b35, 0x01b35,), # Balinese Vowel Sign Tedung + (0x01b3b, 0x01b3b,), # Balinese Vowel Sign Ra Repa Tedung + (0x01b3d, 0x01b41,), # Balinese Vowel Sign La L..Balinese Vowel Sign Tali + (0x01b43, 0x01b44,), # Balinese Vowel Sign Pepe..Balinese Adeg Adeg + (0x01b82, 0x01b82,), # Sundanese Sign Pangwisad + (0x01ba1, 0x01ba1,), # Sundanese Consonant Sign Pamingkal + (0x01ba6, 0x01ba7,), # Sundanese Vowel Sign Pan..Sundanese Vowel Sign Pan + (0x01baa, 0x01baa,), # Sundanese Sign Pamaaeh + (0x01be7, 0x01be7,), # Batak Vowel Sign E + (0x01bea, 0x01bec,), # Batak Vowel Sign I ..Batak Vowel Sign O + (0x01bee, 0x01bee,), # Batak Vowel Sign U + (0x01bf2, 0x01bf3,), # Batak Pangolat ..Batak Panongonan + (0x01c24, 0x01c2b,), # Lepcha Subjoined Letter ..Lepcha Vowel Sign Uu + (0x01c34, 0x01c35,), # Lepcha Consonant Sign Ny..Lepcha Consonant Sign Ka + (0x01ce1, 0x01ce1,), # Vedic Tone Atharvavedic Independent Svarita + (0x01cf7, 0x01cf7,), # Vedic Sign Atikrama + (0x0302e, 0x0302f,), # Hangul Single Dot Tone M..Hangul Double Dot Tone M + (0x0a823, 0x0a824,), # Syloti Nagri Vowel Sign ..Syloti Nagri Vowel Sign + (0x0a827, 0x0a827,), # Syloti Nagri Vowel Sign Oo + (0x0a880, 0x0a881,), # Saurashtra Sign Anusvara..Saurashtra Sign Visarga + (0x0a8b4, 0x0a8c3,), # Saurashtra Consonant Sig..Saurashtra Vowel Sign Au + (0x0a952, 0x0a953,), # Rejang Consonant Sign H ..Rejang Virama + (0x0a983, 0x0a983,), # Javanese Sign Wignyan + (0x0a9b4, 0x0a9b5,), # Javanese Vowel Sign Taru..Javanese Vowel Sign Tolo + (0x0a9ba, 0x0a9bb,), # Javanese Vowel Sign Tali..Javanese Vowel Sign Dirg + (0x0a9be, 0x0a9c0,), # Javanese Consonant Sign ..Javanese Pangkon + (0x0aa2f, 0x0aa30,), # Cham Vowel Sign O ..Cham Vowel Sign Ai + (0x0aa33, 0x0aa34,), # Cham Consonant Sign Ya ..Cham Consonant Sign Ra + (0x0aa4d, 0x0aa4d,), # Cham Consonant Sign Final H + (0x0aa7b, 0x0aa7b,), # Myanmar Sign Pao Karen Tone + (0x0aa7d, 0x0aa7d,), # Myanmar Sign Tai Laing Tone-5 + (0x0aaeb, 0x0aaeb,), # Meetei Mayek Vowel Sign Ii + (0x0aaee, 0x0aaef,), # Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + (0x0aaf5, 0x0aaf5,), # Meetei Mayek Vowel Sign Visarga + (0x0abe3, 0x0abe4,), # Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + (0x0abe6, 0x0abe7,), # Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + (0x0abe9, 0x0abea,), # Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + (0x0abec, 0x0abec,), # Meetei Mayek Lum Iyek + (0x11000, 0x11000,), # Brahmi Sign Candrabindu + (0x11002, 0x11002,), # Brahmi Sign Visarga + (0x11082, 0x11082,), # Kaithi Sign Visarga + (0x110b0, 0x110b2,), # Kaithi Vowel Sign Aa ..Kaithi Vowel Sign Ii + (0x110b7, 0x110b8,), # Kaithi Vowel Sign O ..Kaithi Vowel Sign Au + (0x1112c, 0x1112c,), # Chakma Vowel Sign E + (0x11145, 0x11146,), # Chakma Vowel Sign Aa ..Chakma Vowel Sign Ei + (0x11182, 0x11182,), # Sharada Sign Visarga + (0x111b3, 0x111b5,), # Sharada Vowel Sign Aa ..Sharada Vowel Sign Ii + (0x111bf, 0x111c0,), # Sharada Vowel Sign Au ..Sharada Sign Virama + (0x111ce, 0x111ce,), # Sharada Vowel Sign Prishthamatra E + (0x1122c, 0x1122e,), # Khojki Vowel Sign Aa ..Khojki Vowel Sign Ii + (0x11232, 0x11233,), # Khojki Vowel Sign O ..Khojki Vowel Sign Au + (0x11235, 0x11235,), # Khojki Sign Virama + (0x112e0, 0x112e2,), # Khudawadi Vowel Sign Aa ..Khudawadi Vowel Sign Ii + (0x11302, 0x11303,), # Grantha Sign Anusvara ..Grantha Sign Visarga + (0x1133e, 0x1133f,), # Grantha Vowel Sign Aa ..Grantha Vowel Sign I + (0x11341, 0x11344,), # Grantha Vowel Sign U ..Grantha Vowel Sign Vocal + (0x11347, 0x11348,), # Grantha Vowel Sign Ee ..Grantha Vowel Sign Ai + (0x1134b, 0x1134d,), # Grantha Vowel Sign Oo ..Grantha Sign Virama + (0x11357, 0x11357,), # Grantha Au Length Mark + (0x11362, 0x11363,), # Grantha Vowel Sign Vocal..Grantha Vowel Sign Vocal + (0x113b8, 0x113ba,), # Tulu-tigalari Vowel Sign..Tulu-tigalari Vowel Sign + (0x113c2, 0x113c2,), # Tulu-tigalari Vowel Sign Ee + (0x113c5, 0x113c5,), # Tulu-tigalari Vowel Sign Ai + (0x113c7, 0x113ca,), # Tulu-tigalari Vowel Sign..Tulu-tigalari Sign Candr + (0x113cc, 0x113cd,), # Tulu-tigalari Sign Anusv..Tulu-tigalari Sign Visar + (0x113cf, 0x113cf,), # Tulu-tigalari Sign Looped Virama + (0x11435, 0x11437,), # Newa Vowel Sign Aa ..Newa Vowel Sign Ii + (0x11440, 0x11441,), # Newa Vowel Sign O ..Newa Vowel Sign Au + (0x11445, 0x11445,), # Newa Sign Visarga + (0x114b0, 0x114b2,), # Tirhuta Vowel Sign Aa ..Tirhuta Vowel Sign Ii + (0x114b9, 0x114b9,), # Tirhuta Vowel Sign E + (0x114bb, 0x114be,), # Tirhuta Vowel Sign Ai ..Tirhuta Vowel Sign Au + (0x114c1, 0x114c1,), # Tirhuta Sign Visarga + (0x115af, 0x115b1,), # Siddham Vowel Sign Aa ..Siddham Vowel Sign Ii + (0x115b8, 0x115bb,), # Siddham Vowel Sign E ..Siddham Vowel Sign Au + (0x115be, 0x115be,), # Siddham Sign Visarga + (0x11630, 0x11632,), # Modi Vowel Sign Aa ..Modi Vowel Sign Ii + (0x1163b, 0x1163c,), # Modi Vowel Sign O ..Modi Vowel Sign Au + (0x1163e, 0x1163e,), # Modi Sign Visarga + (0x116ac, 0x116ac,), # Takri Sign Visarga + (0x116ae, 0x116af,), # Takri Vowel Sign I ..Takri Vowel Sign Ii + (0x116b6, 0x116b6,), # Takri Sign Virama + (0x1171e, 0x1171e,), # Ahom Consonant Sign Medial Ra + (0x11720, 0x11721,), # Ahom Vowel Sign A ..Ahom Vowel Sign Aa + (0x11726, 0x11726,), # Ahom Vowel Sign E + (0x1182c, 0x1182e,), # Dogra Vowel Sign Aa ..Dogra Vowel Sign Ii + (0x11838, 0x11838,), # Dogra Sign Visarga + (0x11930, 0x11935,), # Dives Akuru Vowel Sign A..Dives Akuru Vowel Sign E + (0x11937, 0x11938,), # Dives Akuru Vowel Sign A..Dives Akuru Vowel Sign O + (0x1193d, 0x1193d,), # Dives Akuru Sign Halanta + (0x11940, 0x11940,), # Dives Akuru Medial Ya + (0x11942, 0x11942,), # Dives Akuru Medial Ra + (0x119d1, 0x119d3,), # Nandinagari Vowel Sign A..Nandinagari Vowel Sign I + (0x119dc, 0x119df,), # Nandinagari Vowel Sign O..Nandinagari Sign Visarga + (0x119e4, 0x119e4,), # Nandinagari Vowel Sign Prishthamatra E + (0x11a39, 0x11a39,), # Zanabazar Square Sign Visarga + (0x11a57, 0x11a58,), # Soyombo Vowel Sign Ai ..Soyombo Vowel Sign Au + (0x11a97, 0x11a97,), # Soyombo Sign Visarga + (0x11b61, 0x11b61,), # Sharada Vowel Sign Ooe + (0x11b65, 0x11b65,), # Sharada Vowel Sign Short O + (0x11b67, 0x11b67,), # Sharada Vowel Sign Candra O + (0x11c2f, 0x11c2f,), # Bhaiksuki Vowel Sign Aa + (0x11c3e, 0x11c3e,), # Bhaiksuki Sign Visarga + (0x11ca9, 0x11ca9,), # Marchen Subjoined Letter Ya + (0x11cb1, 0x11cb1,), # Marchen Vowel Sign I + (0x11cb4, 0x11cb4,), # Marchen Vowel Sign O + (0x11d8a, 0x11d8e,), # Gunjala Gondi Vowel Sign..Gunjala Gondi Vowel Sign + (0x11d93, 0x11d94,), # Gunjala Gondi Vowel Sign..Gunjala Gondi Vowel Sign + (0x11d96, 0x11d96,), # Gunjala Gondi Sign Visarga + (0x11ef5, 0x11ef6,), # Makasar Vowel Sign E ..Makasar Vowel Sign O + (0x11f03, 0x11f03,), # Kawi Sign Visarga + (0x11f34, 0x11f35,), # Kawi Vowel Sign Aa ..Kawi Vowel Sign Alternat + (0x11f3e, 0x11f3f,), # Kawi Vowel Sign E ..Kawi Vowel Sign Ai + (0x11f41, 0x11f41,), # Kawi Sign Killer + (0x1612a, 0x1612c,), # Gurung Khema Consonant S..Gurung Khema Consonant S + (0x16f51, 0x16f87,), # Miao Sign Aspiration ..Miao Vowel Sign Ui + (0x16ff0, 0x16ff1,), # Vietnamese Alternate Rea..Vietnamese Alternate Rea + (0x1d165, 0x1d166,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d16d, 0x1d172,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d250, 0x1d252,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d25f, 0x1d25f,), # Musical Symbol Combining Buzz Roll Stem + (0x1d280, 0x1d281,), # Musical Symbol Combining..Musical Symbol Combining + ), +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_overrides.py b/.venv/lib/python3.12/site-packages/wcwidth/table_overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..d9f15b7caf2c0f6c95375b7a452c0f2763e577f1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_overrides.py @@ -0,0 +1,979 @@ +""" +Terminal override tables keyed by canonical terminal software name. + +This code generated by python wcwidth using ucs-detect project data. +""" +# pylint: skip-file +from __future__ import annotations + +# For terminals: iterm2 +_SET_WIDE_OVERRIDES_1C271C46: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x18e00, 0x19191,), # Jurchen Character-18e00 ..Jurchen Character-19191 + (0x191a0, 0x191d2,), # Jurchen Radical-01 ..Jurchen Radical-51 + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f6d9, 0x1f6d9,), # Lighthouse + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + (0x1fa8b, 0x1fa8d,), # Meteor ..Net With Handle + (0x1facc, 0x1facc,), # Monarch Butterfly + (0x1fadd, 0x1fadd,), # Pickle + (0x1faeb, 0x1faeb,), # Cracking Face + (0x1faf9, 0x1fafa,), # Leftwards Thumb Sign ..Rightwards Thumb Sign + ), + 'zeroer': ( + (0x0115f, 0x0115f,), # Hangul Choseong Filler + ), +} + +# For terminals: apple_terminal +_SET_WIDE_OVERRIDES_23A62FFD: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x18e00, 0x19191,), # Jurchen Character-18e00 ..Jurchen Character-19191 + (0x191a0, 0x191d2,), # Jurchen Radical-01 ..Jurchen Radical-51 + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f1e6, 0x1f1ff,), # Regional Indicator Symbo..Regional Indicator Symbo + (0x1f6d9, 0x1f6d9,), # Lighthouse + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + (0x1fa8b, 0x1fa8d,), # Meteor ..Net With Handle + (0x1facc, 0x1facc,), # Monarch Butterfly + (0x1fadd, 0x1fadd,), # Pickle + (0x1faeb, 0x1faeb,), # Cracking Face + (0x1faf9, 0x1fafa,), # Leftwards Thumb Sign ..Rightwards Thumb Sign + ), +} + +# For terminals: kitty +_SET_WIDE_OVERRIDES_383629C7: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x18e00, 0x19191,), # Jurchen Character-18e00 ..Jurchen Character-19191 + (0x191a0, 0x191d2,), # Jurchen Radical-01 ..Jurchen Radical-51 + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f6d9, 0x1f6d9,), # Lighthouse + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + (0x1fa8b, 0x1fa8d,), # Meteor ..Net With Handle + (0x1facc, 0x1facc,), # Monarch Butterfly + (0x1fadd, 0x1fadd,), # Pickle + (0x1faeb, 0x1faeb,), # Cracking Face + (0x1faf9, 0x1fafa,), # Leftwards Thumb Sign ..Rightwards Thumb Sign + ), + 'zeroer': ( + (0x1f3fb, 0x1f3ff,), # Emoji Modifier Fitzpatri..Emoji Modifier Fitzpatri + ), +} + +# For terminals: konsole +_SET_WIDE_OVERRIDES_3CBB3895: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x02630, 0x02637,), # Trigram For Heaven ..Trigram For Earth + (0x0268a, 0x0268f,), # Monogram For Yang ..Digram For Greater Yin + (0x02ffc, 0x02fff,), # Ideographic Description ..Ideographic Description + (0x031e4, 0x031e5,), # Cjk Stroke Hxg ..Cjk Stroke Szp + (0x031ef, 0x031ef,), # Ideographic Description Character Subtraction + (0x04dc0, 0x04dff,), # Hexagram For The Creativ..Hexagram For Before Comp + (0x18e00, 0x19191,), # Jurchen Character-18e00 ..Jurchen Character-19191 + (0x191a0, 0x191d2,), # Jurchen Radical-01 ..Jurchen Radical-51 + (0x1d300, 0x1d356,), # Monogram For Earth ..Tetragram For Fostering + (0x1d360, 0x1d376,), # Counting Rod Unit Digit ..Ideographic Tally Mark F + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f6d8, 0x1f6d9,), # Landslide ..Lighthouse + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + (0x1fa89, 0x1fa8f,), # Harp ..Shovel + (0x1fabe, 0x1fabe,), # Leafless Tree + (0x1fac6, 0x1fac6,), # Fingerprint + (0x1fac8, 0x1fac8,), # Hairy Creature + (0x1facc, 0x1facd,), # Monarch Butterfly ..Orca + (0x1fadc, 0x1fadd,), # Root Vegetable ..Pickle + (0x1fadf, 0x1fadf,), # Splatter + (0x1fae9, 0x1faeb,), # Face With Bags Under Eye..Cracking Face + (0x1faef, 0x1faef,), # Fight Cloud + (0x1faf9, 0x1fafa,), # Leftwards Thumb Sign ..Rightwards Thumb Sign + ), +} + +# For terminals: mlterm, warp +_SET_WIDE_OVERRIDES_64DD0D04: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x02630, 0x02637,), # Trigram For Heaven ..Trigram For Earth + (0x0268a, 0x0268f,), # Monogram For Yang ..Digram For Greater Yin + (0x031e4, 0x031e5,), # Cjk Stroke Hxg ..Cjk Stroke Szp + (0x04dc0, 0x04dff,), # Hexagram For The Creativ..Hexagram For Before Comp + (0x18e00, 0x19191,), # Jurchen Character-18e00 ..Jurchen Character-19191 + (0x191a0, 0x191d2,), # Jurchen Radical-01 ..Jurchen Radical-51 + (0x1d300, 0x1d356,), # Monogram For Earth ..Tetragram For Fostering + (0x1d360, 0x1d376,), # Counting Rod Unit Digit ..Ideographic Tally Mark F + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f1e6, 0x1f1ff,), # Regional Indicator Symbo..Regional Indicator Symbo + (0x1f6d8, 0x1f6d9,), # Landslide ..Lighthouse + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + (0x1fa89, 0x1fa8f,), # Harp ..Shovel + (0x1fabe, 0x1fabe,), # Leafless Tree + (0x1fac6, 0x1fac6,), # Fingerprint + (0x1fac8, 0x1fac8,), # Hairy Creature + (0x1facc, 0x1facd,), # Monarch Butterfly ..Orca + (0x1fadc, 0x1fadd,), # Root Vegetable ..Pickle + (0x1fadf, 0x1fadf,), # Splatter + (0x1fae9, 0x1faeb,), # Face With Bags Under Eye..Cracking Face + (0x1faef, 0x1faef,), # Fight Cloud + (0x1faf9, 0x1fafa,), # Leftwards Thumb Sign ..Rightwards Thumb Sign + ), +} + +# For terminals: alacritty, pterm, st, urxvt, wezterm, xterm +_SET_WIDE_OVERRIDES_6E5EF6CC: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x1f1e6, 0x1f1ff,), # Regional Indicator Symbo..Regional Indicator Symbo + ), +} + +# For terminals: extraterm +_SET_WIDE_OVERRIDES_766614D8: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x02630, 0x02637,), # Trigram For Heaven ..Trigram For Earth + (0x0268a, 0x0268f,), # Monogram For Yang ..Digram For Greater Yin + (0x02ffc, 0x02fff,), # Ideographic Description ..Ideographic Description + (0x031e4, 0x031e5,), # Cjk Stroke Hxg ..Cjk Stroke Szp + (0x031ef, 0x031ef,), # Ideographic Description Character Subtraction + (0x04dc0, 0x04dff,), # Hexagram For The Creativ..Hexagram For Before Comp + (0x18e00, 0x19191,), # Jurchen Character-18e00 ..Jurchen Character-19191 + (0x191a0, 0x191d2,), # Jurchen Radical-01 ..Jurchen Radical-51 + (0x1d300, 0x1d356,), # Monogram For Earth ..Tetragram For Fostering + (0x1d360, 0x1d376,), # Counting Rod Unit Digit ..Ideographic Tally Mark F + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f1e6, 0x1f1ff,), # Regional Indicator Symbo..Regional Indicator Symbo + (0x1f6d8, 0x1f6d9,), # Landslide ..Lighthouse + (0x1f6dc, 0x1f6dc,), # Wireless + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + (0x1fa75, 0x1fa77,), # Light Blue Heart ..Pink Heart + (0x1fa87, 0x1fa8f,), # Maracas ..Shovel + (0x1faad, 0x1faaf,), # Folding Hand Fan ..Khanda + (0x1fabb, 0x1fabf,), # Hyacinth ..Goose + (0x1fac6, 0x1fac6,), # Fingerprint + (0x1fac8, 0x1fac8,), # Hairy Creature + (0x1facc, 0x1facf,), # Monarch Butterfly ..Donkey + (0x1fada, 0x1fadd,), # Ginger Root ..Pickle + (0x1fadf, 0x1fadf,), # Splatter + (0x1fae8, 0x1faeb,), # Shaking Face ..Cracking Face + (0x1faef, 0x1faef,), # Fight Cloud + (0x1faf7, 0x1fafa,), # Leftwards Pushing Hand ..Rightwards Thumb Sign + ), +} + +# For terminals: vte +_SET_WIDE_OVERRIDES_78B553AB: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x02630, 0x02637,), # Trigram For Heaven ..Trigram For Earth + (0x0268a, 0x0268f,), # Monogram For Yang ..Digram For Greater Yin + (0x02ffc, 0x02fff,), # Ideographic Description ..Ideographic Description + (0x031e4, 0x031e5,), # Cjk Stroke Hxg ..Cjk Stroke Szp + (0x031ef, 0x031ef,), # Ideographic Description Character Subtraction + (0x04dc0, 0x04dff,), # Hexagram For The Creativ..Hexagram For Before Comp + (0x18e00, 0x19191,), # Jurchen Character-18e00 ..Jurchen Character-19191 + (0x191a0, 0x191d2,), # Jurchen Radical-01 ..Jurchen Radical-51 + (0x1d300, 0x1d356,), # Monogram For Earth ..Tetragram For Fostering + (0x1d360, 0x1d376,), # Counting Rod Unit Digit ..Ideographic Tally Mark F + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f1e6, 0x1f1ff,), # Regional Indicator Symbo..Regional Indicator Symbo + (0x1f6d8, 0x1f6d9,), # Landslide ..Lighthouse + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + (0x1fa89, 0x1fa8f,), # Harp ..Shovel + (0x1fabe, 0x1fabe,), # Leafless Tree + (0x1fac6, 0x1fac6,), # Fingerprint + (0x1fac8, 0x1fac8,), # Hairy Creature + (0x1facc, 0x1facd,), # Monarch Butterfly ..Orca + (0x1fadc, 0x1fadd,), # Root Vegetable ..Pickle + (0x1fadf, 0x1fadf,), # Splatter + (0x1fae9, 0x1faeb,), # Face With Bags Under Eye..Cracking Face + (0x1faef, 0x1faef,), # Fight Cloud + (0x1faf9, 0x1fafa,), # Leftwards Thumb Sign ..Rightwards Thumb Sign + ), +} + +# For terminals: contour +_SET_WIDE_OVERRIDES_7D53D5DB: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x18e00, 0x19191,), # Jurchen Character-18e00 ..Jurchen Character-19191 + (0x191a0, 0x191d2,), # Jurchen Radical-01 ..Jurchen Radical-51 + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f6d9, 0x1f6d9,), # Lighthouse + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + (0x1fa8b, 0x1fa8d,), # Meteor ..Net With Handle + (0x1facc, 0x1facc,), # Monarch Butterfly + (0x1fadd, 0x1fadd,), # Pickle + (0x1faeb, 0x1faeb,), # Cracking Face + (0x1faf9, 0x1fafa,), # Leftwards Thumb Sign ..Rightwards Thumb Sign + ), +} + +# For terminals: foot +_SET_WIDE_OVERRIDES_98684D9B: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x1f1e6, 0x1f1ff,), # Regional Indicator Symbo..Regional Indicator Symbo + (0x1f3fb, 0x1f3ff,), # Emoji Modifier Fitzpatri..Emoji Modifier Fitzpatri + ), +} + +# For terminals: xterm.js +_SET_WIDE_OVERRIDES_A912FF1E: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x02630, 0x02637,), # Trigram For Heaven ..Trigram For Earth + (0x0268a, 0x0268f,), # Monogram For Yang ..Digram For Greater Yin + (0x02ffc, 0x02fff,), # Ideographic Description ..Ideographic Description + (0x031bb, 0x031bf,), # Bopomofo Final Letter G ..Bopomofo Letter Ah + (0x031e4, 0x031e5,), # Cjk Stroke Hxg ..Cjk Stroke Szp + (0x031ef, 0x031ef,), # Ideographic Description Character Subtraction + (0x04dc0, 0x04dff,), # Hexagram For The Creativ..Hexagram For Before Comp + (0x18e00, 0x19191,), # Jurchen Character-18e00 ..Jurchen Character-19191 + (0x191a0, 0x191d2,), # Jurchen Radical-01 ..Jurchen Radical-51 + (0x1aff0, 0x1aff3,), # Katakana Letter Minnan T..Katakana Letter Minnan T + (0x1aff5, 0x1affb,), # Katakana Letter Minnan T..Katakana Letter Minnan N + (0x1affd, 0x1affe,), # Katakana Letter Minnan N..Katakana Letter Minnan N + (0x1d300, 0x1d356,), # Monogram For Earth ..Tetragram For Fostering + (0x1d360, 0x1d376,), # Counting Rod Unit Digit ..Ideographic Tally Mark F + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f1e6, 0x1f1ff,), # Regional Indicator Symbo..Regional Indicator Symbo + (0x1f6d6, 0x1f6d9,), # Hut ..Lighthouse + (0x1f6dc, 0x1f6df,), # Wireless ..Ring Buoy + (0x1f6fb, 0x1f6fc,), # Pickup Truck ..Roller Skate + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + (0x1f7f0, 0x1f7f0,), # Heavy Equals Sign + (0x1f90c, 0x1f90c,), # Pinched Fingers + (0x1f972, 0x1f972,), # Smiling Face With Tear + (0x1f977, 0x1f979,), # Ninja ..Face Holding Back Tears + (0x1f9a3, 0x1f9a4,), # Mammoth ..Dodo + (0x1f9ab, 0x1f9ad,), # Beaver ..Seal + (0x1f9cb, 0x1f9cc,), # Bubble Tea ..Troll + (0x1fa74, 0x1fa77,), # Thong Sandal ..Pink Heart + (0x1fa7b, 0x1fa7c,), # X-ray ..Crutch + (0x1fa83, 0x1fa8f,), # Boomerang ..Shovel + (0x1fa96, 0x1fac6,), # Military Helmet ..Fingerprint + (0x1fac8, 0x1fac8,), # Hairy Creature + (0x1facc, 0x1fadd,), # Monarch Butterfly ..Pickle + (0x1fadf, 0x1faeb,), # Splatter ..Cracking Face + (0x1faef, 0x1fafa,), # Fight Cloud ..Rightwards Thumb Sign + ), +} + +# For terminals: terminology +_SET_WIDE_OVERRIDES_BC68C805: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x02630, 0x02637,), # Trigram For Heaven ..Trigram For Earth + (0x0268a, 0x0268f,), # Monogram For Yang ..Digram For Greater Yin + (0x04dc0, 0x04dff,), # Hexagram For The Creativ..Hexagram For Before Comp + (0x0fada, 0x0faff,), # (nil) + (0x1d300, 0x1d356,), # Monogram For Earth ..Tetragram For Fostering + (0x1d360, 0x1d376,), # Counting Rod Unit Digit ..Ideographic Tally Mark F + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f1e6, 0x1f1ff,), # Regional Indicator Symbo..Regional Indicator Symbo + (0x1f6d8, 0x1f6d9,), # Landslide ..Lighthouse + (0x1f6dc, 0x1f6df,), # Wireless ..Ring Buoy + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + (0x1f7f0, 0x1f7f0,), # Heavy Equals Sign + (0x1fad7, 0x1fadd,), # Pouring Liquid ..Pickle + (0x1fadf, 0x1faeb,), # Splatter ..Cracking Face + (0x1faef, 0x1fafa,), # Fight Cloud ..Rightwards Thumb Sign + ), +} + +# For terminals: ghostty +_SET_WIDE_OVERRIDES_CF30CE25: dict[str, tuple[tuple[int, int], ...]] = { + 'zeroer': ( + (0x0115f, 0x0115f,), # Hangul Choseong Filler + ), +} + +# For terminals: mintty +_SET_WIDE_OVERRIDES_DB01D1AB: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x18e00, 0x19191,), # Jurchen Character-18e00 ..Jurchen Character-19191 + (0x191a0, 0x191d2,), # Jurchen Radical-01 ..Jurchen Radical-51 + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f1e6, 0x1f1ff,), # Regional Indicator Symbo..Regional Indicator Symbo + (0x1f3fb, 0x1f3ff,), # Emoji Modifier Fitzpatri..Emoji Modifier Fitzpatri + (0x1f6d9, 0x1f6d9,), # Lighthouse + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + ), +} + +# For terminals: bobcat +_SET_WIDE_OVERRIDES_ECBD3770: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x03030, 0x03030,), # Wavy Dash + (0x0303d, 0x0303d,), # Part Alternation Mark + (0x03297, 0x03297,), # Circled Ideograph Congratulation + (0x03299, 0x03299,), # Circled Ideograph Secret + (0x18e00, 0x19191,), # Jurchen Character-18e00 ..Jurchen Character-19191 + (0x191a0, 0x191d2,), # Jurchen Radical-01 ..Jurchen Radical-51 + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f202, 0x1f202,), # Squared Katakana Sa + (0x1f237, 0x1f237,), # Squared Cjk Unified Ideograph-6708 + (0x1f6d9, 0x1f6d9,), # Lighthouse + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + (0x1fa8b, 0x1fa8d,), # Meteor ..Net With Handle + (0x1facc, 0x1facc,), # Monarch Butterfly + (0x1fadd, 0x1fadd,), # Pickle + (0x1faeb, 0x1faeb,), # Cracking Face + (0x1faf9, 0x1fafa,), # Leftwards Thumb Sign ..Rightwards Thumb Sign + ), + 'zeroer': ( + (0x1f3fb, 0x1f3ff,), # Emoji Modifier Fitzpatri..Emoji Modifier Fitzpatri + ), +} + +# For terminals: rio +_SET_WIDE_OVERRIDES_EE7A1B97: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x18e00, 0x19191,), # Jurchen Character-18e00 ..Jurchen Character-19191 + (0x191a0, 0x191d2,), # Jurchen Radical-01 ..Jurchen Radical-51 + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f1e6, 0x1f1ff,), # Regional Indicator Symbo..Regional Indicator Symbo + (0x1f3fb, 0x1f3ff,), # Emoji Modifier Fitzpatri..Emoji Modifier Fitzpatri + (0x1f6d9, 0x1f6d9,), # Lighthouse + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + (0x1fa8b, 0x1fa8d,), # Meteor ..Net With Handle + (0x1facc, 0x1facc,), # Monarch Butterfly + (0x1fadd, 0x1fadd,), # Pickle + (0x1faeb, 0x1faeb,), # Cracking Face + (0x1faf9, 0x1fafa,), # Leftwards Thumb Sign ..Rightwards Thumb Sign + ), +} + +WIDE_OVERRIDES: dict[str, dict[str, tuple[tuple[int, int], ...]]] = { + 'alacritty': _SET_WIDE_OVERRIDES_6E5EF6CC, + 'apple_terminal': _SET_WIDE_OVERRIDES_23A62FFD, + 'bobcat': _SET_WIDE_OVERRIDES_ECBD3770, + 'contour': _SET_WIDE_OVERRIDES_7D53D5DB, + 'extraterm': _SET_WIDE_OVERRIDES_766614D8, + 'foot': _SET_WIDE_OVERRIDES_98684D9B, + 'ghostty': _SET_WIDE_OVERRIDES_CF30CE25, + 'iterm2': _SET_WIDE_OVERRIDES_1C271C46, + 'kitty': _SET_WIDE_OVERRIDES_383629C7, + 'konsole': _SET_WIDE_OVERRIDES_3CBB3895, + 'mintty': _SET_WIDE_OVERRIDES_DB01D1AB, + 'mlterm': _SET_WIDE_OVERRIDES_64DD0D04, + 'pterm': _SET_WIDE_OVERRIDES_6E5EF6CC, + 'rio': _SET_WIDE_OVERRIDES_EE7A1B97, + 'st': _SET_WIDE_OVERRIDES_6E5EF6CC, + 'terminology': _SET_WIDE_OVERRIDES_BC68C805, + 'urxvt': _SET_WIDE_OVERRIDES_6E5EF6CC, + 'vte': _SET_WIDE_OVERRIDES_78B553AB, + 'warp': _SET_WIDE_OVERRIDES_64DD0D04, + 'wezterm': _SET_WIDE_OVERRIDES_6E5EF6CC, + 'xterm': _SET_WIDE_OVERRIDES_6E5EF6CC, + 'xterm.js': _SET_WIDE_OVERRIDES_A912FF1E, +} + +# For terminals: alacritty, apple_terminal, extraterm, foot, mintty, mlterm, pterm, rio, st, terminology, urxvt, vte, warp, wezterm, xterm, xterm.js +_SET_SRI_OVERRIDES_6E5EF6CC: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x1f1e6, 0x1f1ff,), # Regional Indicator Symbo..Regional Indicator Symbo + ), +} + +SRI_OVERRIDES: dict[str, dict[str, tuple[tuple[int, int], ...]]] = { + 'alacritty': _SET_SRI_OVERRIDES_6E5EF6CC, + 'apple_terminal': _SET_SRI_OVERRIDES_6E5EF6CC, + 'extraterm': _SET_SRI_OVERRIDES_6E5EF6CC, + 'foot': _SET_SRI_OVERRIDES_6E5EF6CC, + 'mintty': _SET_SRI_OVERRIDES_6E5EF6CC, + 'mlterm': _SET_SRI_OVERRIDES_6E5EF6CC, + 'pterm': _SET_SRI_OVERRIDES_6E5EF6CC, + 'rio': _SET_SRI_OVERRIDES_6E5EF6CC, + 'st': _SET_SRI_OVERRIDES_6E5EF6CC, + 'terminology': _SET_SRI_OVERRIDES_6E5EF6CC, + 'urxvt': _SET_SRI_OVERRIDES_6E5EF6CC, + 'vte': _SET_SRI_OVERRIDES_6E5EF6CC, + 'warp': _SET_SRI_OVERRIDES_6E5EF6CC, + 'wezterm': _SET_SRI_OVERRIDES_6E5EF6CC, + 'xterm': _SET_SRI_OVERRIDES_6E5EF6CC, + 'xterm.js': _SET_SRI_OVERRIDES_6E5EF6CC, +} + +# For terminals: bobcat, kitty +_SET_SFZ_OVERRIDES_73E5B60D: dict[str, tuple[tuple[int, int], ...]] = { + 'zeroer': ( + (0x1f3fb, 0x1f3ff,), # Emoji Modifier Fitzpatri..Emoji Modifier Fitzpatri + ), +} + +# For terminals: foot, mintty, rio +_SET_SFZ_OVERRIDES_8DDFF0C4: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x1f3fb, 0x1f3ff,), # Emoji Modifier Fitzpatri..Emoji Modifier Fitzpatri + ), +} + +SFZ_OVERRIDES: dict[str, dict[str, tuple[tuple[int, int], ...]]] = { + 'bobcat': _SET_SFZ_OVERRIDES_73E5B60D, + 'foot': _SET_SFZ_OVERRIDES_8DDFF0C4, + 'kitty': _SET_SFZ_OVERRIDES_73E5B60D, + 'mintty': _SET_SFZ_OVERRIDES_8DDFF0C4, + 'rio': _SET_SFZ_OVERRIDES_8DDFF0C4, +} + +# For terminals: iterm2 +_SET_VS16_OVERRIDES_82FD018F: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x00023, 0x00023,), # Number Sign + (0x0002a, 0x0002a,), # Asterisk + (0x00030, 0x00039,), # Digit Zero ..Digit Nine + ), +} + +# For terminals: alacritty, apple_terminal, mlterm, pterm, st, terminology, urxvt, vte, wezterm, xterm, xterm.js +_SET_VS16_OVERRIDES_F48531B2: dict[str, tuple[tuple[int, int], ...]] = { + 'narrower': ( + (0x00023, 0x00023,), # Number Sign + (0x0002a, 0x0002a,), # Asterisk + (0x00030, 0x00039,), # Digit Zero ..Digit Nine + (0x000a9, 0x000a9,), # Copyright Sign + (0x000ae, 0x000ae,), # Registered Sign + (0x0203c, 0x0203c,), # Double Exclamation Mark + (0x02049, 0x02049,), # Exclamation Question Mark + (0x02122, 0x02122,), # Trade Mark Sign + (0x02139, 0x02139,), # Information Source + (0x02194, 0x02199,), # Left Right Arrow ..South West Arrow + (0x021a9, 0x021aa,), # Leftwards Arrow With Hoo..Rightwards Arrow With Ho + (0x02328, 0x02328,), # Keyboard + (0x023cf, 0x023cf,), # Eject Symbol + (0x023ed, 0x023ef,), # Black Right-pointing Dou..Black Right-pointing Tri + (0x023f1, 0x023f2,), # Stopwatch ..Timer Clock + (0x023f8, 0x023fa,), # Double Vertical Bar ..Black Circle For Record + (0x024c2, 0x024c2,), # Circled Latin Capital Letter M + (0x025aa, 0x025ab,), # Black Small Square ..White Small Square + (0x025b6, 0x025b6,), # Black Right-pointing Triangle + (0x025c0, 0x025c0,), # Black Left-pointing Triangle + (0x025fb, 0x025fc,), # White Medium Square ..Black Medium Square + (0x02600, 0x02604,), # Black Sun With Rays ..Comet + (0x0260e, 0x0260e,), # Black Telephone + (0x02611, 0x02611,), # Ballot Box With Check + (0x02618, 0x02618,), # Shamrock + (0x0261d, 0x0261d,), # White Up Pointing Index + (0x02620, 0x02620,), # Skull And Crossbones + (0x02622, 0x02623,), # Radioactive Sign ..Biohazard Sign + (0x02626, 0x02626,), # Orthodox Cross + (0x0262a, 0x0262a,), # Star And Crescent + (0x0262e, 0x0262f,), # Peace Symbol ..Yin Yang + (0x02638, 0x0263a,), # Wheel Of Dharma ..White Smiling Face + (0x02640, 0x02640,), # Female Sign + (0x02642, 0x02642,), # Male Sign + (0x0265f, 0x02660,), # Black Chess Pawn ..Black Spade Suit + (0x02663, 0x02663,), # Black Club Suit + (0x02665, 0x02666,), # Black Heart Suit ..Black Diamond Suit + (0x02668, 0x02668,), # Hot Springs + (0x0267b, 0x0267b,), # Black Universal Recycling Symbol + (0x0267e, 0x0267e,), # Permanent Paper Sign + (0x02692, 0x02692,), # Hammer And Pick + (0x02694, 0x02697,), # Crossed Swords ..Alembic + (0x02699, 0x02699,), # Gear + (0x0269b, 0x0269c,), # Atom Symbol ..Fleur-de-lis + (0x026a0, 0x026a0,), # Warning Sign + (0x026a7, 0x026a7,), # Male With Stroke And Male And Female Sign + (0x026b0, 0x026b1,), # Coffin ..Funeral Urn + (0x026c8, 0x026c8,), # Thunder Cloud And Rain + (0x026cf, 0x026cf,), # Pick + (0x026d1, 0x026d1,), # Helmet With White Cross + (0x026d3, 0x026d3,), # Chains + (0x026e9, 0x026e9,), # Shinto Shrine + (0x026f0, 0x026f1,), # Mountain ..Umbrella On Ground + (0x026f4, 0x026f4,), # Ferry + (0x026f7, 0x026f9,), # Skier ..Person With Ball + (0x02702, 0x02702,), # Black Scissors + (0x02708, 0x02709,), # Airplane ..Envelope + (0x0270c, 0x0270d,), # Victory Hand ..Writing Hand + (0x0270f, 0x0270f,), # Pencil + (0x02712, 0x02712,), # Black Nib + (0x02714, 0x02714,), # Heavy Check Mark + (0x02716, 0x02716,), # Heavy Multiplication X + (0x0271d, 0x0271d,), # Latin Cross + (0x02721, 0x02721,), # Star Of David + (0x02733, 0x02734,), # Eight Spoked Asterisk ..Eight Pointed Black Star + (0x02744, 0x02744,), # Snowflake + (0x02747, 0x02747,), # Sparkle + (0x02763, 0x02764,), # Heavy Heart Exclamation ..Heavy Black Heart + (0x027a1, 0x027a1,), # Black Rightwards Arrow + (0x02934, 0x02935,), # Arrow Pointing Rightward..Arrow Pointing Rightward + (0x02b05, 0x02b07,), # Leftwards Black Arrow ..Downwards Black Arrow + (0x1f170, 0x1f171,), # Negative Squared Latin C..Negative Squared Latin C + (0x1f17e, 0x1f17f,), # Negative Squared Latin C..Negative Squared Latin C + (0x1f321, 0x1f321,), # Thermometer + (0x1f324, 0x1f32c,), # White Sun With Small Clo..Wind Blowing Face + (0x1f336, 0x1f336,), # Hot Pepper + (0x1f37d, 0x1f37d,), # Fork And Knife With Plate + (0x1f396, 0x1f397,), # Military Medal ..Reminder Ribbon + (0x1f399, 0x1f39b,), # Studio Microphone ..Control Knobs + (0x1f39e, 0x1f39f,), # Film Frames ..Admission Tickets + (0x1f3cb, 0x1f3ce,), # Weight Lifter ..Racing Car + (0x1f3d4, 0x1f3df,), # Snow Capped Mountain ..Stadium + (0x1f3f3, 0x1f3f3,), # Waving White Flag + (0x1f3f5, 0x1f3f5,), # Rosette + (0x1f3f7, 0x1f3f7,), # Label + (0x1f43f, 0x1f43f,), # Chipmunk + (0x1f441, 0x1f441,), # Eye + (0x1f4fd, 0x1f4fd,), # Film Projector + (0x1f549, 0x1f54a,), # Om Symbol ..Dove Of Peace + (0x1f56f, 0x1f570,), # Candle ..Mantelpiece Clock + (0x1f573, 0x1f579,), # Hole ..Joystick + (0x1f587, 0x1f587,), # Linked Paperclips + (0x1f58a, 0x1f58d,), # Lower Left Ballpoint Pen..Lower Left Crayon + (0x1f590, 0x1f590,), # Raised Hand With Fingers Splayed + (0x1f5a5, 0x1f5a5,), # Desktop Computer + (0x1f5a8, 0x1f5a8,), # Printer + (0x1f5b1, 0x1f5b2,), # Three Button Mouse ..Trackball + (0x1f5bc, 0x1f5bc,), # Frame With Picture + (0x1f5c2, 0x1f5c4,), # Card Index Dividers ..File Cabinet + (0x1f5d1, 0x1f5d3,), # Wastebasket ..Spiral Calendar Pad + (0x1f5dc, 0x1f5de,), # Compression ..Rolled-up Newspaper + (0x1f5e1, 0x1f5e1,), # Dagger Knife + (0x1f5e3, 0x1f5e3,), # Speaking Head In Silhouette + (0x1f5e8, 0x1f5e8,), # Left Speech Bubble + (0x1f5ef, 0x1f5ef,), # Right Anger Bubble + (0x1f5f3, 0x1f5f3,), # Ballot Box With Ballot + (0x1f5fa, 0x1f5fa,), # World Map + (0x1f6cb, 0x1f6cb,), # Couch And Lamp + (0x1f6cd, 0x1f6cf,), # Shopping Bags ..Bed + (0x1f6e0, 0x1f6e5,), # Hammer And Wrench ..Motor Boat + (0x1f6e9, 0x1f6e9,), # Small Airplane + (0x1f6f0, 0x1f6f0,), # Satellite + (0x1f6f3, 0x1f6f3,), # Passenger Ship + ), +} + +VS16_OVERRIDES: dict[str, dict[str, tuple[tuple[int, int], ...]]] = { + 'alacritty': _SET_VS16_OVERRIDES_F48531B2, + 'apple_terminal': _SET_VS16_OVERRIDES_F48531B2, + 'iterm2': _SET_VS16_OVERRIDES_82FD018F, + 'mlterm': _SET_VS16_OVERRIDES_F48531B2, + 'pterm': _SET_VS16_OVERRIDES_F48531B2, + 'st': _SET_VS16_OVERRIDES_F48531B2, + 'terminology': _SET_VS16_OVERRIDES_F48531B2, + 'urxvt': _SET_VS16_OVERRIDES_F48531B2, + 'vte': _SET_VS16_OVERRIDES_F48531B2, + 'wezterm': _SET_VS16_OVERRIDES_F48531B2, + 'xterm': _SET_VS16_OVERRIDES_F48531B2, + 'xterm.js': _SET_VS16_OVERRIDES_F48531B2, +} + +# For terminals: rio +_SET_VS15_OVERRIDES_0F19A03D: dict[str, tuple[tuple[int, int], ...]] = { + 'wider': ( + (0x023eb, 0x023ec,), # Black Up-pointing Double..Black Down-pointing Doub + (0x023f0, 0x023f0,), # Alarm Clock + (0x026ce, 0x026ce,), # Ophiuchus + (0x02705, 0x02705,), # White Heavy Check Mark + (0x0270a, 0x0270b,), # Raised Fist ..Raised Hand + (0x02728, 0x02728,), # Sparkles + (0x0274c, 0x0274c,), # Cross Mark + (0x0274e, 0x0274e,), # Negative Squared Cross Mark + (0x02754, 0x02755,), # White Question Mark Orna..White Exclamation Mark O + (0x02795, 0x02797,), # Heavy Plus Sign ..Heavy Division Sign + (0x027b0, 0x027b0,), # Curly Loop + (0x027bf, 0x027bf,), # Double Curly Loop + ), +} + +# For terminals: bobcat +_SET_VS15_OVERRIDES_72B9888B: dict[str, tuple[tuple[int, int], ...]] = { + 'wider': ( + (0x03030, 0x03030,), # Wavy Dash + (0x0303d, 0x0303d,), # Part Alternation Mark + (0x03297, 0x03297,), # Circled Ideograph Congratulation + (0x03299, 0x03299,), # Circled Ideograph Secret + (0x1f202, 0x1f202,), # Squared Katakana Sa + (0x1f237, 0x1f237,), # Squared Cjk Unified Ideograph-6708 + ), +} + +# For terminals: warp +_SET_VS15_OVERRIDES_D32653C3: dict[str, tuple[tuple[int, int], ...]] = { + 'wider': ( + (0x0231a, 0x0231b,), # Watch ..Hourglass + (0x023e9, 0x023ec,), # Black Right-pointing Dou..Black Down-pointing Doub + (0x023f0, 0x023f0,), # Alarm Clock + (0x023f3, 0x023f3,), # Hourglass With Flowing Sand + (0x025fd, 0x025fe,), # White Medium Small Squar..Black Medium Small Squar + (0x02614, 0x02615,), # Umbrella With Rain Drops..Hot Beverage + (0x02648, 0x02653,), # Aries ..Pisces + (0x0267f, 0x0267f,), # Wheelchair Symbol + (0x02693, 0x02693,), # Anchor + (0x026a1, 0x026a1,), # High Voltage Sign + (0x026aa, 0x026ab,), # Medium White Circle ..Medium Black Circle + (0x026bd, 0x026be,), # Soccer Ball ..Baseball + (0x026c4, 0x026c5,), # Snowman Without Snow ..Sun Behind Cloud + (0x026ce, 0x026ce,), # Ophiuchus + (0x026d4, 0x026d4,), # No Entry + (0x026ea, 0x026ea,), # Church + (0x026f2, 0x026f3,), # Fountain ..Flag In Hole + (0x026f5, 0x026f5,), # Sailboat + (0x026fa, 0x026fa,), # Tent + (0x026fd, 0x026fd,), # Fuel Pump + (0x02705, 0x02705,), # White Heavy Check Mark + (0x0270a, 0x0270b,), # Raised Fist ..Raised Hand + (0x02728, 0x02728,), # Sparkles + (0x0274c, 0x0274c,), # Cross Mark + (0x0274e, 0x0274e,), # Negative Squared Cross Mark + (0x02753, 0x02755,), # Black Question Mark Orna..White Exclamation Mark O + (0x02757, 0x02757,), # Heavy Exclamation Mark Symbol + (0x02795, 0x02797,), # Heavy Plus Sign ..Heavy Division Sign + (0x027b0, 0x027b0,), # Curly Loop + (0x027bf, 0x027bf,), # Double Curly Loop + (0x02b1b, 0x02b1c,), # Black Large Square ..White Large Square + (0x02b50, 0x02b50,), # White Medium Star + (0x02b55, 0x02b55,), # Heavy Large Circle + (0x1f004, 0x1f004,), # Mahjong Tile Red Dragon + (0x1f30d, 0x1f30f,), # Earth Globe Europe-afric..Earth Globe Asia-austral + (0x1f315, 0x1f315,), # Full Moon Symbol + (0x1f31c, 0x1f31c,), # Last Quarter Moon With Face + (0x1f378, 0x1f378,), # Cocktail Glass + (0x1f393, 0x1f393,), # Graduation Cap + (0x1f3a7, 0x1f3a7,), # Headphone + (0x1f3ac, 0x1f3ae,), # Clapper Board ..Video Game + (0x1f3c2, 0x1f3c2,), # Snowboarder + (0x1f3c4, 0x1f3c4,), # Surfer + (0x1f3c6, 0x1f3c6,), # Trophy + (0x1f3ca, 0x1f3ca,), # Swimmer + (0x1f3e0, 0x1f3e0,), # House Building + (0x1f3ed, 0x1f3ed,), # Factory + (0x1f408, 0x1f408,), # Cat + (0x1f415, 0x1f415,), # Dog + (0x1f41f, 0x1f41f,), # Fish + (0x1f426, 0x1f426,), # Bird + (0x1f442, 0x1f442,), # Ear + (0x1f446, 0x1f449,), # White Up Pointing Backha..White Right Pointing Bac + (0x1f44d, 0x1f44e,), # Thumbs Up Sign ..Thumbs Down Sign + (0x1f453, 0x1f453,), # Eyeglasses + (0x1f46a, 0x1f46a,), # Family + (0x1f47d, 0x1f47d,), # Extraterrestrial Alien + (0x1f4a3, 0x1f4a3,), # Bomb + (0x1f4b0, 0x1f4b0,), # Money Bag + (0x1f4b3, 0x1f4b3,), # Credit Card + (0x1f4bb, 0x1f4bb,), # Personal Computer + (0x1f4bf, 0x1f4bf,), # Optical Disc + (0x1f4cb, 0x1f4cb,), # Clipboard + (0x1f4da, 0x1f4da,), # Books + (0x1f4df, 0x1f4df,), # Pager + (0x1f4e4, 0x1f4e6,), # Outbox Tray ..Package + (0x1f4ea, 0x1f4ed,), # Closed Mailbox With Lowe..Open Mailbox With Lowere + (0x1f4f7, 0x1f4f7,), # Camera + (0x1f4f9, 0x1f4fb,), # Video Camera ..Radio + (0x1f508, 0x1f508,), # Speaker + (0x1f50d, 0x1f50d,), # Left-pointing Magnifying Glass + (0x1f512, 0x1f513,), # Lock ..Open Lock + (0x1f550, 0x1f567,), # Clock Face One Oclock ..Clock Face Twelve-thirty + (0x1f610, 0x1f610,), # Neutral Face + (0x1f687, 0x1f687,), # Metro + (0x1f68d, 0x1f68d,), # Oncoming Bus + (0x1f691, 0x1f691,), # Ambulance + (0x1f694, 0x1f694,), # Oncoming Police Car + (0x1f698, 0x1f698,), # Oncoming Automobile + (0x1f6ad, 0x1f6ad,), # No Smoking Symbol + (0x1f6b2, 0x1f6b2,), # Bicycle + (0x1f6b9, 0x1f6ba,), # Mens Symbol ..Womens Symbol + (0x1f6bc, 0x1f6bc,), # Baby Symbol + ), +} + +# For terminals: alacritty, apple_terminal, contour, extraterm, iterm2, konsole, mlterm, pterm, st, terminology, urxvt, vte, wezterm, xterm, xterm.js +_SET_VS15_OVERRIDES_EC2D40AC: dict[str, tuple[tuple[int, int], ...]] = { + 'wider': ( + (0x0231a, 0x0231b,), # Watch ..Hourglass + (0x023e9, 0x023ec,), # Black Right-pointing Dou..Black Down-pointing Doub + (0x023f0, 0x023f0,), # Alarm Clock + (0x023f3, 0x023f3,), # Hourglass With Flowing Sand + (0x025fd, 0x025fe,), # White Medium Small Squar..Black Medium Small Squar + (0x02614, 0x02615,), # Umbrella With Rain Drops..Hot Beverage + (0x02648, 0x02653,), # Aries ..Pisces + (0x0267f, 0x0267f,), # Wheelchair Symbol + (0x02693, 0x02693,), # Anchor + (0x026a1, 0x026a1,), # High Voltage Sign + (0x026aa, 0x026ab,), # Medium White Circle ..Medium Black Circle + (0x026bd, 0x026be,), # Soccer Ball ..Baseball + (0x026c4, 0x026c5,), # Snowman Without Snow ..Sun Behind Cloud + (0x026ce, 0x026ce,), # Ophiuchus + (0x026d4, 0x026d4,), # No Entry + (0x026ea, 0x026ea,), # Church + (0x026f2, 0x026f3,), # Fountain ..Flag In Hole + (0x026f5, 0x026f5,), # Sailboat + (0x026fa, 0x026fa,), # Tent + (0x026fd, 0x026fd,), # Fuel Pump + (0x02705, 0x02705,), # White Heavy Check Mark + (0x0270a, 0x0270b,), # Raised Fist ..Raised Hand + (0x02728, 0x02728,), # Sparkles + (0x0274c, 0x0274c,), # Cross Mark + (0x0274e, 0x0274e,), # Negative Squared Cross Mark + (0x02753, 0x02755,), # Black Question Mark Orna..White Exclamation Mark O + (0x02757, 0x02757,), # Heavy Exclamation Mark Symbol + (0x02795, 0x02797,), # Heavy Plus Sign ..Heavy Division Sign + (0x027b0, 0x027b0,), # Curly Loop + (0x027bf, 0x027bf,), # Double Curly Loop + (0x02b1b, 0x02b1c,), # Black Large Square ..White Large Square + (0x02b50, 0x02b50,), # White Medium Star + (0x02b55, 0x02b55,), # Heavy Large Circle + (0x03030, 0x03030,), # Wavy Dash + (0x0303d, 0x0303d,), # Part Alternation Mark + (0x03297, 0x03297,), # Circled Ideograph Congratulation + (0x03299, 0x03299,), # Circled Ideograph Secret + (0x1f004, 0x1f004,), # Mahjong Tile Red Dragon + (0x1f202, 0x1f202,), # Squared Katakana Sa + (0x1f21a, 0x1f21a,), # Squared Cjk Unified Ideograph-7121 + (0x1f22f, 0x1f22f,), # Squared Cjk Unified Ideograph-6307 + (0x1f237, 0x1f237,), # Squared Cjk Unified Ideograph-6708 + (0x1f30d, 0x1f30f,), # Earth Globe Europe-afric..Earth Globe Asia-austral + (0x1f315, 0x1f315,), # Full Moon Symbol + (0x1f31c, 0x1f31c,), # Last Quarter Moon With Face + (0x1f378, 0x1f378,), # Cocktail Glass + (0x1f393, 0x1f393,), # Graduation Cap + (0x1f3a7, 0x1f3a7,), # Headphone + (0x1f3ac, 0x1f3ae,), # Clapper Board ..Video Game + (0x1f3c2, 0x1f3c2,), # Snowboarder + (0x1f3c4, 0x1f3c4,), # Surfer + (0x1f3c6, 0x1f3c6,), # Trophy + (0x1f3ca, 0x1f3ca,), # Swimmer + (0x1f3e0, 0x1f3e0,), # House Building + (0x1f3ed, 0x1f3ed,), # Factory + (0x1f408, 0x1f408,), # Cat + (0x1f415, 0x1f415,), # Dog + (0x1f41f, 0x1f41f,), # Fish + (0x1f426, 0x1f426,), # Bird + (0x1f442, 0x1f442,), # Ear + (0x1f446, 0x1f449,), # White Up Pointing Backha..White Right Pointing Bac + (0x1f44d, 0x1f44e,), # Thumbs Up Sign ..Thumbs Down Sign + (0x1f453, 0x1f453,), # Eyeglasses + (0x1f46a, 0x1f46a,), # Family + (0x1f47d, 0x1f47d,), # Extraterrestrial Alien + (0x1f4a3, 0x1f4a3,), # Bomb + (0x1f4b0, 0x1f4b0,), # Money Bag + (0x1f4b3, 0x1f4b3,), # Credit Card + (0x1f4bb, 0x1f4bb,), # Personal Computer + (0x1f4bf, 0x1f4bf,), # Optical Disc + (0x1f4cb, 0x1f4cb,), # Clipboard + (0x1f4da, 0x1f4da,), # Books + (0x1f4df, 0x1f4df,), # Pager + (0x1f4e4, 0x1f4e6,), # Outbox Tray ..Package + (0x1f4ea, 0x1f4ed,), # Closed Mailbox With Lowe..Open Mailbox With Lowere + (0x1f4f7, 0x1f4f7,), # Camera + (0x1f4f9, 0x1f4fb,), # Video Camera ..Radio + (0x1f508, 0x1f508,), # Speaker + (0x1f50d, 0x1f50d,), # Left-pointing Magnifying Glass + (0x1f512, 0x1f513,), # Lock ..Open Lock + (0x1f550, 0x1f567,), # Clock Face One Oclock ..Clock Face Twelve-thirty + (0x1f610, 0x1f610,), # Neutral Face + (0x1f687, 0x1f687,), # Metro + (0x1f68d, 0x1f68d,), # Oncoming Bus + (0x1f691, 0x1f691,), # Ambulance + (0x1f694, 0x1f694,), # Oncoming Police Car + (0x1f698, 0x1f698,), # Oncoming Automobile + (0x1f6ad, 0x1f6ad,), # No Smoking Symbol + (0x1f6b2, 0x1f6b2,), # Bicycle + (0x1f6b9, 0x1f6ba,), # Mens Symbol ..Womens Symbol + (0x1f6bc, 0x1f6bc,), # Baby Symbol + ), +} + +VS15_OVERRIDES: dict[str, dict[str, tuple[tuple[int, int], ...]]] = { + 'alacritty': _SET_VS15_OVERRIDES_EC2D40AC, + 'apple_terminal': _SET_VS15_OVERRIDES_EC2D40AC, + 'bobcat': _SET_VS15_OVERRIDES_72B9888B, + 'contour': _SET_VS15_OVERRIDES_EC2D40AC, + 'extraterm': _SET_VS15_OVERRIDES_EC2D40AC, + 'iterm2': _SET_VS15_OVERRIDES_EC2D40AC, + 'konsole': _SET_VS15_OVERRIDES_EC2D40AC, + 'mlterm': _SET_VS15_OVERRIDES_EC2D40AC, + 'pterm': _SET_VS15_OVERRIDES_EC2D40AC, + 'rio': _SET_VS15_OVERRIDES_0F19A03D, + 'st': _SET_VS15_OVERRIDES_EC2D40AC, + 'terminology': _SET_VS15_OVERRIDES_EC2D40AC, + 'urxvt': _SET_VS15_OVERRIDES_EC2D40AC, + 'vte': _SET_VS15_OVERRIDES_EC2D40AC, + 'warp': _SET_VS15_OVERRIDES_D32653C3, + 'wezterm': _SET_VS15_OVERRIDES_EC2D40AC, + 'xterm': _SET_VS15_OVERRIDES_EC2D40AC, + 'xterm.js': _SET_VS15_OVERRIDES_EC2D40AC, +} + +# For terminals: konsole, wezterm +_SET_NARROW_OVERRIDES_3E5607A0: dict[str, tuple[tuple[int, int], ...]] = { + 'narrow_zeroer': ( + (0x000ad, 0x000ad,), # Soft Hyphen + (0x00600, 0x00605,), # Arabic Number Sign ..Arabic Number Mark Above + (0x006dd, 0x006dd,), # Arabic End Of Ayah + (0x0070f, 0x0070f,), # Syriac Abbreviation Mark + (0x00890, 0x00891,), # Arabic Pound Mark Above ..Arabic Piastre Mark Abov + (0x008e2, 0x008e2,), # Arabic Disputed End Of Ayah + (0x110bd, 0x110bd,), # Kaithi Number Sign + (0x110cd, 0x110cd,), # Kaithi Number Sign Above + ), +} + +# For terminals: iterm2 +_SET_NARROW_OVERRIDES_70997F54: dict[str, tuple[tuple[int, int], ...]] = { + 'narrow_zeroer': ( + (0x000ad, 0x000ad,), # Soft Hyphen + (0x0f870, 0x0f87f,), # (nil) + ), +} + +# For terminals: alacritty +_SET_NARROW_OVERRIDES_898E5B73: dict[str, tuple[tuple[int, int], ...]] = { + 'wider': ( + (0x017a4, 0x017a4,), # Khmer Independent Vowel Qaa + (0x017d8, 0x017d8,), # Khmer Sign Beyyal + ), + 'narrow_zeroer': ( + (0x000ad, 0x000ad,), # Soft Hyphen + (0x00605, 0x00605,), # Arabic Number Mark Above + (0x0070f, 0x0070f,), # Syriac Abbreviation Mark + (0x00890, 0x00891,), # Arabic Pound Mark Above ..Arabic Piastre Mark Abov + (0x008e2, 0x008e2,), # Arabic Disputed End Of Ayah + (0x00d4e, 0x00d4e,), # Malayalam Letter Dot Reph + (0x0a8fa, 0x0a8fa,), # Devanagari Caret + (0x0ff9e, 0x0ff9f,), # Halfwidth Katakana Voice..Halfwidth Katakana Semi- + (0x111c2, 0x111c3,), # Sharada Sign Jihvamuliya..Sharada Sign Upadhmaniya + (0x113d1, 0x113d1,), # Tulu-tigalari Repha + (0x1193f, 0x1193f,), # Dives Akuru Prefixed Nasal Sign + (0x11941, 0x11941,), # Dives Akuru Initial Ra + (0x11a84, 0x11a89,), # Soyombo Sign Jihvamuliya..Soyombo Cluster-initial + (0x11d46, 0x11d46,), # Masaram Gondi Repha + (0x11f02, 0x11f02,), # Kawi Sign Repha + ), +} + +# For terminals: foot, mintty, pterm, rio, vte +_SET_NARROW_OVERRIDES_8B501630: dict[str, tuple[tuple[int, int], ...]] = { + 'narrow_zeroer': ( + (0x00600, 0x00605,), # Arabic Number Sign ..Arabic Number Mark Above + (0x006dd, 0x006dd,), # Arabic End Of Ayah + (0x0070f, 0x0070f,), # Syriac Abbreviation Mark + (0x00890, 0x00891,), # Arabic Pound Mark Above ..Arabic Piastre Mark Abov + (0x008e2, 0x008e2,), # Arabic Disputed End Of Ayah + (0x110bd, 0x110bd,), # Kaithi Number Sign + (0x110cd, 0x110cd,), # Kaithi Number Sign Above + ), +} + +# For terminals: st, urxvt, xterm +_SET_NARROW_OVERRIDES_9BC01E8D: dict[str, tuple[tuple[int, int], ...]] = { + 'wider': ( + (0x03248, 0x0324f,), # Circled Number Ten On Bl..Circled Number Eighty On + ), +} + +# For terminals: ghostty +_SET_NARROW_OVERRIDES_AD0BF614: dict[str, tuple[tuple[int, int], ...]] = { + 'narrow_zeroer': ( + (0x16d63, 0x16d63,), # Kirat Rai Vowel Sign Aa + (0x16d67, 0x16d6a,), # Kirat Rai Vowel Sign E ..Kirat Rai Vowel Sign Au + ), +} + +# For terminals: apple_terminal +_SET_NARROW_OVERRIDES_B173F820: dict[str, tuple[tuple[int, int], ...]] = { + 'wider': ( + (0x0f880, 0x0f881,), # (nil) + (0x0f8a1, 0x0f8d6,), # (nil) + ), + 'narrow_zeroer': ( + (0x0f870, 0x0f87f,), # (nil) + (0x0f884, 0x0f899,), # (nil) + (0x0f89f, 0x0f89f,), # (nil) + ), +} + +# For terminals: bobcat +_SET_NARROW_OVERRIDES_B19CC1BB: dict[str, tuple[tuple[int, int], ...]] = { + 'narrow_zeroer': ( + (0x00890, 0x00891,), # Arabic Pound Mark Above ..Arabic Piastre Mark Abov + (0x008e2, 0x008e2,), # Arabic Disputed End Of Ayah + (0x110bd, 0x110bd,), # Kaithi Number Sign + (0x110cd, 0x110cd,), # Kaithi Number Sign Above + ), +} + +# For terminals: kitty +_SET_NARROW_OVERRIDES_DCEE894C: dict[str, tuple[tuple[int, int], ...]] = { + 'wider': ( + (0x0261d, 0x0261d,), # White Up Pointing Index + (0x026f9, 0x026f9,), # Person With Ball + (0x0270c, 0x0270d,), # Victory Hand ..Writing Hand + (0x1f3cb, 0x1f3cc,), # Weight Lifter ..Golfer + (0x1f574, 0x1f575,), # Man In Business Suit Lev..Sleuth Or Spy + (0x1f590, 0x1f590,), # Raised Hand With Fingers Splayed + ), + 'narrow_zeroer': ( + (0x000ad, 0x000ad,), # Soft Hyphen + (0x00600, 0x00605,), # Arabic Number Sign ..Arabic Number Mark Above + (0x006dd, 0x006dd,), # Arabic End Of Ayah + (0x0070f, 0x0070f,), # Syriac Abbreviation Mark + (0x00890, 0x00891,), # Arabic Pound Mark Above ..Arabic Piastre Mark Abov + (0x008e2, 0x008e2,), # Arabic Disputed End Of Ayah + (0x00e33, 0x00e33,), # Thai Character Sara Am + (0x00eb3, 0x00eb3,), # Lao Vowel Sign Am + (0x0ff9e, 0x0ff9f,), # Halfwidth Katakana Voice..Halfwidth Katakana Semi- + (0x110bd, 0x110bd,), # Kaithi Number Sign + (0x110cd, 0x110cd,), # Kaithi Number Sign Above + ), +} + +# For terminals: xterm.js +_SET_NARROW_OVERRIDES_DEEE7699: dict[str, tuple[tuple[int, int], ...]] = { + 'wider': ( + (0x1f93b, 0x1f93b,), # Modern Pentathlon + (0x1f946, 0x1f946,), # Rifle + ), + 'narrow_zeroer': ( + (0x000ad, 0x000ad,), # Soft Hyphen + (0x00600, 0x00605,), # Arabic Number Sign ..Arabic Number Mark Above + (0x006dd, 0x006dd,), # Arabic End Of Ayah + (0x0070f, 0x0070f,), # Syriac Abbreviation Mark + (0x008e2, 0x008e2,), # Arabic Disputed End Of Ayah + (0x110bd, 0x110bd,), # Kaithi Number Sign + (0x110cd, 0x110cd,), # Kaithi Number Sign Above + ), +} + +# For terminals: warp +_SET_NARROW_OVERRIDES_FDEEB1C7: dict[str, tuple[tuple[int, int], ...]] = { + 'wider': ( + (0x017a4, 0x017a4,), # Khmer Independent Vowel Qaa + (0x017d8, 0x017d8,), # Khmer Sign Beyyal + ), + 'narrow_zeroer': ( + (0x000ad, 0x000ad,), # Soft Hyphen + (0x00605, 0x00605,), # Arabic Number Mark Above + (0x0070f, 0x0070f,), # Syriac Abbreviation Mark + (0x00890, 0x00891,), # Arabic Pound Mark Above ..Arabic Piastre Mark Abov + (0x008e2, 0x008e2,), # Arabic Disputed End Of Ayah + (0x00d4e, 0x00d4e,), # Malayalam Letter Dot Reph + (0x0a8fa, 0x0a8fa,), # Devanagari Caret + (0x0ff9e, 0x0ff9f,), # Halfwidth Katakana Voice..Halfwidth Katakana Semi- + (0x111c2, 0x111c3,), # Sharada Sign Jihvamuliya..Sharada Sign Upadhmaniya + (0x1193f, 0x1193f,), # Dives Akuru Prefixed Nasal Sign + (0x11941, 0x11941,), # Dives Akuru Initial Ra + (0x11a3a, 0x11a3a,), # Zanabazar Square Cluster-initial Letter Ra + (0x11a84, 0x11a89,), # Soyombo Sign Jihvamuliya..Soyombo Cluster-initial + (0x11d46, 0x11d46,), # Masaram Gondi Repha + (0x11f02, 0x11f02,), # Kawi Sign Repha + ), +} + +NARROW_OVERRIDES: dict[str, dict[str, tuple[tuple[int, int], ...]]] = { + 'alacritty': _SET_NARROW_OVERRIDES_898E5B73, + 'apple_terminal': _SET_NARROW_OVERRIDES_B173F820, + 'bobcat': _SET_NARROW_OVERRIDES_B19CC1BB, + 'foot': _SET_NARROW_OVERRIDES_8B501630, + 'ghostty': _SET_NARROW_OVERRIDES_AD0BF614, + 'iterm2': _SET_NARROW_OVERRIDES_70997F54, + 'kitty': _SET_NARROW_OVERRIDES_DCEE894C, + 'konsole': _SET_NARROW_OVERRIDES_3E5607A0, + 'mintty': _SET_NARROW_OVERRIDES_8B501630, + 'pterm': _SET_NARROW_OVERRIDES_8B501630, + 'rio': _SET_NARROW_OVERRIDES_8B501630, + 'st': _SET_NARROW_OVERRIDES_9BC01E8D, + 'urxvt': _SET_NARROW_OVERRIDES_9BC01E8D, + 'vte': _SET_NARROW_OVERRIDES_8B501630, + 'warp': _SET_NARROW_OVERRIDES_FDEEB1C7, + 'wezterm': _SET_NARROW_OVERRIDES_3E5607A0, + 'xterm': _SET_NARROW_OVERRIDES_9BC01E8D, + 'xterm.js': _SET_NARROW_OVERRIDES_DEEE7699, +} + +__all__ = ['WIDE_OVERRIDES', 'SRI_OVERRIDES', 'SFZ_OVERRIDES', 'VS16_OVERRIDES', 'VS15_OVERRIDES', 'NARROW_OVERRIDES'] diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_term_programs.py b/.venv/lib/python3.12/site-packages/wcwidth/table_term_programs.py new file mode 100644 index 0000000000000000000000000000000000000000..b15fba227803542589a86df95a18352f41cd4ebc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_term_programs.py @@ -0,0 +1,50 @@ +""" +Canonical terminal names and TERM/TERM_PROGRAM aliases. + +This code generated by python wcwidth using ucs-detect project data. + +Terminal multiplexers (tmux, zellij, libvterm, screen) are excluded because their displayed +presentation depends on the host terminal; cursor-position reports from ucs-detect testing are not +reliable indicators of actual width. +""" +# pylint: skip-file + +KNOWN_TERMINALS = frozenset({ + 'absolutetelnet/ssh', + 'alacritty', + 'apple_terminal', + 'bobcat', + 'contour', + 'extraterm', + 'foot', + 'ghostty', + 'iterm2', + 'kitty', + 'konsole', + 'mintty', + 'mlterm', + 'pterm', + 'rio', + 'st', + 'terminology', + 'urxvt', + 'vte', + 'warp', + 'wezterm', + 'xterm', + 'xterm.js', +}) + +ALIASES = { + 'hyper': 'xterm.js', + 'iterm.app': 'iterm2', + 'putty': 'pterm', + 'rxvt': 'urxvt', + 'rxvt-unicode-256color': 'urxvt', + 'st-256color': 'st', + 'tabby': 'xterm.js', + 'vscode': 'xterm.js', + 'warpterminal': 'warp', + 'xterm-ghostty': 'ghostty', + 'xterm-kitty': 'kitty', +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_vs15.py b/.venv/lib/python3.12/site-packages/wcwidth/table_vs15.py new file mode 100644 index 0000000000000000000000000000000000000000..4d3f4ebc3f92729832703a3b18ed22cadaa4a9fb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_vs15.py @@ -0,0 +1,104 @@ +""" +Exports VS15_WIDE_TO_NARROW table keyed by supporting unicode version level. + +This code generated by python wcwidth project. +""" +# pylint: disable=duplicate-code +VS15_WIDE_TO_NARROW = { + '9.0.0': ( + # Source: 9.0.0 + # Date: 2026-01-09, 12:44:43 GMT + # + (0x0231a, 0x0231b,), # Watch ..Hourglass + (0x023e9, 0x023ec,), # Black Right-pointing Dou..Black Down-pointing Doub + (0x023f0, 0x023f0,), # Alarm Clock + (0x023f3, 0x023f3,), # Hourglass With Flowing Sand + (0x025fd, 0x025fe,), # White Medium Small Squar..Black Medium Small Squar + (0x02614, 0x02615,), # Umbrella With Rain Drops..Hot Beverage + (0x02648, 0x02653,), # Aries ..Pisces + (0x0267f, 0x0267f,), # Wheelchair Symbol + (0x02693, 0x02693,), # Anchor + (0x026a1, 0x026a1,), # High Voltage Sign + (0x026aa, 0x026ab,), # Medium White Circle ..Medium Black Circle + (0x026bd, 0x026be,), # Soccer Ball ..Baseball + (0x026c4, 0x026c5,), # Snowman Without Snow ..Sun Behind Cloud + (0x026ce, 0x026ce,), # Ophiuchus + (0x026d4, 0x026d4,), # No Entry + (0x026ea, 0x026ea,), # Church + (0x026f2, 0x026f3,), # Fountain ..Flag In Hole + (0x026f5, 0x026f5,), # Sailboat + (0x026fa, 0x026fa,), # Tent + (0x026fd, 0x026fd,), # Fuel Pump + (0x02705, 0x02705,), # White Heavy Check Mark + (0x0270a, 0x0270b,), # Raised Fist ..Raised Hand + (0x02728, 0x02728,), # Sparkles + (0x0274c, 0x0274c,), # Cross Mark + (0x0274e, 0x0274e,), # Negative Squared Cross Mark + (0x02753, 0x02755,), # Black Question Mark Orna..White Exclamation Mark O + (0x02757, 0x02757,), # Heavy Exclamation Mark Symbol + (0x02795, 0x02797,), # Heavy Plus Sign ..Heavy Division Sign + (0x027b0, 0x027b0,), # Curly Loop + (0x027bf, 0x027bf,), # Double Curly Loop + (0x02b1b, 0x02b1c,), # Black Large Square ..White Large Square + (0x02b50, 0x02b50,), # White Medium Star + (0x02b55, 0x02b55,), # Heavy Large Circle + (0x03030, 0x03030,), # Wavy Dash + (0x0303d, 0x0303d,), # Part Alternation Mark + (0x03297, 0x03297,), # Circled Ideograph Congratulation + (0x03299, 0x03299,), # Circled Ideograph Secret + (0x1f004, 0x1f004,), # Mahjong Tile Red Dragon + (0x1f202, 0x1f202,), # Squared Katakana Sa + (0x1f21a, 0x1f21a,), # Squared Cjk Unified Ideograph-7121 + (0x1f22f, 0x1f22f,), # Squared Cjk Unified Ideograph-6307 + (0x1f237, 0x1f237,), # Squared Cjk Unified Ideograph-6708 + (0x1f30d, 0x1f30f,), # Earth Globe Europe-afric..Earth Globe Asia-austral + (0x1f315, 0x1f315,), # Full Moon Symbol + (0x1f31c, 0x1f31c,), # Last Quarter Moon With Face + (0x1f378, 0x1f378,), # Cocktail Glass + (0x1f393, 0x1f393,), # Graduation Cap + (0x1f3a7, 0x1f3a7,), # Headphone + (0x1f3ac, 0x1f3ae,), # Clapper Board ..Video Game + (0x1f3c2, 0x1f3c2,), # Snowboarder + (0x1f3c4, 0x1f3c4,), # Surfer + (0x1f3c6, 0x1f3c6,), # Trophy + (0x1f3ca, 0x1f3ca,), # Swimmer + (0x1f3e0, 0x1f3e0,), # House Building + (0x1f3ed, 0x1f3ed,), # Factory + (0x1f408, 0x1f408,), # Cat + (0x1f415, 0x1f415,), # Dog + (0x1f41f, 0x1f41f,), # Fish + (0x1f426, 0x1f426,), # Bird + (0x1f442, 0x1f442,), # Ear + (0x1f446, 0x1f449,), # White Up Pointing Backha..White Right Pointing Bac + (0x1f44d, 0x1f44e,), # Thumbs Up Sign ..Thumbs Down Sign + (0x1f453, 0x1f453,), # Eyeglasses + (0x1f46a, 0x1f46a,), # Family + (0x1f47d, 0x1f47d,), # Extraterrestrial Alien + (0x1f4a3, 0x1f4a3,), # Bomb + (0x1f4b0, 0x1f4b0,), # Money Bag + (0x1f4b3, 0x1f4b3,), # Credit Card + (0x1f4bb, 0x1f4bb,), # Personal Computer + (0x1f4bf, 0x1f4bf,), # Optical Disc + (0x1f4cb, 0x1f4cb,), # Clipboard + (0x1f4da, 0x1f4da,), # Books + (0x1f4df, 0x1f4df,), # Pager + (0x1f4e4, 0x1f4e6,), # Outbox Tray ..Package + (0x1f4ea, 0x1f4ed,), # Closed Mailbox With Lowe..Open Mailbox With Lowere + (0x1f4f7, 0x1f4f7,), # Camera + (0x1f4f9, 0x1f4fb,), # Video Camera ..Radio + (0x1f508, 0x1f508,), # Speaker + (0x1f50d, 0x1f50d,), # Left-pointing Magnifying Glass + (0x1f512, 0x1f513,), # Lock ..Open Lock + (0x1f550, 0x1f567,), # Clock Face One Oclock ..Clock Face Twelve-thirty + (0x1f610, 0x1f610,), # Neutral Face + (0x1f687, 0x1f687,), # Metro + (0x1f68d, 0x1f68d,), # Oncoming Bus + (0x1f691, 0x1f691,), # Ambulance + (0x1f694, 0x1f694,), # Oncoming Police Car + (0x1f698, 0x1f698,), # Oncoming Automobile + (0x1f6ad, 0x1f6ad,), # No Smoking Symbol + (0x1f6b2, 0x1f6b2,), # Bicycle + (0x1f6b9, 0x1f6ba,), # Mens Symbol ..Womens Symbol + (0x1f6bc, 0x1f6bc,), # Baby Symbol + ), +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_vs16.py b/.venv/lib/python3.12/site-packages/wcwidth/table_vs16.py new file mode 100644 index 0000000000000000000000000000000000000000..065a4aaeed21f22b48806d5895ac95e4fe1a8197 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_vs16.py @@ -0,0 +1,126 @@ +""" +Exports VS16_NARROW_TO_WIDE table keyed by supporting unicode version level. + +This code generated by python wcwidth project. +""" +# pylint: disable=duplicate-code +VS16_NARROW_TO_WIDE = { + '9.0.0': ( + # Source: 9.0.0 + # Date: 2026-01-09, 12:44:43 GMT + # + (0x00023, 0x00023,), # Number Sign + (0x0002a, 0x0002a,), # Asterisk + (0x00030, 0x00039,), # Digit Zero ..Digit Nine + (0x000a9, 0x000a9,), # Copyright Sign + (0x000ae, 0x000ae,), # Registered Sign + (0x0203c, 0x0203c,), # Double Exclamation Mark + (0x02049, 0x02049,), # Exclamation Question Mark + (0x02122, 0x02122,), # Trade Mark Sign + (0x02139, 0x02139,), # Information Source + (0x02194, 0x02199,), # Left Right Arrow ..South West Arrow + (0x021a9, 0x021aa,), # Leftwards Arrow With Hoo..Rightwards Arrow With Ho + (0x02328, 0x02328,), # Keyboard + (0x023cf, 0x023cf,), # Eject Symbol + (0x023ed, 0x023ef,), # Black Right-pointing Dou..Black Right-pointing Tri + (0x023f1, 0x023f2,), # Stopwatch ..Timer Clock + (0x023f8, 0x023fa,), # Double Vertical Bar ..Black Circle For Record + (0x024c2, 0x024c2,), # Circled Latin Capital Letter M + (0x025aa, 0x025ab,), # Black Small Square ..White Small Square + (0x025b6, 0x025b6,), # Black Right-pointing Triangle + (0x025c0, 0x025c0,), # Black Left-pointing Triangle + (0x025fb, 0x025fc,), # White Medium Square ..Black Medium Square + (0x02600, 0x02604,), # Black Sun With Rays ..Comet + (0x0260e, 0x0260e,), # Black Telephone + (0x02611, 0x02611,), # Ballot Box With Check + (0x02618, 0x02618,), # Shamrock + (0x0261d, 0x0261d,), # White Up Pointing Index + (0x02620, 0x02620,), # Skull And Crossbones + (0x02622, 0x02623,), # Radioactive Sign ..Biohazard Sign + (0x02626, 0x02626,), # Orthodox Cross + (0x0262a, 0x0262a,), # Star And Crescent + (0x0262e, 0x0262f,), # Peace Symbol ..Yin Yang + (0x02638, 0x0263a,), # Wheel Of Dharma ..White Smiling Face + (0x02640, 0x02640,), # Female Sign + (0x02642, 0x02642,), # Male Sign + (0x0265f, 0x02660,), # Black Chess Pawn ..Black Spade Suit + (0x02663, 0x02663,), # Black Club Suit + (0x02665, 0x02666,), # Black Heart Suit ..Black Diamond Suit + (0x02668, 0x02668,), # Hot Springs + (0x0267b, 0x0267b,), # Black Universal Recycling Symbol + (0x0267e, 0x0267e,), # Permanent Paper Sign + (0x02692, 0x02692,), # Hammer And Pick + (0x02694, 0x02697,), # Crossed Swords ..Alembic + (0x02699, 0x02699,), # Gear + (0x0269b, 0x0269c,), # Atom Symbol ..Fleur-de-lis + (0x026a0, 0x026a0,), # Warning Sign + (0x026a7, 0x026a7,), # Male With Stroke And Male And Female Sign + (0x026b0, 0x026b1,), # Coffin ..Funeral Urn + (0x026c8, 0x026c8,), # Thunder Cloud And Rain + (0x026cf, 0x026cf,), # Pick + (0x026d1, 0x026d1,), # Helmet With White Cross + (0x026d3, 0x026d3,), # Chains + (0x026e9, 0x026e9,), # Shinto Shrine + (0x026f0, 0x026f1,), # Mountain ..Umbrella On Ground + (0x026f4, 0x026f4,), # Ferry + (0x026f7, 0x026f9,), # Skier ..Person With Ball + (0x02702, 0x02702,), # Black Scissors + (0x02708, 0x02709,), # Airplane ..Envelope + (0x0270c, 0x0270d,), # Victory Hand ..Writing Hand + (0x0270f, 0x0270f,), # Pencil + (0x02712, 0x02712,), # Black Nib + (0x02714, 0x02714,), # Heavy Check Mark + (0x02716, 0x02716,), # Heavy Multiplication X + (0x0271d, 0x0271d,), # Latin Cross + (0x02721, 0x02721,), # Star Of David + (0x02733, 0x02734,), # Eight Spoked Asterisk ..Eight Pointed Black Star + (0x02744, 0x02744,), # Snowflake + (0x02747, 0x02747,), # Sparkle + (0x02763, 0x02764,), # Heavy Heart Exclamation ..Heavy Black Heart + (0x027a1, 0x027a1,), # Black Rightwards Arrow + (0x02934, 0x02935,), # Arrow Pointing Rightward..Arrow Pointing Rightward + (0x02b05, 0x02b07,), # Leftwards Black Arrow ..Downwards Black Arrow + (0x1f170, 0x1f171,), # Negative Squared Latin C..Negative Squared Latin C + (0x1f17e, 0x1f17f,), # Negative Squared Latin C..Negative Squared Latin C + (0x1f321, 0x1f321,), # Thermometer + (0x1f324, 0x1f32c,), # White Sun With Small Clo..Wind Blowing Face + (0x1f336, 0x1f336,), # Hot Pepper + (0x1f37d, 0x1f37d,), # Fork And Knife With Plate + (0x1f396, 0x1f397,), # Military Medal ..Reminder Ribbon + (0x1f399, 0x1f39b,), # Studio Microphone ..Control Knobs + (0x1f39e, 0x1f39f,), # Film Frames ..Admission Tickets + (0x1f3cb, 0x1f3ce,), # Weight Lifter ..Racing Car + (0x1f3d4, 0x1f3df,), # Snow Capped Mountain ..Stadium + (0x1f3f3, 0x1f3f3,), # Waving White Flag + (0x1f3f5, 0x1f3f5,), # Rosette + (0x1f3f7, 0x1f3f7,), # Label + (0x1f43f, 0x1f43f,), # Chipmunk + (0x1f441, 0x1f441,), # Eye + (0x1f4fd, 0x1f4fd,), # Film Projector + (0x1f549, 0x1f54a,), # Om Symbol ..Dove Of Peace + (0x1f56f, 0x1f570,), # Candle ..Mantelpiece Clock + (0x1f573, 0x1f579,), # Hole ..Joystick + (0x1f587, 0x1f587,), # Linked Paperclips + (0x1f58a, 0x1f58d,), # Lower Left Ballpoint Pen..Lower Left Crayon + (0x1f590, 0x1f590,), # Raised Hand With Fingers Splayed + (0x1f5a5, 0x1f5a5,), # Desktop Computer + (0x1f5a8, 0x1f5a8,), # Printer + (0x1f5b1, 0x1f5b2,), # Three Button Mouse ..Trackball + (0x1f5bc, 0x1f5bc,), # Frame With Picture + (0x1f5c2, 0x1f5c4,), # Card Index Dividers ..File Cabinet + (0x1f5d1, 0x1f5d3,), # Wastebasket ..Spiral Calendar Pad + (0x1f5dc, 0x1f5de,), # Compression ..Rolled-up Newspaper + (0x1f5e1, 0x1f5e1,), # Dagger Knife + (0x1f5e3, 0x1f5e3,), # Speaking Head In Silhouette + (0x1f5e8, 0x1f5e8,), # Left Speech Bubble + (0x1f5ef, 0x1f5ef,), # Right Anger Bubble + (0x1f5f3, 0x1f5f3,), # Ballot Box With Ballot + (0x1f5fa, 0x1f5fa,), # World Map + (0x1f6cb, 0x1f6cb,), # Couch And Lamp + (0x1f6cd, 0x1f6cf,), # Shopping Bags ..Bed + (0x1f6e0, 0x1f6e5,), # Hammer And Wrench ..Motor Boat + (0x1f6e9, 0x1f6e9,), # Small Airplane + (0x1f6f0, 0x1f6f0,), # Satellite + (0x1f6f3, 0x1f6f3,), # Passenger Ship + ), +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_wide.py b/.venv/lib/python3.12/site-packages/wcwidth/table_wide.py new file mode 100644 index 0000000000000000000000000000000000000000..af9f86f1910b629aa75d0f5c111c6e36f0b1435e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_wide.py @@ -0,0 +1,141 @@ +""" +Exports WIDE_EASTASIAN table keyed by supporting unicode version level. + +This code generated by python wcwidth project. +""" +# pylint: disable=duplicate-code +WIDE_EASTASIAN = { + '18.0.0': ( + # Source: EastAsianWidth-18.0.0.txt + # Date: 2026-06-29, 15:25:05 GMT + # + (0x01100, 0x0115f,), # Hangul Choseong Kiyeok ..Hangul Choseong Filler + (0x0231a, 0x0231b,), # Watch ..Hourglass + (0x02329, 0x0232a,), # Left-pointing Angle Brac..Right-pointing Angle Bra + (0x023e9, 0x023ec,), # Black Right-pointing Dou..Black Down-pointing Doub + (0x023f0, 0x023f0,), # Alarm Clock + (0x023f3, 0x023f3,), # Hourglass With Flowing Sand + (0x025fd, 0x025fe,), # White Medium Small Squar..Black Medium Small Squar + (0x02614, 0x02615,), # Umbrella With Rain Drops..Hot Beverage + (0x02630, 0x02637,), # Trigram For Heaven ..Trigram For Earth + (0x02648, 0x02653,), # Aries ..Pisces + (0x0267f, 0x0267f,), # Wheelchair Symbol + (0x0268a, 0x0268f,), # Monogram For Yang ..Digram For Greater Yin + (0x02693, 0x02693,), # Anchor + (0x026a1, 0x026a1,), # High Voltage Sign + (0x026aa, 0x026ab,), # Medium White Circle ..Medium Black Circle + (0x026bd, 0x026be,), # Soccer Ball ..Baseball + (0x026c4, 0x026c5,), # Snowman Without Snow ..Sun Behind Cloud + (0x026ce, 0x026ce,), # Ophiuchus + (0x026d4, 0x026d4,), # No Entry + (0x026ea, 0x026ea,), # Church + (0x026f2, 0x026f3,), # Fountain ..Flag In Hole + (0x026f5, 0x026f5,), # Sailboat + (0x026fa, 0x026fa,), # Tent + (0x026fd, 0x026fd,), # Fuel Pump + (0x02705, 0x02705,), # White Heavy Check Mark + (0x0270a, 0x0270b,), # Raised Fist ..Raised Hand + (0x02728, 0x02728,), # Sparkles + (0x0274c, 0x0274c,), # Cross Mark + (0x0274e, 0x0274e,), # Negative Squared Cross Mark + (0x02753, 0x02755,), # Black Question Mark Orna..White Exclamation Mark O + (0x02757, 0x02757,), # Heavy Exclamation Mark Symbol + (0x02795, 0x02797,), # Heavy Plus Sign ..Heavy Division Sign + (0x027b0, 0x027b0,), # Curly Loop + (0x027bf, 0x027bf,), # Double Curly Loop + (0x02b1b, 0x02b1c,), # Black Large Square ..White Large Square + (0x02b50, 0x02b50,), # White Medium Star + (0x02b55, 0x02b55,), # Heavy Large Circle + (0x02e80, 0x02e99,), # Cjk Radical Repeat ..Cjk Radical Rap + (0x02e9b, 0x02ef3,), # Cjk Radical Choke ..Cjk Radical C-simplified + (0x02f00, 0x02fd5,), # Kangxi Radical One ..Kangxi Radical Flute + (0x02ff0, 0x03029,), # Ideographic Description ..Hangzhou Numeral Nine + (0x03030, 0x0303e,), # Wavy Dash ..Ideographic Variation In + (0x03041, 0x03096,), # Hiragana Letter Small A ..Hiragana Letter Small Ke + (0x0309b, 0x030ff,), # Katakana-hiragana Voiced..Katakana Digraph Koto + (0x03105, 0x0312f,), # Bopomofo Letter B ..Bopomofo Letter Nn + (0x03131, 0x03163,), # Hangul Letter Kiyeok ..Hangul Letter I + (0x03165, 0x0318e,), # Hangul Letter Ssangnieun..Hangul Letter Araeae + (0x03190, 0x031e5,), # Ideographic Annotation L..Cjk Stroke Szp + (0x031ef, 0x0321e,), # Ideographic Description ..Parenthesized Korean Cha + (0x03220, 0x03247,), # Parenthesized Ideograph ..Circled Ideograph Koto + (0x03250, 0x0a48c,), # Partnership Sign ..Yi Syllable Yyr + (0x0a490, 0x0a4c6,), # Yi Radical Qot ..Yi Radical Ke + (0x0a960, 0x0a97c,), # Hangul Choseong Tikeut-m..Hangul Choseong Ssangyeo + (0x0ac00, 0x0d7a3,), # Hangul Syllable Ga ..Hangul Syllable Hih + (0x0f900, 0x0faff,), # Cjk Compatibility Ideogr..(nil) + (0x0fe10, 0x0fe19,), # Presentation Form For Ve..Presentation Form For Ve + (0x0fe30, 0x0fe52,), # Presentation Form For Ve..Small Full Stop + (0x0fe54, 0x0fe66,), # Small Semicolon ..Small Equals Sign + (0x0fe68, 0x0fe6b,), # Small Reverse Solidus ..Small Commercial At + (0x0ff01, 0x0ff60,), # Fullwidth Exclamation Ma..Fullwidth Right White Pa + (0x0ffe0, 0x0ffe6,), # Fullwidth Cent Sign ..Fullwidth Won Sign + (0x16fe0, 0x16fe3,), # Tangut Iteration Mark ..Old Chinese Iteration Ma + (0x16ff2, 0x16ff6,), # Chinese Small Simplified..Yangqin Sign Slow Two Be + (0x17000, 0x18cda,), # Tangut Ideograph-17000 ..Khitan Small Script Char + (0x18cff, 0x18d20,), # Khitan Small Script Char..Tangut Ideograph-18d20 + (0x18d80, 0x18df2,), # Tangut Component-769 ..Tangut Component-883 + (0x18e00, 0x19191,), # Jurchen Character-18e00 ..Jurchen Character-19191 + (0x191a0, 0x191d2,), # Jurchen Radical-01 ..Jurchen Radical-51 + (0x1aff0, 0x1aff3,), # Katakana Letter Minnan T..Katakana Letter Minnan T + (0x1aff5, 0x1affb,), # Katakana Letter Minnan T..Katakana Letter Minnan N + (0x1affd, 0x1affe,), # Katakana Letter Minnan N..Katakana Letter Minnan N + (0x1b000, 0x1b128,), # Katakana Letter Archaic ..Katakana Letter Alternat + (0x1b132, 0x1b132,), # Hiragana Letter Small Ko + (0x1b150, 0x1b152,), # Hiragana Letter Small Wi..Hiragana Letter Small Wo + (0x1b155, 0x1b155,), # Katakana Letter Small Ko + (0x1b164, 0x1b168,), # Katakana Letter Small Wi..Katakana Letter Small Ar + (0x1b170, 0x1b2fb,), # Nushu Character-1b170 ..Nushu Character-1b2fb + (0x1d300, 0x1d356,), # Monogram For Earth ..Tetragram For Fostering + (0x1d360, 0x1d376,), # Counting Rod Unit Digit ..Ideographic Tally Mark F + (0x1f004, 0x1f004,), # Mahjong Tile Red Dragon + (0x1f0cf, 0x1f0cf,), # Playing Card Black Joker + (0x1f18e, 0x1f18e,), # Negative Squared Ab + (0x1f191, 0x1f19a,), # Squared Cl ..Squared Vs + (0x1f1ae, 0x1f1ae,), # Tomobiki Symbol + (0x1f1e6, 0x1f202,), # Regional Indicator Symbo..Squared Katakana Sa + (0x1f210, 0x1f23b,), # Squared Cjk Unified Ideo..Squared Cjk Unified Ideo + (0x1f240, 0x1f248,), # Tortoise Shell Bracketed..Tortoise Shell Bracketed + (0x1f250, 0x1f251,), # Circled Ideograph Advant..Circled Ideograph Accept + (0x1f260, 0x1f265,), # Rounded Symbol For Fu ..Rounded Symbol For Cai + (0x1f300, 0x1f320,), # Cyclone ..Shooting Star + (0x1f32d, 0x1f335,), # Hot Dog ..Cactus + (0x1f337, 0x1f37c,), # Tulip ..Baby Bottle + (0x1f37e, 0x1f393,), # Bottle With Popping Cork..Graduation Cap + (0x1f3a0, 0x1f3ca,), # Carousel Horse ..Swimmer + (0x1f3cf, 0x1f3d3,), # Cricket Bat And Ball ..Table Tennis Paddle And + (0x1f3e0, 0x1f3f0,), # House Building ..European Castle + (0x1f3f4, 0x1f3f4,), # Waving Black Flag + (0x1f3f8, 0x1f43e,), # Badminton Racquet And Sh..Paw Prints + (0x1f440, 0x1f440,), # Eyes + (0x1f442, 0x1f4fc,), # Ear ..Videocassette + (0x1f4ff, 0x1f53d,), # Prayer Beads ..Down-pointing Small Red + (0x1f54b, 0x1f54e,), # Kaaba ..Menorah With Nine Branch + (0x1f550, 0x1f567,), # Clock Face One Oclock ..Clock Face Twelve-thirty + (0x1f57a, 0x1f57a,), # Man Dancing + (0x1f595, 0x1f596,), # Reversed Hand With Middl..Raised Hand With Part Be + (0x1f5a4, 0x1f5a4,), # Black Heart + (0x1f5fb, 0x1f64f,), # Mount Fuji ..Person With Folded Hands + (0x1f680, 0x1f6c5,), # Rocket ..Left Luggage + (0x1f6cc, 0x1f6cc,), # Sleeping Accommodation + (0x1f6d0, 0x1f6d2,), # Place Of Worship ..Shopping Trolley + (0x1f6d5, 0x1f6d9,), # Hindu Temple ..Lighthouse + (0x1f6dc, 0x1f6df,), # Wireless ..Ring Buoy + (0x1f6eb, 0x1f6ec,), # Airplane Departure ..Airplane Arriving + (0x1f6f4, 0x1f6fc,), # Scooter ..Roller Skate + (0x1f7da, 0x1f7da,), # Black Circle With White Vertical Bar + (0x1f7e0, 0x1f7eb,), # Large Orange Circle ..Large Brown Square + (0x1f7f0, 0x1f7f0,), # Heavy Equals Sign + (0x1f90c, 0x1f93a,), # Pinched Fingers ..Fencer + (0x1f93c, 0x1f945,), # Wrestlers ..Goal Net + (0x1f947, 0x1f9ff,), # First Place Medal ..Nazar Amulet + (0x1fa70, 0x1fa7c,), # Ballet Shoes ..Crutch + (0x1fa80, 0x1fac6,), # Yo-yo ..Fingerprint + (0x1fac8, 0x1fac8,), # Hairy Creature + (0x1facc, 0x1fadd,), # Monarch Butterfly ..Pickle + (0x1fadf, 0x1faeb,), # Splatter ..Cracking Face + (0x1faef, 0x1fafa,), # Fight Cloud ..Rightwards Thumb Sign + (0x20000, 0x2fffd,), # Cjk Unified Ideograph-20..(nil) + (0x30000, 0x3fffd,), # Cjk Unified Ideograph-30..(nil) + ), +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/table_zero.py b/.venv/lib/python3.12/site-packages/wcwidth/table_zero.py new file mode 100644 index 0000000000000000000000000000000000000000..be763e6fe1e3bf4fce2f74d87677af8246909143 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/table_zero.py @@ -0,0 +1,356 @@ +""" +Exports ZERO_WIDTH table keyed by supporting unicode version level. + +This code generated by python wcwidth project. +""" +# pylint: disable=duplicate-code +ZERO_WIDTH = { + '18.0.0': ( + # Source: DerivedGeneralCategory-18.0.0.txt + # Date: 2026-06-29, 15:25:02 GMT + # + (0x00000, 0x00000,), # Null + (0x00300, 0x0036f,), # Combining Grave Accent ..Combining Latin Small Le + (0x00483, 0x00489,), # Combining Cyrillic Titlo..Combining Cyrillic Milli + (0x00591, 0x005bd,), # Hebrew Accent Etnahta ..Hebrew Point Meteg + (0x005bf, 0x005bf,), # Hebrew Point Rafe + (0x005c1, 0x005c2,), # Hebrew Point Shin Dot ..Hebrew Point Sin Dot + (0x005c4, 0x005c5,), # Hebrew Mark Upper Dot ..Hebrew Mark Lower Dot + (0x005c7, 0x005c9,), # Hebrew Point Qamats Qata..Hebrew Point Dagesh Haza + (0x00610, 0x0061a,), # Arabic Sign Sallallahou ..Arabic Small Kasra + (0x0061c, 0x0061c,), # Arabic Letter Mark + (0x0064b, 0x0065f,), # Arabic Fathatan ..Arabic Wavy Hamza Below + (0x00670, 0x00670,), # Arabic Letter Superscript Alef + (0x006d6, 0x006dc,), # Arabic Small High Ligatu..Arabic Small High Seen + (0x006df, 0x006e4,), # Arabic Small High Rounde..Arabic Small High Madda + (0x006e7, 0x006e8,), # Arabic Small High Yeh ..Arabic Small High Noon + (0x006ea, 0x006ed,), # Arabic Empty Centre Low ..Arabic Small Low Meem + (0x00711, 0x00711,), # Syriac Letter Superscript Alaph + (0x00730, 0x0074a,), # Syriac Pthaha Above ..Syriac Barrekh + (0x007a6, 0x007b0,), # Thaana Abafili ..Thaana Sukun + (0x007eb, 0x007f3,), # Nko Combining Short High..Nko Combining Double Dot + (0x007fd, 0x007fd,), # Nko Dantayalan + (0x00816, 0x00819,), # Samaritan Mark In ..Samaritan Mark Dagesh + (0x0081b, 0x00823,), # Samaritan Mark Epentheti..Samaritan Vowel Sign A + (0x00825, 0x00827,), # Samaritan Vowel Sign Sho..Samaritan Vowel Sign U + (0x00829, 0x0082d,), # Samaritan Vowel Sign Lon..Samaritan Mark Nequdaa + (0x00859, 0x0085b,), # Mandaic Affrication Mark..Mandaic Gemination Mark + (0x00897, 0x0089f,), # Arabic Pepet ..Arabic Half Madda Over M + (0x008ca, 0x008e1,), # Arabic Small High Farsi ..Arabic Small High Sign S + (0x008e3, 0x00903,), # Arabic Turned Damma Belo..Devanagari Sign Visarga + (0x0093a, 0x0093c,), # Devanagari Vowel Sign Oe..Devanagari Sign Nukta + (0x0093e, 0x0094f,), # Devanagari Vowel Sign Aa..Devanagari Vowel Sign Aw + (0x00951, 0x00957,), # Devanagari Stress Sign U..Devanagari Vowel Sign Uu + (0x00962, 0x00963,), # Devanagari Vowel Sign Vo..Devanagari Vowel Sign Vo + (0x00981, 0x00983,), # Bengali Sign Candrabindu..Bengali Sign Visarga + (0x009bc, 0x009bc,), # Bengali Sign Nukta + (0x009be, 0x009c4,), # Bengali Vowel Sign Aa ..Bengali Vowel Sign Vocal + (0x009c7, 0x009c8,), # Bengali Vowel Sign E ..Bengali Vowel Sign Ai + (0x009cb, 0x009cd,), # Bengali Vowel Sign O ..Bengali Sign Virama + (0x009d7, 0x009d7,), # Bengali Au Length Mark + (0x009e2, 0x009e3,), # Bengali Vowel Sign Vocal..Bengali Vowel Sign Vocal + (0x009fe, 0x009fe,), # Bengali Sandhi Mark + (0x00a01, 0x00a03,), # Gurmukhi Sign Adak Bindi..Gurmukhi Sign Visarga + (0x00a3c, 0x00a3c,), # Gurmukhi Sign Nukta + (0x00a3e, 0x00a42,), # Gurmukhi Vowel Sign Aa ..Gurmukhi Vowel Sign Uu + (0x00a47, 0x00a48,), # Gurmukhi Vowel Sign Ee ..Gurmukhi Vowel Sign Ai + (0x00a4b, 0x00a4d,), # Gurmukhi Vowel Sign Oo ..Gurmukhi Sign Virama + (0x00a51, 0x00a51,), # Gurmukhi Sign Udaat + (0x00a70, 0x00a71,), # Gurmukhi Tippi ..Gurmukhi Addak + (0x00a75, 0x00a75,), # Gurmukhi Sign Yakash + (0x00a81, 0x00a83,), # Gujarati Sign Candrabind..Gujarati Sign Visarga + (0x00abc, 0x00abc,), # Gujarati Sign Nukta + (0x00abe, 0x00ac5,), # Gujarati Vowel Sign Aa ..Gujarati Vowel Sign Cand + (0x00ac7, 0x00ac9,), # Gujarati Vowel Sign E ..Gujarati Vowel Sign Cand + (0x00acb, 0x00acd,), # Gujarati Vowel Sign O ..Gujarati Sign Virama + (0x00ae2, 0x00ae3,), # Gujarati Vowel Sign Voca..Gujarati Vowel Sign Voca + (0x00afa, 0x00aff,), # Gujarati Sign Sukun ..Gujarati Sign Two-circle + (0x00b01, 0x00b03,), # Oriya Sign Candrabindu ..Oriya Sign Visarga + (0x00b3c, 0x00b3c,), # Oriya Sign Nukta + (0x00b3e, 0x00b44,), # Oriya Vowel Sign Aa ..Oriya Vowel Sign Vocalic + (0x00b47, 0x00b48,), # Oriya Vowel Sign E ..Oriya Vowel Sign Ai + (0x00b4b, 0x00b4d,), # Oriya Vowel Sign O ..Oriya Sign Virama + (0x00b53, 0x00b57,), # Oriya Sign Dot Above ..Oriya Au Length Mark + (0x00b62, 0x00b63,), # Oriya Vowel Sign Vocalic..Oriya Vowel Sign Vocalic + (0x00b82, 0x00b82,), # Tamil Sign Anusvara + (0x00bbe, 0x00bc2,), # Tamil Vowel Sign Aa ..Tamil Vowel Sign Uu + (0x00bc6, 0x00bc8,), # Tamil Vowel Sign E ..Tamil Vowel Sign Ai + (0x00bca, 0x00bcd,), # Tamil Vowel Sign O ..Tamil Sign Virama + (0x00bd7, 0x00bd7,), # Tamil Au Length Mark + (0x00c00, 0x00c04,), # Telugu Sign Combining Ca..Telugu Sign Combining An + (0x00c3c, 0x00c3c,), # Telugu Sign Nukta + (0x00c3e, 0x00c44,), # Telugu Vowel Sign Aa ..Telugu Vowel Sign Vocali + (0x00c46, 0x00c48,), # Telugu Vowel Sign E ..Telugu Vowel Sign Ai + (0x00c4a, 0x00c4d,), # Telugu Vowel Sign O ..Telugu Sign Virama + (0x00c55, 0x00c56,), # Telugu Length Mark ..Telugu Ai Length Mark + (0x00c62, 0x00c63,), # Telugu Vowel Sign Vocali..Telugu Vowel Sign Vocali + (0x00c81, 0x00c83,), # Kannada Sign Candrabindu..Kannada Sign Visarga + (0x00cbc, 0x00cbc,), # Kannada Sign Nukta + (0x00cbe, 0x00cc4,), # Kannada Vowel Sign Aa ..Kannada Vowel Sign Vocal + (0x00cc6, 0x00cc8,), # Kannada Vowel Sign E ..Kannada Vowel Sign Ai + (0x00cca, 0x00ccd,), # Kannada Vowel Sign O ..Kannada Sign Virama + (0x00cd5, 0x00cd6,), # Kannada Length Mark ..Kannada Ai Length Mark + (0x00ce2, 0x00ce3,), # Kannada Vowel Sign Vocal..Kannada Vowel Sign Vocal + (0x00cf3, 0x00cf3,), # Kannada Sign Combining Anusvara Above Right + (0x00d00, 0x00d03,), # Malayalam Sign Combining..Malayalam Sign Visarga + (0x00d3b, 0x00d3c,), # Malayalam Sign Vertical ..Malayalam Sign Circular + (0x00d3e, 0x00d44,), # Malayalam Vowel Sign Aa ..Malayalam Vowel Sign Voc + (0x00d46, 0x00d48,), # Malayalam Vowel Sign E ..Malayalam Vowel Sign Ai + (0x00d4a, 0x00d4d,), # Malayalam Vowel Sign O ..Malayalam Sign Virama + (0x00d57, 0x00d57,), # Malayalam Au Length Mark + (0x00d62, 0x00d63,), # Malayalam Vowel Sign Voc..Malayalam Vowel Sign Voc + (0x00d81, 0x00d83,), # Sinhala Sign Candrabindu..Sinhala Sign Visargaya + (0x00dca, 0x00dca,), # Sinhala Sign Al-lakuna + (0x00dcf, 0x00dd4,), # Sinhala Vowel Sign Aela-..Sinhala Vowel Sign Ketti + (0x00dd6, 0x00dd6,), # Sinhala Vowel Sign Diga Paa-pilla + (0x00dd8, 0x00ddf,), # Sinhala Vowel Sign Gaett..Sinhala Vowel Sign Gayan + (0x00df2, 0x00df3,), # Sinhala Vowel Sign Diga ..Sinhala Vowel Sign Diga + (0x00e31, 0x00e31,), # Thai Character Mai Han-akat + (0x00e34, 0x00e3a,), # Thai Character Sara I ..Thai Character Phinthu + (0x00e47, 0x00e4e,), # Thai Character Maitaikhu..Thai Character Yamakkan + (0x00eb1, 0x00eb1,), # Lao Vowel Sign Mai Kan + (0x00eb4, 0x00ebc,), # Lao Vowel Sign I ..Lao Semivowel Sign Lo + (0x00ec8, 0x00ece,), # Lao Tone Mai Ek ..Lao Yamakkan + (0x00f18, 0x00f19,), # Tibetan Astrological Sig..Tibetan Astrological Sig + (0x00f35, 0x00f35,), # Tibetan Mark Ngas Bzung Nyi Zla + (0x00f37, 0x00f37,), # Tibetan Mark Ngas Bzung Sgor Rtags + (0x00f39, 0x00f39,), # Tibetan Mark Tsa -phru + (0x00f3e, 0x00f3f,), # Tibetan Sign Yar Tshes ..Tibetan Sign Mar Tshes + (0x00f71, 0x00f84,), # Tibetan Vowel Sign Aa ..Tibetan Mark Halanta + (0x00f86, 0x00f87,), # Tibetan Sign Lci Rtags ..Tibetan Sign Yang Rtags + (0x00f8d, 0x00f97,), # Tibetan Subjoined Sign L..Tibetan Subjoined Letter + (0x00f99, 0x00fbc,), # Tibetan Subjoined Letter..Tibetan Subjoined Letter + (0x00fc6, 0x00fc6,), # Tibetan Symbol Padma Gdan + (0x0102b, 0x0103e,), # Myanmar Vowel Sign Tall ..Myanmar Consonant Sign M + (0x01056, 0x01059,), # Myanmar Vowel Sign Vocal..Myanmar Vowel Sign Vocal + (0x0105e, 0x01060,), # Myanmar Consonant Sign M..Myanmar Consonant Sign M + (0x01062, 0x01064,), # Myanmar Vowel Sign Sgaw ..Myanmar Tone Mark Sgaw K + (0x01067, 0x0106d,), # Myanmar Vowel Sign Weste..Myanmar Sign Western Pwo + (0x01071, 0x01074,), # Myanmar Vowel Sign Geba ..Myanmar Vowel Sign Kayah + (0x01082, 0x0108d,), # Myanmar Consonant Sign S..Myanmar Sign Shan Counci + (0x0108f, 0x0108f,), # Myanmar Sign Rumai Palaung Tone-5 + (0x0109a, 0x0109d,), # Myanmar Sign Khamti Tone..Myanmar Vowel Sign Aiton + (0x01160, 0x011ff,), # Hangul Jungseong Filler ..Hangul Jongseong Ssangni + (0x0135d, 0x0135f,), # Ethiopic Combining Gemin..Ethiopic Combining Gemin + (0x01712, 0x01715,), # Tagalog Vowel Sign I ..Tagalog Sign Pamudpod + (0x01732, 0x01734,), # Hanunoo Vowel Sign I ..Hanunoo Sign Pamudpod + (0x01752, 0x01753,), # Buhid Vowel Sign I ..Buhid Vowel Sign U + (0x01772, 0x01773,), # Tagbanwa Vowel Sign I ..Tagbanwa Vowel Sign U + (0x017b4, 0x017d3,), # Khmer Vowel Inherent Aq ..Khmer Sign Bathamasat + (0x017dd, 0x017dd,), # Khmer Sign Atthacan + (0x0180b, 0x0180f,), # Mongolian Free Variation..Mongolian Free Variation + (0x01885, 0x01886,), # Mongolian Letter Ali Gal..Mongolian Letter Ali Gal + (0x018a9, 0x018a9,), # Mongolian Letter Ali Gali Dagalga + (0x01920, 0x0192b,), # Limbu Vowel Sign A ..Limbu Subjoined Letter W + (0x01930, 0x0193b,), # Limbu Small Letter Ka ..Limbu Sign Sa-i + (0x01a17, 0x01a1b,), # Buginese Vowel Sign I ..Buginese Vowel Sign Ae + (0x01a55, 0x01a5e,), # Tai Tham Consonant Sign ..Tai Tham Consonant Sign + (0x01a60, 0x01a7c,), # Tai Tham Sign Sakot ..Tai Tham Sign Khuen-lue + (0x01a7f, 0x01a7f,), # Tai Tham Combining Cryptogrammic Dot + (0x01ab0, 0x01af0,), # Combining Doubled Circum..Combining Double Comma A + (0x01b00, 0x01b04,), # Balinese Sign Ulu Ricem ..Balinese Sign Bisah + (0x01b34, 0x01b44,), # Balinese Sign Rerekan ..Balinese Adeg Adeg + (0x01b6b, 0x01b73,), # Balinese Musical Symbol ..Balinese Musical Symbol + (0x01b80, 0x01b82,), # Sundanese Sign Panyecek ..Sundanese Sign Pangwisad + (0x01ba1, 0x01bad,), # Sundanese Consonant Sign..Sundanese Consonant Sign + (0x01be6, 0x01bf3,), # Batak Sign Tompi ..Batak Panongonan + (0x01c24, 0x01c37,), # Lepcha Subjoined Letter ..Lepcha Sign Nukta + (0x01cd0, 0x01cd2,), # Vedic Tone Karshana ..Vedic Tone Prenkha + (0x01cd4, 0x01ce8,), # Vedic Sign Yajurvedic Mi..Vedic Sign Visarga Anuda + (0x01ced, 0x01ced,), # Vedic Sign Tiryak + (0x01cf4, 0x01cf4,), # Vedic Tone Candra Above + (0x01cf7, 0x01cf9,), # Vedic Sign Atikrama ..Vedic Tone Double Ring A + (0x01dc0, 0x01dff,), # Combining Dotted Grave A..Combining Right Arrowhea + (0x0200b, 0x0200f,), # Zero Width Space ..Right-to-left Mark + (0x02028, 0x0202e,), # Line Separator ..Right-to-left Override + (0x02060, 0x0206f,), # Word Joiner ..Nominal Digit Shapes + (0x020d0, 0x020f0,), # Combining Left Harpoon A..Combining Asterisk Above + (0x02cef, 0x02cf1,), # Coptic Combining Ni Abov..Coptic Combining Spiritu + (0x02d7f, 0x02d7f,), # Tifinagh Consonant Joiner + (0x02de0, 0x02dff,), # Combining Cyrillic Lette..Combining Cyrillic Lette + (0x0302a, 0x0302f,), # Ideographic Level Tone M..Hangul Double Dot Tone M + (0x03099, 0x0309a,), # Combining Katakana-hirag..Combining Katakana-hirag + (0x03164, 0x03164,), # Hangul Filler + (0x0a66f, 0x0a672,), # Combining Cyrillic Vzmet..Combining Cyrillic Thous + (0x0a674, 0x0a67d,), # Combining Cyrillic Lette..Combining Cyrillic Payer + (0x0a69e, 0x0a69f,), # Combining Cyrillic Lette..Combining Cyrillic Lette + (0x0a6f0, 0x0a6f1,), # Bamum Combining Mark Koq..Bamum Combining Mark Tuk + (0x0a802, 0x0a802,), # Syloti Nagri Sign Dvisvara + (0x0a806, 0x0a806,), # Syloti Nagri Sign Hasanta + (0x0a80b, 0x0a80b,), # Syloti Nagri Sign Anusvara + (0x0a823, 0x0a827,), # Syloti Nagri Vowel Sign ..Syloti Nagri Vowel Sign + (0x0a82c, 0x0a82c,), # Syloti Nagri Sign Alternate Hasanta + (0x0a880, 0x0a881,), # Saurashtra Sign Anusvara..Saurashtra Sign Visarga + (0x0a8b4, 0x0a8c5,), # Saurashtra Consonant Sig..Saurashtra Sign Candrabi + (0x0a8e0, 0x0a8f1,), # Combining Devanagari Dig..Combining Devanagari Sig + (0x0a8ff, 0x0a8ff,), # Devanagari Vowel Sign Ay + (0x0a926, 0x0a92d,), # Kayah Li Vowel Ue ..Kayah Li Tone Calya Plop + (0x0a947, 0x0a953,), # Rejang Vowel Sign I ..Rejang Virama + (0x0a980, 0x0a983,), # Javanese Sign Panyangga ..Javanese Sign Wignyan + (0x0a9b3, 0x0a9c0,), # Javanese Sign Cecak Telu..Javanese Pangkon + (0x0a9e5, 0x0a9e5,), # Myanmar Sign Shan Saw + (0x0aa29, 0x0aa36,), # Cham Vowel Sign Aa ..Cham Consonant Sign Wa + (0x0aa43, 0x0aa43,), # Cham Consonant Sign Final Ng + (0x0aa4c, 0x0aa4d,), # Cham Consonant Sign Fina..Cham Consonant Sign Fina + (0x0aa7b, 0x0aa7d,), # Myanmar Sign Pao Karen T..Myanmar Sign Tai Laing T + (0x0aab0, 0x0aab0,), # Tai Viet Mai Kang + (0x0aab2, 0x0aab4,), # Tai Viet Vowel I ..Tai Viet Vowel U + (0x0aab7, 0x0aab8,), # Tai Viet Mai Khit ..Tai Viet Vowel Ia + (0x0aabe, 0x0aabf,), # Tai Viet Vowel Am ..Tai Viet Tone Mai Ek + (0x0aac1, 0x0aac1,), # Tai Viet Tone Mai Tho + (0x0aaeb, 0x0aaef,), # Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + (0x0aaf5, 0x0aaf6,), # Meetei Mayek Vowel Sign ..Meetei Mayek Virama + (0x0abe3, 0x0abea,), # Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + (0x0abec, 0x0abed,), # Meetei Mayek Lum Iyek ..Meetei Mayek Apun Iyek + (0x0d7b0, 0x0d7ff,), # Hangul Jungseong O-yeo ..(nil) + (0x0fb1e, 0x0fb1e,), # Hebrew Point Judeo-spanish Varika + (0x0fe00, 0x0fe0f,), # Variation Selector-1 ..Variation Selector-16 + (0x0fe20, 0x0fe2f,), # Combining Ligature Left ..Combining Cyrillic Titlo + (0x0feff, 0x0feff,), # Zero Width No-break Space + (0x0ffa0, 0x0ffa0,), # Halfwidth Hangul Filler + (0x0fff0, 0x0fffb,), # (nil) ..Interlinear Annotation T + (0x101fd, 0x101fd,), # Phaistos Disc Sign Combining Oblique Stroke + (0x102e0, 0x102e0,), # Coptic Epact Thousands Mark + (0x10376, 0x1037a,), # Combining Old Permic Let..Combining Old Permic Let + (0x10a01, 0x10a03,), # Kharoshthi Vowel Sign I ..Kharoshthi Vowel Sign Vo + (0x10a05, 0x10a06,), # Kharoshthi Vowel Sign E ..Kharoshthi Vowel Sign O + (0x10a0c, 0x10a0f,), # Kharoshthi Vowel Length ..Kharoshthi Sign Visarga + (0x10a38, 0x10a3a,), # Kharoshthi Sign Bar Abov..Kharoshthi Sign Dot Belo + (0x10a3f, 0x10a3f,), # Kharoshthi Virama + (0x10ae5, 0x10ae6,), # Manichaean Abbreviation ..Manichaean Abbreviation + (0x10d24, 0x10d27,), # Hanifi Rohingya Sign Har..Hanifi Rohingya Sign Tas + (0x10d69, 0x10d6d,), # Garay Vowel Sign E ..Garay Consonant Nasaliza + (0x10eab, 0x10eac,), # Yezidi Combining Hamza M..Yezidi Combining Madda M + (0x10ecb, 0x10ecf,), # Arabic Northeast Pointin..Arabic Large Circle Abov + (0x10ef0, 0x10eff,), # Arabic Small Low Upright..Arabic Small Low Word Ma + (0x10f46, 0x10f50,), # Sogdian Combining Dot Be..Sogdian Combining Stroke + (0x10f82, 0x10f85,), # Old Uyghur Combining Dot..Old Uyghur Combining Two + (0x11000, 0x11002,), # Brahmi Sign Candrabindu ..Brahmi Sign Visarga + (0x11038, 0x11046,), # Brahmi Vowel Sign Aa ..Brahmi Virama + (0x11070, 0x11070,), # Brahmi Sign Old Tamil Virama + (0x11073, 0x11074,), # Brahmi Vowel Sign Old Ta..Brahmi Vowel Sign Old Ta + (0x1107f, 0x11082,), # Brahmi Number Joiner ..Kaithi Sign Visarga + (0x110b0, 0x110ba,), # Kaithi Vowel Sign Aa ..Kaithi Sign Nukta + (0x110c2, 0x110c2,), # Kaithi Vowel Sign Vocalic R + (0x11100, 0x11102,), # Chakma Sign Candrabindu ..Chakma Sign Visarga + (0x11127, 0x11134,), # Chakma Vowel Sign A ..Chakma Maayyaa + (0x11145, 0x11146,), # Chakma Vowel Sign Aa ..Chakma Vowel Sign Ei + (0x11173, 0x11173,), # Mahajani Sign Nukta + (0x11180, 0x11182,), # Sharada Sign Candrabindu..Sharada Sign Visarga + (0x111b3, 0x111c0,), # Sharada Vowel Sign Aa ..Sharada Sign Virama + (0x111c9, 0x111cc,), # Sharada Sandhi Mark ..Sharada Extra Short Vowe + (0x111ce, 0x111cf,), # Sharada Vowel Sign Prish..Sharada Sign Inverted Ca + (0x1122c, 0x11237,), # Khojki Vowel Sign Aa ..Khojki Sign Shadda + (0x1123e, 0x1123e,), # Khojki Sign Sukun + (0x11241, 0x11241,), # Khojki Vowel Sign Vocalic R + (0x112df, 0x112ea,), # Khudawadi Sign Anusvara ..Khudawadi Sign Virama + (0x11300, 0x11303,), # Grantha Sign Combining A..Grantha Sign Visarga + (0x1133b, 0x1133c,), # Combining Bindu Below ..Grantha Sign Nukta + (0x1133e, 0x11344,), # Grantha Vowel Sign Aa ..Grantha Vowel Sign Vocal + (0x11347, 0x11348,), # Grantha Vowel Sign Ee ..Grantha Vowel Sign Ai + (0x1134b, 0x1134d,), # Grantha Vowel Sign Oo ..Grantha Sign Virama + (0x11357, 0x11357,), # Grantha Au Length Mark + (0x11362, 0x11363,), # Grantha Vowel Sign Vocal..Grantha Vowel Sign Vocal + (0x11366, 0x1136c,), # Combining Grantha Digit ..Combining Grantha Digit + (0x11370, 0x11374,), # Combining Grantha Letter..Combining Grantha Letter + (0x113b8, 0x113c0,), # Tulu-tigalari Vowel Sign..Tulu-tigalari Vowel Sign + (0x113c2, 0x113c2,), # Tulu-tigalari Vowel Sign Ee + (0x113c5, 0x113c5,), # Tulu-tigalari Vowel Sign Ai + (0x113c7, 0x113ca,), # Tulu-tigalari Vowel Sign..Tulu-tigalari Sign Candr + (0x113cc, 0x113d0,), # Tulu-tigalari Sign Anusv..Tulu-tigalari Conjoiner + (0x113d2, 0x113d2,), # Tulu-tigalari Gemination Mark + (0x113e1, 0x113e2,), # Tulu-tigalari Vedic Tone..Tulu-tigalari Vedic Tone + (0x11435, 0x11446,), # Newa Vowel Sign Aa ..Newa Sign Nukta + (0x1145e, 0x1145e,), # Newa Sandhi Mark + (0x114b0, 0x114c3,), # Tirhuta Vowel Sign Aa ..Tirhuta Sign Nukta + (0x115af, 0x115b5,), # Siddham Vowel Sign Aa ..Siddham Vowel Sign Vocal + (0x115b8, 0x115c0,), # Siddham Vowel Sign E ..Siddham Sign Nukta + (0x115dc, 0x115dd,), # Siddham Vowel Sign Alter..Siddham Vowel Sign Alter + (0x11630, 0x11640,), # Modi Vowel Sign Aa ..Modi Sign Ardhacandra + (0x116ab, 0x116b7,), # Takri Sign Anusvara ..Takri Sign Nukta + (0x1171d, 0x1172b,), # Ahom Consonant Sign Medi..Ahom Sign Killer + (0x1182c, 0x1183a,), # Dogra Vowel Sign Aa ..Dogra Sign Nukta + (0x11930, 0x11935,), # Dives Akuru Vowel Sign A..Dives Akuru Vowel Sign E + (0x11937, 0x11938,), # Dives Akuru Vowel Sign A..Dives Akuru Vowel Sign O + (0x1193b, 0x1193e,), # Dives Akuru Sign Anusvar..Dives Akuru Virama + (0x11940, 0x11940,), # Dives Akuru Medial Ya + (0x11942, 0x11943,), # Dives Akuru Medial Ra ..Dives Akuru Sign Nukta + (0x119d1, 0x119d7,), # Nandinagari Vowel Sign A..Nandinagari Vowel Sign V + (0x119da, 0x119e0,), # Nandinagari Vowel Sign E..Nandinagari Sign Virama + (0x119e4, 0x119e4,), # Nandinagari Vowel Sign Prishthamatra E + (0x11a01, 0x11a0a,), # Zanabazar Square Vowel S..Zanabazar Square Vowel L + (0x11a33, 0x11a39,), # Zanabazar Square Final C..Zanabazar Square Sign Vi + (0x11a3b, 0x11a3e,), # Zanabazar Square Cluster..Zanabazar Square Cluster + (0x11a47, 0x11a47,), # Zanabazar Square Subjoiner + (0x11a51, 0x11a5b,), # Soyombo Vowel Sign I ..Soyombo Vowel Length Mar + (0x11a8a, 0x11a99,), # Soyombo Final Consonant ..Soyombo Subjoiner + (0x11b60, 0x11b67,), # Sharada Vowel Sign Oe ..Sharada Vowel Sign Candr + (0x11c2f, 0x11c36,), # Bhaiksuki Vowel Sign Aa ..Bhaiksuki Vowel Sign Voc + (0x11c38, 0x11c3f,), # Bhaiksuki Vowel Sign E ..Bhaiksuki Sign Virama + (0x11c92, 0x11ca7,), # Marchen Subjoined Letter..Marchen Subjoined Letter + (0x11ca9, 0x11cb6,), # Marchen Subjoined Letter..Marchen Sign Candrabindu + (0x11d31, 0x11d36,), # Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign + (0x11d3a, 0x11d3a,), # Masaram Gondi Vowel Sign E + (0x11d3c, 0x11d3d,), # Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign + (0x11d3f, 0x11d45,), # Masaram Gondi Vowel Sign..Masaram Gondi Virama + (0x11d47, 0x11d47,), # Masaram Gondi Ra-kara + (0x11d8a, 0x11d8e,), # Gunjala Gondi Vowel Sign..Gunjala Gondi Vowel Sign + (0x11d90, 0x11d91,), # Gunjala Gondi Vowel Sign..Gunjala Gondi Vowel Sign + (0x11d93, 0x11d97,), # Gunjala Gondi Vowel Sign..Gunjala Gondi Virama + (0x11df0, 0x11df0,), # Bengali Sign Combining Anusvara Above + (0x11ef3, 0x11ef6,), # Makasar Vowel Sign I ..Makasar Vowel Sign O + (0x11f00, 0x11f01,), # Kawi Sign Candrabindu ..Kawi Sign Anusvara + (0x11f03, 0x11f03,), # Kawi Sign Visarga + (0x11f34, 0x11f3a,), # Kawi Vowel Sign Aa ..Kawi Vowel Sign Vocalic + (0x11f3e, 0x11f42,), # Kawi Vowel Sign E ..Kawi Conjoiner + (0x11f5a, 0x11f5a,), # Kawi Sign Nukta + (0x13430, 0x13440,), # Egyptian Hieroglyph Vert..Egyptian Hieroglyph Mirr + (0x13447, 0x13455,), # Egyptian Hieroglyph Modi..Egyptian Hieroglyph Modi + (0x1611e, 0x1612f,), # Gurung Khema Vowel Sign ..Gurung Khema Sign Tholho + (0x16af0, 0x16af4,), # Bassa Vah Combining High..Bassa Vah Combining High + (0x16b30, 0x16b36,), # Pahawh Hmong Mark Cim Tu..Pahawh Hmong Mark Cim Ta + (0x16f4f, 0x16f4f,), # Miao Sign Consonant Modifier Bar + (0x16f51, 0x16f87,), # Miao Sign Aspiration ..Miao Vowel Sign Ui + (0x16f8f, 0x16f92,), # Miao Tone Right ..Miao Tone Below + (0x16fe4, 0x16fe4,), # Khitan Small Script Filler + (0x16ff0, 0x16ff1,), # Vietnamese Alternate Rea..Vietnamese Alternate Rea + (0x1bc9d, 0x1bc9e,), # Duployan Thick Letter Se..Duployan Double Mark + (0x1bca0, 0x1bca3,), # Shorthand Format Letter ..Shorthand Format Up Step + (0x1cf00, 0x1cf2d,), # Znamenny Combining Mark ..Znamenny Combining Mark + (0x1cf30, 0x1cf46,), # Znamenny Combining Tonal..Znamenny Priznak Modifie + (0x1d127, 0x1d128,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d165, 0x1d169,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d16d, 0x1d182,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d185, 0x1d18b,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d1aa, 0x1d1ad,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d242, 0x1d244,), # Combining Greek Musical ..Combining Greek Musical + (0x1d250, 0x1d252,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d25b, 0x1d25c,), # Musical Symbol Combining..Musical Symbol Combining + (0x1d25f, 0x1d25f,), # Musical Symbol Combining Buzz Roll Stem + (0x1d280, 0x1d281,), # Musical Symbol Combining..Musical Symbol Combining + (0x1da00, 0x1da36,), # Signwriting Head Rim ..Signwriting Air Sucking + (0x1da3b, 0x1da6c,), # Signwriting Mouth Closed..Signwriting Excitement + (0x1da75, 0x1da75,), # Signwriting Upper Body Tilting From Hip Joints + (0x1da84, 0x1da84,), # Signwriting Location Head Neck + (0x1da9b, 0x1da9f,), # Signwriting Fill Modifie..Signwriting Fill Modifie + (0x1daa1, 0x1daaf,), # Signwriting Rotation Mod..Signwriting Rotation Mod + (0x1e000, 0x1e006,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e008, 0x1e018,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e01b, 0x1e021,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e023, 0x1e024,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e026, 0x1e02a,), # Combining Glagolitic Let..Combining Glagolitic Let + (0x1e08f, 0x1e08f,), # Combining Cyrillic Small Letter Byelorussian-ukr + (0x1e130, 0x1e136,), # Nyiakeng Puachue Hmong T..Nyiakeng Puachue Hmong T + (0x1e2ae, 0x1e2ae,), # Toto Sign Rising Tone + (0x1e2ec, 0x1e2ef,), # Wancho Tone Tup ..Wancho Tone Koini + (0x1e4ec, 0x1e4ef,), # Nag Mundari Sign Muhor ..Nag Mundari Sign Sutuh + (0x1e5ee, 0x1e5ef,), # Ol Onal Sign Mu ..Ol Onal Sign Ikir + (0x1e6e3, 0x1e6e3,), # Tai Yo Sign Ue + (0x1e6e6, 0x1e6e6,), # Tai Yo Sign Au + (0x1e6ee, 0x1e6ef,), # Tai Yo Sign Ay ..Tai Yo Sign Ang + (0x1e6f5, 0x1e6f5,), # Tai Yo Sign Om + (0x1e8d0, 0x1e8d6,), # Mende Kikakui Combining ..Mende Kikakui Combining + (0x1e944, 0x1e94a,), # Adlam Alif Lengthener ..Adlam Nukta + (0xe0000, 0xe0fff,), # (nil) + ), +} diff --git a/.venv/lib/python3.12/site-packages/wcwidth/text_sizing.py b/.venv/lib/python3.12/site-packages/wcwidth/text_sizing.py new file mode 100644 index 0000000000000000000000000000000000000000..e9348f743f2c297e3426c4a26d89728c9c4e26f9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/text_sizing.py @@ -0,0 +1,203 @@ +r""" +`kitty text sizing protocol`_ (OSC 66) parsing and measurement. + +The kitty text sizing protocol allows terminal apps to explicitly tell +terminals how many cells text occupies, using the escape sequence:: + + ESC ] 66 ; metadata [ ; text ] BEL/ST + +The ``text`` field is optional; when omitted, the sequence occupies +``s * w`` cells (or zero when ``w`` is also unset). + +Metadata is colon-separated ``key=value`` pairs: + +- ``s``: scale +- ``w``: width in cells +- ``n``: fractional numerator +- ``d``: fractional denominator +- ``v``: vertical alignment +- ``h``: horizontal alignment + +Parsing is pretty straight-forward: + +- When ``w > 0``, return ``s * w``. +- Otherwise ``w == 0``, ``s * wcswidth(inner_text_width)`` cells. + +Numerator, denominator, and alignment codes and values are parsed but otherwise ignored +and have no effect on measurements made in this library. + +.. _`kitty text sizing protocol`: https://sw.kovidgoyal.net/kitty/text-sizing-protocol/ + +.. versionadded:: 0.7.0 +""" + +from __future__ import annotations + +# std imports +import re + +import typing + +# local +from ._wcswidth import wcswidth + + +class _FieldMeta(typing.NamedTuple): + name: str + low: int + high: int + default: int + + +TEXT_FIELD_MAPPING: dict[str, _FieldMeta] = { + 's': _FieldMeta(name='scale', low=1, high=7, default=1), + 'w': _FieldMeta(name='width', low=0, high=7, default=0), + 'n': _FieldMeta(name='numerator', low=0, high=15, default=0), + 'd': _FieldMeta(name='denominator', low=0, high=15, default=0), + 'v': _FieldMeta(name='vertical_align', low=0, high=2, default=0), + 'h': _FieldMeta(name='horizontal_align', low=0, high=2, default=0)} + + +class TextSizingParams(typing.NamedTuple): + """ + Parsed parameters from a text sizing escape sequence (OSC 66). + + :param scale: Scale factor (1-7). Text occupies ``scale`` rows tall and ``scale * width`` + columns wide. + :param width: Width in cells (0-7). When 0, width is auto-calculated from the inner text. + :param numerator: Fractional scaling numerator (0-15). + :param denominator: Fractional scaling denominator (0-15). + :param vertical_align: Vertical alignment (0=top, 1=bottom, 2=center). + :param horizontal_align: Horizontal alignment (0=left, 1=right, 2=center). + """ + + scale: int = 1 + width: int = 0 + numerator: int = 0 + denominator: int = 0 + vertical_align: int = 0 + horizontal_align: int = 0 + + def __repr__(self) -> str: + """ + Return a compact representation including only non-default fields. + + This avoids verbose output when most fields are defaults. + """ + # modified to show values only when non-default + repr_fmt = ', '.join(f'{field.name}={getattr(self, field.name)}' + for field in TEXT_FIELD_MAPPING.values() + if getattr(self, field.name) != field.default) + return f'{self.__class__.__name__}({repr_fmt})' + + def make_sequence(self) -> str: + """Build and return sub-part of an OSC 66 sequence.""" + parts = [] + # build string for all known parameters of non-default values + for field_key, field in TEXT_FIELD_MAPPING.items(): + if (val := getattr(self, field.name)) != field.default: + parts.append(f'{field_key}={val}') + return ':'.join(parts) + + @classmethod + def from_params(cls, raw: str, control_codes: str = 'parse') -> TextSizingParams: + """ + Parse colon-separated ``key=value`` metadata string. + + :param raw: Metadata string, e.g. ``'s=2:w=3'``. + :param control_codes: 'parse' or 'strict'. + :raises ValueError: If ``control_codes='strict'`` unrecognized text sizing parameters raise + ValueError. + :returns: Parsed parameters with values clamped to valid ranges. + Unknown keys are ignored. Non-integer values use defaults. + + Example:: + + >>> TextSizingParams.from_params('s=2:w=3') + TextSizingParams(scale=2, width=3) + """ + kwargs: typing.Dict[str, int] = {} + if not raw: + return cls() + for part in raw.split(':'): + if '=' not in part: + if control_codes == 'strict': + raise ValueError(f"Expected '=' in text sizing parameter (key=val), " + f"got {part!r} in OSC 66 sequence, {raw!r}") + continue + key, _eq, val = part.partition('=') + field = TEXT_FIELD_MAPPING.get(key) + if field is None: + if control_codes == 'strict': + raise ValueError(f"Unknown text sizing field '{key}' " + f"in OSC 66 sequence, {raw!r}") + # ignore unknown fields unless 'strict' + continue + try: + value = int(val) + except ValueError as exc: + if control_codes == 'strict': + raise ValueError(f"Illegal text sizing value '{val}' " + f"in OSC 66 sequence, {raw!r}: {exc}") from exc + # ignore value, uses default value without warning unless 'strict' + continue + if control_codes == 'strict' and (value > field.high or value < field.low): + raise ValueError(f"Out of bounds text sizing value '{val}' " + f"in OSC 66 sequence, {raw!r}: " + f"allowed range for '{key}' ({field.name}) " + f"is {field.low} to {field.high}") + kwargs[field.name] = max(field.low, min(field.high, value)) + return cls(**kwargs) + + +class TextSizing(typing.NamedTuple): + """Basic horizontal width measurement for kitty text sizing protocol.""" + + params: TextSizingParams + text: str + terminator: str + + @classmethod + def from_match(cls, match: re.Match[str], control_codes: str = 'parse') -> TextSizing: + r""" + Parse using matching OSC 66 Sequence. + + :param match: match object from :attr:`wcwidth.escape_sequences.TEXT_SIZING_PATTERN`. + :param control_codes: 'parse' or 'strict', same meaning as delegated by + :func:`wcwidth.width`. + :raises ValueError: When ``control_codes='strict'`` for unrecognized, invalid, or out of + bounds text sizing parameters. + :returns: TextSizing object from parsed sequence + + Example:: + + >>> from wcwidth.escape_sequences import TEXT_SIZING_PATTERN + >>> TextSizing.from_match(TEXT_SIZING_PATTERN.match('\x1b]66;w=2;XY\x07')) + TextSizing(params=TextSizingParams(width=2), text='XY', terminator='\x07') + """ + return cls(params=TextSizingParams.from_params(match.group(1), control_codes=control_codes), + text=match.group(2) or '', + terminator=match.group(3)) + + def display_width(self, ambiguous_width: int = 1) -> int: + """ + Calculate the display width of a text sizing sequence. + + :param ambiguous_width: Width for East Asian Ambiguous characters. + :returns: Display width in terminal cells. When ``width > 0``, returns + ``params.scale * params.width``. When ``width == 0``, returns + ``params.scale * measured_inner_width``. + + .. note: Fractional scaling (numerator/denominator) does not affect the + cell count, it adjusts only the font size within the cells allocated by 'w'. + """ + if self.params.width > 0: + return self.params.scale * self.params.width + w = wcswidth(self.text, ambiguous_width=ambiguous_width) + if w < 0: + w = 0 + return self.params.scale * w + + def make_sequence(self) -> str: + """Build and return complete OSC 66 Terminal Sequence.""" + return f'\x1b]66;{self.params.make_sequence()};{self.text}{self.terminator}' diff --git a/.venv/lib/python3.12/site-packages/wcwidth/textwrap.py b/.venv/lib/python3.12/site-packages/wcwidth/textwrap.py new file mode 100644 index 0000000000000000000000000000000000000000..b14aef21dd8df8f3bf8b52865d113930f8b2aafe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/textwrap.py @@ -0,0 +1,662 @@ +""" +Sequence-aware text wrapping functions. + +This module provides functions for wrapping text that may contain terminal escape sequences, with +proper handling of Unicode grapheme clusters and character display widths. +""" + +from __future__ import annotations + +# std imports +import secrets +import textwrap + +from typing import TYPE_CHECKING, Optional + +# local +from ._width import width as wcwidth_width +from .grapheme import iter_graphemes +from .hyperlink import HyperlinkParams +from .sgr_state import propagate_sgr as _propagate_sgr +from .escape_sequences import ZERO_WIDTH_PATTERN, iter_sequences + +if TYPE_CHECKING: # pragma: no cover + from typing import Any, Literal + + +class SequenceTextWrapper(textwrap.TextWrapper): + """ + Sequence-aware text wrapper extending :class:`textwrap.TextWrapper`. + + This wrapper properly handles terminal escape sequences and Unicode grapheme clusters when + calculating text width for wrapping. + + This implementation is based on the SequenceTextWrapper from the 'blessed' library, with + contributions from Avram Lubkin and grayjk. + + The key difference from the blessed implementation is the addition of grapheme cluster support + via :func:`~.iter_graphemes`, providing width calculation for ZWJ emoji sequences, VS-16 emojis + and variations, regional indicator flags, and combining characters. + + OSC 8 hyperlinks are handled specially: when a hyperlink must span multiple lines, each line + receives complete open/close sequences with a shared ``id`` parameter, ensuring terminals + treat the fragments as a single hyperlink for hover underlining. If the original hyperlink + already has an ``id`` parameter, it is preserved; otherwise, one is generated. + """ + + def __init__(self, width: int = 70, *, + control_codes: Literal['parse', 'strict', 'ignore'] = 'parse', + tabsize: int = 8, + ambiguous_width: int = 1, + term_program: bool | str = False, + **kwargs: Any) -> None: + """ + Initialize the wrapper. + + :param width: Maximum line width in display cells. + :param control_codes: How to handle control sequences (see :func:`~.width`). + :param tabsize: Tab stop width for tab expansion. + :param ambiguous_width: Width to use for East Asian Ambiguous (A) characters. + :param term_program: Terminal software identifier for table correction. + ``False`` (default) disables override lookup. ``True`` reads the + ``TERM_PROGRAM`` or ``TERM`` environment variable for auto-detection. + Accepts a canonical terminal name matching :func:`list_term_programs`, + such as from XTVERSION_, ENQ_, or ``TERM_PROGRAM``. + + .. versionadded:: 0.8.0 + :param kwargs: Additional arguments passed to :class:`textwrap.TextWrapper`. + """ + super().__init__(width=width, **kwargs) + self.control_codes = control_codes + self.tabsize = tabsize + self.ambiguous_width = ambiguous_width + self.term_program = term_program + + @staticmethod + def _next_hyperlink_id() -> str: + """Generate unique hyperlink id as 8-character hex string.""" + return secrets.token_hex(4) + + def _width(self, text: str) -> int: + """Measure text width accounting for sequences.""" + return wcwidth_width(text, control_codes=self.control_codes, tabsize=self.tabsize, + ambiguous_width=self.ambiguous_width, + term_program=self.term_program) + + def _strip_sequences(self, text: str) -> str: + """Strip all terminal sequences from text.""" + result = [] + for segment, is_seq in iter_sequences(text): + if not is_seq: + result.append(segment) + return ''.join(result) + + def _extract_sequences(self, text: str) -> str: + """Extract only terminal sequences from text.""" + result = [] + for segment, is_seq in iter_sequences(text): + if is_seq: + result.append(segment) + return ''.join(result) + + def _split(self, text: str) -> list[str]: # pylint: disable=too-many-locals + r""" + Sequence-aware variant of :meth:`textwrap.TextWrapper._split`. + + This method ensures that terminal escape sequences don't interfere with the text splitting + logic, particularly for hyphen-based word breaking. It builds a position mapping from + stripped text to original text, calls the parent's _split on stripped text, then maps chunks + back. + + OSC hyperlink sequences are treated as word boundaries:: + + >>> wrap('foo \x1b]8;;https://example.com\x07link\x1b]8;;\x07 bar', 6) + ['foo', '\x1b]8;;https://example.com\x07link\x1b]8;;\x07', 'bar'] + + Both BEL (``\x07``) and ST (``\x1b\\``) terminators are supported. + """ + # pylint: disable=too-many-locals,too-many-branches + # Build a mapping from stripped text positions to original text positions. + # + # Track where each character ENDS so that sequences between characters + # attach to the following text, keeping them when whitespace is dropped. + # + # char_end[i] = position in original text right after the i-th stripped char + char_end: list[int] = [] + stripped_text = '' + original_pos = 0 + prev_was_hyperlink_close = False + + for segment, is_seq in iter_sequences(text): + if not is_seq: + # Conditionally insert space after hyperlink close to force word boundary + if prev_was_hyperlink_close and segment and not segment[0].isspace(): + stripped_text += ' ' + char_end.append(original_pos) + for char in segment: + original_pos += 1 + char_end.append(original_pos) + stripped_text += char + prev_was_hyperlink_close = False + else: + is_hyperlink_close = segment.startswith(('\x1b]8;;\x1b\\', '\x1b]8;;\x07')) + + # Conditionally insert space before OSC sequences to artificially create word + # boundary, but *not* before hyperlink close sequences, to ensure hyperlink is + # terminated on the same line. + if (segment.startswith('\x1b]') and stripped_text and not + stripped_text[-1].isspace()): + if not is_hyperlink_close: + stripped_text += ' ' + char_end.append(original_pos) + + # Escape sequences advance position but don't add to stripped text + original_pos += len(segment) + prev_was_hyperlink_close = is_hyperlink_close + + # Add sentinel for final position + char_end.append(original_pos) + + # Use parent's _split on the stripped text + # pylint: disable-next=protected-access + stripped_chunks = textwrap.TextWrapper._split(self, stripped_text) + + # Handle text that contains only sequences (no visible characters). + # Return the sequences as a single chunk to preserve them. + if not stripped_chunks and text: + return [text] + + # Map the chunks back to the original text with sequences + result: list[str] = [] + stripped_pos = 0 + num_chunks = len(stripped_chunks) + + for idx, chunk in enumerate(stripped_chunks): + chunk_len = len(chunk) + + # Start is where previous character ended (or 0 for first chunk) + start_orig = 0 if stripped_pos == 0 else char_end[stripped_pos - 1] + + # End is where next character starts. For last chunk, use sentinel + # to include any trailing sequences. + if idx == num_chunks - 1: + end_orig = char_end[-1] # sentinel includes trailing sequences + else: + end_orig = char_end[stripped_pos + chunk_len - 1] + + # Extract the corresponding portion from the original text + # Skip empty chunks (from virtual spaces inserted at OSC boundaries) + if start_orig != end_orig: + result.append(text[start_orig:end_orig]) + stripped_pos += chunk_len + + return result + + def _wrap_chunks(self, chunks: list[str]) -> list[str]: # pylint: disable=too-many-branches + """ + Wrap chunks into lines using sequence-aware width. + + Override TextWrapper._wrap_chunks to measure with _width. Follows stdlib's algorithm: + greedily fill lines, handle long words. Also handle OSC hyperlink processing. When + hyperlinks span multiple lines, each line gets complete open/close sequences with matching + id parameters for hover underlining continuity per OSC 8 spec. + """ + # pylint: disable=too-many-branches,too-many-statements,too-complex,too-many-locals + # pylint: disable=too-many-nested-blocks + # The hyperlink code pushes the complexity rating of this method. It stays in one method + # because of the shared local state. + if self.width <= 0: + raise ValueError('invalid width %r (must be > 0)' % self.width) + if not chunks: + return [] + + if self.max_lines is not None: + if self.max_lines > 1: + indent = self.subsequent_indent + else: + indent = self.initial_indent + if (self._width(indent) + + self._width(self.placeholder.lstrip()) + > self.width): + raise ValueError("placeholder too large for max width") + + lines: list[str] = [] + is_first_line = True + + hyperlink_state: Optional[HyperlinkParams] = None + # Track the id we're using for the current hyperlink continuation + current_hyperlink_id: Optional[str] = None + + # Arrange in reverse order so items can be efficiently popped + chunks = list(reversed(chunks)) + + while chunks: + current_line: list[str] = [] + current_width = 0 + + # Get the indent and available width for current line + indent = self.initial_indent if is_first_line else self.subsequent_indent + line_width = self.width - self._width(indent) + + # If continuing a hyperlink from previous line, prepend open sequence + if hyperlink_state is not None: + open_seq = HyperlinkParams( + url=hyperlink_state.url, + params=hyperlink_state.params, + terminator=hyperlink_state.terminator, + ).make_open() + chunks[-1] = open_seq + chunks[-1] + + # Drop leading whitespace (except at very start) + # When dropping, transfer any sequences to the next chunk. + # Only drop when actual whitespace text is present. + stripped = self._strip_sequences(chunks[-1]) + if self.drop_whitespace and lines and stripped and not stripped.strip(): + sequences = self._extract_sequences(chunks[-1]) + del chunks[-1] + if sequences and chunks: + chunks[-1] = sequences + chunks[-1] + + # Greedily add chunks that fit + while chunks: + chunk = chunks[-1] + chunk_width = self._width(chunk) + + if current_width + chunk_width <= line_width: + current_line.append(chunks.pop()) + current_width += chunk_width + else: + break + + # Handle chunk that's too long for any line + if chunks and self._width(chunks[-1]) > line_width: + self._handle_long_word( + chunks, current_line, current_width, line_width + ) + current_width = self._width(''.join(current_line)) + # Remove any empty chunks left by _handle_long_word + while chunks and not chunks[-1]: + del chunks[-1] + + # Drop trailing whitespace + # When dropping, transfer any sequences to the previous chunk. + # Only drop when actual whitespace text is present. + stripped_last = self._strip_sequences(current_line[-1]) if current_line else '' + if (self.drop_whitespace and current_line and + stripped_last and not stripped_last.strip()): + sequences = self._extract_sequences(current_line[-1]) + current_width -= self._width(current_line[-1]) + del current_line[-1] + if sequences and current_line: + current_line[-1] = current_line[-1] + sequences + + if current_line: + # Check whether this is a normal append or max_lines + # truncation. Matches stdlib textwrap precedence: + # normal if max_lines not set, not yet reached, or no + # remaining visible content that would need truncation. + no_more_content = ( + not chunks or + self.drop_whitespace and + len(chunks) == 1 and + not self._strip_sequences(chunks[0]).strip() + ) + if (self.max_lines is None or + len(lines) + 1 < self.max_lines or + no_more_content + and current_width <= line_width): + line_content = ''.join(current_line) + + # Track hyperlink state through this line's content + new_state = self._track_hyperlink_state(line_content, hyperlink_state) + + # If we end inside a hyperlink, append close sequence + if new_state is not None: + # Ensure we have an id for continuation + if current_hyperlink_id is None: + if 'id=' in new_state.params: + current_hyperlink_id = new_state.params + elif new_state.params: + # Prepend id to existing params. Per OSC 8 spec, params can have + # multiple key=value pairs separated by ':'. + current_hyperlink_id = ( + f'id={self._next_hyperlink_id()}:{new_state.params}') + else: + current_hyperlink_id = f'id={self._next_hyperlink_id()}' + line_content += HyperlinkParams( + terminator=new_state.terminator, url='').make_close() + + # Also need to inject the id into the opening + # sequence if it didn't have one + if 'id=' not in new_state.params: + # Find and replace the original open sequence with one that has id + old_open = HyperlinkParams( + url=new_state.url, + params=new_state.params, + terminator=new_state.terminator, + ).make_open() + new_open = HyperlinkParams( + url=new_state.url, + params=current_hyperlink_id, + terminator=new_state.terminator, + ).make_open() + line_content = line_content.replace(old_open, new_open, 1) + + # Update state for next line, using computed id + hyperlink_state = HyperlinkParams( + new_state.url, current_hyperlink_id, new_state.terminator) + else: + hyperlink_state = None + current_hyperlink_id = None # Reset id when hyperlink closes + + # Strip trailing whitespace when drop_whitespace is enabled + # (matches CPython #140627 fix behavior) + if self.drop_whitespace: + line_content = line_content.rstrip() + lines.append(indent + line_content) + is_first_line = False + else: + # max_lines reached with remaining content. + # pop chunks until placeholder fits, then break. + placeholder_w = self._width(self.placeholder) + while current_line: + last_text = self._strip_sequences(current_line[-1]) + if (last_text.strip() + and current_width + placeholder_w <= line_width): + line_content = ''.join(current_line) + new_state = self._track_hyperlink_state( + line_content, hyperlink_state) + if new_state is not None: + line_content += HyperlinkParams( + terminator=new_state.terminator, url='').make_close() + lines.append(indent + line_content + self.placeholder) + break + current_width -= self._width(current_line[-1]) + del current_line[-1] + else: + if lines: + prev_line = self._rstrip_visible(lines[-1]) + if (self._width(prev_line) + placeholder_w + <= self.width): + lines[-1] = prev_line + self.placeholder + break + lines.append(indent + self.placeholder.lstrip()) + break + + return lines + + def _track_hyperlink_state( + self, text: str, + state: Optional[HyperlinkParams]) -> Optional[HyperlinkParams]: + """ + Track hyperlink state through text. + + :param text: Text to scan for hyperlink sequences. + :param state: Current state or None if outside hyperlink. + :returns: Updated state after processing text. + """ + for segment, is_seq in iter_sequences(text): + if is_seq: + parsed_link = HyperlinkParams.parse(segment) + if parsed_link is not None and parsed_link.url: # has URL = open + state = parsed_link + elif segment.startswith(('\x1b]8;;\x1b\\', '\x1b]8;;\x07')): # close + state = None + return state + + def _handle_long_word(self, reversed_chunks: list[str], + cur_line: list[str], cur_len: int, + width: int) -> None: + """ + Sequence-aware :meth:`textwrap.TextWrapper._handle_long_word`. + + This method ensures that word boundaries are not broken mid-sequence, and respects grapheme + cluster boundaries when breaking long words. + """ + if width < 1: + space_left = 1 + else: + space_left = width - cur_len + + chunk = reversed_chunks[-1] + + if self.break_long_words: + break_at_hyphen = False + hyphen_end = 0 + # End of the prefix that fits within space_left by display width. + prefix_end = self._find_break_position(chunk, space_left) + + # Handle break_on_hyphens: find last hyphen in the portion that fits. + if self.break_on_hyphens: + stripped = self._strip_sequences(chunk[:prefix_end]) + hyphen_pos = stripped.rfind('-') + if hyphen_pos > 0 and any(c != '-' for c in stripped[:hyphen_pos]): + # Map back to original position including sequences + hyphen_end = self._map_stripped_pos_to_original(chunk, hyphen_pos + 1) + break_at_hyphen = True + + # Break at grapheme boundaries to avoid splitting multi-codepoint characters + if break_at_hyphen: + actual_end = hyphen_end + else: + actual_end = prefix_end + # Include first visible unit when break would take only leading sequences. + if not cur_line and ( + actual_end == 0 + or (actual_end < len(chunk) + and self._width(chunk[:actual_end]) == 0)): + actual_end = self._find_first_visible_break(chunk) + cur_line.append(chunk[:actual_end]) + reversed_chunks[-1] = chunk[actual_end:] + + elif not cur_line: + cur_line.append(reversed_chunks.pop()) + + def _map_stripped_pos_to_original(self, text: str, stripped_pos: int) -> int: + """Map a position in stripped text back to original text position.""" + stripped_idx = 0 + original_idx = 0 + + for segment, is_seq in iter_sequences(text): + if is_seq: + original_idx += len(segment) + elif stripped_idx + len(segment) > stripped_pos: + # Position is within this segment + return original_idx + (stripped_pos - stripped_idx) + else: + stripped_idx += len(segment) + original_idx += len(segment) + + # Caller guarantees stripped_pos < total stripped chars, so we always + # return from within the loop. This line satisfies the type checker. + return original_idx # pragma: no cover + + def _find_break_position(self, text: str, max_width: int) -> int: + """Find string index in text that fits within max_width cells.""" + idx = 0 + width_so_far = 0 + + while idx < len(text): + char = text[idx] + + # Skip escape sequences (they don't add width) + if char == '\x1b': + match = ZERO_WIDTH_PATTERN.match(text, idx) + if match: + idx = match.end() + continue + + # Get grapheme (use start= to avoid slice allocation) + grapheme = next(iter_graphemes(text, start=idx)) + + grapheme_width = self._width(grapheme) + if width_so_far + grapheme_width > max_width: + return idx # Found break point + + width_so_far += grapheme_width + idx += len(grapheme) + + # Caller guarantees chunk_width > max_width, so a grapheme always + # exceeds and we return from within the loop. Type checker requires this. + return idx # pragma: no cover + + def _find_first_visible_break(self, text: str) -> int: + """End of leading escape sequences plus the first grapheme.""" + idx = 0 + while idx < len(text) and text[idx] == '\x1b': + match = ZERO_WIDTH_PATTERN.match(text, idx) + if match is None: + break + idx = match.end() + return idx + len(next(iter_graphemes(text, start=idx))) + + def _rstrip_visible(self, text: str) -> str: + """Strip trailing visible whitespace, preserving trailing sequences.""" + segments = list(iter_sequences(text)) + last_vis = -1 + for i, (segment, is_seq) in enumerate(segments): + if not is_seq and segment.rstrip(): + last_vis = i + if last_vis == -1: + return '' + result = [] + for i, (segment, is_seq) in enumerate(segments): + if i < last_vis: + result.append(segment) + elif i == last_vis: + result.append(segment.rstrip()) + elif is_seq: + result.append(segment) + return ''.join(result) + + +def wrap(text: str, width: int = 70, *, + control_codes: Literal['parse', 'strict', 'ignore'] = 'parse', + tabsize: int = 8, + expand_tabs: bool = True, + replace_whitespace: bool = True, + ambiguous_width: int = 1, + term_program: bool | str = False, + initial_indent: str = '', + subsequent_indent: str = '', + fix_sentence_endings: bool = False, + break_long_words: bool = True, + break_on_hyphens: bool = True, + drop_whitespace: bool = True, + max_lines: Optional[int] = None, + placeholder: str = ' [...]', + propagate_sgr: bool = True) -> list[str]: + r""" + Wrap text to fit within given width, returning a list of wrapped lines. + + Like :func:`textwrap.wrap`, but measures width in display cells, correctly + handling wide characters, combining marks, and terminal + escape sequences. + + :param text: Text to wrap, may contain terminal sequences. + :param width: Maximum line width in display cells. + :param control_codes: How to handle terminal sequences (see :func:`~.width`). + :param tabsize: Tab stop width for tab expansion. + :param expand_tabs: If True (default), tab characters are expanded + to spaces using ``tabsize``. + :param replace_whitespace: If True (default), each whitespace character + is replaced with a single space after tab expansion. When False, + control whitespace like ``\n`` has zero display width (unlike + :func:`textwrap.wrap` which counts ``len()``), so wrap points + may differ from stdlib for non-space whitespace characters. + :param ambiguous_width: Width to use for East Asian Ambiguous (A) + characters. Default is ``1`` (narrow). Set to ``2`` for CJK contexts. + :param term_program: Terminal software identifier for table correction. + ``False`` (default) disables override lookup. ``True`` reads the + ``TERM_PROGRAM`` or ``TERM`` environment variable for auto-detection. + Accepts a canonical terminal name matching :func:`list_term_programs`, + such as from XTVERSION_, ENQ_, or ``TERM_PROGRAM``. + + .. versionadded:: 0.8.0 + :param initial_indent: String prepended to first line. + :param subsequent_indent: String prepended to subsequent lines. + :param fix_sentence_endings: If True, ensure sentences are always + separated by exactly two spaces. + :param break_long_words: If True, break words longer than width. + :param break_on_hyphens: If True, allow breaking at hyphens. + :param drop_whitespace: If True (default), whitespace at the beginning + and end of each line (after wrapping but before indenting) is dropped. + Set to False to preserve whitespace. + :param max_lines: If set, output contains at most this many lines, with + ``placeholder`` appended to the last line if the text was truncated. + :param placeholder: String appended to the last line when text is + truncated by ``max_lines``. Default is ``' [...]'``. + :param propagate_sgr: If True (default), SGR (terminal styling) sequences + are propagated across wrapped lines. Each line ends with a reset + sequence and the next line begins with the active style restored. + :returns: List of wrapped lines without trailing newlines. + + SGR (terminal styling) sequences are propagated across wrapped lines + by default. Each line ends with a reset sequence and the next line + begins with the active style restored:: + + >>> wrap('\x1b[1;34mHello world\x1b[0m', width=6) + ['\x1b[1;34mHello\x1b[0m', '\x1b[1;34mworld\x1b[0m'] + + Set ``propagate_sgr=False`` to disable this behavior. + + Like :func:`textwrap.wrap`, newlines in the input text are treated as + whitespace and collapsed. To preserve paragraph breaks, wrap each + paragraph separately:: + + >>> text = 'First line.\nSecond line.' + >>> wrap(text, 40) # newline collapsed to space + ['First line. Second line.'] + >>> [line for para in text.split('\n') + ... for line in (wrap(para, 40) if para else [''])] + ['First line.', 'Second line.'] + + .. seealso:: + + :func:`textwrap.wrap`, :class:`textwrap.TextWrapper` + Standard library text wrapping (character-based). + + :class:`.SequenceTextWrapper` + Class interface for advanced wrapping options. + + .. versionadded:: 0.3.0 + + .. versionchanged:: 0.5.0 + Added ``propagate_sgr`` parameter (default True). + + .. versionchanged:: 0.6.0 + Added ``expand_tabs``, ``replace_whitespace``, ``fix_sentence_endings``, + ``drop_whitespace``, ``max_lines``, and ``placeholder`` parameters. + + Example:: + + >>> from wcwidth import wrap + >>> wrap('hello world', 5) + ['hello', 'world'] + >>> wrap('中文字符', 4) # CJK characters (2 cells each) + ['中文', '字符'] + """ + # pylint: disable=too-many-arguments,too-many-locals + wrapper = SequenceTextWrapper( + width=width, + control_codes=control_codes, + tabsize=tabsize, + expand_tabs=expand_tabs, + replace_whitespace=replace_whitespace, + ambiguous_width=ambiguous_width, + term_program=term_program, + initial_indent=initial_indent, + subsequent_indent=subsequent_indent, + fix_sentence_endings=fix_sentence_endings, + break_long_words=break_long_words, + break_on_hyphens=break_on_hyphens, + drop_whitespace=drop_whitespace, + max_lines=max_lines, + placeholder=placeholder, + ) + lines = wrapper.wrap(text) + + if propagate_sgr: + lines = _propagate_sgr(lines) + + return lines diff --git a/.venv/lib/python3.12/site-packages/wcwidth/unicode_versions.py b/.venv/lib/python3.12/site-packages/wcwidth/unicode_versions.py new file mode 100644 index 0000000000000000000000000000000000000000..0df7aa2cd704d0342cf49d3b912d24fdb049186e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/unicode_versions.py @@ -0,0 +1,21 @@ +""" +Exports function list_versions() for unicode version level support. + +This code generated by python wcwidth project. +""" + +from __future__ import annotations + + +def list_versions() -> tuple[str, ...]: + """ + Return Unicode version levels supported by this module release. + + .. versionchanged:: 0.5.0 + Now returns a single-element tuple containing only the latest version. + + :returns: Supported Unicode version numbers in ascending sorted order. + """ + return ( + "18.0.0", + ) diff --git a/.venv/lib/python3.12/site-packages/wcwidth/wcwidth.py b/.venv/lib/python3.12/site-packages/wcwidth/wcwidth.py new file mode 100644 index 0000000000000000000000000000000000000000..523c34f9df59d796e0f5f735838c0b4e11c4ca9a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/wcwidth/wcwidth.py @@ -0,0 +1,88 @@ +""" +Legacy compatibility module for wcwidth.wcwidth. + +This file contains no new definitions and is provided only for backwards compatibility. This module +exists solely to support legacy "absolute" import paths, when this module published everything under +this single file, 'wcwidth':: + + from wcwidth.wcwidth import wcswidth + import wcwidth.wcwidth as wc_module +""" +# pylint: disable=unused-import + +__lazy_modules__ = [ + "wcwidth._clip", + "wcwidth._constants", + "wcwidth._wcswidth", + "wcwidth._wcwidth", + "wcwidth._width", + "wcwidth.align", + "wcwidth.bisearch", + "wcwidth.control_codes", + "wcwidth.escape_sequences", + "wcwidth.grapheme", + "wcwidth.sgr_state", + "wcwidth.table_ambiguous", + "wcwidth.table_grapheme", + "wcwidth.table_mc", + "wcwidth.table_vs16", + "wcwidth.table_wide", + "wcwidth.table_zero", + "wcwidth.unicode_versions", +] + +# local +from ._clip import clip +from .align import ljust, rjust, center +from ._width import _CONTROL_CHAR_TABLE, _WIDTH_FAST_PATH_MIN_LEN, width, _width_ignored_codes +from ._wcwidth import wcwidth, _wcmatch_version, _wcversion_value +from .bisearch import bisearch as _bisearch +from .grapheme import iter_graphemes +from .table_mc import CATEGORY_MC +from ._wcswidth import wcswidth, wcstwidth +from .sgr_state import (_SGR_PATTERN, + _SGR_STATE_DEFAULT, + _sgr_state_update, + _sgr_state_is_active, + _sgr_state_to_sequence) +from ._constants import (_EMOJI_ZWJ_SET, + _ISC_VIRAMA_SET, + _LATEST_VERSION, + _AMBIGUOUS_TABLE, + _ZERO_WIDTH_TABLE, + _CATEGORY_MC_TABLE, + _FITZPATRICK_RANGE, + _WIDE_EASTASIAN_TABLE, + _REGIONAL_INDICATOR_SET) +from .table_vs16 import VS16_NARROW_TO_WIDE +from .table_wide import WIDE_EASTASIAN +from .table_zero import ZERO_WIDTH +from .control_codes import ILLEGAL_CTRL, VERTICAL_CTRL, HORIZONTAL_CTRL, ZERO_WIDTH_CTRL +from .table_ambiguous import AMBIGUOUS_EASTASIAN +from .escape_sequences import (ZERO_WIDTH_PATTERN, + CURSOR_LEFT_SEQUENCE, + CURSOR_RIGHT_SEQUENCE, + INDETERMINATE_EFFECT_SEQUENCE, + iter_sequences, + strip_sequences) +from .unicode_versions import list_versions + +__all__ = ( + 'ZERO_WIDTH', + 'WIDE_EASTASIAN', + 'AMBIGUOUS_EASTASIAN', + 'VS16_NARROW_TO_WIDE', + 'list_versions', + 'wcwidth', + 'wcswidth', + 'wcstwidth', + 'width', + 'iter_sequences', + 'ljust', + 'rjust', + 'center', + 'clip', + 'strip_sequences', + '_wcmatch_version', + '_wcversion_value', +) diff --git a/.venv/lib/python3.12/site-packages/yaml/__init__.py b/.venv/lib/python3.12/site-packages/yaml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d58f0891737def7f38e5d86dde2dbf9be0c13dce --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/__init__.py @@ -0,0 +1,390 @@ + +from .error import * + +from .tokens import * +from .events import * +from .nodes import * + +from .loader import * +from .dumper import * + +__version__ = '6.0.3' +try: + from .cyaml import * + __with_libyaml__ = True +except ImportError: + __with_libyaml__ = False + +import io + +#------------------------------------------------------------------------------ +# XXX "Warnings control" is now deprecated. Leaving in the API function to not +# break code that uses it. +#------------------------------------------------------------------------------ +def warnings(settings=None): + if settings is None: + return {} + +#------------------------------------------------------------------------------ +def scan(stream, Loader=Loader): + """ + Scan a YAML stream and produce scanning tokens. + """ + loader = Loader(stream) + try: + while loader.check_token(): + yield loader.get_token() + finally: + loader.dispose() + +def parse(stream, Loader=Loader): + """ + Parse a YAML stream and produce parsing events. + """ + loader = Loader(stream) + try: + while loader.check_event(): + yield loader.get_event() + finally: + loader.dispose() + +def compose(stream, Loader=Loader): + """ + Parse the first YAML document in a stream + and produce the corresponding representation tree. + """ + loader = Loader(stream) + try: + return loader.get_single_node() + finally: + loader.dispose() + +def compose_all(stream, Loader=Loader): + """ + Parse all YAML documents in a stream + and produce corresponding representation trees. + """ + loader = Loader(stream) + try: + while loader.check_node(): + yield loader.get_node() + finally: + loader.dispose() + +def load(stream, Loader): + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + """ + loader = Loader(stream) + try: + return loader.get_single_data() + finally: + loader.dispose() + +def load_all(stream, Loader): + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + """ + loader = Loader(stream) + try: + while loader.check_data(): + yield loader.get_data() + finally: + loader.dispose() + +def full_load(stream): + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + + Resolve all tags except those known to be + unsafe on untrusted input. + """ + return load(stream, FullLoader) + +def full_load_all(stream): + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + + Resolve all tags except those known to be + unsafe on untrusted input. + """ + return load_all(stream, FullLoader) + +def safe_load(stream): + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + + Resolve only basic YAML tags. This is known + to be safe for untrusted input. + """ + return load(stream, SafeLoader) + +def safe_load_all(stream): + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + + Resolve only basic YAML tags. This is known + to be safe for untrusted input. + """ + return load_all(stream, SafeLoader) + +def unsafe_load(stream): + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + + Resolve all tags, even those known to be + unsafe on untrusted input. + """ + return load(stream, UnsafeLoader) + +def unsafe_load_all(stream): + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + + Resolve all tags, even those known to be + unsafe on untrusted input. + """ + return load_all(stream, UnsafeLoader) + +def emit(events, stream=None, Dumper=Dumper, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None): + """ + Emit YAML parsing events into a stream. + If stream is None, return the produced string instead. + """ + getvalue = None + if stream is None: + stream = io.StringIO() + getvalue = stream.getvalue + dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break) + try: + for event in events: + dumper.emit(event) + finally: + dumper.dispose() + if getvalue: + return getvalue() + +def serialize_all(nodes, stream=None, Dumper=Dumper, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None): + """ + Serialize a sequence of representation trees into a YAML stream. + If stream is None, return the produced string instead. + """ + getvalue = None + if stream is None: + if encoding is None: + stream = io.StringIO() + else: + stream = io.BytesIO() + getvalue = stream.getvalue + dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break, + encoding=encoding, version=version, tags=tags, + explicit_start=explicit_start, explicit_end=explicit_end) + try: + dumper.open() + for node in nodes: + dumper.serialize(node) + dumper.close() + finally: + dumper.dispose() + if getvalue: + return getvalue() + +def serialize(node, stream=None, Dumper=Dumper, **kwds): + """ + Serialize a representation tree into a YAML stream. + If stream is None, return the produced string instead. + """ + return serialize_all([node], stream, Dumper=Dumper, **kwds) + +def dump_all(documents, stream=None, Dumper=Dumper, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + """ + Serialize a sequence of Python objects into a YAML stream. + If stream is None, return the produced string instead. + """ + getvalue = None + if stream is None: + if encoding is None: + stream = io.StringIO() + else: + stream = io.BytesIO() + getvalue = stream.getvalue + dumper = Dumper(stream, default_style=default_style, + default_flow_style=default_flow_style, + canonical=canonical, indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break, + encoding=encoding, version=version, tags=tags, + explicit_start=explicit_start, explicit_end=explicit_end, sort_keys=sort_keys) + try: + dumper.open() + for data in documents: + dumper.represent(data) + dumper.close() + finally: + dumper.dispose() + if getvalue: + return getvalue() + +def dump(data, stream=None, Dumper=Dumper, **kwds): + """ + Serialize a Python object into a YAML stream. + If stream is None, return the produced string instead. + """ + return dump_all([data], stream, Dumper=Dumper, **kwds) + +def safe_dump_all(documents, stream=None, **kwds): + """ + Serialize a sequence of Python objects into a YAML stream. + Produce only basic YAML tags. + If stream is None, return the produced string instead. + """ + return dump_all(documents, stream, Dumper=SafeDumper, **kwds) + +def safe_dump(data, stream=None, **kwds): + """ + Serialize a Python object into a YAML stream. + Produce only basic YAML tags. + If stream is None, return the produced string instead. + """ + return dump_all([data], stream, Dumper=SafeDumper, **kwds) + +def add_implicit_resolver(tag, regexp, first=None, + Loader=None, Dumper=Dumper): + """ + Add an implicit scalar detector. + If an implicit scalar value matches the given regexp, + the corresponding tag is assigned to the scalar. + first is a sequence of possible initial characters or None. + """ + if Loader is None: + loader.Loader.add_implicit_resolver(tag, regexp, first) + loader.FullLoader.add_implicit_resolver(tag, regexp, first) + loader.UnsafeLoader.add_implicit_resolver(tag, regexp, first) + else: + Loader.add_implicit_resolver(tag, regexp, first) + Dumper.add_implicit_resolver(tag, regexp, first) + +def add_path_resolver(tag, path, kind=None, Loader=None, Dumper=Dumper): + """ + Add a path based resolver for the given tag. + A path is a list of keys that forms a path + to a node in the representation tree. + Keys can be string values, integers, or None. + """ + if Loader is None: + loader.Loader.add_path_resolver(tag, path, kind) + loader.FullLoader.add_path_resolver(tag, path, kind) + loader.UnsafeLoader.add_path_resolver(tag, path, kind) + else: + Loader.add_path_resolver(tag, path, kind) + Dumper.add_path_resolver(tag, path, kind) + +def add_constructor(tag, constructor, Loader=None): + """ + Add a constructor for the given tag. + Constructor is a function that accepts a Loader instance + and a node object and produces the corresponding Python object. + """ + if Loader is None: + loader.Loader.add_constructor(tag, constructor) + loader.FullLoader.add_constructor(tag, constructor) + loader.UnsafeLoader.add_constructor(tag, constructor) + else: + Loader.add_constructor(tag, constructor) + +def add_multi_constructor(tag_prefix, multi_constructor, Loader=None): + """ + Add a multi-constructor for the given tag prefix. + Multi-constructor is called for a node if its tag starts with tag_prefix. + Multi-constructor accepts a Loader instance, a tag suffix, + and a node object and produces the corresponding Python object. + """ + if Loader is None: + loader.Loader.add_multi_constructor(tag_prefix, multi_constructor) + loader.FullLoader.add_multi_constructor(tag_prefix, multi_constructor) + loader.UnsafeLoader.add_multi_constructor(tag_prefix, multi_constructor) + else: + Loader.add_multi_constructor(tag_prefix, multi_constructor) + +def add_representer(data_type, representer, Dumper=Dumper): + """ + Add a representer for the given type. + Representer is a function accepting a Dumper instance + and an instance of the given data type + and producing the corresponding representation node. + """ + Dumper.add_representer(data_type, representer) + +def add_multi_representer(data_type, multi_representer, Dumper=Dumper): + """ + Add a representer for the given type. + Multi-representer is a function accepting a Dumper instance + and an instance of the given data type or subtype + and producing the corresponding representation node. + """ + Dumper.add_multi_representer(data_type, multi_representer) + +class YAMLObjectMetaclass(type): + """ + The metaclass for YAMLObject. + """ + def __init__(cls, name, bases, kwds): + super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds) + if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None: + if isinstance(cls.yaml_loader, list): + for loader in cls.yaml_loader: + loader.add_constructor(cls.yaml_tag, cls.from_yaml) + else: + cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml) + + cls.yaml_dumper.add_representer(cls, cls.to_yaml) + +class YAMLObject(metaclass=YAMLObjectMetaclass): + """ + An object that can dump itself to a YAML stream + and load itself from a YAML stream. + """ + + __slots__ = () # no direct instantiation, so allow immutable subclasses + + yaml_loader = [Loader, FullLoader, UnsafeLoader] + yaml_dumper = Dumper + + yaml_tag = None + yaml_flow_style = None + + @classmethod + def from_yaml(cls, loader, node): + """ + Convert a representation node to a Python object. + """ + return loader.construct_yaml_object(node, cls) + + @classmethod + def to_yaml(cls, dumper, data): + """ + Convert a Python object to a representation node. + """ + return dumper.represent_yaml_object(cls.yaml_tag, data, cls, + flow_style=cls.yaml_flow_style) + diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48f793986206fee7e90f707fb8160d4b7c14b4b7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/composer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/composer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e7cc8a3af4c1b2e532c4a2b88cb5f98ec407c77 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/composer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/constructor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/constructor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ffb75cb364504ecfaa9d539eeda73556a6fb1c5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/constructor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/cyaml.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/cyaml.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2976fe498df94ad31d350981da0a4c82c8632fd3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/cyaml.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/dumper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/dumper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca241f099cec93fe062827175a9a3e0c1f059739 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/dumper.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/emitter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/emitter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..494a36a02770628f1f39bb9deefa2e0c425dfe92 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/emitter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/error.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab83dac543f1fb5871ffd551b8e97a91021fe961 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/error.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/events.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/events.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5b5ee33e727464a9551369964343610f9ce99f4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/events.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/loader.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/loader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a20765cba6fde35c0d41b1bb989dc6b93d8a4a5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/loader.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/nodes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/nodes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70e416c94f41b84e8ff49f1be35a50524cf00da6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/nodes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/parser.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abf37a9fd99aeb63740aed026483329a47761920 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/parser.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/reader.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/reader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..676b3d5017ec4be186be8fbdb8340c23db1c8335 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/reader.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/representer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/representer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6406ee5e3ac8b121994342f0be63c13b65757d9e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/representer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/resolver.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/resolver.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c8eb9ad609fca9c54e393bd5d19c0640fda4bc1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/resolver.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/scanner.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/scanner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa023f56319ccd0fe098854566615110253855ce Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/scanner.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/serializer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/serializer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c7c46ab078dc0ee5c68ea294325ce23ce49b1e9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/serializer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/__pycache__/tokens.cpython-312.pyc b/.venv/lib/python3.12/site-packages/yaml/__pycache__/tokens.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4acc465d25e4b03269055c563ff0d270ccadb0a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/yaml/__pycache__/tokens.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/yaml/_yaml.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/yaml/_yaml.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..5a17311d6696643869b7726d2cd50c046db77b68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/_yaml.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:957a099a4521c1f7669306fb6f79ca63fa4b9a0b4c463f7cac833a65a5c5c0cb +size 2679264 diff --git a/.venv/lib/python3.12/site-packages/yaml/composer.py b/.venv/lib/python3.12/site-packages/yaml/composer.py new file mode 100644 index 0000000000000000000000000000000000000000..6d15cb40e3b4198819c91c6f8d8b32807fcf53b2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/composer.py @@ -0,0 +1,139 @@ + +__all__ = ['Composer', 'ComposerError'] + +from .error import MarkedYAMLError +from .events import * +from .nodes import * + +class ComposerError(MarkedYAMLError): + pass + +class Composer: + + def __init__(self): + self.anchors = {} + + def check_node(self): + # Drop the STREAM-START event. + if self.check_event(StreamStartEvent): + self.get_event() + + # If there are more documents available? + return not self.check_event(StreamEndEvent) + + def get_node(self): + # Get the root node of the next document. + if not self.check_event(StreamEndEvent): + return self.compose_document() + + def get_single_node(self): + # Drop the STREAM-START event. + self.get_event() + + # Compose a document if the stream is not empty. + document = None + if not self.check_event(StreamEndEvent): + document = self.compose_document() + + # Ensure that the stream contains no more documents. + if not self.check_event(StreamEndEvent): + event = self.get_event() + raise ComposerError("expected a single document in the stream", + document.start_mark, "but found another document", + event.start_mark) + + # Drop the STREAM-END event. + self.get_event() + + return document + + def compose_document(self): + # Drop the DOCUMENT-START event. + self.get_event() + + # Compose the root node. + node = self.compose_node(None, None) + + # Drop the DOCUMENT-END event. + self.get_event() + + self.anchors = {} + return node + + def compose_node(self, parent, index): + if self.check_event(AliasEvent): + event = self.get_event() + anchor = event.anchor + if anchor not in self.anchors: + raise ComposerError(None, None, "found undefined alias %r" + % anchor, event.start_mark) + return self.anchors[anchor] + event = self.peek_event() + anchor = event.anchor + if anchor is not None: + if anchor in self.anchors: + raise ComposerError("found duplicate anchor %r; first occurrence" + % anchor, self.anchors[anchor].start_mark, + "second occurrence", event.start_mark) + self.descend_resolver(parent, index) + if self.check_event(ScalarEvent): + node = self.compose_scalar_node(anchor) + elif self.check_event(SequenceStartEvent): + node = self.compose_sequence_node(anchor) + elif self.check_event(MappingStartEvent): + node = self.compose_mapping_node(anchor) + self.ascend_resolver() + return node + + def compose_scalar_node(self, anchor): + event = self.get_event() + tag = event.tag + if tag is None or tag == '!': + tag = self.resolve(ScalarNode, event.value, event.implicit) + node = ScalarNode(tag, event.value, + event.start_mark, event.end_mark, style=event.style) + if anchor is not None: + self.anchors[anchor] = node + return node + + def compose_sequence_node(self, anchor): + start_event = self.get_event() + tag = start_event.tag + if tag is None or tag == '!': + tag = self.resolve(SequenceNode, None, start_event.implicit) + node = SequenceNode(tag, [], + start_event.start_mark, None, + flow_style=start_event.flow_style) + if anchor is not None: + self.anchors[anchor] = node + index = 0 + while not self.check_event(SequenceEndEvent): + node.value.append(self.compose_node(node, index)) + index += 1 + end_event = self.get_event() + node.end_mark = end_event.end_mark + return node + + def compose_mapping_node(self, anchor): + start_event = self.get_event() + tag = start_event.tag + if tag is None or tag == '!': + tag = self.resolve(MappingNode, None, start_event.implicit) + node = MappingNode(tag, [], + start_event.start_mark, None, + flow_style=start_event.flow_style) + if anchor is not None: + self.anchors[anchor] = node + while not self.check_event(MappingEndEvent): + #key_event = self.peek_event() + item_key = self.compose_node(node, None) + #if item_key in node.value: + # raise ComposerError("while composing a mapping", start_event.start_mark, + # "found duplicate key", key_event.start_mark) + item_value = self.compose_node(node, item_key) + #node.value[item_key] = item_value + node.value.append((item_key, item_value)) + end_event = self.get_event() + node.end_mark = end_event.end_mark + return node + diff --git a/.venv/lib/python3.12/site-packages/yaml/constructor.py b/.venv/lib/python3.12/site-packages/yaml/constructor.py new file mode 100644 index 0000000000000000000000000000000000000000..619acd3070a4845c653fcf22a626e05158035bc2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/constructor.py @@ -0,0 +1,748 @@ + +__all__ = [ + 'BaseConstructor', + 'SafeConstructor', + 'FullConstructor', + 'UnsafeConstructor', + 'Constructor', + 'ConstructorError' +] + +from .error import * +from .nodes import * + +import collections.abc, datetime, base64, binascii, re, sys, types + +class ConstructorError(MarkedYAMLError): + pass + +class BaseConstructor: + + yaml_constructors = {} + yaml_multi_constructors = {} + + def __init__(self): + self.constructed_objects = {} + self.recursive_objects = {} + self.state_generators = [] + self.deep_construct = False + + def check_data(self): + # If there are more documents available? + return self.check_node() + + def check_state_key(self, key): + """Block special attributes/methods from being set in a newly created + object, to prevent user-controlled methods from being called during + deserialization""" + if self.get_state_keys_blacklist_regexp().match(key): + raise ConstructorError(None, None, + "blacklisted key '%s' in instance state found" % (key,), None) + + def get_data(self): + # Construct and return the next document. + if self.check_node(): + return self.construct_document(self.get_node()) + + def get_single_data(self): + # Ensure that the stream contains a single document and construct it. + node = self.get_single_node() + if node is not None: + return self.construct_document(node) + return None + + def construct_document(self, node): + data = self.construct_object(node) + while self.state_generators: + state_generators = self.state_generators + self.state_generators = [] + for generator in state_generators: + for dummy in generator: + pass + self.constructed_objects = {} + self.recursive_objects = {} + self.deep_construct = False + return data + + def construct_object(self, node, deep=False): + if node in self.constructed_objects: + return self.constructed_objects[node] + if deep: + old_deep = self.deep_construct + self.deep_construct = True + if node in self.recursive_objects: + raise ConstructorError(None, None, + "found unconstructable recursive node", node.start_mark) + self.recursive_objects[node] = None + constructor = None + tag_suffix = None + if node.tag in self.yaml_constructors: + constructor = self.yaml_constructors[node.tag] + else: + for tag_prefix in self.yaml_multi_constructors: + if tag_prefix is not None and node.tag.startswith(tag_prefix): + tag_suffix = node.tag[len(tag_prefix):] + constructor = self.yaml_multi_constructors[tag_prefix] + break + else: + if None in self.yaml_multi_constructors: + tag_suffix = node.tag + constructor = self.yaml_multi_constructors[None] + elif None in self.yaml_constructors: + constructor = self.yaml_constructors[None] + elif isinstance(node, ScalarNode): + constructor = self.__class__.construct_scalar + elif isinstance(node, SequenceNode): + constructor = self.__class__.construct_sequence + elif isinstance(node, MappingNode): + constructor = self.__class__.construct_mapping + if tag_suffix is None: + data = constructor(self, node) + else: + data = constructor(self, tag_suffix, node) + if isinstance(data, types.GeneratorType): + generator = data + data = next(generator) + if self.deep_construct: + for dummy in generator: + pass + else: + self.state_generators.append(generator) + self.constructed_objects[node] = data + del self.recursive_objects[node] + if deep: + self.deep_construct = old_deep + return data + + def construct_scalar(self, node): + if not isinstance(node, ScalarNode): + raise ConstructorError(None, None, + "expected a scalar node, but found %s" % node.id, + node.start_mark) + return node.value + + def construct_sequence(self, node, deep=False): + if not isinstance(node, SequenceNode): + raise ConstructorError(None, None, + "expected a sequence node, but found %s" % node.id, + node.start_mark) + return [self.construct_object(child, deep=deep) + for child in node.value] + + def construct_mapping(self, node, deep=False): + if not isinstance(node, MappingNode): + raise ConstructorError(None, None, + "expected a mapping node, but found %s" % node.id, + node.start_mark) + mapping = {} + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) + if not isinstance(key, collections.abc.Hashable): + raise ConstructorError("while constructing a mapping", node.start_mark, + "found unhashable key", key_node.start_mark) + value = self.construct_object(value_node, deep=deep) + mapping[key] = value + return mapping + + def construct_pairs(self, node, deep=False): + if not isinstance(node, MappingNode): + raise ConstructorError(None, None, + "expected a mapping node, but found %s" % node.id, + node.start_mark) + pairs = [] + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) + value = self.construct_object(value_node, deep=deep) + pairs.append((key, value)) + return pairs + + @classmethod + def add_constructor(cls, tag, constructor): + if not 'yaml_constructors' in cls.__dict__: + cls.yaml_constructors = cls.yaml_constructors.copy() + cls.yaml_constructors[tag] = constructor + + @classmethod + def add_multi_constructor(cls, tag_prefix, multi_constructor): + if not 'yaml_multi_constructors' in cls.__dict__: + cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy() + cls.yaml_multi_constructors[tag_prefix] = multi_constructor + +class SafeConstructor(BaseConstructor): + + def construct_scalar(self, node): + if isinstance(node, MappingNode): + for key_node, value_node in node.value: + if key_node.tag == 'tag:yaml.org,2002:value': + return self.construct_scalar(value_node) + return super().construct_scalar(node) + + def flatten_mapping(self, node): + merge = [] + index = 0 + while index < len(node.value): + key_node, value_node = node.value[index] + if key_node.tag == 'tag:yaml.org,2002:merge': + del node.value[index] + if isinstance(value_node, MappingNode): + self.flatten_mapping(value_node) + merge.extend(value_node.value) + elif isinstance(value_node, SequenceNode): + submerge = [] + for subnode in value_node.value: + if not isinstance(subnode, MappingNode): + raise ConstructorError("while constructing a mapping", + node.start_mark, + "expected a mapping for merging, but found %s" + % subnode.id, subnode.start_mark) + self.flatten_mapping(subnode) + submerge.append(subnode.value) + submerge.reverse() + for value in submerge: + merge.extend(value) + else: + raise ConstructorError("while constructing a mapping", node.start_mark, + "expected a mapping or list of mappings for merging, but found %s" + % value_node.id, value_node.start_mark) + elif key_node.tag == 'tag:yaml.org,2002:value': + key_node.tag = 'tag:yaml.org,2002:str' + index += 1 + else: + index += 1 + if merge: + node.value = merge + node.value + + def construct_mapping(self, node, deep=False): + if isinstance(node, MappingNode): + self.flatten_mapping(node) + return super().construct_mapping(node, deep=deep) + + def construct_yaml_null(self, node): + self.construct_scalar(node) + return None + + bool_values = { + 'yes': True, + 'no': False, + 'true': True, + 'false': False, + 'on': True, + 'off': False, + } + + def construct_yaml_bool(self, node): + value = self.construct_scalar(node) + return self.bool_values[value.lower()] + + def construct_yaml_int(self, node): + value = self.construct_scalar(node) + value = value.replace('_', '') + sign = +1 + if value[0] == '-': + sign = -1 + if value[0] in '+-': + value = value[1:] + if value == '0': + return 0 + elif value.startswith('0b'): + return sign*int(value[2:], 2) + elif value.startswith('0x'): + return sign*int(value[2:], 16) + elif value[0] == '0': + return sign*int(value, 8) + elif ':' in value: + digits = [int(part) for part in value.split(':')] + digits.reverse() + base = 1 + value = 0 + for digit in digits: + value += digit*base + base *= 60 + return sign*value + else: + return sign*int(value) + + inf_value = 1e300 + while inf_value != inf_value*inf_value: + inf_value *= inf_value + nan_value = -inf_value/inf_value # Trying to make a quiet NaN (like C99). + + def construct_yaml_float(self, node): + value = self.construct_scalar(node) + value = value.replace('_', '').lower() + sign = +1 + if value[0] == '-': + sign = -1 + if value[0] in '+-': + value = value[1:] + if value == '.inf': + return sign*self.inf_value + elif value == '.nan': + return self.nan_value + elif ':' in value: + digits = [float(part) for part in value.split(':')] + digits.reverse() + base = 1 + value = 0.0 + for digit in digits: + value += digit*base + base *= 60 + return sign*value + else: + return sign*float(value) + + def construct_yaml_binary(self, node): + try: + value = self.construct_scalar(node).encode('ascii') + except UnicodeEncodeError as exc: + raise ConstructorError(None, None, + "failed to convert base64 data into ascii: %s" % exc, + node.start_mark) + try: + if hasattr(base64, 'decodebytes'): + return base64.decodebytes(value) + else: + return base64.decodestring(value) + except binascii.Error as exc: + raise ConstructorError(None, None, + "failed to decode base64 data: %s" % exc, node.start_mark) + + timestamp_regexp = re.compile( + r'''^(?P[0-9][0-9][0-9][0-9]) + -(?P[0-9][0-9]?) + -(?P[0-9][0-9]?) + (?:(?:[Tt]|[ \t]+) + (?P[0-9][0-9]?) + :(?P[0-9][0-9]) + :(?P[0-9][0-9]) + (?:\.(?P[0-9]*))? + (?:[ \t]*(?PZ|(?P[-+])(?P[0-9][0-9]?) + (?::(?P[0-9][0-9]))?))?)?$''', re.X) + + def construct_yaml_timestamp(self, node): + value = self.construct_scalar(node) + match = self.timestamp_regexp.match(node.value) + values = match.groupdict() + year = int(values['year']) + month = int(values['month']) + day = int(values['day']) + if not values['hour']: + return datetime.date(year, month, day) + hour = int(values['hour']) + minute = int(values['minute']) + second = int(values['second']) + fraction = 0 + tzinfo = None + if values['fraction']: + fraction = values['fraction'][:6] + while len(fraction) < 6: + fraction += '0' + fraction = int(fraction) + if values['tz_sign']: + tz_hour = int(values['tz_hour']) + tz_minute = int(values['tz_minute'] or 0) + delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute) + if values['tz_sign'] == '-': + delta = -delta + tzinfo = datetime.timezone(delta) + elif values['tz']: + tzinfo = datetime.timezone.utc + return datetime.datetime(year, month, day, hour, minute, second, fraction, + tzinfo=tzinfo) + + def construct_yaml_omap(self, node): + # Note: we do not check for duplicate keys, because it's too + # CPU-expensive. + omap = [] + yield omap + if not isinstance(node, SequenceNode): + raise ConstructorError("while constructing an ordered map", node.start_mark, + "expected a sequence, but found %s" % node.id, node.start_mark) + for subnode in node.value: + if not isinstance(subnode, MappingNode): + raise ConstructorError("while constructing an ordered map", node.start_mark, + "expected a mapping of length 1, but found %s" % subnode.id, + subnode.start_mark) + if len(subnode.value) != 1: + raise ConstructorError("while constructing an ordered map", node.start_mark, + "expected a single mapping item, but found %d items" % len(subnode.value), + subnode.start_mark) + key_node, value_node = subnode.value[0] + key = self.construct_object(key_node) + value = self.construct_object(value_node) + omap.append((key, value)) + + def construct_yaml_pairs(self, node): + # Note: the same code as `construct_yaml_omap`. + pairs = [] + yield pairs + if not isinstance(node, SequenceNode): + raise ConstructorError("while constructing pairs", node.start_mark, + "expected a sequence, but found %s" % node.id, node.start_mark) + for subnode in node.value: + if not isinstance(subnode, MappingNode): + raise ConstructorError("while constructing pairs", node.start_mark, + "expected a mapping of length 1, but found %s" % subnode.id, + subnode.start_mark) + if len(subnode.value) != 1: + raise ConstructorError("while constructing pairs", node.start_mark, + "expected a single mapping item, but found %d items" % len(subnode.value), + subnode.start_mark) + key_node, value_node = subnode.value[0] + key = self.construct_object(key_node) + value = self.construct_object(value_node) + pairs.append((key, value)) + + def construct_yaml_set(self, node): + data = set() + yield data + value = self.construct_mapping(node) + data.update(value) + + def construct_yaml_str(self, node): + return self.construct_scalar(node) + + def construct_yaml_seq(self, node): + data = [] + yield data + data.extend(self.construct_sequence(node)) + + def construct_yaml_map(self, node): + data = {} + yield data + value = self.construct_mapping(node) + data.update(value) + + def construct_yaml_object(self, node, cls): + data = cls.__new__(cls) + yield data + if hasattr(data, '__setstate__'): + state = self.construct_mapping(node, deep=True) + data.__setstate__(state) + else: + state = self.construct_mapping(node) + data.__dict__.update(state) + + def construct_undefined(self, node): + raise ConstructorError(None, None, + "could not determine a constructor for the tag %r" % node.tag, + node.start_mark) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:null', + SafeConstructor.construct_yaml_null) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:bool', + SafeConstructor.construct_yaml_bool) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:int', + SafeConstructor.construct_yaml_int) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:float', + SafeConstructor.construct_yaml_float) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:binary', + SafeConstructor.construct_yaml_binary) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:timestamp', + SafeConstructor.construct_yaml_timestamp) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:omap', + SafeConstructor.construct_yaml_omap) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:pairs', + SafeConstructor.construct_yaml_pairs) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:set', + SafeConstructor.construct_yaml_set) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:str', + SafeConstructor.construct_yaml_str) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:seq', + SafeConstructor.construct_yaml_seq) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:map', + SafeConstructor.construct_yaml_map) + +SafeConstructor.add_constructor(None, + SafeConstructor.construct_undefined) + +class FullConstructor(SafeConstructor): + # 'extend' is blacklisted because it is used by + # construct_python_object_apply to add `listitems` to a newly generate + # python instance + def get_state_keys_blacklist(self): + return ['^extend$', '^__.*__$'] + + def get_state_keys_blacklist_regexp(self): + if not hasattr(self, 'state_keys_blacklist_regexp'): + self.state_keys_blacklist_regexp = re.compile('(' + '|'.join(self.get_state_keys_blacklist()) + ')') + return self.state_keys_blacklist_regexp + + def construct_python_str(self, node): + return self.construct_scalar(node) + + def construct_python_unicode(self, node): + return self.construct_scalar(node) + + def construct_python_bytes(self, node): + try: + value = self.construct_scalar(node).encode('ascii') + except UnicodeEncodeError as exc: + raise ConstructorError(None, None, + "failed to convert base64 data into ascii: %s" % exc, + node.start_mark) + try: + if hasattr(base64, 'decodebytes'): + return base64.decodebytes(value) + else: + return base64.decodestring(value) + except binascii.Error as exc: + raise ConstructorError(None, None, + "failed to decode base64 data: %s" % exc, node.start_mark) + + def construct_python_long(self, node): + return self.construct_yaml_int(node) + + def construct_python_complex(self, node): + return complex(self.construct_scalar(node)) + + def construct_python_tuple(self, node): + return tuple(self.construct_sequence(node)) + + def find_python_module(self, name, mark, unsafe=False): + if not name: + raise ConstructorError("while constructing a Python module", mark, + "expected non-empty name appended to the tag", mark) + if unsafe: + try: + __import__(name) + except ImportError as exc: + raise ConstructorError("while constructing a Python module", mark, + "cannot find module %r (%s)" % (name, exc), mark) + if name not in sys.modules: + raise ConstructorError("while constructing a Python module", mark, + "module %r is not imported" % name, mark) + return sys.modules[name] + + def find_python_name(self, name, mark, unsafe=False): + if not name: + raise ConstructorError("while constructing a Python object", mark, + "expected non-empty name appended to the tag", mark) + if '.' in name: + module_name, object_name = name.rsplit('.', 1) + else: + module_name = 'builtins' + object_name = name + if unsafe: + try: + __import__(module_name) + except ImportError as exc: + raise ConstructorError("while constructing a Python object", mark, + "cannot find module %r (%s)" % (module_name, exc), mark) + if module_name not in sys.modules: + raise ConstructorError("while constructing a Python object", mark, + "module %r is not imported" % module_name, mark) + module = sys.modules[module_name] + if not hasattr(module, object_name): + raise ConstructorError("while constructing a Python object", mark, + "cannot find %r in the module %r" + % (object_name, module.__name__), mark) + return getattr(module, object_name) + + def construct_python_name(self, suffix, node): + value = self.construct_scalar(node) + if value: + raise ConstructorError("while constructing a Python name", node.start_mark, + "expected the empty value, but found %r" % value, node.start_mark) + return self.find_python_name(suffix, node.start_mark) + + def construct_python_module(self, suffix, node): + value = self.construct_scalar(node) + if value: + raise ConstructorError("while constructing a Python module", node.start_mark, + "expected the empty value, but found %r" % value, node.start_mark) + return self.find_python_module(suffix, node.start_mark) + + def make_python_instance(self, suffix, node, + args=None, kwds=None, newobj=False, unsafe=False): + if not args: + args = [] + if not kwds: + kwds = {} + cls = self.find_python_name(suffix, node.start_mark) + if not (unsafe or isinstance(cls, type)): + raise ConstructorError("while constructing a Python instance", node.start_mark, + "expected a class, but found %r" % type(cls), + node.start_mark) + if newobj and isinstance(cls, type): + return cls.__new__(cls, *args, **kwds) + else: + return cls(*args, **kwds) + + def set_python_instance_state(self, instance, state, unsafe=False): + if hasattr(instance, '__setstate__'): + instance.__setstate__(state) + else: + slotstate = {} + if isinstance(state, tuple) and len(state) == 2: + state, slotstate = state + if hasattr(instance, '__dict__'): + if not unsafe and state: + for key in state.keys(): + self.check_state_key(key) + instance.__dict__.update(state) + elif state: + slotstate.update(state) + for key, value in slotstate.items(): + if not unsafe: + self.check_state_key(key) + setattr(instance, key, value) + + def construct_python_object(self, suffix, node): + # Format: + # !!python/object:module.name { ... state ... } + instance = self.make_python_instance(suffix, node, newobj=True) + yield instance + deep = hasattr(instance, '__setstate__') + state = self.construct_mapping(node, deep=deep) + self.set_python_instance_state(instance, state) + + def construct_python_object_apply(self, suffix, node, newobj=False): + # Format: + # !!python/object/apply # (or !!python/object/new) + # args: [ ... arguments ... ] + # kwds: { ... keywords ... } + # state: ... state ... + # listitems: [ ... listitems ... ] + # dictitems: { ... dictitems ... } + # or short format: + # !!python/object/apply [ ... arguments ... ] + # The difference between !!python/object/apply and !!python/object/new + # is how an object is created, check make_python_instance for details. + if isinstance(node, SequenceNode): + args = self.construct_sequence(node, deep=True) + kwds = {} + state = {} + listitems = [] + dictitems = {} + else: + value = self.construct_mapping(node, deep=True) + args = value.get('args', []) + kwds = value.get('kwds', {}) + state = value.get('state', {}) + listitems = value.get('listitems', []) + dictitems = value.get('dictitems', {}) + instance = self.make_python_instance(suffix, node, args, kwds, newobj) + if state: + self.set_python_instance_state(instance, state) + if listitems: + instance.extend(listitems) + if dictitems: + for key in dictitems: + instance[key] = dictitems[key] + return instance + + def construct_python_object_new(self, suffix, node): + return self.construct_python_object_apply(suffix, node, newobj=True) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/none', + FullConstructor.construct_yaml_null) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/bool', + FullConstructor.construct_yaml_bool) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/str', + FullConstructor.construct_python_str) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/unicode', + FullConstructor.construct_python_unicode) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/bytes', + FullConstructor.construct_python_bytes) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/int', + FullConstructor.construct_yaml_int) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/long', + FullConstructor.construct_python_long) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/float', + FullConstructor.construct_yaml_float) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/complex', + FullConstructor.construct_python_complex) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/list', + FullConstructor.construct_yaml_seq) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/tuple', + FullConstructor.construct_python_tuple) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/dict', + FullConstructor.construct_yaml_map) + +FullConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/name:', + FullConstructor.construct_python_name) + +class UnsafeConstructor(FullConstructor): + + def find_python_module(self, name, mark): + return super(UnsafeConstructor, self).find_python_module(name, mark, unsafe=True) + + def find_python_name(self, name, mark): + return super(UnsafeConstructor, self).find_python_name(name, mark, unsafe=True) + + def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False): + return super(UnsafeConstructor, self).make_python_instance( + suffix, node, args, kwds, newobj, unsafe=True) + + def set_python_instance_state(self, instance, state): + return super(UnsafeConstructor, self).set_python_instance_state( + instance, state, unsafe=True) + +UnsafeConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/module:', + UnsafeConstructor.construct_python_module) + +UnsafeConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/object:', + UnsafeConstructor.construct_python_object) + +UnsafeConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/object/new:', + UnsafeConstructor.construct_python_object_new) + +UnsafeConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/object/apply:', + UnsafeConstructor.construct_python_object_apply) + +# Constructor is same as UnsafeConstructor. Need to leave this in place in case +# people have extended it directly. +class Constructor(UnsafeConstructor): + pass diff --git a/.venv/lib/python3.12/site-packages/yaml/cyaml.py b/.venv/lib/python3.12/site-packages/yaml/cyaml.py new file mode 100644 index 0000000000000000000000000000000000000000..0c21345879b298bb8668201bebe7d289586b17f9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/cyaml.py @@ -0,0 +1,101 @@ + +__all__ = [ + 'CBaseLoader', 'CSafeLoader', 'CFullLoader', 'CUnsafeLoader', 'CLoader', + 'CBaseDumper', 'CSafeDumper', 'CDumper' +] + +from yaml._yaml import CParser, CEmitter + +from .constructor import * + +from .serializer import * +from .representer import * + +from .resolver import * + +class CBaseLoader(CParser, BaseConstructor, BaseResolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + BaseConstructor.__init__(self) + BaseResolver.__init__(self) + +class CSafeLoader(CParser, SafeConstructor, Resolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + SafeConstructor.__init__(self) + Resolver.__init__(self) + +class CFullLoader(CParser, FullConstructor, Resolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + FullConstructor.__init__(self) + Resolver.__init__(self) + +class CUnsafeLoader(CParser, UnsafeConstructor, Resolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + UnsafeConstructor.__init__(self) + Resolver.__init__(self) + +class CLoader(CParser, Constructor, Resolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + Constructor.__init__(self) + Resolver.__init__(self) + +class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + CEmitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, encoding=encoding, + allow_unicode=allow_unicode, line_break=line_break, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + Representer.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + +class CSafeDumper(CEmitter, SafeRepresenter, Resolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + CEmitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, encoding=encoding, + allow_unicode=allow_unicode, line_break=line_break, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + SafeRepresenter.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + +class CDumper(CEmitter, Serializer, Representer, Resolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + CEmitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, encoding=encoding, + allow_unicode=allow_unicode, line_break=line_break, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + Representer.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + diff --git a/.venv/lib/python3.12/site-packages/yaml/dumper.py b/.venv/lib/python3.12/site-packages/yaml/dumper.py new file mode 100644 index 0000000000000000000000000000000000000000..6aadba551f3836b02f4752277f4b3027073defad --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/dumper.py @@ -0,0 +1,62 @@ + +__all__ = ['BaseDumper', 'SafeDumper', 'Dumper'] + +from .emitter import * +from .serializer import * +from .representer import * +from .resolver import * + +class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + Emitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break) + Serializer.__init__(self, encoding=encoding, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + Representer.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + +class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + Emitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break) + Serializer.__init__(self, encoding=encoding, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + SafeRepresenter.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + +class Dumper(Emitter, Serializer, Representer, Resolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + Emitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break) + Serializer.__init__(self, encoding=encoding, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + Representer.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + diff --git a/.venv/lib/python3.12/site-packages/yaml/emitter.py b/.venv/lib/python3.12/site-packages/yaml/emitter.py new file mode 100644 index 0000000000000000000000000000000000000000..a664d011162af69184df2f8e59ab7feec818f7c7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/emitter.py @@ -0,0 +1,1137 @@ + +# Emitter expects events obeying the following grammar: +# stream ::= STREAM-START document* STREAM-END +# document ::= DOCUMENT-START node DOCUMENT-END +# node ::= SCALAR | sequence | mapping +# sequence ::= SEQUENCE-START node* SEQUENCE-END +# mapping ::= MAPPING-START (node node)* MAPPING-END + +__all__ = ['Emitter', 'EmitterError'] + +from .error import YAMLError +from .events import * + +class EmitterError(YAMLError): + pass + +class ScalarAnalysis: + def __init__(self, scalar, empty, multiline, + allow_flow_plain, allow_block_plain, + allow_single_quoted, allow_double_quoted, + allow_block): + self.scalar = scalar + self.empty = empty + self.multiline = multiline + self.allow_flow_plain = allow_flow_plain + self.allow_block_plain = allow_block_plain + self.allow_single_quoted = allow_single_quoted + self.allow_double_quoted = allow_double_quoted + self.allow_block = allow_block + +class Emitter: + + DEFAULT_TAG_PREFIXES = { + '!' : '!', + 'tag:yaml.org,2002:' : '!!', + } + + def __init__(self, stream, canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None): + + # The stream should have the methods `write` and possibly `flush`. + self.stream = stream + + # Encoding can be overridden by STREAM-START. + self.encoding = None + + # Emitter is a state machine with a stack of states to handle nested + # structures. + self.states = [] + self.state = self.expect_stream_start + + # Current event and the event queue. + self.events = [] + self.event = None + + # The current indentation level and the stack of previous indents. + self.indents = [] + self.indent = None + + # Flow level. + self.flow_level = 0 + + # Contexts. + self.root_context = False + self.sequence_context = False + self.mapping_context = False + self.simple_key_context = False + + # Characteristics of the last emitted character: + # - current position. + # - is it a whitespace? + # - is it an indention character + # (indentation space, '-', '?', or ':')? + self.line = 0 + self.column = 0 + self.whitespace = True + self.indention = True + + # Whether the document requires an explicit document indicator + self.open_ended = False + + # Formatting details. + self.canonical = canonical + self.allow_unicode = allow_unicode + self.best_indent = 2 + if indent and 1 < indent < 10: + self.best_indent = indent + self.best_width = 80 + if width and width > self.best_indent*2: + self.best_width = width + self.best_line_break = '\n' + if line_break in ['\r', '\n', '\r\n']: + self.best_line_break = line_break + + # Tag prefixes. + self.tag_prefixes = None + + # Prepared anchor and tag. + self.prepared_anchor = None + self.prepared_tag = None + + # Scalar analysis and style. + self.analysis = None + self.style = None + + def dispose(self): + # Reset the state attributes (to clear self-references) + self.states = [] + self.state = None + + def emit(self, event): + self.events.append(event) + while not self.need_more_events(): + self.event = self.events.pop(0) + self.state() + self.event = None + + # In some cases, we wait for a few next events before emitting. + + def need_more_events(self): + if not self.events: + return True + event = self.events[0] + if isinstance(event, DocumentStartEvent): + return self.need_events(1) + elif isinstance(event, SequenceStartEvent): + return self.need_events(2) + elif isinstance(event, MappingStartEvent): + return self.need_events(3) + else: + return False + + def need_events(self, count): + level = 0 + for event in self.events[1:]: + if isinstance(event, (DocumentStartEvent, CollectionStartEvent)): + level += 1 + elif isinstance(event, (DocumentEndEvent, CollectionEndEvent)): + level -= 1 + elif isinstance(event, StreamEndEvent): + level = -1 + if level < 0: + return False + return (len(self.events) < count+1) + + def increase_indent(self, flow=False, indentless=False): + self.indents.append(self.indent) + if self.indent is None: + if flow: + self.indent = self.best_indent + else: + self.indent = 0 + elif not indentless: + self.indent += self.best_indent + + # States. + + # Stream handlers. + + def expect_stream_start(self): + if isinstance(self.event, StreamStartEvent): + if self.event.encoding and not hasattr(self.stream, 'encoding'): + self.encoding = self.event.encoding + self.write_stream_start() + self.state = self.expect_first_document_start + else: + raise EmitterError("expected StreamStartEvent, but got %s" + % self.event) + + def expect_nothing(self): + raise EmitterError("expected nothing, but got %s" % self.event) + + # Document handlers. + + def expect_first_document_start(self): + return self.expect_document_start(first=True) + + def expect_document_start(self, first=False): + if isinstance(self.event, DocumentStartEvent): + if (self.event.version or self.event.tags) and self.open_ended: + self.write_indicator('...', True) + self.write_indent() + if self.event.version: + version_text = self.prepare_version(self.event.version) + self.write_version_directive(version_text) + self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy() + if self.event.tags: + handles = sorted(self.event.tags.keys()) + for handle in handles: + prefix = self.event.tags[handle] + self.tag_prefixes[prefix] = handle + handle_text = self.prepare_tag_handle(handle) + prefix_text = self.prepare_tag_prefix(prefix) + self.write_tag_directive(handle_text, prefix_text) + implicit = (first and not self.event.explicit and not self.canonical + and not self.event.version and not self.event.tags + and not self.check_empty_document()) + if not implicit: + self.write_indent() + self.write_indicator('---', True) + if self.canonical: + self.write_indent() + self.state = self.expect_document_root + elif isinstance(self.event, StreamEndEvent): + if self.open_ended: + self.write_indicator('...', True) + self.write_indent() + self.write_stream_end() + self.state = self.expect_nothing + else: + raise EmitterError("expected DocumentStartEvent, but got %s" + % self.event) + + def expect_document_end(self): + if isinstance(self.event, DocumentEndEvent): + self.write_indent() + if self.event.explicit: + self.write_indicator('...', True) + self.write_indent() + self.flush_stream() + self.state = self.expect_document_start + else: + raise EmitterError("expected DocumentEndEvent, but got %s" + % self.event) + + def expect_document_root(self): + self.states.append(self.expect_document_end) + self.expect_node(root=True) + + # Node handlers. + + def expect_node(self, root=False, sequence=False, mapping=False, + simple_key=False): + self.root_context = root + self.sequence_context = sequence + self.mapping_context = mapping + self.simple_key_context = simple_key + if isinstance(self.event, AliasEvent): + self.expect_alias() + elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)): + self.process_anchor('&') + self.process_tag() + if isinstance(self.event, ScalarEvent): + self.expect_scalar() + elif isinstance(self.event, SequenceStartEvent): + if self.flow_level or self.canonical or self.event.flow_style \ + or self.check_empty_sequence(): + self.expect_flow_sequence() + else: + self.expect_block_sequence() + elif isinstance(self.event, MappingStartEvent): + if self.flow_level or self.canonical or self.event.flow_style \ + or self.check_empty_mapping(): + self.expect_flow_mapping() + else: + self.expect_block_mapping() + else: + raise EmitterError("expected NodeEvent, but got %s" % self.event) + + def expect_alias(self): + if self.event.anchor is None: + raise EmitterError("anchor is not specified for alias") + self.process_anchor('*') + self.state = self.states.pop() + + def expect_scalar(self): + self.increase_indent(flow=True) + self.process_scalar() + self.indent = self.indents.pop() + self.state = self.states.pop() + + # Flow sequence handlers. + + def expect_flow_sequence(self): + self.write_indicator('[', True, whitespace=True) + self.flow_level += 1 + self.increase_indent(flow=True) + self.state = self.expect_first_flow_sequence_item + + def expect_first_flow_sequence_item(self): + if isinstance(self.event, SequenceEndEvent): + self.indent = self.indents.pop() + self.flow_level -= 1 + self.write_indicator(']', False) + self.state = self.states.pop() + else: + if self.canonical or self.column > self.best_width: + self.write_indent() + self.states.append(self.expect_flow_sequence_item) + self.expect_node(sequence=True) + + def expect_flow_sequence_item(self): + if isinstance(self.event, SequenceEndEvent): + self.indent = self.indents.pop() + self.flow_level -= 1 + if self.canonical: + self.write_indicator(',', False) + self.write_indent() + self.write_indicator(']', False) + self.state = self.states.pop() + else: + self.write_indicator(',', False) + if self.canonical or self.column > self.best_width: + self.write_indent() + self.states.append(self.expect_flow_sequence_item) + self.expect_node(sequence=True) + + # Flow mapping handlers. + + def expect_flow_mapping(self): + self.write_indicator('{', True, whitespace=True) + self.flow_level += 1 + self.increase_indent(flow=True) + self.state = self.expect_first_flow_mapping_key + + def expect_first_flow_mapping_key(self): + if isinstance(self.event, MappingEndEvent): + self.indent = self.indents.pop() + self.flow_level -= 1 + self.write_indicator('}', False) + self.state = self.states.pop() + else: + if self.canonical or self.column > self.best_width: + self.write_indent() + if not self.canonical and self.check_simple_key(): + self.states.append(self.expect_flow_mapping_simple_value) + self.expect_node(mapping=True, simple_key=True) + else: + self.write_indicator('?', True) + self.states.append(self.expect_flow_mapping_value) + self.expect_node(mapping=True) + + def expect_flow_mapping_key(self): + if isinstance(self.event, MappingEndEvent): + self.indent = self.indents.pop() + self.flow_level -= 1 + if self.canonical: + self.write_indicator(',', False) + self.write_indent() + self.write_indicator('}', False) + self.state = self.states.pop() + else: + self.write_indicator(',', False) + if self.canonical or self.column > self.best_width: + self.write_indent() + if not self.canonical and self.check_simple_key(): + self.states.append(self.expect_flow_mapping_simple_value) + self.expect_node(mapping=True, simple_key=True) + else: + self.write_indicator('?', True) + self.states.append(self.expect_flow_mapping_value) + self.expect_node(mapping=True) + + def expect_flow_mapping_simple_value(self): + self.write_indicator(':', False) + self.states.append(self.expect_flow_mapping_key) + self.expect_node(mapping=True) + + def expect_flow_mapping_value(self): + if self.canonical or self.column > self.best_width: + self.write_indent() + self.write_indicator(':', True) + self.states.append(self.expect_flow_mapping_key) + self.expect_node(mapping=True) + + # Block sequence handlers. + + def expect_block_sequence(self): + indentless = (self.mapping_context and not self.indention) + self.increase_indent(flow=False, indentless=indentless) + self.state = self.expect_first_block_sequence_item + + def expect_first_block_sequence_item(self): + return self.expect_block_sequence_item(first=True) + + def expect_block_sequence_item(self, first=False): + if not first and isinstance(self.event, SequenceEndEvent): + self.indent = self.indents.pop() + self.state = self.states.pop() + else: + self.write_indent() + self.write_indicator('-', True, indention=True) + self.states.append(self.expect_block_sequence_item) + self.expect_node(sequence=True) + + # Block mapping handlers. + + def expect_block_mapping(self): + self.increase_indent(flow=False) + self.state = self.expect_first_block_mapping_key + + def expect_first_block_mapping_key(self): + return self.expect_block_mapping_key(first=True) + + def expect_block_mapping_key(self, first=False): + if not first and isinstance(self.event, MappingEndEvent): + self.indent = self.indents.pop() + self.state = self.states.pop() + else: + self.write_indent() + if self.check_simple_key(): + self.states.append(self.expect_block_mapping_simple_value) + self.expect_node(mapping=True, simple_key=True) + else: + self.write_indicator('?', True, indention=True) + self.states.append(self.expect_block_mapping_value) + self.expect_node(mapping=True) + + def expect_block_mapping_simple_value(self): + self.write_indicator(':', False) + self.states.append(self.expect_block_mapping_key) + self.expect_node(mapping=True) + + def expect_block_mapping_value(self): + self.write_indent() + self.write_indicator(':', True, indention=True) + self.states.append(self.expect_block_mapping_key) + self.expect_node(mapping=True) + + # Checkers. + + def check_empty_sequence(self): + return (isinstance(self.event, SequenceStartEvent) and self.events + and isinstance(self.events[0], SequenceEndEvent)) + + def check_empty_mapping(self): + return (isinstance(self.event, MappingStartEvent) and self.events + and isinstance(self.events[0], MappingEndEvent)) + + def check_empty_document(self): + if not isinstance(self.event, DocumentStartEvent) or not self.events: + return False + event = self.events[0] + return (isinstance(event, ScalarEvent) and event.anchor is None + and event.tag is None and event.implicit and event.value == '') + + def check_simple_key(self): + length = 0 + if isinstance(self.event, NodeEvent) and self.event.anchor is not None: + if self.prepared_anchor is None: + self.prepared_anchor = self.prepare_anchor(self.event.anchor) + length += len(self.prepared_anchor) + if isinstance(self.event, (ScalarEvent, CollectionStartEvent)) \ + and self.event.tag is not None: + if self.prepared_tag is None: + self.prepared_tag = self.prepare_tag(self.event.tag) + length += len(self.prepared_tag) + if isinstance(self.event, ScalarEvent): + if self.analysis is None: + self.analysis = self.analyze_scalar(self.event.value) + length += len(self.analysis.scalar) + return (length < 128 and (isinstance(self.event, AliasEvent) + or (isinstance(self.event, ScalarEvent) + and not self.analysis.empty and not self.analysis.multiline) + or self.check_empty_sequence() or self.check_empty_mapping())) + + # Anchor, Tag, and Scalar processors. + + def process_anchor(self, indicator): + if self.event.anchor is None: + self.prepared_anchor = None + return + if self.prepared_anchor is None: + self.prepared_anchor = self.prepare_anchor(self.event.anchor) + if self.prepared_anchor: + self.write_indicator(indicator+self.prepared_anchor, True) + self.prepared_anchor = None + + def process_tag(self): + tag = self.event.tag + if isinstance(self.event, ScalarEvent): + if self.style is None: + self.style = self.choose_scalar_style() + if ((not self.canonical or tag is None) and + ((self.style == '' and self.event.implicit[0]) + or (self.style != '' and self.event.implicit[1]))): + self.prepared_tag = None + return + if self.event.implicit[0] and tag is None: + tag = '!' + self.prepared_tag = None + else: + if (not self.canonical or tag is None) and self.event.implicit: + self.prepared_tag = None + return + if tag is None: + raise EmitterError("tag is not specified") + if self.prepared_tag is None: + self.prepared_tag = self.prepare_tag(tag) + if self.prepared_tag: + self.write_indicator(self.prepared_tag, True) + self.prepared_tag = None + + def choose_scalar_style(self): + if self.analysis is None: + self.analysis = self.analyze_scalar(self.event.value) + if self.event.style == '"' or self.canonical: + return '"' + if not self.event.style and self.event.implicit[0]: + if (not (self.simple_key_context and + (self.analysis.empty or self.analysis.multiline)) + and (self.flow_level and self.analysis.allow_flow_plain + or (not self.flow_level and self.analysis.allow_block_plain))): + return '' + if self.event.style and self.event.style in '|>': + if (not self.flow_level and not self.simple_key_context + and self.analysis.allow_block): + return self.event.style + if not self.event.style or self.event.style == '\'': + if (self.analysis.allow_single_quoted and + not (self.simple_key_context and self.analysis.multiline)): + return '\'' + return '"' + + def process_scalar(self): + if self.analysis is None: + self.analysis = self.analyze_scalar(self.event.value) + if self.style is None: + self.style = self.choose_scalar_style() + split = (not self.simple_key_context) + #if self.analysis.multiline and split \ + # and (not self.style or self.style in '\'\"'): + # self.write_indent() + if self.style == '"': + self.write_double_quoted(self.analysis.scalar, split) + elif self.style == '\'': + self.write_single_quoted(self.analysis.scalar, split) + elif self.style == '>': + self.write_folded(self.analysis.scalar) + elif self.style == '|': + self.write_literal(self.analysis.scalar) + else: + self.write_plain(self.analysis.scalar, split) + self.analysis = None + self.style = None + + # Analyzers. + + def prepare_version(self, version): + major, minor = version + if major != 1: + raise EmitterError("unsupported YAML version: %d.%d" % (major, minor)) + return '%d.%d' % (major, minor) + + def prepare_tag_handle(self, handle): + if not handle: + raise EmitterError("tag handle must not be empty") + if handle[0] != '!' or handle[-1] != '!': + raise EmitterError("tag handle must start and end with '!': %r" % handle) + for ch in handle[1:-1]: + if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_'): + raise EmitterError("invalid character %r in the tag handle: %r" + % (ch, handle)) + return handle + + def prepare_tag_prefix(self, prefix): + if not prefix: + raise EmitterError("tag prefix must not be empty") + chunks = [] + start = end = 0 + if prefix[0] == '!': + end = 1 + while end < len(prefix): + ch = prefix[end] + if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-;/?!:@&=+$,_.~*\'()[]': + end += 1 + else: + if start < end: + chunks.append(prefix[start:end]) + start = end = end+1 + data = ch.encode('utf-8') + for ch in data: + chunks.append('%%%02X' % ord(ch)) + if start < end: + chunks.append(prefix[start:end]) + return ''.join(chunks) + + def prepare_tag(self, tag): + if not tag: + raise EmitterError("tag must not be empty") + if tag == '!': + return tag + handle = None + suffix = tag + prefixes = sorted(self.tag_prefixes.keys()) + for prefix in prefixes: + if tag.startswith(prefix) \ + and (prefix == '!' or len(prefix) < len(tag)): + handle = self.tag_prefixes[prefix] + suffix = tag[len(prefix):] + chunks = [] + start = end = 0 + while end < len(suffix): + ch = suffix[end] + if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-;/?:@&=+$,_.~*\'()[]' \ + or (ch == '!' and handle != '!'): + end += 1 + else: + if start < end: + chunks.append(suffix[start:end]) + start = end = end+1 + data = ch.encode('utf-8') + for ch in data: + chunks.append('%%%02X' % ch) + if start < end: + chunks.append(suffix[start:end]) + suffix_text = ''.join(chunks) + if handle: + return '%s%s' % (handle, suffix_text) + else: + return '!<%s>' % suffix_text + + def prepare_anchor(self, anchor): + if not anchor: + raise EmitterError("anchor must not be empty") + for ch in anchor: + if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_'): + raise EmitterError("invalid character %r in the anchor: %r" + % (ch, anchor)) + return anchor + + def analyze_scalar(self, scalar): + + # Empty scalar is a special case. + if not scalar: + return ScalarAnalysis(scalar=scalar, empty=True, multiline=False, + allow_flow_plain=False, allow_block_plain=True, + allow_single_quoted=True, allow_double_quoted=True, + allow_block=False) + + # Indicators and special characters. + block_indicators = False + flow_indicators = False + line_breaks = False + special_characters = False + + # Important whitespace combinations. + leading_space = False + leading_break = False + trailing_space = False + trailing_break = False + break_space = False + space_break = False + + # Check document indicators. + if scalar.startswith('---') or scalar.startswith('...'): + block_indicators = True + flow_indicators = True + + # First character or preceded by a whitespace. + preceded_by_whitespace = True + + # Last character or followed by a whitespace. + followed_by_whitespace = (len(scalar) == 1 or + scalar[1] in '\0 \t\r\n\x85\u2028\u2029') + + # The previous character is a space. + previous_space = False + + # The previous character is a break. + previous_break = False + + index = 0 + while index < len(scalar): + ch = scalar[index] + + # Check for indicators. + if index == 0: + # Leading indicators are special characters. + if ch in '#,[]{}&*!|>\'\"%@`': + flow_indicators = True + block_indicators = True + if ch in '?:': + flow_indicators = True + if followed_by_whitespace: + block_indicators = True + if ch == '-' and followed_by_whitespace: + flow_indicators = True + block_indicators = True + else: + # Some indicators cannot appear within a scalar as well. + if ch in ',?[]{}': + flow_indicators = True + if ch == ':': + flow_indicators = True + if followed_by_whitespace: + block_indicators = True + if ch == '#' and preceded_by_whitespace: + flow_indicators = True + block_indicators = True + + # Check for line breaks, special, and unicode characters. + if ch in '\n\x85\u2028\u2029': + line_breaks = True + if not (ch == '\n' or '\x20' <= ch <= '\x7E'): + if (ch == '\x85' or '\xA0' <= ch <= '\uD7FF' + or '\uE000' <= ch <= '\uFFFD' + or '\U00010000' <= ch < '\U0010ffff') and ch != '\uFEFF': + unicode_characters = True + if not self.allow_unicode: + special_characters = True + else: + special_characters = True + + # Detect important whitespace combinations. + if ch == ' ': + if index == 0: + leading_space = True + if index == len(scalar)-1: + trailing_space = True + if previous_break: + break_space = True + previous_space = True + previous_break = False + elif ch in '\n\x85\u2028\u2029': + if index == 0: + leading_break = True + if index == len(scalar)-1: + trailing_break = True + if previous_space: + space_break = True + previous_space = False + previous_break = True + else: + previous_space = False + previous_break = False + + # Prepare for the next character. + index += 1 + preceded_by_whitespace = (ch in '\0 \t\r\n\x85\u2028\u2029') + followed_by_whitespace = (index+1 >= len(scalar) or + scalar[index+1] in '\0 \t\r\n\x85\u2028\u2029') + + # Let's decide what styles are allowed. + allow_flow_plain = True + allow_block_plain = True + allow_single_quoted = True + allow_double_quoted = True + allow_block = True + + # Leading and trailing whitespaces are bad for plain scalars. + if (leading_space or leading_break + or trailing_space or trailing_break): + allow_flow_plain = allow_block_plain = False + + # We do not permit trailing spaces for block scalars. + if trailing_space: + allow_block = False + + # Spaces at the beginning of a new line are only acceptable for block + # scalars. + if break_space: + allow_flow_plain = allow_block_plain = allow_single_quoted = False + + # Spaces followed by breaks, as well as special character are only + # allowed for double quoted scalars. + if space_break or special_characters: + allow_flow_plain = allow_block_plain = \ + allow_single_quoted = allow_block = False + + # Although the plain scalar writer supports breaks, we never emit + # multiline plain scalars. + if line_breaks: + allow_flow_plain = allow_block_plain = False + + # Flow indicators are forbidden for flow plain scalars. + if flow_indicators: + allow_flow_plain = False + + # Block indicators are forbidden for block plain scalars. + if block_indicators: + allow_block_plain = False + + return ScalarAnalysis(scalar=scalar, + empty=False, multiline=line_breaks, + allow_flow_plain=allow_flow_plain, + allow_block_plain=allow_block_plain, + allow_single_quoted=allow_single_quoted, + allow_double_quoted=allow_double_quoted, + allow_block=allow_block) + + # Writers. + + def flush_stream(self): + if hasattr(self.stream, 'flush'): + self.stream.flush() + + def write_stream_start(self): + # Write BOM if needed. + if self.encoding and self.encoding.startswith('utf-16'): + self.stream.write('\uFEFF'.encode(self.encoding)) + + def write_stream_end(self): + self.flush_stream() + + def write_indicator(self, indicator, need_whitespace, + whitespace=False, indention=False): + if self.whitespace or not need_whitespace: + data = indicator + else: + data = ' '+indicator + self.whitespace = whitespace + self.indention = self.indention and indention + self.column += len(data) + self.open_ended = False + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + + def write_indent(self): + indent = self.indent or 0 + if not self.indention or self.column > indent \ + or (self.column == indent and not self.whitespace): + self.write_line_break() + if self.column < indent: + self.whitespace = True + data = ' '*(indent-self.column) + self.column = indent + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + + def write_line_break(self, data=None): + if data is None: + data = self.best_line_break + self.whitespace = True + self.indention = True + self.line += 1 + self.column = 0 + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + + def write_version_directive(self, version_text): + data = '%%YAML %s' % version_text + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + self.write_line_break() + + def write_tag_directive(self, handle_text, prefix_text): + data = '%%TAG %s %s' % (handle_text, prefix_text) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + self.write_line_break() + + # Scalar streams. + + def write_single_quoted(self, text, split=True): + self.write_indicator('\'', True) + spaces = False + breaks = False + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if spaces: + if ch is None or ch != ' ': + if start+1 == end and self.column > self.best_width and split \ + and start != 0 and end != len(text): + self.write_indent() + else: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + elif breaks: + if ch is None or ch not in '\n\x85\u2028\u2029': + if text[start] == '\n': + self.write_line_break() + for br in text[start:end]: + if br == '\n': + self.write_line_break() + else: + self.write_line_break(br) + self.write_indent() + start = end + else: + if ch is None or ch in ' \n\x85\u2028\u2029' or ch == '\'': + if start < end: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + if ch == '\'': + data = '\'\'' + self.column += 2 + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + 1 + if ch is not None: + spaces = (ch == ' ') + breaks = (ch in '\n\x85\u2028\u2029') + end += 1 + self.write_indicator('\'', False) + + ESCAPE_REPLACEMENTS = { + '\0': '0', + '\x07': 'a', + '\x08': 'b', + '\x09': 't', + '\x0A': 'n', + '\x0B': 'v', + '\x0C': 'f', + '\x0D': 'r', + '\x1B': 'e', + '\"': '\"', + '\\': '\\', + '\x85': 'N', + '\xA0': '_', + '\u2028': 'L', + '\u2029': 'P', + } + + def write_double_quoted(self, text, split=True): + self.write_indicator('"', True) + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if ch is None or ch in '"\\\x85\u2028\u2029\uFEFF' \ + or not ('\x20' <= ch <= '\x7E' + or (self.allow_unicode + and ('\xA0' <= ch <= '\uD7FF' + or '\uE000' <= ch <= '\uFFFD'))): + if start < end: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + if ch is not None: + if ch in self.ESCAPE_REPLACEMENTS: + data = '\\'+self.ESCAPE_REPLACEMENTS[ch] + elif ch <= '\xFF': + data = '\\x%02X' % ord(ch) + elif ch <= '\uFFFF': + data = '\\u%04X' % ord(ch) + else: + data = '\\U%08X' % ord(ch) + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end+1 + if 0 < end < len(text)-1 and (ch == ' ' or start >= end) \ + and self.column+(end-start) > self.best_width and split: + data = text[start:end]+'\\' + if start < end: + start = end + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + self.write_indent() + self.whitespace = False + self.indention = False + if text[start] == ' ': + data = '\\' + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + end += 1 + self.write_indicator('"', False) + + def determine_block_hints(self, text): + hints = '' + if text: + if text[0] in ' \n\x85\u2028\u2029': + hints += str(self.best_indent) + if text[-1] not in '\n\x85\u2028\u2029': + hints += '-' + elif len(text) == 1 or text[-2] in '\n\x85\u2028\u2029': + hints += '+' + return hints + + def write_folded(self, text): + hints = self.determine_block_hints(text) + self.write_indicator('>'+hints, True) + if hints[-1:] == '+': + self.open_ended = True + self.write_line_break() + leading_space = True + spaces = False + breaks = True + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if breaks: + if ch is None or ch not in '\n\x85\u2028\u2029': + if not leading_space and ch is not None and ch != ' ' \ + and text[start] == '\n': + self.write_line_break() + leading_space = (ch == ' ') + for br in text[start:end]: + if br == '\n': + self.write_line_break() + else: + self.write_line_break(br) + if ch is not None: + self.write_indent() + start = end + elif spaces: + if ch != ' ': + if start+1 == end and self.column > self.best_width: + self.write_indent() + else: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + else: + if ch is None or ch in ' \n\x85\u2028\u2029': + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + if ch is None: + self.write_line_break() + start = end + if ch is not None: + breaks = (ch in '\n\x85\u2028\u2029') + spaces = (ch == ' ') + end += 1 + + def write_literal(self, text): + hints = self.determine_block_hints(text) + self.write_indicator('|'+hints, True) + if hints[-1:] == '+': + self.open_ended = True + self.write_line_break() + breaks = True + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if breaks: + if ch is None or ch not in '\n\x85\u2028\u2029': + for br in text[start:end]: + if br == '\n': + self.write_line_break() + else: + self.write_line_break(br) + if ch is not None: + self.write_indent() + start = end + else: + if ch is None or ch in '\n\x85\u2028\u2029': + data = text[start:end] + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + if ch is None: + self.write_line_break() + start = end + if ch is not None: + breaks = (ch in '\n\x85\u2028\u2029') + end += 1 + + def write_plain(self, text, split=True): + if self.root_context: + self.open_ended = True + if not text: + return + if not self.whitespace: + data = ' ' + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + self.whitespace = False + self.indention = False + spaces = False + breaks = False + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if spaces: + if ch != ' ': + if start+1 == end and self.column > self.best_width and split: + self.write_indent() + self.whitespace = False + self.indention = False + else: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + elif breaks: + if ch not in '\n\x85\u2028\u2029': + if text[start] == '\n': + self.write_line_break() + for br in text[start:end]: + if br == '\n': + self.write_line_break() + else: + self.write_line_break(br) + self.write_indent() + self.whitespace = False + self.indention = False + start = end + else: + if ch is None or ch in ' \n\x85\u2028\u2029': + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + if ch is not None: + spaces = (ch == ' ') + breaks = (ch in '\n\x85\u2028\u2029') + end += 1 diff --git a/.venv/lib/python3.12/site-packages/yaml/error.py b/.venv/lib/python3.12/site-packages/yaml/error.py new file mode 100644 index 0000000000000000000000000000000000000000..b796b4dc519512c4825ff539a2e6aa20f4d370d0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/error.py @@ -0,0 +1,75 @@ + +__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError'] + +class Mark: + + def __init__(self, name, index, line, column, buffer, pointer): + self.name = name + self.index = index + self.line = line + self.column = column + self.buffer = buffer + self.pointer = pointer + + def get_snippet(self, indent=4, max_length=75): + if self.buffer is None: + return None + head = '' + start = self.pointer + while start > 0 and self.buffer[start-1] not in '\0\r\n\x85\u2028\u2029': + start -= 1 + if self.pointer-start > max_length/2-1: + head = ' ... ' + start += 5 + break + tail = '' + end = self.pointer + while end < len(self.buffer) and self.buffer[end] not in '\0\r\n\x85\u2028\u2029': + end += 1 + if end-self.pointer > max_length/2-1: + tail = ' ... ' + end -= 5 + break + snippet = self.buffer[start:end] + return ' '*indent + head + snippet + tail + '\n' \ + + ' '*(indent+self.pointer-start+len(head)) + '^' + + def __str__(self): + snippet = self.get_snippet() + where = " in \"%s\", line %d, column %d" \ + % (self.name, self.line+1, self.column+1) + if snippet is not None: + where += ":\n"+snippet + return where + +class YAMLError(Exception): + pass + +class MarkedYAMLError(YAMLError): + + def __init__(self, context=None, context_mark=None, + problem=None, problem_mark=None, note=None): + self.context = context + self.context_mark = context_mark + self.problem = problem + self.problem_mark = problem_mark + self.note = note + + def __str__(self): + lines = [] + if self.context is not None: + lines.append(self.context) + if self.context_mark is not None \ + and (self.problem is None or self.problem_mark is None + or self.context_mark.name != self.problem_mark.name + or self.context_mark.line != self.problem_mark.line + or self.context_mark.column != self.problem_mark.column): + lines.append(str(self.context_mark)) + if self.problem is not None: + lines.append(self.problem) + if self.problem_mark is not None: + lines.append(str(self.problem_mark)) + if self.note is not None: + lines.append(self.note) + return '\n'.join(lines) + diff --git a/.venv/lib/python3.12/site-packages/yaml/events.py b/.venv/lib/python3.12/site-packages/yaml/events.py new file mode 100644 index 0000000000000000000000000000000000000000..f79ad389cb6c9517e391dcd25534866bc9ccd36a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/events.py @@ -0,0 +1,86 @@ + +# Abstract classes. + +class Event(object): + def __init__(self, start_mark=None, end_mark=None): + self.start_mark = start_mark + self.end_mark = end_mark + def __repr__(self): + attributes = [key for key in ['anchor', 'tag', 'implicit', 'value'] + if hasattr(self, key)] + arguments = ', '.join(['%s=%r' % (key, getattr(self, key)) + for key in attributes]) + return '%s(%s)' % (self.__class__.__name__, arguments) + +class NodeEvent(Event): + def __init__(self, anchor, start_mark=None, end_mark=None): + self.anchor = anchor + self.start_mark = start_mark + self.end_mark = end_mark + +class CollectionStartEvent(NodeEvent): + def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None, + flow_style=None): + self.anchor = anchor + self.tag = tag + self.implicit = implicit + self.start_mark = start_mark + self.end_mark = end_mark + self.flow_style = flow_style + +class CollectionEndEvent(Event): + pass + +# Implementations. + +class StreamStartEvent(Event): + def __init__(self, start_mark=None, end_mark=None, encoding=None): + self.start_mark = start_mark + self.end_mark = end_mark + self.encoding = encoding + +class StreamEndEvent(Event): + pass + +class DocumentStartEvent(Event): + def __init__(self, start_mark=None, end_mark=None, + explicit=None, version=None, tags=None): + self.start_mark = start_mark + self.end_mark = end_mark + self.explicit = explicit + self.version = version + self.tags = tags + +class DocumentEndEvent(Event): + def __init__(self, start_mark=None, end_mark=None, + explicit=None): + self.start_mark = start_mark + self.end_mark = end_mark + self.explicit = explicit + +class AliasEvent(NodeEvent): + pass + +class ScalarEvent(NodeEvent): + def __init__(self, anchor, tag, implicit, value, + start_mark=None, end_mark=None, style=None): + self.anchor = anchor + self.tag = tag + self.implicit = implicit + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + self.style = style + +class SequenceStartEvent(CollectionStartEvent): + pass + +class SequenceEndEvent(CollectionEndEvent): + pass + +class MappingStartEvent(CollectionStartEvent): + pass + +class MappingEndEvent(CollectionEndEvent): + pass + diff --git a/.venv/lib/python3.12/site-packages/yaml/loader.py b/.venv/lib/python3.12/site-packages/yaml/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..e90c11224c38e559cdf0cb205f0692ebd4fb8681 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/loader.py @@ -0,0 +1,63 @@ + +__all__ = ['BaseLoader', 'FullLoader', 'SafeLoader', 'Loader', 'UnsafeLoader'] + +from .reader import * +from .scanner import * +from .parser import * +from .composer import * +from .constructor import * +from .resolver import * + +class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + BaseConstructor.__init__(self) + BaseResolver.__init__(self) + +class FullLoader(Reader, Scanner, Parser, Composer, FullConstructor, Resolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + FullConstructor.__init__(self) + Resolver.__init__(self) + +class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + SafeConstructor.__init__(self) + Resolver.__init__(self) + +class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + Constructor.__init__(self) + Resolver.__init__(self) + +# UnsafeLoader is the same as Loader (which is and was always unsafe on +# untrusted input). Use of either Loader or UnsafeLoader should be rare, since +# FullLoad should be able to load almost all YAML safely. Loader is left intact +# to ensure backwards compatibility. +class UnsafeLoader(Reader, Scanner, Parser, Composer, Constructor, Resolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + Constructor.__init__(self) + Resolver.__init__(self) diff --git a/.venv/lib/python3.12/site-packages/yaml/nodes.py b/.venv/lib/python3.12/site-packages/yaml/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..c4f070c41e1fb1bc01af27d69329e92dded38908 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/nodes.py @@ -0,0 +1,49 @@ + +class Node(object): + def __init__(self, tag, value, start_mark, end_mark): + self.tag = tag + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + def __repr__(self): + value = self.value + #if isinstance(value, list): + # if len(value) == 0: + # value = '' + # elif len(value) == 1: + # value = '<1 item>' + # else: + # value = '<%d items>' % len(value) + #else: + # if len(value) > 75: + # value = repr(value[:70]+u' ... ') + # else: + # value = repr(value) + value = repr(value) + return '%s(tag=%r, value=%s)' % (self.__class__.__name__, self.tag, value) + +class ScalarNode(Node): + id = 'scalar' + def __init__(self, tag, value, + start_mark=None, end_mark=None, style=None): + self.tag = tag + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + self.style = style + +class CollectionNode(Node): + def __init__(self, tag, value, + start_mark=None, end_mark=None, flow_style=None): + self.tag = tag + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + self.flow_style = flow_style + +class SequenceNode(CollectionNode): + id = 'sequence' + +class MappingNode(CollectionNode): + id = 'mapping' + diff --git a/.venv/lib/python3.12/site-packages/yaml/parser.py b/.venv/lib/python3.12/site-packages/yaml/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..13a5995d292045d0f865a99abf692bd35dc87814 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/parser.py @@ -0,0 +1,589 @@ + +# The following YAML grammar is LL(1) and is parsed by a recursive descent +# parser. +# +# stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +# implicit_document ::= block_node DOCUMENT-END* +# explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +# block_node_or_indentless_sequence ::= +# ALIAS +# | properties (block_content | indentless_block_sequence)? +# | block_content +# | indentless_block_sequence +# block_node ::= ALIAS +# | properties block_content? +# | block_content +# flow_node ::= ALIAS +# | properties flow_content? +# | flow_content +# properties ::= TAG ANCHOR? | ANCHOR TAG? +# block_content ::= block_collection | flow_collection | SCALAR +# flow_content ::= flow_collection | SCALAR +# block_collection ::= block_sequence | block_mapping +# flow_collection ::= flow_sequence | flow_mapping +# block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +# indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +# block_mapping ::= BLOCK-MAPPING_START +# ((KEY block_node_or_indentless_sequence?)? +# (VALUE block_node_or_indentless_sequence?)?)* +# BLOCK-END +# flow_sequence ::= FLOW-SEQUENCE-START +# (flow_sequence_entry FLOW-ENTRY)* +# flow_sequence_entry? +# FLOW-SEQUENCE-END +# flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +# flow_mapping ::= FLOW-MAPPING-START +# (flow_mapping_entry FLOW-ENTRY)* +# flow_mapping_entry? +# FLOW-MAPPING-END +# flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +# +# FIRST sets: +# +# stream: { STREAM-START } +# explicit_document: { DIRECTIVE DOCUMENT-START } +# implicit_document: FIRST(block_node) +# block_node: { ALIAS TAG ANCHOR SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START } +# flow_node: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START } +# block_content: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR } +# flow_content: { FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR } +# block_collection: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START } +# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START } +# block_sequence: { BLOCK-SEQUENCE-START } +# block_mapping: { BLOCK-MAPPING-START } +# block_node_or_indentless_sequence: { ALIAS ANCHOR TAG SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START BLOCK-ENTRY } +# indentless_sequence: { ENTRY } +# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START } +# flow_sequence: { FLOW-SEQUENCE-START } +# flow_mapping: { FLOW-MAPPING-START } +# flow_sequence_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY } +# flow_mapping_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY } + +__all__ = ['Parser', 'ParserError'] + +from .error import MarkedYAMLError +from .tokens import * +from .events import * +from .scanner import * + +class ParserError(MarkedYAMLError): + pass + +class Parser: + # Since writing a recursive-descendant parser is a straightforward task, we + # do not give many comments here. + + DEFAULT_TAGS = { + '!': '!', + '!!': 'tag:yaml.org,2002:', + } + + def __init__(self): + self.current_event = None + self.yaml_version = None + self.tag_handles = {} + self.states = [] + self.marks = [] + self.state = self.parse_stream_start + + def dispose(self): + # Reset the state attributes (to clear self-references) + self.states = [] + self.state = None + + def check_event(self, *choices): + # Check the type of the next event. + if self.current_event is None: + if self.state: + self.current_event = self.state() + if self.current_event is not None: + if not choices: + return True + for choice in choices: + if isinstance(self.current_event, choice): + return True + return False + + def peek_event(self): + # Get the next event. + if self.current_event is None: + if self.state: + self.current_event = self.state() + return self.current_event + + def get_event(self): + # Get the next event and proceed further. + if self.current_event is None: + if self.state: + self.current_event = self.state() + value = self.current_event + self.current_event = None + return value + + # stream ::= STREAM-START implicit_document? explicit_document* STREAM-END + # implicit_document ::= block_node DOCUMENT-END* + # explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* + + def parse_stream_start(self): + + # Parse the stream start. + token = self.get_token() + event = StreamStartEvent(token.start_mark, token.end_mark, + encoding=token.encoding) + + # Prepare the next state. + self.state = self.parse_implicit_document_start + + return event + + def parse_implicit_document_start(self): + + # Parse an implicit document. + if not self.check_token(DirectiveToken, DocumentStartToken, + StreamEndToken): + self.tag_handles = self.DEFAULT_TAGS + token = self.peek_token() + start_mark = end_mark = token.start_mark + event = DocumentStartEvent(start_mark, end_mark, + explicit=False) + + # Prepare the next state. + self.states.append(self.parse_document_end) + self.state = self.parse_block_node + + return event + + else: + return self.parse_document_start() + + def parse_document_start(self): + + # Parse any extra document end indicators. + while self.check_token(DocumentEndToken): + self.get_token() + + # Parse an explicit document. + if not self.check_token(StreamEndToken): + token = self.peek_token() + start_mark = token.start_mark + version, tags = self.process_directives() + if not self.check_token(DocumentStartToken): + raise ParserError(None, None, + "expected '', but found %r" + % self.peek_token().id, + self.peek_token().start_mark) + token = self.get_token() + end_mark = token.end_mark + event = DocumentStartEvent(start_mark, end_mark, + explicit=True, version=version, tags=tags) + self.states.append(self.parse_document_end) + self.state = self.parse_document_content + else: + # Parse the end of the stream. + token = self.get_token() + event = StreamEndEvent(token.start_mark, token.end_mark) + assert not self.states + assert not self.marks + self.state = None + return event + + def parse_document_end(self): + + # Parse the document end. + token = self.peek_token() + start_mark = end_mark = token.start_mark + explicit = False + if self.check_token(DocumentEndToken): + token = self.get_token() + end_mark = token.end_mark + explicit = True + event = DocumentEndEvent(start_mark, end_mark, + explicit=explicit) + + # Prepare the next state. + self.state = self.parse_document_start + + return event + + def parse_document_content(self): + if self.check_token(DirectiveToken, + DocumentStartToken, DocumentEndToken, StreamEndToken): + event = self.process_empty_scalar(self.peek_token().start_mark) + self.state = self.states.pop() + return event + else: + return self.parse_block_node() + + def process_directives(self): + self.yaml_version = None + self.tag_handles = {} + while self.check_token(DirectiveToken): + token = self.get_token() + if token.name == 'YAML': + if self.yaml_version is not None: + raise ParserError(None, None, + "found duplicate YAML directive", token.start_mark) + major, minor = token.value + if major != 1: + raise ParserError(None, None, + "found incompatible YAML document (version 1.* is required)", + token.start_mark) + self.yaml_version = token.value + elif token.name == 'TAG': + handle, prefix = token.value + if handle in self.tag_handles: + raise ParserError(None, None, + "duplicate tag handle %r" % handle, + token.start_mark) + self.tag_handles[handle] = prefix + if self.tag_handles: + value = self.yaml_version, self.tag_handles.copy() + else: + value = self.yaml_version, None + for key in self.DEFAULT_TAGS: + if key not in self.tag_handles: + self.tag_handles[key] = self.DEFAULT_TAGS[key] + return value + + # block_node_or_indentless_sequence ::= ALIAS + # | properties (block_content | indentless_block_sequence)? + # | block_content + # | indentless_block_sequence + # block_node ::= ALIAS + # | properties block_content? + # | block_content + # flow_node ::= ALIAS + # | properties flow_content? + # | flow_content + # properties ::= TAG ANCHOR? | ANCHOR TAG? + # block_content ::= block_collection | flow_collection | SCALAR + # flow_content ::= flow_collection | SCALAR + # block_collection ::= block_sequence | block_mapping + # flow_collection ::= flow_sequence | flow_mapping + + def parse_block_node(self): + return self.parse_node(block=True) + + def parse_flow_node(self): + return self.parse_node() + + def parse_block_node_or_indentless_sequence(self): + return self.parse_node(block=True, indentless_sequence=True) + + def parse_node(self, block=False, indentless_sequence=False): + if self.check_token(AliasToken): + token = self.get_token() + event = AliasEvent(token.value, token.start_mark, token.end_mark) + self.state = self.states.pop() + else: + anchor = None + tag = None + start_mark = end_mark = tag_mark = None + if self.check_token(AnchorToken): + token = self.get_token() + start_mark = token.start_mark + end_mark = token.end_mark + anchor = token.value + if self.check_token(TagToken): + token = self.get_token() + tag_mark = token.start_mark + end_mark = token.end_mark + tag = token.value + elif self.check_token(TagToken): + token = self.get_token() + start_mark = tag_mark = token.start_mark + end_mark = token.end_mark + tag = token.value + if self.check_token(AnchorToken): + token = self.get_token() + end_mark = token.end_mark + anchor = token.value + if tag is not None: + handle, suffix = tag + if handle is not None: + if handle not in self.tag_handles: + raise ParserError("while parsing a node", start_mark, + "found undefined tag handle %r" % handle, + tag_mark) + tag = self.tag_handles[handle]+suffix + else: + tag = suffix + #if tag == '!': + # raise ParserError("while parsing a node", start_mark, + # "found non-specific tag '!'", tag_mark, + # "Please check 'http://pyyaml.org/wiki/YAMLNonSpecificTag' and share your opinion.") + if start_mark is None: + start_mark = end_mark = self.peek_token().start_mark + event = None + implicit = (tag is None or tag == '!') + if indentless_sequence and self.check_token(BlockEntryToken): + end_mark = self.peek_token().end_mark + event = SequenceStartEvent(anchor, tag, implicit, + start_mark, end_mark) + self.state = self.parse_indentless_sequence_entry + else: + if self.check_token(ScalarToken): + token = self.get_token() + end_mark = token.end_mark + if (token.plain and tag is None) or tag == '!': + implicit = (True, False) + elif tag is None: + implicit = (False, True) + else: + implicit = (False, False) + event = ScalarEvent(anchor, tag, implicit, token.value, + start_mark, end_mark, style=token.style) + self.state = self.states.pop() + elif self.check_token(FlowSequenceStartToken): + end_mark = self.peek_token().end_mark + event = SequenceStartEvent(anchor, tag, implicit, + start_mark, end_mark, flow_style=True) + self.state = self.parse_flow_sequence_first_entry + elif self.check_token(FlowMappingStartToken): + end_mark = self.peek_token().end_mark + event = MappingStartEvent(anchor, tag, implicit, + start_mark, end_mark, flow_style=True) + self.state = self.parse_flow_mapping_first_key + elif block and self.check_token(BlockSequenceStartToken): + end_mark = self.peek_token().start_mark + event = SequenceStartEvent(anchor, tag, implicit, + start_mark, end_mark, flow_style=False) + self.state = self.parse_block_sequence_first_entry + elif block and self.check_token(BlockMappingStartToken): + end_mark = self.peek_token().start_mark + event = MappingStartEvent(anchor, tag, implicit, + start_mark, end_mark, flow_style=False) + self.state = self.parse_block_mapping_first_key + elif anchor is not None or tag is not None: + # Empty scalars are allowed even if a tag or an anchor is + # specified. + event = ScalarEvent(anchor, tag, (implicit, False), '', + start_mark, end_mark) + self.state = self.states.pop() + else: + if block: + node = 'block' + else: + node = 'flow' + token = self.peek_token() + raise ParserError("while parsing a %s node" % node, start_mark, + "expected the node content, but found %r" % token.id, + token.start_mark) + return event + + # block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END + + def parse_block_sequence_first_entry(self): + token = self.get_token() + self.marks.append(token.start_mark) + return self.parse_block_sequence_entry() + + def parse_block_sequence_entry(self): + if self.check_token(BlockEntryToken): + token = self.get_token() + if not self.check_token(BlockEntryToken, BlockEndToken): + self.states.append(self.parse_block_sequence_entry) + return self.parse_block_node() + else: + self.state = self.parse_block_sequence_entry + return self.process_empty_scalar(token.end_mark) + if not self.check_token(BlockEndToken): + token = self.peek_token() + raise ParserError("while parsing a block collection", self.marks[-1], + "expected , but found %r" % token.id, token.start_mark) + token = self.get_token() + event = SequenceEndEvent(token.start_mark, token.end_mark) + self.state = self.states.pop() + self.marks.pop() + return event + + # indentless_sequence ::= (BLOCK-ENTRY block_node?)+ + + def parse_indentless_sequence_entry(self): + if self.check_token(BlockEntryToken): + token = self.get_token() + if not self.check_token(BlockEntryToken, + KeyToken, ValueToken, BlockEndToken): + self.states.append(self.parse_indentless_sequence_entry) + return self.parse_block_node() + else: + self.state = self.parse_indentless_sequence_entry + return self.process_empty_scalar(token.end_mark) + token = self.peek_token() + event = SequenceEndEvent(token.start_mark, token.start_mark) + self.state = self.states.pop() + return event + + # block_mapping ::= BLOCK-MAPPING_START + # ((KEY block_node_or_indentless_sequence?)? + # (VALUE block_node_or_indentless_sequence?)?)* + # BLOCK-END + + def parse_block_mapping_first_key(self): + token = self.get_token() + self.marks.append(token.start_mark) + return self.parse_block_mapping_key() + + def parse_block_mapping_key(self): + if self.check_token(KeyToken): + token = self.get_token() + if not self.check_token(KeyToken, ValueToken, BlockEndToken): + self.states.append(self.parse_block_mapping_value) + return self.parse_block_node_or_indentless_sequence() + else: + self.state = self.parse_block_mapping_value + return self.process_empty_scalar(token.end_mark) + if not self.check_token(BlockEndToken): + token = self.peek_token() + raise ParserError("while parsing a block mapping", self.marks[-1], + "expected , but found %r" % token.id, token.start_mark) + token = self.get_token() + event = MappingEndEvent(token.start_mark, token.end_mark) + self.state = self.states.pop() + self.marks.pop() + return event + + def parse_block_mapping_value(self): + if self.check_token(ValueToken): + token = self.get_token() + if not self.check_token(KeyToken, ValueToken, BlockEndToken): + self.states.append(self.parse_block_mapping_key) + return self.parse_block_node_or_indentless_sequence() + else: + self.state = self.parse_block_mapping_key + return self.process_empty_scalar(token.end_mark) + else: + self.state = self.parse_block_mapping_key + token = self.peek_token() + return self.process_empty_scalar(token.start_mark) + + # flow_sequence ::= FLOW-SEQUENCE-START + # (flow_sequence_entry FLOW-ENTRY)* + # flow_sequence_entry? + # FLOW-SEQUENCE-END + # flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + # + # Note that while production rules for both flow_sequence_entry and + # flow_mapping_entry are equal, their interpretations are different. + # For `flow_sequence_entry`, the part `KEY flow_node? (VALUE flow_node?)?` + # generate an inline mapping (set syntax). + + def parse_flow_sequence_first_entry(self): + token = self.get_token() + self.marks.append(token.start_mark) + return self.parse_flow_sequence_entry(first=True) + + def parse_flow_sequence_entry(self, first=False): + if not self.check_token(FlowSequenceEndToken): + if not first: + if self.check_token(FlowEntryToken): + self.get_token() + else: + token = self.peek_token() + raise ParserError("while parsing a flow sequence", self.marks[-1], + "expected ',' or ']', but got %r" % token.id, token.start_mark) + + if self.check_token(KeyToken): + token = self.peek_token() + event = MappingStartEvent(None, None, True, + token.start_mark, token.end_mark, + flow_style=True) + self.state = self.parse_flow_sequence_entry_mapping_key + return event + elif not self.check_token(FlowSequenceEndToken): + self.states.append(self.parse_flow_sequence_entry) + return self.parse_flow_node() + token = self.get_token() + event = SequenceEndEvent(token.start_mark, token.end_mark) + self.state = self.states.pop() + self.marks.pop() + return event + + def parse_flow_sequence_entry_mapping_key(self): + token = self.get_token() + if not self.check_token(ValueToken, + FlowEntryToken, FlowSequenceEndToken): + self.states.append(self.parse_flow_sequence_entry_mapping_value) + return self.parse_flow_node() + else: + self.state = self.parse_flow_sequence_entry_mapping_value + return self.process_empty_scalar(token.end_mark) + + def parse_flow_sequence_entry_mapping_value(self): + if self.check_token(ValueToken): + token = self.get_token() + if not self.check_token(FlowEntryToken, FlowSequenceEndToken): + self.states.append(self.parse_flow_sequence_entry_mapping_end) + return self.parse_flow_node() + else: + self.state = self.parse_flow_sequence_entry_mapping_end + return self.process_empty_scalar(token.end_mark) + else: + self.state = self.parse_flow_sequence_entry_mapping_end + token = self.peek_token() + return self.process_empty_scalar(token.start_mark) + + def parse_flow_sequence_entry_mapping_end(self): + self.state = self.parse_flow_sequence_entry + token = self.peek_token() + return MappingEndEvent(token.start_mark, token.start_mark) + + # flow_mapping ::= FLOW-MAPPING-START + # (flow_mapping_entry FLOW-ENTRY)* + # flow_mapping_entry? + # FLOW-MAPPING-END + # flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + + def parse_flow_mapping_first_key(self): + token = self.get_token() + self.marks.append(token.start_mark) + return self.parse_flow_mapping_key(first=True) + + def parse_flow_mapping_key(self, first=False): + if not self.check_token(FlowMappingEndToken): + if not first: + if self.check_token(FlowEntryToken): + self.get_token() + else: + token = self.peek_token() + raise ParserError("while parsing a flow mapping", self.marks[-1], + "expected ',' or '}', but got %r" % token.id, token.start_mark) + if self.check_token(KeyToken): + token = self.get_token() + if not self.check_token(ValueToken, + FlowEntryToken, FlowMappingEndToken): + self.states.append(self.parse_flow_mapping_value) + return self.parse_flow_node() + else: + self.state = self.parse_flow_mapping_value + return self.process_empty_scalar(token.end_mark) + elif not self.check_token(FlowMappingEndToken): + self.states.append(self.parse_flow_mapping_empty_value) + return self.parse_flow_node() + token = self.get_token() + event = MappingEndEvent(token.start_mark, token.end_mark) + self.state = self.states.pop() + self.marks.pop() + return event + + def parse_flow_mapping_value(self): + if self.check_token(ValueToken): + token = self.get_token() + if not self.check_token(FlowEntryToken, FlowMappingEndToken): + self.states.append(self.parse_flow_mapping_key) + return self.parse_flow_node() + else: + self.state = self.parse_flow_mapping_key + return self.process_empty_scalar(token.end_mark) + else: + self.state = self.parse_flow_mapping_key + token = self.peek_token() + return self.process_empty_scalar(token.start_mark) + + def parse_flow_mapping_empty_value(self): + self.state = self.parse_flow_mapping_key + return self.process_empty_scalar(self.peek_token().start_mark) + + def process_empty_scalar(self, mark): + return ScalarEvent(None, None, (True, False), '', mark, mark) + diff --git a/.venv/lib/python3.12/site-packages/yaml/reader.py b/.venv/lib/python3.12/site-packages/yaml/reader.py new file mode 100644 index 0000000000000000000000000000000000000000..774b0219b5932a0ee1c27e637371de5ba8d9cb16 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/reader.py @@ -0,0 +1,185 @@ +# This module contains abstractions for the input stream. You don't have to +# looks further, there are no pretty code. +# +# We define two classes here. +# +# Mark(source, line, column) +# It's just a record and its only use is producing nice error messages. +# Parser does not use it for any other purposes. +# +# Reader(source, data) +# Reader determines the encoding of `data` and converts it to unicode. +# Reader provides the following methods and attributes: +# reader.peek(length=1) - return the next `length` characters +# reader.forward(length=1) - move the current position to `length` characters. +# reader.index - the number of the current character. +# reader.line, stream.column - the line and the column of the current character. + +__all__ = ['Reader', 'ReaderError'] + +from .error import YAMLError, Mark + +import codecs, re + +class ReaderError(YAMLError): + + def __init__(self, name, position, character, encoding, reason): + self.name = name + self.character = character + self.position = position + self.encoding = encoding + self.reason = reason + + def __str__(self): + if isinstance(self.character, bytes): + return "'%s' codec can't decode byte #x%02x: %s\n" \ + " in \"%s\", position %d" \ + % (self.encoding, ord(self.character), self.reason, + self.name, self.position) + else: + return "unacceptable character #x%04x: %s\n" \ + " in \"%s\", position %d" \ + % (self.character, self.reason, + self.name, self.position) + +class Reader(object): + # Reader: + # - determines the data encoding and converts it to a unicode string, + # - checks if characters are in allowed range, + # - adds '\0' to the end. + + # Reader accepts + # - a `bytes` object, + # - a `str` object, + # - a file-like object with its `read` method returning `str`, + # - a file-like object with its `read` method returning `unicode`. + + # Yeah, it's ugly and slow. + + def __init__(self, stream): + self.name = None + self.stream = None + self.stream_pointer = 0 + self.eof = True + self.buffer = '' + self.pointer = 0 + self.raw_buffer = None + self.raw_decode = None + self.encoding = None + self.index = 0 + self.line = 0 + self.column = 0 + if isinstance(stream, str): + self.name = "" + self.check_printable(stream) + self.buffer = stream+'\0' + elif isinstance(stream, bytes): + self.name = "" + self.raw_buffer = stream + self.determine_encoding() + else: + self.stream = stream + self.name = getattr(stream, 'name', "") + self.eof = False + self.raw_buffer = None + self.determine_encoding() + + def peek(self, index=0): + try: + return self.buffer[self.pointer+index] + except IndexError: + self.update(index+1) + return self.buffer[self.pointer+index] + + def prefix(self, length=1): + if self.pointer+length >= len(self.buffer): + self.update(length) + return self.buffer[self.pointer:self.pointer+length] + + def forward(self, length=1): + if self.pointer+length+1 >= len(self.buffer): + self.update(length+1) + while length: + ch = self.buffer[self.pointer] + self.pointer += 1 + self.index += 1 + if ch in '\n\x85\u2028\u2029' \ + or (ch == '\r' and self.buffer[self.pointer] != '\n'): + self.line += 1 + self.column = 0 + elif ch != '\uFEFF': + self.column += 1 + length -= 1 + + def get_mark(self): + if self.stream is None: + return Mark(self.name, self.index, self.line, self.column, + self.buffer, self.pointer) + else: + return Mark(self.name, self.index, self.line, self.column, + None, None) + + def determine_encoding(self): + while not self.eof and (self.raw_buffer is None or len(self.raw_buffer) < 2): + self.update_raw() + if isinstance(self.raw_buffer, bytes): + if self.raw_buffer.startswith(codecs.BOM_UTF16_LE): + self.raw_decode = codecs.utf_16_le_decode + self.encoding = 'utf-16-le' + elif self.raw_buffer.startswith(codecs.BOM_UTF16_BE): + self.raw_decode = codecs.utf_16_be_decode + self.encoding = 'utf-16-be' + else: + self.raw_decode = codecs.utf_8_decode + self.encoding = 'utf-8' + self.update(1) + + NON_PRINTABLE = re.compile('[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]') + def check_printable(self, data): + match = self.NON_PRINTABLE.search(data) + if match: + character = match.group() + position = self.index+(len(self.buffer)-self.pointer)+match.start() + raise ReaderError(self.name, position, ord(character), + 'unicode', "special characters are not allowed") + + def update(self, length): + if self.raw_buffer is None: + return + self.buffer = self.buffer[self.pointer:] + self.pointer = 0 + while len(self.buffer) < length: + if not self.eof: + self.update_raw() + if self.raw_decode is not None: + try: + data, converted = self.raw_decode(self.raw_buffer, + 'strict', self.eof) + except UnicodeDecodeError as exc: + character = self.raw_buffer[exc.start] + if self.stream is not None: + position = self.stream_pointer-len(self.raw_buffer)+exc.start + else: + position = exc.start + raise ReaderError(self.name, position, character, + exc.encoding, exc.reason) + else: + data = self.raw_buffer + converted = len(data) + self.check_printable(data) + self.buffer += data + self.raw_buffer = self.raw_buffer[converted:] + if self.eof: + self.buffer += '\0' + self.raw_buffer = None + break + + def update_raw(self, size=4096): + data = self.stream.read(size) + if self.raw_buffer is None: + self.raw_buffer = data + else: + self.raw_buffer += data + self.stream_pointer += len(data) + if not data: + self.eof = True diff --git a/.venv/lib/python3.12/site-packages/yaml/representer.py b/.venv/lib/python3.12/site-packages/yaml/representer.py new file mode 100644 index 0000000000000000000000000000000000000000..808ca06dfbd60c9a23eb079151b74a82ef688749 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/representer.py @@ -0,0 +1,389 @@ + +__all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer', + 'RepresenterError'] + +from .error import * +from .nodes import * + +import datetime, copyreg, types, base64, collections + +class RepresenterError(YAMLError): + pass + +class BaseRepresenter: + + yaml_representers = {} + yaml_multi_representers = {} + + def __init__(self, default_style=None, default_flow_style=False, sort_keys=True): + self.default_style = default_style + self.sort_keys = sort_keys + self.default_flow_style = default_flow_style + self.represented_objects = {} + self.object_keeper = [] + self.alias_key = None + + def represent(self, data): + node = self.represent_data(data) + self.serialize(node) + self.represented_objects = {} + self.object_keeper = [] + self.alias_key = None + + def represent_data(self, data): + if self.ignore_aliases(data): + self.alias_key = None + else: + self.alias_key = id(data) + if self.alias_key is not None: + if self.alias_key in self.represented_objects: + node = self.represented_objects[self.alias_key] + #if node is None: + # raise RepresenterError("recursive objects are not allowed: %r" % data) + return node + #self.represented_objects[alias_key] = None + self.object_keeper.append(data) + data_types = type(data).__mro__ + if data_types[0] in self.yaml_representers: + node = self.yaml_representers[data_types[0]](self, data) + else: + for data_type in data_types: + if data_type in self.yaml_multi_representers: + node = self.yaml_multi_representers[data_type](self, data) + break + else: + if None in self.yaml_multi_representers: + node = self.yaml_multi_representers[None](self, data) + elif None in self.yaml_representers: + node = self.yaml_representers[None](self, data) + else: + node = ScalarNode(None, str(data)) + #if alias_key is not None: + # self.represented_objects[alias_key] = node + return node + + @classmethod + def add_representer(cls, data_type, representer): + if not 'yaml_representers' in cls.__dict__: + cls.yaml_representers = cls.yaml_representers.copy() + cls.yaml_representers[data_type] = representer + + @classmethod + def add_multi_representer(cls, data_type, representer): + if not 'yaml_multi_representers' in cls.__dict__: + cls.yaml_multi_representers = cls.yaml_multi_representers.copy() + cls.yaml_multi_representers[data_type] = representer + + def represent_scalar(self, tag, value, style=None): + if style is None: + style = self.default_style + node = ScalarNode(tag, value, style=style) + if self.alias_key is not None: + self.represented_objects[self.alias_key] = node + return node + + def represent_sequence(self, tag, sequence, flow_style=None): + value = [] + node = SequenceNode(tag, value, flow_style=flow_style) + if self.alias_key is not None: + self.represented_objects[self.alias_key] = node + best_style = True + for item in sequence: + node_item = self.represent_data(item) + if not (isinstance(node_item, ScalarNode) and not node_item.style): + best_style = False + value.append(node_item) + if flow_style is None: + if self.default_flow_style is not None: + node.flow_style = self.default_flow_style + else: + node.flow_style = best_style + return node + + def represent_mapping(self, tag, mapping, flow_style=None): + value = [] + node = MappingNode(tag, value, flow_style=flow_style) + if self.alias_key is not None: + self.represented_objects[self.alias_key] = node + best_style = True + if hasattr(mapping, 'items'): + mapping = list(mapping.items()) + if self.sort_keys: + try: + mapping = sorted(mapping) + except TypeError: + pass + for item_key, item_value in mapping: + node_key = self.represent_data(item_key) + node_value = self.represent_data(item_value) + if not (isinstance(node_key, ScalarNode) and not node_key.style): + best_style = False + if not (isinstance(node_value, ScalarNode) and not node_value.style): + best_style = False + value.append((node_key, node_value)) + if flow_style is None: + if self.default_flow_style is not None: + node.flow_style = self.default_flow_style + else: + node.flow_style = best_style + return node + + def ignore_aliases(self, data): + return False + +class SafeRepresenter(BaseRepresenter): + + def ignore_aliases(self, data): + if data is None: + return True + if isinstance(data, tuple) and data == (): + return True + if isinstance(data, (str, bytes, bool, int, float)): + return True + + def represent_none(self, data): + return self.represent_scalar('tag:yaml.org,2002:null', 'null') + + def represent_str(self, data): + return self.represent_scalar('tag:yaml.org,2002:str', data) + + def represent_binary(self, data): + if hasattr(base64, 'encodebytes'): + data = base64.encodebytes(data).decode('ascii') + else: + data = base64.encodestring(data).decode('ascii') + return self.represent_scalar('tag:yaml.org,2002:binary', data, style='|') + + def represent_bool(self, data): + if data: + value = 'true' + else: + value = 'false' + return self.represent_scalar('tag:yaml.org,2002:bool', value) + + def represent_int(self, data): + return self.represent_scalar('tag:yaml.org,2002:int', str(data)) + + inf_value = 1e300 + while repr(inf_value) != repr(inf_value*inf_value): + inf_value *= inf_value + + def represent_float(self, data): + if data != data or (data == 0.0 and data == 1.0): + value = '.nan' + elif data == self.inf_value: + value = '.inf' + elif data == -self.inf_value: + value = '-.inf' + else: + value = repr(data).lower() + # Note that in some cases `repr(data)` represents a float number + # without the decimal parts. For instance: + # >>> repr(1e17) + # '1e17' + # Unfortunately, this is not a valid float representation according + # to the definition of the `!!float` tag. We fix this by adding + # '.0' before the 'e' symbol. + if '.' not in value and 'e' in value: + value = value.replace('e', '.0e', 1) + return self.represent_scalar('tag:yaml.org,2002:float', value) + + def represent_list(self, data): + #pairs = (len(data) > 0 and isinstance(data, list)) + #if pairs: + # for item in data: + # if not isinstance(item, tuple) or len(item) != 2: + # pairs = False + # break + #if not pairs: + return self.represent_sequence('tag:yaml.org,2002:seq', data) + #value = [] + #for item_key, item_value in data: + # value.append(self.represent_mapping(u'tag:yaml.org,2002:map', + # [(item_key, item_value)])) + #return SequenceNode(u'tag:yaml.org,2002:pairs', value) + + def represent_dict(self, data): + return self.represent_mapping('tag:yaml.org,2002:map', data) + + def represent_set(self, data): + value = {} + for key in data: + value[key] = None + return self.represent_mapping('tag:yaml.org,2002:set', value) + + def represent_date(self, data): + value = data.isoformat() + return self.represent_scalar('tag:yaml.org,2002:timestamp', value) + + def represent_datetime(self, data): + value = data.isoformat(' ') + return self.represent_scalar('tag:yaml.org,2002:timestamp', value) + + def represent_yaml_object(self, tag, data, cls, flow_style=None): + if hasattr(data, '__getstate__'): + state = data.__getstate__() + else: + state = data.__dict__.copy() + return self.represent_mapping(tag, state, flow_style=flow_style) + + def represent_undefined(self, data): + raise RepresenterError("cannot represent an object", data) + +SafeRepresenter.add_representer(type(None), + SafeRepresenter.represent_none) + +SafeRepresenter.add_representer(str, + SafeRepresenter.represent_str) + +SafeRepresenter.add_representer(bytes, + SafeRepresenter.represent_binary) + +SafeRepresenter.add_representer(bool, + SafeRepresenter.represent_bool) + +SafeRepresenter.add_representer(int, + SafeRepresenter.represent_int) + +SafeRepresenter.add_representer(float, + SafeRepresenter.represent_float) + +SafeRepresenter.add_representer(list, + SafeRepresenter.represent_list) + +SafeRepresenter.add_representer(tuple, + SafeRepresenter.represent_list) + +SafeRepresenter.add_representer(dict, + SafeRepresenter.represent_dict) + +SafeRepresenter.add_representer(set, + SafeRepresenter.represent_set) + +SafeRepresenter.add_representer(datetime.date, + SafeRepresenter.represent_date) + +SafeRepresenter.add_representer(datetime.datetime, + SafeRepresenter.represent_datetime) + +SafeRepresenter.add_representer(None, + SafeRepresenter.represent_undefined) + +class Representer(SafeRepresenter): + + def represent_complex(self, data): + if data.imag == 0.0: + data = '%r' % data.real + elif data.real == 0.0: + data = '%rj' % data.imag + elif data.imag > 0: + data = '%r+%rj' % (data.real, data.imag) + else: + data = '%r%rj' % (data.real, data.imag) + return self.represent_scalar('tag:yaml.org,2002:python/complex', data) + + def represent_tuple(self, data): + return self.represent_sequence('tag:yaml.org,2002:python/tuple', data) + + def represent_name(self, data): + name = '%s.%s' % (data.__module__, data.__name__) + return self.represent_scalar('tag:yaml.org,2002:python/name:'+name, '') + + def represent_module(self, data): + return self.represent_scalar( + 'tag:yaml.org,2002:python/module:'+data.__name__, '') + + def represent_object(self, data): + # We use __reduce__ API to save the data. data.__reduce__ returns + # a tuple of length 2-5: + # (function, args, state, listitems, dictitems) + + # For reconstructing, we calls function(*args), then set its state, + # listitems, and dictitems if they are not None. + + # A special case is when function.__name__ == '__newobj__'. In this + # case we create the object with args[0].__new__(*args). + + # Another special case is when __reduce__ returns a string - we don't + # support it. + + # We produce a !!python/object, !!python/object/new or + # !!python/object/apply node. + + cls = type(data) + if cls in copyreg.dispatch_table: + reduce = copyreg.dispatch_table[cls](data) + elif hasattr(data, '__reduce_ex__'): + reduce = data.__reduce_ex__(2) + elif hasattr(data, '__reduce__'): + reduce = data.__reduce__() + else: + raise RepresenterError("cannot represent an object", data) + reduce = (list(reduce)+[None]*5)[:5] + function, args, state, listitems, dictitems = reduce + args = list(args) + if state is None: + state = {} + if listitems is not None: + listitems = list(listitems) + if dictitems is not None: + dictitems = dict(dictitems) + if function.__name__ == '__newobj__': + function = args[0] + args = args[1:] + tag = 'tag:yaml.org,2002:python/object/new:' + newobj = True + else: + tag = 'tag:yaml.org,2002:python/object/apply:' + newobj = False + function_name = '%s.%s' % (function.__module__, function.__name__) + if not args and not listitems and not dictitems \ + and isinstance(state, dict) and newobj: + return self.represent_mapping( + 'tag:yaml.org,2002:python/object:'+function_name, state) + if not listitems and not dictitems \ + and isinstance(state, dict) and not state: + return self.represent_sequence(tag+function_name, args) + value = {} + if args: + value['args'] = args + if state or not isinstance(state, dict): + value['state'] = state + if listitems: + value['listitems'] = listitems + if dictitems: + value['dictitems'] = dictitems + return self.represent_mapping(tag+function_name, value) + + def represent_ordered_dict(self, data): + # Provide uniform representation across different Python versions. + data_type = type(data) + tag = 'tag:yaml.org,2002:python/object/apply:%s.%s' \ + % (data_type.__module__, data_type.__name__) + items = [[key, value] for key, value in data.items()] + return self.represent_sequence(tag, [items]) + +Representer.add_representer(complex, + Representer.represent_complex) + +Representer.add_representer(tuple, + Representer.represent_tuple) + +Representer.add_multi_representer(type, + Representer.represent_name) + +Representer.add_representer(collections.OrderedDict, + Representer.represent_ordered_dict) + +Representer.add_representer(types.FunctionType, + Representer.represent_name) + +Representer.add_representer(types.BuiltinFunctionType, + Representer.represent_name) + +Representer.add_representer(types.ModuleType, + Representer.represent_module) + +Representer.add_multi_representer(object, + Representer.represent_object) + diff --git a/.venv/lib/python3.12/site-packages/yaml/resolver.py b/.venv/lib/python3.12/site-packages/yaml/resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..3522bdaaf6358110b608f4e6503b9d314c82d887 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/resolver.py @@ -0,0 +1,227 @@ + +__all__ = ['BaseResolver', 'Resolver'] + +from .error import * +from .nodes import * + +import re + +class ResolverError(YAMLError): + pass + +class BaseResolver: + + DEFAULT_SCALAR_TAG = 'tag:yaml.org,2002:str' + DEFAULT_SEQUENCE_TAG = 'tag:yaml.org,2002:seq' + DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map' + + yaml_implicit_resolvers = {} + yaml_path_resolvers = {} + + def __init__(self): + self.resolver_exact_paths = [] + self.resolver_prefix_paths = [] + + @classmethod + def add_implicit_resolver(cls, tag, regexp, first): + if not 'yaml_implicit_resolvers' in cls.__dict__: + implicit_resolvers = {} + for key in cls.yaml_implicit_resolvers: + implicit_resolvers[key] = cls.yaml_implicit_resolvers[key][:] + cls.yaml_implicit_resolvers = implicit_resolvers + if first is None: + first = [None] + for ch in first: + cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp)) + + @classmethod + def add_path_resolver(cls, tag, path, kind=None): + # Note: `add_path_resolver` is experimental. The API could be changed. + # `new_path` is a pattern that is matched against the path from the + # root to the node that is being considered. `node_path` elements are + # tuples `(node_check, index_check)`. `node_check` is a node class: + # `ScalarNode`, `SequenceNode`, `MappingNode` or `None`. `None` + # matches any kind of a node. `index_check` could be `None`, a boolean + # value, a string value, or a number. `None` and `False` match against + # any _value_ of sequence and mapping nodes. `True` matches against + # any _key_ of a mapping node. A string `index_check` matches against + # a mapping value that corresponds to a scalar key which content is + # equal to the `index_check` value. An integer `index_check` matches + # against a sequence value with the index equal to `index_check`. + if not 'yaml_path_resolvers' in cls.__dict__: + cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy() + new_path = [] + for element in path: + if isinstance(element, (list, tuple)): + if len(element) == 2: + node_check, index_check = element + elif len(element) == 1: + node_check = element[0] + index_check = True + else: + raise ResolverError("Invalid path element: %s" % element) + else: + node_check = None + index_check = element + if node_check is str: + node_check = ScalarNode + elif node_check is list: + node_check = SequenceNode + elif node_check is dict: + node_check = MappingNode + elif node_check not in [ScalarNode, SequenceNode, MappingNode] \ + and not isinstance(node_check, str) \ + and node_check is not None: + raise ResolverError("Invalid node checker: %s" % node_check) + if not isinstance(index_check, (str, int)) \ + and index_check is not None: + raise ResolverError("Invalid index checker: %s" % index_check) + new_path.append((node_check, index_check)) + if kind is str: + kind = ScalarNode + elif kind is list: + kind = SequenceNode + elif kind is dict: + kind = MappingNode + elif kind not in [ScalarNode, SequenceNode, MappingNode] \ + and kind is not None: + raise ResolverError("Invalid node kind: %s" % kind) + cls.yaml_path_resolvers[tuple(new_path), kind] = tag + + def descend_resolver(self, current_node, current_index): + if not self.yaml_path_resolvers: + return + exact_paths = {} + prefix_paths = [] + if current_node: + depth = len(self.resolver_prefix_paths) + for path, kind in self.resolver_prefix_paths[-1]: + if self.check_resolver_prefix(depth, path, kind, + current_node, current_index): + if len(path) > depth: + prefix_paths.append((path, kind)) + else: + exact_paths[kind] = self.yaml_path_resolvers[path, kind] + else: + for path, kind in self.yaml_path_resolvers: + if not path: + exact_paths[kind] = self.yaml_path_resolvers[path, kind] + else: + prefix_paths.append((path, kind)) + self.resolver_exact_paths.append(exact_paths) + self.resolver_prefix_paths.append(prefix_paths) + + def ascend_resolver(self): + if not self.yaml_path_resolvers: + return + self.resolver_exact_paths.pop() + self.resolver_prefix_paths.pop() + + def check_resolver_prefix(self, depth, path, kind, + current_node, current_index): + node_check, index_check = path[depth-1] + if isinstance(node_check, str): + if current_node.tag != node_check: + return + elif node_check is not None: + if not isinstance(current_node, node_check): + return + if index_check is True and current_index is not None: + return + if (index_check is False or index_check is None) \ + and current_index is None: + return + if isinstance(index_check, str): + if not (isinstance(current_index, ScalarNode) + and index_check == current_index.value): + return + elif isinstance(index_check, int) and not isinstance(index_check, bool): + if index_check != current_index: + return + return True + + def resolve(self, kind, value, implicit): + if kind is ScalarNode and implicit[0]: + if value == '': + resolvers = self.yaml_implicit_resolvers.get('', []) + else: + resolvers = self.yaml_implicit_resolvers.get(value[0], []) + wildcard_resolvers = self.yaml_implicit_resolvers.get(None, []) + for tag, regexp in resolvers + wildcard_resolvers: + if regexp.match(value): + return tag + implicit = implicit[1] + if self.yaml_path_resolvers: + exact_paths = self.resolver_exact_paths[-1] + if kind in exact_paths: + return exact_paths[kind] + if None in exact_paths: + return exact_paths[None] + if kind is ScalarNode: + return self.DEFAULT_SCALAR_TAG + elif kind is SequenceNode: + return self.DEFAULT_SEQUENCE_TAG + elif kind is MappingNode: + return self.DEFAULT_MAPPING_TAG + +class Resolver(BaseResolver): + pass + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:bool', + re.compile(r'''^(?:yes|Yes|YES|no|No|NO + |true|True|TRUE|false|False|FALSE + |on|On|ON|off|Off|OFF)$''', re.X), + list('yYnNtTfFoO')) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:float', + re.compile(r'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)? + |\.[0-9][0-9_]*(?:[eE][-+][0-9]+)? + |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]* + |[-+]?\.(?:inf|Inf|INF) + |\.(?:nan|NaN|NAN))$''', re.X), + list('-+0123456789.')) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:int', + re.compile(r'''^(?:[-+]?0b[0-1_]+ + |[-+]?0[0-7_]+ + |[-+]?(?:0|[1-9][0-9_]*) + |[-+]?0x[0-9a-fA-F_]+ + |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X), + list('-+0123456789')) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:merge', + re.compile(r'^(?:<<)$'), + ['<']) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:null', + re.compile(r'''^(?: ~ + |null|Null|NULL + | )$''', re.X), + ['~', 'n', 'N', '']) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:timestamp', + re.compile(r'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] + |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]? + (?:[Tt]|[ \t]+)[0-9][0-9]? + :[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)? + (?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X), + list('0123456789')) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:value', + re.compile(r'^(?:=)$'), + ['=']) + +# The following resolver is only for documentation purposes. It cannot work +# because plain scalars cannot start with '!', '&', or '*'. +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:yaml', + re.compile(r'^(?:!|&|\*)$'), + list('!&*')) + diff --git a/.venv/lib/python3.12/site-packages/yaml/scanner.py b/.venv/lib/python3.12/site-packages/yaml/scanner.py new file mode 100644 index 0000000000000000000000000000000000000000..de925b07f1eaec33c9c305a8a69f9eb7ac5983c5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/scanner.py @@ -0,0 +1,1435 @@ + +# Scanner produces tokens of the following types: +# STREAM-START +# STREAM-END +# DIRECTIVE(name, value) +# DOCUMENT-START +# DOCUMENT-END +# BLOCK-SEQUENCE-START +# BLOCK-MAPPING-START +# BLOCK-END +# FLOW-SEQUENCE-START +# FLOW-MAPPING-START +# FLOW-SEQUENCE-END +# FLOW-MAPPING-END +# BLOCK-ENTRY +# FLOW-ENTRY +# KEY +# VALUE +# ALIAS(value) +# ANCHOR(value) +# TAG(value) +# SCALAR(value, plain, style) +# +# Read comments in the Scanner code for more details. +# + +__all__ = ['Scanner', 'ScannerError'] + +from .error import MarkedYAMLError +from .tokens import * + +class ScannerError(MarkedYAMLError): + pass + +class SimpleKey: + # See below simple keys treatment. + + def __init__(self, token_number, required, index, line, column, mark): + self.token_number = token_number + self.required = required + self.index = index + self.line = line + self.column = column + self.mark = mark + +class Scanner: + + def __init__(self): + """Initialize the scanner.""" + # It is assumed that Scanner and Reader will have a common descendant. + # Reader do the dirty work of checking for BOM and converting the + # input data to Unicode. It also adds NUL to the end. + # + # Reader supports the following methods + # self.peek(i=0) # peek the next i-th character + # self.prefix(l=1) # peek the next l characters + # self.forward(l=1) # read the next l characters and move the pointer. + + # Had we reached the end of the stream? + self.done = False + + # The number of unclosed '{' and '['. `flow_level == 0` means block + # context. + self.flow_level = 0 + + # List of processed tokens that are not yet emitted. + self.tokens = [] + + # Add the STREAM-START token. + self.fetch_stream_start() + + # Number of tokens that were emitted through the `get_token` method. + self.tokens_taken = 0 + + # The current indentation level. + self.indent = -1 + + # Past indentation levels. + self.indents = [] + + # Variables related to simple keys treatment. + + # A simple key is a key that is not denoted by the '?' indicator. + # Example of simple keys: + # --- + # block simple key: value + # ? not a simple key: + # : { flow simple key: value } + # We emit the KEY token before all keys, so when we find a potential + # simple key, we try to locate the corresponding ':' indicator. + # Simple keys should be limited to a single line and 1024 characters. + + # Can a simple key start at the current position? A simple key may + # start: + # - at the beginning of the line, not counting indentation spaces + # (in block context), + # - after '{', '[', ',' (in the flow context), + # - after '?', ':', '-' (in the block context). + # In the block context, this flag also signifies if a block collection + # may start at the current position. + self.allow_simple_key = True + + # Keep track of possible simple keys. This is a dictionary. The key + # is `flow_level`; there can be no more that one possible simple key + # for each level. The value is a SimpleKey record: + # (token_number, required, index, line, column, mark) + # A simple key may start with ALIAS, ANCHOR, TAG, SCALAR(flow), + # '[', or '{' tokens. + self.possible_simple_keys = {} + + # Public methods. + + def check_token(self, *choices): + # Check if the next token is one of the given types. + while self.need_more_tokens(): + self.fetch_more_tokens() + if self.tokens: + if not choices: + return True + for choice in choices: + if isinstance(self.tokens[0], choice): + return True + return False + + def peek_token(self): + # Return the next token, but do not delete if from the queue. + # Return None if no more tokens. + while self.need_more_tokens(): + self.fetch_more_tokens() + if self.tokens: + return self.tokens[0] + else: + return None + + def get_token(self): + # Return the next token. + while self.need_more_tokens(): + self.fetch_more_tokens() + if self.tokens: + self.tokens_taken += 1 + return self.tokens.pop(0) + + # Private methods. + + def need_more_tokens(self): + if self.done: + return False + if not self.tokens: + return True + # The current token may be a potential simple key, so we + # need to look further. + self.stale_possible_simple_keys() + if self.next_possible_simple_key() == self.tokens_taken: + return True + + def fetch_more_tokens(self): + + # Eat whitespaces and comments until we reach the next token. + self.scan_to_next_token() + + # Remove obsolete possible simple keys. + self.stale_possible_simple_keys() + + # Compare the current indentation and column. It may add some tokens + # and decrease the current indentation level. + self.unwind_indent(self.column) + + # Peek the next character. + ch = self.peek() + + # Is it the end of stream? + if ch == '\0': + return self.fetch_stream_end() + + # Is it a directive? + if ch == '%' and self.check_directive(): + return self.fetch_directive() + + # Is it the document start? + if ch == '-' and self.check_document_start(): + return self.fetch_document_start() + + # Is it the document end? + if ch == '.' and self.check_document_end(): + return self.fetch_document_end() + + # TODO: support for BOM within a stream. + #if ch == '\uFEFF': + # return self.fetch_bom() <-- issue BOMToken + + # Note: the order of the following checks is NOT significant. + + # Is it the flow sequence start indicator? + if ch == '[': + return self.fetch_flow_sequence_start() + + # Is it the flow mapping start indicator? + if ch == '{': + return self.fetch_flow_mapping_start() + + # Is it the flow sequence end indicator? + if ch == ']': + return self.fetch_flow_sequence_end() + + # Is it the flow mapping end indicator? + if ch == '}': + return self.fetch_flow_mapping_end() + + # Is it the flow entry indicator? + if ch == ',': + return self.fetch_flow_entry() + + # Is it the block entry indicator? + if ch == '-' and self.check_block_entry(): + return self.fetch_block_entry() + + # Is it the key indicator? + if ch == '?' and self.check_key(): + return self.fetch_key() + + # Is it the value indicator? + if ch == ':' and self.check_value(): + return self.fetch_value() + + # Is it an alias? + if ch == '*': + return self.fetch_alias() + + # Is it an anchor? + if ch == '&': + return self.fetch_anchor() + + # Is it a tag? + if ch == '!': + return self.fetch_tag() + + # Is it a literal scalar? + if ch == '|' and not self.flow_level: + return self.fetch_literal() + + # Is it a folded scalar? + if ch == '>' and not self.flow_level: + return self.fetch_folded() + + # Is it a single quoted scalar? + if ch == '\'': + return self.fetch_single() + + # Is it a double quoted scalar? + if ch == '\"': + return self.fetch_double() + + # It must be a plain scalar then. + if self.check_plain(): + return self.fetch_plain() + + # No? It's an error. Let's produce a nice error message. + raise ScannerError("while scanning for the next token", None, + "found character %r that cannot start any token" % ch, + self.get_mark()) + + # Simple keys treatment. + + def next_possible_simple_key(self): + # Return the number of the nearest possible simple key. Actually we + # don't need to loop through the whole dictionary. We may replace it + # with the following code: + # if not self.possible_simple_keys: + # return None + # return self.possible_simple_keys[ + # min(self.possible_simple_keys.keys())].token_number + min_token_number = None + for level in self.possible_simple_keys: + key = self.possible_simple_keys[level] + if min_token_number is None or key.token_number < min_token_number: + min_token_number = key.token_number + return min_token_number + + def stale_possible_simple_keys(self): + # Remove entries that are no longer possible simple keys. According to + # the YAML specification, simple keys + # - should be limited to a single line, + # - should be no longer than 1024 characters. + # Disabling this procedure will allow simple keys of any length and + # height (may cause problems if indentation is broken though). + for level in list(self.possible_simple_keys): + key = self.possible_simple_keys[level] + if key.line != self.line \ + or self.index-key.index > 1024: + if key.required: + raise ScannerError("while scanning a simple key", key.mark, + "could not find expected ':'", self.get_mark()) + del self.possible_simple_keys[level] + + def save_possible_simple_key(self): + # The next token may start a simple key. We check if it's possible + # and save its position. This function is called for + # ALIAS, ANCHOR, TAG, SCALAR(flow), '[', and '{'. + + # Check if a simple key is required at the current position. + required = not self.flow_level and self.indent == self.column + + # The next token might be a simple key. Let's save it's number and + # position. + if self.allow_simple_key: + self.remove_possible_simple_key() + token_number = self.tokens_taken+len(self.tokens) + key = SimpleKey(token_number, required, + self.index, self.line, self.column, self.get_mark()) + self.possible_simple_keys[self.flow_level] = key + + def remove_possible_simple_key(self): + # Remove the saved possible key position at the current flow level. + if self.flow_level in self.possible_simple_keys: + key = self.possible_simple_keys[self.flow_level] + + if key.required: + raise ScannerError("while scanning a simple key", key.mark, + "could not find expected ':'", self.get_mark()) + + del self.possible_simple_keys[self.flow_level] + + # Indentation functions. + + def unwind_indent(self, column): + + ## In flow context, tokens should respect indentation. + ## Actually the condition should be `self.indent >= column` according to + ## the spec. But this condition will prohibit intuitively correct + ## constructions such as + ## key : { + ## } + #if self.flow_level and self.indent > column: + # raise ScannerError(None, None, + # "invalid indentation or unclosed '[' or '{'", + # self.get_mark()) + + # In the flow context, indentation is ignored. We make the scanner less + # restrictive then specification requires. + if self.flow_level: + return + + # In block context, we may need to issue the BLOCK-END tokens. + while self.indent > column: + mark = self.get_mark() + self.indent = self.indents.pop() + self.tokens.append(BlockEndToken(mark, mark)) + + def add_indent(self, column): + # Check if we need to increase indentation. + if self.indent < column: + self.indents.append(self.indent) + self.indent = column + return True + return False + + # Fetchers. + + def fetch_stream_start(self): + # We always add STREAM-START as the first token and STREAM-END as the + # last token. + + # Read the token. + mark = self.get_mark() + + # Add STREAM-START. + self.tokens.append(StreamStartToken(mark, mark, + encoding=self.encoding)) + + + def fetch_stream_end(self): + + # Set the current indentation to -1. + self.unwind_indent(-1) + + # Reset simple keys. + self.remove_possible_simple_key() + self.allow_simple_key = False + self.possible_simple_keys = {} + + # Read the token. + mark = self.get_mark() + + # Add STREAM-END. + self.tokens.append(StreamEndToken(mark, mark)) + + # The steam is finished. + self.done = True + + def fetch_directive(self): + + # Set the current indentation to -1. + self.unwind_indent(-1) + + # Reset simple keys. + self.remove_possible_simple_key() + self.allow_simple_key = False + + # Scan and add DIRECTIVE. + self.tokens.append(self.scan_directive()) + + def fetch_document_start(self): + self.fetch_document_indicator(DocumentStartToken) + + def fetch_document_end(self): + self.fetch_document_indicator(DocumentEndToken) + + def fetch_document_indicator(self, TokenClass): + + # Set the current indentation to -1. + self.unwind_indent(-1) + + # Reset simple keys. Note that there could not be a block collection + # after '---'. + self.remove_possible_simple_key() + self.allow_simple_key = False + + # Add DOCUMENT-START or DOCUMENT-END. + start_mark = self.get_mark() + self.forward(3) + end_mark = self.get_mark() + self.tokens.append(TokenClass(start_mark, end_mark)) + + def fetch_flow_sequence_start(self): + self.fetch_flow_collection_start(FlowSequenceStartToken) + + def fetch_flow_mapping_start(self): + self.fetch_flow_collection_start(FlowMappingStartToken) + + def fetch_flow_collection_start(self, TokenClass): + + # '[' and '{' may start a simple key. + self.save_possible_simple_key() + + # Increase the flow level. + self.flow_level += 1 + + # Simple keys are allowed after '[' and '{'. + self.allow_simple_key = True + + # Add FLOW-SEQUENCE-START or FLOW-MAPPING-START. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(TokenClass(start_mark, end_mark)) + + def fetch_flow_sequence_end(self): + self.fetch_flow_collection_end(FlowSequenceEndToken) + + def fetch_flow_mapping_end(self): + self.fetch_flow_collection_end(FlowMappingEndToken) + + def fetch_flow_collection_end(self, TokenClass): + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Decrease the flow level. + self.flow_level -= 1 + + # No simple keys after ']' or '}'. + self.allow_simple_key = False + + # Add FLOW-SEQUENCE-END or FLOW-MAPPING-END. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(TokenClass(start_mark, end_mark)) + + def fetch_flow_entry(self): + + # Simple keys are allowed after ','. + self.allow_simple_key = True + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Add FLOW-ENTRY. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(FlowEntryToken(start_mark, end_mark)) + + def fetch_block_entry(self): + + # Block context needs additional checks. + if not self.flow_level: + + # Are we allowed to start a new entry? + if not self.allow_simple_key: + raise ScannerError(None, None, + "sequence entries are not allowed here", + self.get_mark()) + + # We may need to add BLOCK-SEQUENCE-START. + if self.add_indent(self.column): + mark = self.get_mark() + self.tokens.append(BlockSequenceStartToken(mark, mark)) + + # It's an error for the block entry to occur in the flow context, + # but we let the parser detect this. + else: + pass + + # Simple keys are allowed after '-'. + self.allow_simple_key = True + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Add BLOCK-ENTRY. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(BlockEntryToken(start_mark, end_mark)) + + def fetch_key(self): + + # Block context needs additional checks. + if not self.flow_level: + + # Are we allowed to start a key (not necessary a simple)? + if not self.allow_simple_key: + raise ScannerError(None, None, + "mapping keys are not allowed here", + self.get_mark()) + + # We may need to add BLOCK-MAPPING-START. + if self.add_indent(self.column): + mark = self.get_mark() + self.tokens.append(BlockMappingStartToken(mark, mark)) + + # Simple keys are allowed after '?' in the block context. + self.allow_simple_key = not self.flow_level + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Add KEY. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(KeyToken(start_mark, end_mark)) + + def fetch_value(self): + + # Do we determine a simple key? + if self.flow_level in self.possible_simple_keys: + + # Add KEY. + key = self.possible_simple_keys[self.flow_level] + del self.possible_simple_keys[self.flow_level] + self.tokens.insert(key.token_number-self.tokens_taken, + KeyToken(key.mark, key.mark)) + + # If this key starts a new block mapping, we need to add + # BLOCK-MAPPING-START. + if not self.flow_level: + if self.add_indent(key.column): + self.tokens.insert(key.token_number-self.tokens_taken, + BlockMappingStartToken(key.mark, key.mark)) + + # There cannot be two simple keys one after another. + self.allow_simple_key = False + + # It must be a part of a complex key. + else: + + # Block context needs additional checks. + # (Do we really need them? They will be caught by the parser + # anyway.) + if not self.flow_level: + + # We are allowed to start a complex value if and only if + # we can start a simple key. + if not self.allow_simple_key: + raise ScannerError(None, None, + "mapping values are not allowed here", + self.get_mark()) + + # If this value starts a new block mapping, we need to add + # BLOCK-MAPPING-START. It will be detected as an error later by + # the parser. + if not self.flow_level: + if self.add_indent(self.column): + mark = self.get_mark() + self.tokens.append(BlockMappingStartToken(mark, mark)) + + # Simple keys are allowed after ':' in the block context. + self.allow_simple_key = not self.flow_level + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Add VALUE. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(ValueToken(start_mark, end_mark)) + + def fetch_alias(self): + + # ALIAS could be a simple key. + self.save_possible_simple_key() + + # No simple keys after ALIAS. + self.allow_simple_key = False + + # Scan and add ALIAS. + self.tokens.append(self.scan_anchor(AliasToken)) + + def fetch_anchor(self): + + # ANCHOR could start a simple key. + self.save_possible_simple_key() + + # No simple keys after ANCHOR. + self.allow_simple_key = False + + # Scan and add ANCHOR. + self.tokens.append(self.scan_anchor(AnchorToken)) + + def fetch_tag(self): + + # TAG could start a simple key. + self.save_possible_simple_key() + + # No simple keys after TAG. + self.allow_simple_key = False + + # Scan and add TAG. + self.tokens.append(self.scan_tag()) + + def fetch_literal(self): + self.fetch_block_scalar(style='|') + + def fetch_folded(self): + self.fetch_block_scalar(style='>') + + def fetch_block_scalar(self, style): + + # A simple key may follow a block scalar. + self.allow_simple_key = True + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Scan and add SCALAR. + self.tokens.append(self.scan_block_scalar(style)) + + def fetch_single(self): + self.fetch_flow_scalar(style='\'') + + def fetch_double(self): + self.fetch_flow_scalar(style='"') + + def fetch_flow_scalar(self, style): + + # A flow scalar could be a simple key. + self.save_possible_simple_key() + + # No simple keys after flow scalars. + self.allow_simple_key = False + + # Scan and add SCALAR. + self.tokens.append(self.scan_flow_scalar(style)) + + def fetch_plain(self): + + # A plain scalar could be a simple key. + self.save_possible_simple_key() + + # No simple keys after plain scalars. But note that `scan_plain` will + # change this flag if the scan is finished at the beginning of the + # line. + self.allow_simple_key = False + + # Scan and add SCALAR. May change `allow_simple_key`. + self.tokens.append(self.scan_plain()) + + # Checkers. + + def check_directive(self): + + # DIRECTIVE: ^ '%' ... + # The '%' indicator is already checked. + if self.column == 0: + return True + + def check_document_start(self): + + # DOCUMENT-START: ^ '---' (' '|'\n') + if self.column == 0: + if self.prefix(3) == '---' \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + return True + + def check_document_end(self): + + # DOCUMENT-END: ^ '...' (' '|'\n') + if self.column == 0: + if self.prefix(3) == '...' \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + return True + + def check_block_entry(self): + + # BLOCK-ENTRY: '-' (' '|'\n') + return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' + + def check_key(self): + + # KEY(flow context): '?' + if self.flow_level: + return True + + # KEY(block context): '?' (' '|'\n') + else: + return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' + + def check_value(self): + + # VALUE(flow context): ':' + if self.flow_level: + return True + + # VALUE(block context): ':' (' '|'\n') + else: + return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' + + def check_plain(self): + + # A plain scalar may start with any non-space character except: + # '-', '?', ':', ',', '[', ']', '{', '}', + # '#', '&', '*', '!', '|', '>', '\'', '\"', + # '%', '@', '`'. + # + # It may also start with + # '-', '?', ':' + # if it is followed by a non-space character. + # + # Note that we limit the last rule to the block context (except the + # '-' character) because we want the flow context to be space + # independent. + ch = self.peek() + return ch not in '\0 \t\r\n\x85\u2028\u2029-?:,[]{}#&*!|>\'\"%@`' \ + or (self.peek(1) not in '\0 \t\r\n\x85\u2028\u2029' + and (ch == '-' or (not self.flow_level and ch in '?:'))) + + # Scanners. + + def scan_to_next_token(self): + # We ignore spaces, line breaks and comments. + # If we find a line break in the block context, we set the flag + # `allow_simple_key` on. + # The byte order mark is stripped if it's the first character in the + # stream. We do not yet support BOM inside the stream as the + # specification requires. Any such mark will be considered as a part + # of the document. + # + # TODO: We need to make tab handling rules more sane. A good rule is + # Tabs cannot precede tokens + # BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, BLOCK-END, + # KEY(block), VALUE(block), BLOCK-ENTRY + # So the checking code is + # if : + # self.allow_simple_keys = False + # We also need to add the check for `allow_simple_keys == True` to + # `unwind_indent` before issuing BLOCK-END. + # Scanners for block, flow, and plain scalars need to be modified. + + if self.index == 0 and self.peek() == '\uFEFF': + self.forward() + found = False + while not found: + while self.peek() == ' ': + self.forward() + if self.peek() == '#': + while self.peek() not in '\0\r\n\x85\u2028\u2029': + self.forward() + if self.scan_line_break(): + if not self.flow_level: + self.allow_simple_key = True + else: + found = True + + def scan_directive(self): + # See the specification for details. + start_mark = self.get_mark() + self.forward() + name = self.scan_directive_name(start_mark) + value = None + if name == 'YAML': + value = self.scan_yaml_directive_value(start_mark) + end_mark = self.get_mark() + elif name == 'TAG': + value = self.scan_tag_directive_value(start_mark) + end_mark = self.get_mark() + else: + end_mark = self.get_mark() + while self.peek() not in '\0\r\n\x85\u2028\u2029': + self.forward() + self.scan_directive_ignored_line(start_mark) + return DirectiveToken(name, value, start_mark, end_mark) + + def scan_directive_name(self, start_mark): + # See the specification for details. + length = 0 + ch = self.peek(length) + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_': + length += 1 + ch = self.peek(length) + if not length: + raise ScannerError("while scanning a directive", start_mark, + "expected alphabetic or numeric character, but found %r" + % ch, self.get_mark()) + value = self.prefix(length) + self.forward(length) + ch = self.peek() + if ch not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a directive", start_mark, + "expected alphabetic or numeric character, but found %r" + % ch, self.get_mark()) + return value + + def scan_yaml_directive_value(self, start_mark): + # See the specification for details. + while self.peek() == ' ': + self.forward() + major = self.scan_yaml_directive_number(start_mark) + if self.peek() != '.': + raise ScannerError("while scanning a directive", start_mark, + "expected a digit or '.', but found %r" % self.peek(), + self.get_mark()) + self.forward() + minor = self.scan_yaml_directive_number(start_mark) + if self.peek() not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a directive", start_mark, + "expected a digit or ' ', but found %r" % self.peek(), + self.get_mark()) + return (major, minor) + + def scan_yaml_directive_number(self, start_mark): + # See the specification for details. + ch = self.peek() + if not ('0' <= ch <= '9'): + raise ScannerError("while scanning a directive", start_mark, + "expected a digit, but found %r" % ch, self.get_mark()) + length = 0 + while '0' <= self.peek(length) <= '9': + length += 1 + value = int(self.prefix(length)) + self.forward(length) + return value + + def scan_tag_directive_value(self, start_mark): + # See the specification for details. + while self.peek() == ' ': + self.forward() + handle = self.scan_tag_directive_handle(start_mark) + while self.peek() == ' ': + self.forward() + prefix = self.scan_tag_directive_prefix(start_mark) + return (handle, prefix) + + def scan_tag_directive_handle(self, start_mark): + # See the specification for details. + value = self.scan_tag_handle('directive', start_mark) + ch = self.peek() + if ch != ' ': + raise ScannerError("while scanning a directive", start_mark, + "expected ' ', but found %r" % ch, self.get_mark()) + return value + + def scan_tag_directive_prefix(self, start_mark): + # See the specification for details. + value = self.scan_tag_uri('directive', start_mark) + ch = self.peek() + if ch not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a directive", start_mark, + "expected ' ', but found %r" % ch, self.get_mark()) + return value + + def scan_directive_ignored_line(self, start_mark): + # See the specification for details. + while self.peek() == ' ': + self.forward() + if self.peek() == '#': + while self.peek() not in '\0\r\n\x85\u2028\u2029': + self.forward() + ch = self.peek() + if ch not in '\0\r\n\x85\u2028\u2029': + raise ScannerError("while scanning a directive", start_mark, + "expected a comment or a line break, but found %r" + % ch, self.get_mark()) + self.scan_line_break() + + def scan_anchor(self, TokenClass): + # The specification does not restrict characters for anchors and + # aliases. This may lead to problems, for instance, the document: + # [ *alias, value ] + # can be interpreted in two ways, as + # [ "value" ] + # and + # [ *alias , "value" ] + # Therefore we restrict aliases to numbers and ASCII letters. + start_mark = self.get_mark() + indicator = self.peek() + if indicator == '*': + name = 'alias' + else: + name = 'anchor' + self.forward() + length = 0 + ch = self.peek(length) + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_': + length += 1 + ch = self.peek(length) + if not length: + raise ScannerError("while scanning an %s" % name, start_mark, + "expected alphabetic or numeric character, but found %r" + % ch, self.get_mark()) + value = self.prefix(length) + self.forward(length) + ch = self.peek() + if ch not in '\0 \t\r\n\x85\u2028\u2029?:,]}%@`': + raise ScannerError("while scanning an %s" % name, start_mark, + "expected alphabetic or numeric character, but found %r" + % ch, self.get_mark()) + end_mark = self.get_mark() + return TokenClass(value, start_mark, end_mark) + + def scan_tag(self): + # See the specification for details. + start_mark = self.get_mark() + ch = self.peek(1) + if ch == '<': + handle = None + self.forward(2) + suffix = self.scan_tag_uri('tag', start_mark) + if self.peek() != '>': + raise ScannerError("while parsing a tag", start_mark, + "expected '>', but found %r" % self.peek(), + self.get_mark()) + self.forward() + elif ch in '\0 \t\r\n\x85\u2028\u2029': + handle = None + suffix = '!' + self.forward() + else: + length = 1 + use_handle = False + while ch not in '\0 \r\n\x85\u2028\u2029': + if ch == '!': + use_handle = True + break + length += 1 + ch = self.peek(length) + handle = '!' + if use_handle: + handle = self.scan_tag_handle('tag', start_mark) + else: + handle = '!' + self.forward() + suffix = self.scan_tag_uri('tag', start_mark) + ch = self.peek() + if ch not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a tag", start_mark, + "expected ' ', but found %r" % ch, self.get_mark()) + value = (handle, suffix) + end_mark = self.get_mark() + return TagToken(value, start_mark, end_mark) + + def scan_block_scalar(self, style): + # See the specification for details. + + if style == '>': + folded = True + else: + folded = False + + chunks = [] + start_mark = self.get_mark() + + # Scan the header. + self.forward() + chomping, increment = self.scan_block_scalar_indicators(start_mark) + self.scan_block_scalar_ignored_line(start_mark) + + # Determine the indentation level and go to the first non-empty line. + min_indent = self.indent+1 + if min_indent < 1: + min_indent = 1 + if increment is None: + breaks, max_indent, end_mark = self.scan_block_scalar_indentation() + indent = max(min_indent, max_indent) + else: + indent = min_indent+increment-1 + breaks, end_mark = self.scan_block_scalar_breaks(indent) + line_break = '' + + # Scan the inner part of the block scalar. + while self.column == indent and self.peek() != '\0': + chunks.extend(breaks) + leading_non_space = self.peek() not in ' \t' + length = 0 + while self.peek(length) not in '\0\r\n\x85\u2028\u2029': + length += 1 + chunks.append(self.prefix(length)) + self.forward(length) + line_break = self.scan_line_break() + breaks, end_mark = self.scan_block_scalar_breaks(indent) + if self.column == indent and self.peek() != '\0': + + # Unfortunately, folding rules are ambiguous. + # + # This is the folding according to the specification: + + if folded and line_break == '\n' \ + and leading_non_space and self.peek() not in ' \t': + if not breaks: + chunks.append(' ') + else: + chunks.append(line_break) + + # This is Clark Evans's interpretation (also in the spec + # examples): + # + #if folded and line_break == '\n': + # if not breaks: + # if self.peek() not in ' \t': + # chunks.append(' ') + # else: + # chunks.append(line_break) + #else: + # chunks.append(line_break) + else: + break + + # Chomp the tail. + if chomping is not False: + chunks.append(line_break) + if chomping is True: + chunks.extend(breaks) + + # We are done. + return ScalarToken(''.join(chunks), False, start_mark, end_mark, + style) + + def scan_block_scalar_indicators(self, start_mark): + # See the specification for details. + chomping = None + increment = None + ch = self.peek() + if ch in '+-': + if ch == '+': + chomping = True + else: + chomping = False + self.forward() + ch = self.peek() + if ch in '0123456789': + increment = int(ch) + if increment == 0: + raise ScannerError("while scanning a block scalar", start_mark, + "expected indentation indicator in the range 1-9, but found 0", + self.get_mark()) + self.forward() + elif ch in '0123456789': + increment = int(ch) + if increment == 0: + raise ScannerError("while scanning a block scalar", start_mark, + "expected indentation indicator in the range 1-9, but found 0", + self.get_mark()) + self.forward() + ch = self.peek() + if ch in '+-': + if ch == '+': + chomping = True + else: + chomping = False + self.forward() + ch = self.peek() + if ch not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a block scalar", start_mark, + "expected chomping or indentation indicators, but found %r" + % ch, self.get_mark()) + return chomping, increment + + def scan_block_scalar_ignored_line(self, start_mark): + # See the specification for details. + while self.peek() == ' ': + self.forward() + if self.peek() == '#': + while self.peek() not in '\0\r\n\x85\u2028\u2029': + self.forward() + ch = self.peek() + if ch not in '\0\r\n\x85\u2028\u2029': + raise ScannerError("while scanning a block scalar", start_mark, + "expected a comment or a line break, but found %r" % ch, + self.get_mark()) + self.scan_line_break() + + def scan_block_scalar_indentation(self): + # See the specification for details. + chunks = [] + max_indent = 0 + end_mark = self.get_mark() + while self.peek() in ' \r\n\x85\u2028\u2029': + if self.peek() != ' ': + chunks.append(self.scan_line_break()) + end_mark = self.get_mark() + else: + self.forward() + if self.column > max_indent: + max_indent = self.column + return chunks, max_indent, end_mark + + def scan_block_scalar_breaks(self, indent): + # See the specification for details. + chunks = [] + end_mark = self.get_mark() + while self.column < indent and self.peek() == ' ': + self.forward() + while self.peek() in '\r\n\x85\u2028\u2029': + chunks.append(self.scan_line_break()) + end_mark = self.get_mark() + while self.column < indent and self.peek() == ' ': + self.forward() + return chunks, end_mark + + def scan_flow_scalar(self, style): + # See the specification for details. + # Note that we loose indentation rules for quoted scalars. Quoted + # scalars don't need to adhere indentation because " and ' clearly + # mark the beginning and the end of them. Therefore we are less + # restrictive then the specification requires. We only need to check + # that document separators are not included in scalars. + if style == '"': + double = True + else: + double = False + chunks = [] + start_mark = self.get_mark() + quote = self.peek() + self.forward() + chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark)) + while self.peek() != quote: + chunks.extend(self.scan_flow_scalar_spaces(double, start_mark)) + chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark)) + self.forward() + end_mark = self.get_mark() + return ScalarToken(''.join(chunks), False, start_mark, end_mark, + style) + + ESCAPE_REPLACEMENTS = { + '0': '\0', + 'a': '\x07', + 'b': '\x08', + 't': '\x09', + '\t': '\x09', + 'n': '\x0A', + 'v': '\x0B', + 'f': '\x0C', + 'r': '\x0D', + 'e': '\x1B', + ' ': '\x20', + '\"': '\"', + '\\': '\\', + '/': '/', + 'N': '\x85', + '_': '\xA0', + 'L': '\u2028', + 'P': '\u2029', + } + + ESCAPE_CODES = { + 'x': 2, + 'u': 4, + 'U': 8, + } + + def scan_flow_scalar_non_spaces(self, double, start_mark): + # See the specification for details. + chunks = [] + while True: + length = 0 + while self.peek(length) not in '\'\"\\\0 \t\r\n\x85\u2028\u2029': + length += 1 + if length: + chunks.append(self.prefix(length)) + self.forward(length) + ch = self.peek() + if not double and ch == '\'' and self.peek(1) == '\'': + chunks.append('\'') + self.forward(2) + elif (double and ch == '\'') or (not double and ch in '\"\\'): + chunks.append(ch) + self.forward() + elif double and ch == '\\': + self.forward() + ch = self.peek() + if ch in self.ESCAPE_REPLACEMENTS: + chunks.append(self.ESCAPE_REPLACEMENTS[ch]) + self.forward() + elif ch in self.ESCAPE_CODES: + length = self.ESCAPE_CODES[ch] + self.forward() + for k in range(length): + if self.peek(k) not in '0123456789ABCDEFabcdef': + raise ScannerError("while scanning a double-quoted scalar", start_mark, + "expected escape sequence of %d hexadecimal numbers, but found %r" % + (length, self.peek(k)), self.get_mark()) + code = int(self.prefix(length), 16) + chunks.append(chr(code)) + self.forward(length) + elif ch in '\r\n\x85\u2028\u2029': + self.scan_line_break() + chunks.extend(self.scan_flow_scalar_breaks(double, start_mark)) + else: + raise ScannerError("while scanning a double-quoted scalar", start_mark, + "found unknown escape character %r" % ch, self.get_mark()) + else: + return chunks + + def scan_flow_scalar_spaces(self, double, start_mark): + # See the specification for details. + chunks = [] + length = 0 + while self.peek(length) in ' \t': + length += 1 + whitespaces = self.prefix(length) + self.forward(length) + ch = self.peek() + if ch == '\0': + raise ScannerError("while scanning a quoted scalar", start_mark, + "found unexpected end of stream", self.get_mark()) + elif ch in '\r\n\x85\u2028\u2029': + line_break = self.scan_line_break() + breaks = self.scan_flow_scalar_breaks(double, start_mark) + if line_break != '\n': + chunks.append(line_break) + elif not breaks: + chunks.append(' ') + chunks.extend(breaks) + else: + chunks.append(whitespaces) + return chunks + + def scan_flow_scalar_breaks(self, double, start_mark): + # See the specification for details. + chunks = [] + while True: + # Instead of checking indentation, we check for document + # separators. + prefix = self.prefix(3) + if (prefix == '---' or prefix == '...') \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + raise ScannerError("while scanning a quoted scalar", start_mark, + "found unexpected document separator", self.get_mark()) + while self.peek() in ' \t': + self.forward() + if self.peek() in '\r\n\x85\u2028\u2029': + chunks.append(self.scan_line_break()) + else: + return chunks + + def scan_plain(self): + # See the specification for details. + # We add an additional restriction for the flow context: + # plain scalars in the flow context cannot contain ',' or '?'. + # We also keep track of the `allow_simple_key` flag here. + # Indentation rules are loosed for the flow context. + chunks = [] + start_mark = self.get_mark() + end_mark = start_mark + indent = self.indent+1 + # We allow zero indentation for scalars, but then we need to check for + # document separators at the beginning of the line. + #if indent == 0: + # indent = 1 + spaces = [] + while True: + length = 0 + if self.peek() == '#': + break + while True: + ch = self.peek(length) + if ch in '\0 \t\r\n\x85\u2028\u2029' \ + or (ch == ':' and + self.peek(length+1) in '\0 \t\r\n\x85\u2028\u2029' + + (u',[]{}' if self.flow_level else u''))\ + or (self.flow_level and ch in ',?[]{}'): + break + length += 1 + if length == 0: + break + self.allow_simple_key = False + chunks.extend(spaces) + chunks.append(self.prefix(length)) + self.forward(length) + end_mark = self.get_mark() + spaces = self.scan_plain_spaces(indent, start_mark) + if not spaces or self.peek() == '#' \ + or (not self.flow_level and self.column < indent): + break + return ScalarToken(''.join(chunks), True, start_mark, end_mark) + + def scan_plain_spaces(self, indent, start_mark): + # See the specification for details. + # The specification is really confusing about tabs in plain scalars. + # We just forbid them completely. Do not use tabs in YAML! + chunks = [] + length = 0 + while self.peek(length) in ' ': + length += 1 + whitespaces = self.prefix(length) + self.forward(length) + ch = self.peek() + if ch in '\r\n\x85\u2028\u2029': + line_break = self.scan_line_break() + self.allow_simple_key = True + prefix = self.prefix(3) + if (prefix == '---' or prefix == '...') \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + return + breaks = [] + while self.peek() in ' \r\n\x85\u2028\u2029': + if self.peek() == ' ': + self.forward() + else: + breaks.append(self.scan_line_break()) + prefix = self.prefix(3) + if (prefix == '---' or prefix == '...') \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + return + if line_break != '\n': + chunks.append(line_break) + elif not breaks: + chunks.append(' ') + chunks.extend(breaks) + elif whitespaces: + chunks.append(whitespaces) + return chunks + + def scan_tag_handle(self, name, start_mark): + # See the specification for details. + # For some strange reasons, the specification does not allow '_' in + # tag handles. I have allowed it anyway. + ch = self.peek() + if ch != '!': + raise ScannerError("while scanning a %s" % name, start_mark, + "expected '!', but found %r" % ch, self.get_mark()) + length = 1 + ch = self.peek(length) + if ch != ' ': + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_': + length += 1 + ch = self.peek(length) + if ch != '!': + self.forward(length) + raise ScannerError("while scanning a %s" % name, start_mark, + "expected '!', but found %r" % ch, self.get_mark()) + length += 1 + value = self.prefix(length) + self.forward(length) + return value + + def scan_tag_uri(self, name, start_mark): + # See the specification for details. + # Note: we do not check if URI is well-formed. + chunks = [] + length = 0 + ch = self.peek(length) + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-;/?:@&=+$,_.!~*\'()[]%': + if ch == '%': + chunks.append(self.prefix(length)) + self.forward(length) + length = 0 + chunks.append(self.scan_uri_escapes(name, start_mark)) + else: + length += 1 + ch = self.peek(length) + if length: + chunks.append(self.prefix(length)) + self.forward(length) + length = 0 + if not chunks: + raise ScannerError("while parsing a %s" % name, start_mark, + "expected URI, but found %r" % ch, self.get_mark()) + return ''.join(chunks) + + def scan_uri_escapes(self, name, start_mark): + # See the specification for details. + codes = [] + mark = self.get_mark() + while self.peek() == '%': + self.forward() + for k in range(2): + if self.peek(k) not in '0123456789ABCDEFabcdef': + raise ScannerError("while scanning a %s" % name, start_mark, + "expected URI escape sequence of 2 hexadecimal numbers, but found %r" + % self.peek(k), self.get_mark()) + codes.append(int(self.prefix(2), 16)) + self.forward(2) + try: + value = bytes(codes).decode('utf-8') + except UnicodeDecodeError as exc: + raise ScannerError("while scanning a %s" % name, start_mark, str(exc), mark) + return value + + def scan_line_break(self): + # Transforms: + # '\r\n' : '\n' + # '\r' : '\n' + # '\n' : '\n' + # '\x85' : '\n' + # '\u2028' : '\u2028' + # '\u2029 : '\u2029' + # default : '' + ch = self.peek() + if ch in '\r\n\x85': + if self.prefix(2) == '\r\n': + self.forward(2) + else: + self.forward() + return '\n' + elif ch in '\u2028\u2029': + self.forward() + return ch + return '' diff --git a/.venv/lib/python3.12/site-packages/yaml/serializer.py b/.venv/lib/python3.12/site-packages/yaml/serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..fe911e67ae7a739abb491fbbc6834b9c37bbda4b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/serializer.py @@ -0,0 +1,111 @@ + +__all__ = ['Serializer', 'SerializerError'] + +from .error import YAMLError +from .events import * +from .nodes import * + +class SerializerError(YAMLError): + pass + +class Serializer: + + ANCHOR_TEMPLATE = 'id%03d' + + def __init__(self, encoding=None, + explicit_start=None, explicit_end=None, version=None, tags=None): + self.use_encoding = encoding + self.use_explicit_start = explicit_start + self.use_explicit_end = explicit_end + self.use_version = version + self.use_tags = tags + self.serialized_nodes = {} + self.anchors = {} + self.last_anchor_id = 0 + self.closed = None + + def open(self): + if self.closed is None: + self.emit(StreamStartEvent(encoding=self.use_encoding)) + self.closed = False + elif self.closed: + raise SerializerError("serializer is closed") + else: + raise SerializerError("serializer is already opened") + + def close(self): + if self.closed is None: + raise SerializerError("serializer is not opened") + elif not self.closed: + self.emit(StreamEndEvent()) + self.closed = True + + #def __del__(self): + # self.close() + + def serialize(self, node): + if self.closed is None: + raise SerializerError("serializer is not opened") + elif self.closed: + raise SerializerError("serializer is closed") + self.emit(DocumentStartEvent(explicit=self.use_explicit_start, + version=self.use_version, tags=self.use_tags)) + self.anchor_node(node) + self.serialize_node(node, None, None) + self.emit(DocumentEndEvent(explicit=self.use_explicit_end)) + self.serialized_nodes = {} + self.anchors = {} + self.last_anchor_id = 0 + + def anchor_node(self, node): + if node in self.anchors: + if self.anchors[node] is None: + self.anchors[node] = self.generate_anchor(node) + else: + self.anchors[node] = None + if isinstance(node, SequenceNode): + for item in node.value: + self.anchor_node(item) + elif isinstance(node, MappingNode): + for key, value in node.value: + self.anchor_node(key) + self.anchor_node(value) + + def generate_anchor(self, node): + self.last_anchor_id += 1 + return self.ANCHOR_TEMPLATE % self.last_anchor_id + + def serialize_node(self, node, parent, index): + alias = self.anchors[node] + if node in self.serialized_nodes: + self.emit(AliasEvent(alias)) + else: + self.serialized_nodes[node] = True + self.descend_resolver(parent, index) + if isinstance(node, ScalarNode): + detected_tag = self.resolve(ScalarNode, node.value, (True, False)) + default_tag = self.resolve(ScalarNode, node.value, (False, True)) + implicit = (node.tag == detected_tag), (node.tag == default_tag) + self.emit(ScalarEvent(alias, node.tag, implicit, node.value, + style=node.style)) + elif isinstance(node, SequenceNode): + implicit = (node.tag + == self.resolve(SequenceNode, node.value, True)) + self.emit(SequenceStartEvent(alias, node.tag, implicit, + flow_style=node.flow_style)) + index = 0 + for item in node.value: + self.serialize_node(item, node, index) + index += 1 + self.emit(SequenceEndEvent()) + elif isinstance(node, MappingNode): + implicit = (node.tag + == self.resolve(MappingNode, node.value, True)) + self.emit(MappingStartEvent(alias, node.tag, implicit, + flow_style=node.flow_style)) + for key, value in node.value: + self.serialize_node(key, node, None) + self.serialize_node(value, node, key) + self.emit(MappingEndEvent()) + self.ascend_resolver() + diff --git a/.venv/lib/python3.12/site-packages/yaml/tokens.py b/.venv/lib/python3.12/site-packages/yaml/tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0b48a394ac8c019b401516a12f688df361cf90 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/yaml/tokens.py @@ -0,0 +1,104 @@ + +class Token(object): + def __init__(self, start_mark, end_mark): + self.start_mark = start_mark + self.end_mark = end_mark + def __repr__(self): + attributes = [key for key in self.__dict__ + if not key.endswith('_mark')] + attributes.sort() + arguments = ', '.join(['%s=%r' % (key, getattr(self, key)) + for key in attributes]) + return '%s(%s)' % (self.__class__.__name__, arguments) + +#class BOMToken(Token): +# id = '' + +class DirectiveToken(Token): + id = '' + def __init__(self, name, value, start_mark, end_mark): + self.name = name + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + +class DocumentStartToken(Token): + id = '' + +class DocumentEndToken(Token): + id = '' + +class StreamStartToken(Token): + id = '' + def __init__(self, start_mark=None, end_mark=None, + encoding=None): + self.start_mark = start_mark + self.end_mark = end_mark + self.encoding = encoding + +class StreamEndToken(Token): + id = '' + +class BlockSequenceStartToken(Token): + id = '' + +class BlockMappingStartToken(Token): + id = '' + +class BlockEndToken(Token): + id = '' + +class FlowSequenceStartToken(Token): + id = '[' + +class FlowMappingStartToken(Token): + id = '{' + +class FlowSequenceEndToken(Token): + id = ']' + +class FlowMappingEndToken(Token): + id = '}' + +class KeyToken(Token): + id = '?' + +class ValueToken(Token): + id = ':' + +class BlockEntryToken(Token): + id = '-' + +class FlowEntryToken(Token): + id = ',' + +class AliasToken(Token): + id = '' + def __init__(self, value, start_mark, end_mark): + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + +class AnchorToken(Token): + id = '' + def __init__(self, value, start_mark, end_mark): + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + +class TagToken(Token): + id = '' + def __init__(self, value, start_mark, end_mark): + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + +class ScalarToken(Token): + id = '' + def __init__(self, value, plain, start_mark, end_mark, style=None): + self.value = value + self.plain = plain + self.start_mark = start_mark + self.end_mark = end_mark + self.style = style + diff --git a/.venv/pyvenv.cfg b/.venv/pyvenv.cfg new file mode 100644 index 0000000000000000000000000000000000000000..812be661dad91e60814046078aa6dc4bba93bcbe --- /dev/null +++ b/.venv/pyvenv.cfg @@ -0,0 +1,5 @@ +home = /usr/bin +include-system-site-packages = false +version = 3.12.3 +executable = /usr/bin/python3.12 +command = /usr/bin/python3 -m venv /home/taruns/Downloads/scraper/.venv diff --git a/.venv/share/man/man1/isympy.1 b/.venv/share/man/man1/isympy.1 new file mode 100644 index 0000000000000000000000000000000000000000..0ff966158a28c5ad1a6cd954e454842b25fdd999 --- /dev/null +++ b/.venv/share/man/man1/isympy.1 @@ -0,0 +1,188 @@ +'\" -*- coding: us-ascii -*- +.if \n(.g .ds T< \\FC +.if \n(.g .ds T> \\F[\n[.fam]] +.de URL +\\$2 \(la\\$1\(ra\\$3 +.. +.if \n(.g .mso www.tmac +.TH isympy 1 2007-10-8 "" "" +.SH NAME +isympy \- interactive shell for SymPy +.SH SYNOPSIS +'nh +.fi +.ad l +\fBisympy\fR \kx +.if (\nx>(\n(.l/2)) .nr x (\n(.l/5) +'in \n(.iu+\nxu +[\fB-c\fR | \fB--console\fR] [\fB-p\fR ENCODING | \fB--pretty\fR ENCODING] [\fB-t\fR TYPE | \fB--types\fR TYPE] [\fB-o\fR ORDER | \fB--order\fR ORDER] [\fB-q\fR | \fB--quiet\fR] [\fB-d\fR | \fB--doctest\fR] [\fB-C\fR | \fB--no-cache\fR] [\fB-a\fR | \fB--auto\fR] [\fB-D\fR | \fB--debug\fR] [ +-- | PYTHONOPTIONS] +'in \n(.iu-\nxu +.ad b +'hy +'nh +.fi +.ad l +\fBisympy\fR \kx +.if (\nx>(\n(.l/2)) .nr x (\n(.l/5) +'in \n(.iu+\nxu +[ +{\fB-h\fR | \fB--help\fR} +| +{\fB-v\fR | \fB--version\fR} +] +'in \n(.iu-\nxu +.ad b +'hy +.SH DESCRIPTION +isympy is a Python shell for SymPy. It is just a normal python shell +(ipython shell if you have the ipython package installed) that executes +the following commands so that you don't have to: +.PP +.nf +\*(T< +>>> from __future__ import division +>>> from sympy import * +>>> x, y, z = symbols("x,y,z") +>>> k, m, n = symbols("k,m,n", integer=True) + \*(T> +.fi +.PP +So starting isympy is equivalent to starting python (or ipython) and +executing the above commands by hand. It is intended for easy and quick +experimentation with SymPy. For more complicated programs, it is recommended +to write a script and import things explicitly (using the "from sympy +import sin, log, Symbol, ..." idiom). +.SH OPTIONS +.TP +\*(T<\fB\-c \fR\*(T>\fISHELL\fR, \*(T<\fB\-\-console=\fR\*(T>\fISHELL\fR +Use the specified shell (python or ipython) as +console backend instead of the default one (ipython +if present or python otherwise). + +Example: isympy -c python + +\fISHELL\fR could be either +\&'ipython' or 'python' +.TP +\*(T<\fB\-p \fR\*(T>\fIENCODING\fR, \*(T<\fB\-\-pretty=\fR\*(T>\fIENCODING\fR +Setup pretty printing in SymPy. By default, the most pretty, unicode +printing is enabled (if the terminal supports it). You can use less +pretty ASCII printing instead or no pretty printing at all. + +Example: isympy -p no + +\fIENCODING\fR must be one of 'unicode', +\&'ascii' or 'no'. +.TP +\*(T<\fB\-t \fR\*(T>\fITYPE\fR, \*(T<\fB\-\-types=\fR\*(T>\fITYPE\fR +Setup the ground types for the polys. By default, gmpy ground types +are used if gmpy2 or gmpy is installed, otherwise it falls back to python +ground types, which are a little bit slower. You can manually +choose python ground types even if gmpy is installed (e.g., for testing purposes). + +Note that sympy ground types are not supported, and should be used +only for experimental purposes. + +Note that the gmpy1 ground type is primarily intended for testing; it the +use of gmpy even if gmpy2 is available. + +This is the same as setting the environment variable +SYMPY_GROUND_TYPES to the given ground type (e.g., +SYMPY_GROUND_TYPES='gmpy') + +The ground types can be determined interactively from the variable +sympy.polys.domains.GROUND_TYPES inside the isympy shell itself. + +Example: isympy -t python + +\fITYPE\fR must be one of 'gmpy', +\&'gmpy1' or 'python'. +.TP +\*(T<\fB\-o \fR\*(T>\fIORDER\fR, \*(T<\fB\-\-order=\fR\*(T>\fIORDER\fR +Setup the ordering of terms for printing. The default is lex, which +orders terms lexicographically (e.g., x**2 + x + 1). You can choose +other orderings, such as rev-lex, which will use reverse +lexicographic ordering (e.g., 1 + x + x**2). + +Note that for very large expressions, ORDER='none' may speed up +printing considerably, with the tradeoff that the order of the terms +in the printed expression will have no canonical order + +Example: isympy -o rev-lax + +\fIORDER\fR must be one of 'lex', 'rev-lex', 'grlex', +\&'rev-grlex', 'grevlex', 'rev-grevlex', 'old', or 'none'. +.TP +\*(T<\fB\-q\fR\*(T>, \*(T<\fB\-\-quiet\fR\*(T> +Print only Python's and SymPy's versions to stdout at startup, and nothing else. +.TP +\*(T<\fB\-d\fR\*(T>, \*(T<\fB\-\-doctest\fR\*(T> +Use the same format that should be used for doctests. This is +equivalent to '\fIisympy -c python -p no\fR'. +.TP +\*(T<\fB\-C\fR\*(T>, \*(T<\fB\-\-no\-cache\fR\*(T> +Disable the caching mechanism. Disabling the cache may slow certain +operations down considerably. This is useful for testing the cache, +or for benchmarking, as the cache can result in deceptive benchmark timings. + +This is the same as setting the environment variable SYMPY_USE_CACHE +to 'no'. +.TP +\*(T<\fB\-a\fR\*(T>, \*(T<\fB\-\-auto\fR\*(T> +Automatically create missing symbols. Normally, typing a name of a +Symbol that has not been instantiated first would raise NameError, +but with this option enabled, any undefined name will be +automatically created as a Symbol. This only works in IPython 0.11. + +Note that this is intended only for interactive, calculator style +usage. In a script that uses SymPy, Symbols should be instantiated +at the top, so that it's clear what they are. + +This will not override any names that are already defined, which +includes the single character letters represented by the mnemonic +QCOSINE (see the "Gotchas and Pitfalls" document in the +documentation). You can delete existing names by executing "del +name" in the shell itself. You can see if a name is defined by typing +"'name' in globals()". + +The Symbols that are created using this have default assumptions. +If you want to place assumptions on symbols, you should create them +using symbols() or var(). + +Finally, this only works in the top level namespace. So, for +example, if you define a function in isympy with an undefined +Symbol, it will not work. +.TP +\*(T<\fB\-D\fR\*(T>, \*(T<\fB\-\-debug\fR\*(T> +Enable debugging output. This is the same as setting the +environment variable SYMPY_DEBUG to 'True'. The debug status is set +in the variable SYMPY_DEBUG within isympy. +.TP +-- \fIPYTHONOPTIONS\fR +These options will be passed on to \fIipython (1)\fR shell. +Only supported when ipython is being used (standard python shell not supported). + +Two dashes (--) are required to separate \fIPYTHONOPTIONS\fR +from the other isympy options. + +For example, to run iSymPy without startup banner and colors: + +isympy -q -c ipython -- --colors=NoColor +.TP +\*(T<\fB\-h\fR\*(T>, \*(T<\fB\-\-help\fR\*(T> +Print help output and exit. +.TP +\*(T<\fB\-v\fR\*(T>, \*(T<\fB\-\-version\fR\*(T> +Print isympy version information and exit. +.SH FILES +.TP +\*(T<\fI${HOME}/.sympy\-history\fR\*(T> +Saves the history of commands when using the python +shell as backend. +.SH BUGS +The upstreams BTS can be found at \(lahttps://github.com/sympy/sympy/issues\(ra +Please report all bugs that you find in there, this will help improve +the overall quality of SymPy. +.SH "SEE ALSO" +\fBipython\fR(1), \fBpython\fR(1) diff --git a/.venv/share/man/man1/ttx.1 b/.venv/share/man/man1/ttx.1 new file mode 100644 index 0000000000000000000000000000000000000000..bba23b5e51629509a499f4471fc8196e9863d211 --- /dev/null +++ b/.venv/share/man/man1/ttx.1 @@ -0,0 +1,225 @@ +.Dd May 18, 2004 +.\" ttx is not specific to any OS, but contrary to what groff_mdoc(7) +.\" seems to imply, entirely omitting the .Os macro causes 'BSD' to +.\" be used, so I give a zero-width space as its argument. +.Os \& +.\" The "FontTools Manual" argument apparently has no effect in +.\" groff 1.18.1. I think it is a bug in the -mdoc groff package. +.Dt TTX 1 "FontTools Manual" +.Sh NAME +.Nm ttx +.Nd tool for manipulating TrueType and OpenType fonts +.Sh SYNOPSIS +.Nm +.Bk +.Op Ar option ... +.Ek +.Bk +.Ar file ... +.Ek +.Sh DESCRIPTION +.Nm +is a tool for manipulating TrueType and OpenType fonts. It can convert +TrueType and OpenType fonts to and from an +.Tn XML Ns -based format called +.Tn TTX . +.Tn TTX +files have a +.Ql .ttx +extension. +.Pp +For each +.Ar file +argument it is given, +.Nm +detects whether it is a +.Ql .ttf , +.Ql .otf +or +.Ql .ttx +file and acts accordingly: if it is a +.Ql .ttf +or +.Ql .otf +file, it generates a +.Ql .ttx +file; if it is a +.Ql .ttx +file, it generates a +.Ql .ttf +or +.Ql .otf +file. +.Pp +By default, every output file is created in the same directory as the +corresponding input file and with the same name except for the +extension, which is substituted appropriately. +.Nm +never overwrites existing files; if necessary, it appends a suffix to +the output file name before the extension, as in +.Pa Arial#1.ttf . +.Ss "General options" +.Bl -tag -width ".Fl t Ar table" +.It Fl h +Display usage information. +.It Fl d Ar dir +Write the output files to directory +.Ar dir +instead of writing every output file to the same directory as the +corresponding input file. +.It Fl o Ar file +Write the output to +.Ar file +instead of writing it to the same directory as the +corresponding input file. +.It Fl v +Be verbose. Write more messages to the standard output describing what +is being done. +.It Fl a +Allow virtual glyphs ID's on compile or decompile. +.El +.Ss "Dump options" +The following options control the process of dumping font files +(TrueType or OpenType) to +.Tn TTX +files. +.Bl -tag -width ".Fl t Ar table" +.It Fl l +List table information. Instead of dumping the font to a +.Tn TTX +file, display minimal information about each table. +.It Fl t Ar table +Dump table +.Ar table . +This option may be given multiple times to dump several tables at +once. When not specified, all tables are dumped. +.It Fl x Ar table +Exclude table +.Ar table +from the list of tables to dump. This option may be given multiple +times to exclude several tables from the dump. The +.Fl t +and +.Fl x +options are mutually exclusive. +.It Fl s +Split tables. Dump each table to a separate +.Tn TTX +file and write (under the name that would have been used for the output +file if the +.Fl s +option had not been given) one small +.Tn TTX +file containing references to the individual table dump files. This +file can be used as input to +.Nm +as long as the referenced files can be found in the same directory. +.It Fl i +.\" XXX: I suppose OpenType programs (exist and) are also affected. +Don't disassemble TrueType instructions. When this option is specified, +all TrueType programs (glyph programs, the font program and the +pre-program) are written to the +.Tn TTX +file as hexadecimal data instead of +assembly. This saves some time and results in smaller +.Tn TTX +files. +.It Fl y Ar n +When decompiling a TrueType Collection (TTC) file, +decompile font number +.Ar n , +starting from 0. +.El +.Ss "Compilation options" +The following options control the process of compiling +.Tn TTX +files into font files (TrueType or OpenType): +.Bl -tag -width ".Fl t Ar table" +.It Fl m Ar fontfile +Merge the input +.Tn TTX +file +.Ar file +with +.Ar fontfile . +No more than one +.Ar file +argument can be specified when this option is used. +.It Fl b +Don't recalculate glyph bounding boxes. Use the values in the +.Tn TTX +file as is. +.El +.Sh "THE TTX FILE FORMAT" +You can find some information about the +.Tn TTX +file format in +.Pa documentation.html . +In particular, you will find in that file the list of tables understood by +.Nm +and the relations between TrueType GlyphIDs and the glyph names used in +.Tn TTX +files. +.Sh EXAMPLES +In the following examples, all files are read from and written to the +current directory. Additionally, the name given for the output file +assumes in every case that it did not exist before +.Nm +was invoked. +.Pp +Dump the TrueType font contained in +.Pa FreeSans.ttf +to +.Pa FreeSans.ttx : +.Pp +.Dl ttx FreeSans.ttf +.Pp +Compile +.Pa MyFont.ttx +into a TrueType or OpenType font file: +.Pp +.Dl ttx MyFont.ttx +.Pp +List the tables in +.Pa FreeSans.ttf +along with some information: +.Pp +.Dl ttx -l FreeSans.ttf +.Pp +Dump the +.Sq cmap +table from +.Pa FreeSans.ttf +to +.Pa FreeSans.ttx : +.Pp +.Dl ttx -t cmap FreeSans.ttf +.Sh NOTES +On MS\-Windows and MacOS, +.Nm +is available as a graphical application to which files can be dropped. +.Sh SEE ALSO +.Pa documentation.html +.Pp +.Xr fontforge 1 , +.Xr ftinfo 1 , +.Xr gfontview 1 , +.Xr xmbdfed 1 , +.Xr Font::TTF 3pm +.Sh AUTHORS +.Nm +was written by +.An -nosplit +.An "Just van Rossum" Aq just@letterror.com . +.Pp +This manual page was written by +.An "Florent Rougon" Aq f.rougon@free.fr +for the Debian GNU/Linux system based on the existing FontTools +documentation. It may be freely used, modified and distributed without +restrictions. +.\" For Emacs: +.\" Local Variables: +.\" fill-column: 72 +.\" sentence-end: "[.?!][]\"')}]*\\($\\| $\\| \\| \\)[ \n]*" +.\" sentence-end-double-space: t +.\" End: \ No newline at end of file diff --git a/Micro_component_dataset/README.md b/Micro_component_dataset/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0bc162313e5b08e661299f712822fb1b4c4da6e2 --- /dev/null +++ b/Micro_component_dataset/README.md @@ -0,0 +1,63 @@ +--- +language: +- en +license: cc-by-4.0 +tags: +- computer-vision +- object-detection +- yolo +- ewaste +- pcb +- recycling +- hardware-fraud +size_categories: +- 1K